Skip to content

fix: false positive cycle detection for shared struct references#101

Open
Yanhu007 wants to merge 1 commit intokr:mainfrom
Yanhu007:fix/false-positive-cycle-detection
Open

fix: false positive cycle detection for shared struct references#101
Yanhu007 wants to merge 1 commit intokr:mainfrom
Yanhu007:fix/false-positive-cycle-detection

Conversation

@Yanhu007
Copy link
Copy Markdown

Fixes #96

Problem

When two struct fields point to the same struct (shared reference, not a cycle), the second field is falsely flagged as (CYCLIC REFERENCE):

shared := &Inner{Value: 42}
o := Outer{A: shared, B: shared}
fmt.Sprintf("%# v", pretty.Formatter(o))
// B is falsely printed as: Inner{(CYCLIC REFERENCE)}

The visited map tracks all previously seen pointer addresses globally, but never removes them. So when a sibling field refers to the same struct, it appears as if we're revisiting an ancestor.

Fix

Delete the visit entry from visited after the struct is fully printed. This way only ancestors on the current recursion path are tracked, correctly distinguishing:

  • Shared references (same pointer from sibling fields) → allowed
  • Real cycles (pointer back to an ancestor) → detected

Verified both cases:

  • Shared reference: no false positive ✅
  • Real cycle (A→B→A): correctly detected ✅
  • All existing tests pass ✅

The visited map was never cleaned up after printing a struct, so
when two sibling fields pointed to the same struct, the second
reference was falsely flagged as a cyclic reference.

Fix by deleting the visit entry after the struct is fully printed.
This way only ancestors on the current path are tracked, not all
previously seen nodes.

Real cycles are still correctly detected because the entry exists
while recursing into the struct's fields.

Fixes kr#96
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

false positive in cycle check

1 participant