* feat(dep): teach bd dep cycles to traverse tracks edges (gc-818bx) Adds DetectCyclesRequest.IncludeTracks and a CanonicalMixedCyclePaths walk so a molecule-root deadlock closing through a tracks edge (root --blocks--> its own entry step, step --tracks--> root) is detectable, while a cycle made entirely of tracks edges stays silent by construction (guards against the PR #4933 false-positive regression). Wired end to end: public issueops.DetectCyclesRequest -> pure CanonicalMixedCyclePaths/AppendMixedCycleGraphInTx -> DetectCycleReportInTx -> dolt/embeddeddolt/uow-domain transactional wrappers -> `bd dep cycles --include-tracks`. Default request behavior is unchanged (byte-identical code path when IncludeTracks is false). Tests: pure-function unit tests for the new DFS variant (rotation, parallel-edge dedup, self-loops, map-order determinism); conformance cases against both dolt and embeddeddolt real backends plus the uow provider (RunCycleDetectorIncludeTracksIgnoresAPureTracksLoop, RunCycleDetectorIncludeTracksFindsTheMoleculeRootShape, and an added DepTracks case in RunCycleDetectorFollowsOnlyBlockingEdges pinning the default's exclusion); CLI-level flag registration and threading tests. Scope: fix candidate 3 only, per gascity-pl's 2026-08-10 scope-narrowing comment on gc-818bx (candidates 1/2 addressed upstream by gastownhall/ gascity PR #5202). * fix(dep): find mixed cycles by SCC instead of single-pass DFS (gc-818bx) CanonicalMixedCyclePaths could report no cycle for a graph that has a qualifying one. A single global visited/onPath set only detects a back edge to a node still on the active recursion stack, so a tracks-only loop that fully closes and unwinds first (a->b->a) leaves b marked visited-but-off-path by the time a scheduling edge into the same component (a->c->b) is examined, and the c->b return edge is invisible to the DFS. Every internal edge of a strongly connected component lies on some cycle within it, so replace the DFS with Tarjan's algorithm: find each SCC, and for any SCC containing a scheduling edge, walk a deterministic BFS return path back to that edge's source. Nodes, adjacency, SCC membership, the chosen edge, and the return path are all sorted so the result stays a pure function of the graph, matching the existing determinism guarantee. Adds the counterexample from exact-head review: a--tracks-->b, b--tracks-->a, a--blocks-->c, c--tracks-->b, which the prior implementation reported as acyclic despite the qualifying a->c->b->a cycle. * fix(dep): fail loudly if SCC path invariant breaks (gc-zo8a7) Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of sjarmak * fix(dep): keep every default cycle in the --include-tracks report CanonicalMixedCyclePaths emitted one cycle per strongly connected component, so a tracks edge joining two separate blocks-only deadlocks collapsed them into one reported cycle and --include-tracks could report fewer cycles than the default walk. The widened report is now the union of the default depth-first walk on the scheduling-only subgraph and, for each blocks/conditional-blocks edge inside a component of the widened graph, that edge closed by its shortest return path over either edge type. The first set is the default report by construction; the second adds cycles that close through tracks edges. Every reported cycle still contains a scheduling edge, so tracks-only loops stay out. The report holds at most one cycle per internal scheduling edge plus the default cycles. A missing return path inside a component is an invariant breach; it now returns an error through DetectCycles instead of panicking. * test(dep): pin tracks edge direction in the cycle detector contract A two-node cycle reads the same under edge reversal, so the existing IncludeTracks cases could not tell a walk that follows issue_id -> depends_on_id from one that follows the reverse. The new three-node case seeds a -> c (tracks), c -> b (blocks), b -> a (tracks), whose reported path is a, c, b and becomes a, b, c if the edges are reversed. Also refresh the cycledetector.go line citations this branch shifted. * perf(dep): share one return-path search per target in the --include-tracks report CanonicalMixedCyclePaths ran one breadth-first search per scheduling edge inside a component, O(E(V+E)). On a dense tangle E grows with the square of V, so the report grew with the fourth power of the component size. Group the component's scheduling edges by target and close every edge into a target from one shortestPathTree rooted there, confined to the component. closeMixedCycle now reads the return path out of that tree and still returns an error, never loops, when the tree does not reach the edge's source. TestShortestPathTreeClosesEachEdgeAsAPerEdgeSearchDid checks over generated graphs that each edge closes to the cycle reachPath produced for it alone, ties included. BenchmarkCanonicalMixedCyclePathsDenseTangle (80 issues, a blocks edge for every ordered pair, one tracks edge back): 26.3 ms and 27.8 MB per call before, 5.4 ms and 2.8 MB after. * fix(dep): scope the --include-tracks guarantee and bound its output Review iteration 1 (maintainer fixup) for the one gating major. The IncludeTracks doc claimed that requiring "at least one blocks/ conditional-blocks edge" on every reported cycle is what keeps out the `bd doctor` regression that "produced thousands of cycles". That rule is NECESSARY, NOT SUFFICIENT. One tracks-only loop fuses everything it touches into a single strongly connected component, after which every scheduling edge inside that component lies on a cycle and is reported -- even where those scheduling edges alone are strictly acyclic and the default walk reports nothing. A 10-step molecule whose entry step tracks back to its root yields 9 reports against the default walk's 0. The doc's own BOUND paragraph conceded the volume ("never more than twice the distinct scheduling edges") while the paragraph above it claimed the guard prevented it. The algorithm is correct and is unchanged; what was wrong is the contract written over it, plus the absence of any cap on a diagnostic that can now be edge-count sized. A census found the claim in 5 sites, not the 2 the review cited: issueops/cycledetector.go IncludeTracks field doc internal/storage/issueops/cycle_report.go the BOUND paragraph internal/storage/issueops/cycles.go AppendMixedCycleGraphInTx cmd/bd/dep.go flag registration comment internal/storage/issueops/cycle_report_test.go section header backend/conformance/cycle_detector_contract.go:246 already scoped it correctly ("a loop made entirely of tracks edges stays silent") and is left alone. The PR body and the contributor's commit messages assert only the true narrow rule, so neither needed correcting. --limit caps the RENDERED list (default 50, 0 = no limit), matching the idiom in list/search/stale/find_duplicates. It is a rendering cap and not a narrower request because CycleReport.Cycles promises to omit no cycle: the printed total stays the whole report's, the truncation says how much it held back, and --json is never capped. TestCanonicalMixedCyclePathsBoundsAFusedMoleculeByItsSchedulingEdges pins the manufacture direction ...KeepsDeadlocksATracksEdgeFuses left open -- that one fuses two real deadlocks and checks neither is lost; this one fuses none at all and still gets 9 reports. Also taken, both non-gating: dropped the dormant `json:"include_tracks,omitempty"` tag, since no serializer of DetectCyclesRequest exists in the tree and handleDependencyCycles calls requireNoQuery, so the tag advertised a wire contract the server refuses; and added a comment naming the backend conformance cases as the only pin on the row->edge admission switch. Declined this iteration: factoring appendDependencyGraphInTx and AppendMixedCycleGraphInTx onto one shared row loop (nit, gate impact none). It restructures the SQL read path that, per the finding directly above it, is pinned only at the conformance layer, and appendDependencyGraphInTx also backs AppendSchedulingGraphInTx -- the write-time gate behind every `bd dep add`. That is a wider blast radius than a zero-gate-impact nit earns inside a fixup whose subject is a doc overclaim; it belongs in its own change. Validation: go build ./... clean; go vet clean on the 4 touched packages; golangci-lint v2.10.1 reports 0 issues on issueops/..., internal/storage/issueops/... and cmd/bd/...; internal/storage/issueops full package 749 PASS / 0 FAIL / 0 SKIP (748 before, +1 new); cmd/bd dep-cycles selector 9 PASS / 0 FAIL / 0 SKIP; internal/httpapi Cycle|SpecParity 6 PASS / 0 FAIL. Mutation: making tracks edges unable to fuse a component reds the new pin plus 5 incumbents (the feature dies); reporting only one cycle per component reds the new pin ALONE (1 of 14), so it covers a degradation no existing test catches. Review iteration 2: the remedy above re-entered its own finding class. Both iteration-2 items indict text THIS fixup wrote, not the contributor's. The --limit cap is UNCONDITIONAL -- `if limit > 0 && len(shown) > limit` never consults includeTracks -- yet every rationale iteration 1 wrote for it was scoped to the widened walk, and the IncludeTracks field doc still closed with "the base walk this type's doc above describes is unchanged". True of the walk; false of its rendering, since plain `bd dep cycles` printed every cycle at base and now prints at most 50. That is the same defect class as the major this commit exists to fix: a doc claiming a scope the mechanism does not honor. Of the two arms the review offered, only documenting the true scope is available. Gating the cap on includeTracks reds this PR's own incumbent test: printCycleReportForTest calls runDepCycles(false, limit), so TestDepCyclesTruncatesTheRenderedListButNotTheCount/capped asserts the DEFAULT walk truncates. Measured, not assumed -- that arm fails capped and registered_default while no_limit passes. The implementation, the flag's help string and the tests already agreed the cap is unconditional; only the prose disagreed, so the prose moved: cmd/bd/dep_cycles.go runDepCycles doc: the cap is unconditional, bounds both walks, and names the behavior change vs base cmd/bd/dep.go flag comment: caps both walks; the widened walk is what makes the cap necessary, not what scopes it issueops/cycledetector.go the "Default false" closer: the walk is unchanged, its RENDERING is not Also the nit: the opening paragraph argued no flag can narrow either question while --limit had no carve-out, where IncludeTracks had one. It now says no flag narrows the ANSWER, and that --limit caps only what is PRINTED. New renderer arm "registered default" closes the gap the minor named: every existing arm drove an explicit limit, so the shipped 50 was pinned only by TestDepCyclesLimitFlagRegistration's DefValue != "0". It reads the default off the command and renders past it, so it tracks whatever ships; ids are fixed-width so "past the cap" cannot match as a prefix of one inside it. Mutation (3 arms, control restored byte-identical by cp -- the fixset was uncommitted): gate the cap on includeTracks => capped + registered_default RED; default 50 -> 0 => LimitFlagRegistration + registered_default RED (the new arm independently catches an unbounded default); shown[:limit+1] => capped + registered_default RED, so the arm pins the boundary and not merely "some truncation". no_limit stays green under all three by design. Validation: gofmt clean, git diff --check clean, go build ./... rc=0, go vet clean on cmd/bd and issueops, cmd/bd dep-cycles selector 9 PASS / 0 FAIL / 0 SKIP (same top-level roster, +1 subtest). No production behavior changed this iteration -- doc text plus one test arm. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: sjarmak <t@t.co> Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
197 lines
11 KiB
Go
197 lines
11 KiB
Go
package issueops
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/steveyegge/beads/internal/types"
|
|
)
|
|
|
|
// DetectCyclesRequest asks for the whole blocking graph's cycles.
|
|
//
|
|
// The zero value carries no NARROWING predicate, and that absence is the
|
|
// honest shape rather than a placeholder: a cycle is a property of the graph
|
|
// as a whole, so there is no predicate that narrows it — narrowing the EDGE
|
|
// set would delete cycles that exist and narrowing the reported set would need
|
|
// an anchor this question does not have. `bd dep cycles` takes no flag that
|
|
// narrows either ANSWER for the same reason: its `--limit` caps how much of the
|
|
// report is PRINTED and never what the report holds, which is why it does not
|
|
// contradict this paragraph either.
|
|
//
|
|
// IncludeTracks is the one WIDENING option, not a narrowing one, which is why
|
|
// it does not contradict the paragraph above. It exists as a field rather than
|
|
// a new method precisely for the reason this type does: a later option is a
|
|
// field, not a changed signature.
|
|
type DetectCyclesRequest struct {
|
|
// IncludeTracks additionally walks `tracks` edges on top of the default
|
|
// blocks/conditional-blocks graph, so a cycle that closes through a
|
|
// tracking edge is reported — the shape where a molecule root
|
|
// blocks-depends (transitively) on its own entry step, which
|
|
// tracks-depends back to the root.
|
|
//
|
|
// It does not report a cycle made ENTIRELY of tracks edges. Ordinary
|
|
// convoy/tracking topology is densely interconnected through tracks
|
|
// alone, and reporting every loop in it is the regression a previous
|
|
// change to `bd doctor`'s cycle check caused and had to revert (it
|
|
// produced "thousands of cycles" that were not deadlocks). A cycle is
|
|
// therefore reported under this option only when at least one of its
|
|
// edges — the closing edge included — is a blocks/conditional-blocks
|
|
// edge; tracks edges may only complete a path, never make one up alone.
|
|
//
|
|
// THAT GUARD IS NECESSARY, NOT SUFFICIENT, and it excludes a PURE tracks
|
|
// loop and nothing more. It is not a bound on volume: one tracks-only
|
|
// loop fuses everything it touches into a single strongly connected
|
|
// component, and every blocks/conditional-blocks edge inside a component
|
|
// lies on a cycle and is reported — even where those scheduling edges
|
|
// alone form a strictly acyclic chain and the default walk reports
|
|
// nothing. A molecule whose entry step tracks back to its root therefore
|
|
// yields about one report per scheduling edge beneath it. What the option
|
|
// promises is the bound below, which counts EDGES and not deadlocks; that
|
|
// is why it is opt-in, and why `bd dep cycles` truncates its rendering.
|
|
//
|
|
// IT ONLY ADDS TO THE ANSWER. Every cycle the default request reports on
|
|
// the same data is also in this report, so turning the option on never
|
|
// hides a blocks-only deadlock, even where tracks edges join separate
|
|
// deadlocks into one tangle. On top of those, each blocks/conditional-blocks
|
|
// edge that lies on any cycle of the widened graph adds at most one more:
|
|
// that edge, closed by its shortest return path over either edge type. The
|
|
// report therefore holds at most twice as many cycles as there are
|
|
// blocks/conditional-blocks edges.
|
|
//
|
|
// Default false: the base walk this type's doc above describes is
|
|
// unchanged. Its RENDERING is not — `bd dep cycles` caps the printed list
|
|
// at `--limit` without consulting this field, so the default invocation
|
|
// prints at most 50 cycles of a report that still holds every one of them.
|
|
IncludeTracks bool
|
|
}
|
|
|
|
// CycleMember is one node on a detected cycle.
|
|
//
|
|
// ID IS ALWAYS SET; Issue may be nil. The two are separate fields because they
|
|
// come from different places and can disagree in exactly one direction: the id
|
|
// is read off the dependency edge, which is what proves the node is on the
|
|
// cycle, and the issue is a SECOND lookup that can find nothing — a target in
|
|
// another repository's namespace, an "external:" reference, or a row whose edges
|
|
// outlived it.
|
|
//
|
|
// A nil Issue therefore means "this node is on the cycle and this database
|
|
// cannot describe it", never "this node is not really on the cycle". A caller
|
|
// rendering a path prints ID for every member and reaches for Issue only to
|
|
// decorate it.
|
|
type CycleMember struct {
|
|
// ID is the node's id as the dependency edge spells it.
|
|
ID string `json:"id"`
|
|
// Issue is the hydrated row, or nil when this database holds none. It is
|
|
// ABSENT from the JSON encoding rather than null in that case, which is the
|
|
// same "absent means not set" rule every other surface in this tree reads.
|
|
//
|
|
// Callers MUST NOT mutate it: implementations do not promise a fresh copy
|
|
// per member, and a node appearing on two cycles may be the same pointer in
|
|
// both.
|
|
Issue *types.Issue `json:"issue,omitempty"`
|
|
}
|
|
|
|
// Cycle is one detected cycle: its members in EDGE ORDER, so member[i] blocks
|
|
// on member[i+1] and the last member blocks on the first. The closing edge is
|
|
// implied and is not repeated as a final member.
|
|
//
|
|
// IT IS CANONICAL. Members are rotated so the LOWEST id comes first, and the
|
|
// report's cycles are sorted, so two runs against an unchanged database produce
|
|
// the same bytes. That was not true before: the detector walked a Go map, so
|
|
// both the order of the cycles and the starting point of each one moved between
|
|
// runs — including under `--json`, where a caller diffing two snapshots saw
|
|
// changes that were not changes. Rotation is safe because the members of a
|
|
// cycle are DISTINCT, so the lowest id is unique and names one rotation.
|
|
type Cycle struct {
|
|
// Members are the nodes, in edge order, starting at the lowest id. Never
|
|
// empty.
|
|
Members []CycleMember `json:"members"`
|
|
// Partial is true when at least one member has a nil Issue. It is emitted
|
|
// even when false: a consumer must be able to read "this path is complete"
|
|
// from the answer rather than from the absence of a key.
|
|
//
|
|
// It is a field rather than something a caller derives because it is the
|
|
// thing a caller must not silently miss. The previous behavior DROPPED
|
|
// unhydratable members from the path, so a three-node cycle rendered as a
|
|
// two-node one and looked complete; a wholly unhydratable cycle disappeared
|
|
// from the report and from its count. Members is complete now, and this
|
|
// flag says the descriptions beside it are not.
|
|
Partial bool `json:"partial"`
|
|
}
|
|
|
|
// CycleReport is every cycle the detector found.
|
|
type CycleReport struct {
|
|
// Cycles is the canonical, sorted set. It is empty — never nil — when the
|
|
// graph is acyclic.
|
|
//
|
|
// ITS LENGTH IS THE TOTAL FOUND BY THE SELECTED WALK, and that is the point
|
|
// of carrying unhydratable members rather than dropping them: a cycle
|
|
// nothing can describe is still counted here, so "found N cycles" cannot
|
|
// shrink because a row went missing. There is no separate count field,
|
|
// because there is no cycle this slice omits.
|
|
//
|
|
// IT IS NOT PROMISED TO BE EVERY SIMPLE CYCLE IN THE GRAPH. Enumerating
|
|
// those is exponential in the worst case. The default detector records one
|
|
// cycle per back edge of a depth-first walk, so a cycle whose edges the walk
|
|
// already crossed on another cycle can go unreported: given a -> b -> c -> a
|
|
// plus the chord a -> c, it reports a-b-c and not a-c. IncludeTracks reports
|
|
// a superset of the default report on the same data: all of those cycles,
|
|
// plus, for each blocks/conditional-blocks edge on a cycle of the widened
|
|
// graph, the cycle that edge closes by its shortest return path (a-c
|
|
// included, in the example). What IS promised is that the slice is empty
|
|
// exactly when the selected walk has no qualifying cycle, and that the same
|
|
// graph and request always yield the same slice.
|
|
Cycles []Cycle `json:"cycles"`
|
|
}
|
|
|
|
// CycleDetector describes finding circular dependencies: the operation
|
|
// `bd dep cycles` performs, and the sweep both `bd dep add` routes run to warn
|
|
// after an edge lands. Like Lifecycle, Reader, ReadyClaimer, BatchCloser,
|
|
// DependencyEditor, Commenter, Counter and Relations it is a role with its own
|
|
// accessor. A new capability gets a new role interface and its own accessor;
|
|
// never append a method here.
|
|
//
|
|
// IT IS ITS OWN ROLE RATHER THAN A THIRD Relations METHOD because it answers a
|
|
// question with no ANCHOR. Relations answers about the edges around one issue —
|
|
// every request it takes names a source — and DependencyEditor refuses a cycle
|
|
// it is about to create. This one is asked of the whole graph and hands back
|
|
// paths rather than neighbors, so a Relations request type would have carried an
|
|
// anchor field a cycle sweep must ignore.
|
|
//
|
|
// WHAT COUNTS AS AN EDGE HERE is narrower than what counts when an edge is
|
|
// ADDED, and the two must not be confused. This walk follows `blocks` and
|
|
// `conditional-blocks` only. `waits-for` is excluded — gate semantics, so a
|
|
// mutual wait is not a deadlock — and so is `parent-child`, which the
|
|
// add-time gate DOES walk (a chain mixing blocking and hierarchy is a
|
|
// scheduling livelock the editor refuses). A graph this role calls acyclic can
|
|
// therefore still refuse an edge, and that is not a contradiction: the editor
|
|
// answers "would this be a livelock", this answers "is there a blocking cycle
|
|
// now". DetectCyclesRequest.IncludeTracks widens this walk to also follow
|
|
// `tracks`, under the guard documented on that field.
|
|
//
|
|
// BOTH PLANES ARE ONE GRAPH. Durable and ephemeral edges are merged before the
|
|
// walk, so a cycle that runs issue → wisp → issue is found; it is the reason
|
|
// this cannot be answered by reading one table.
|
|
//
|
|
// HOW CYCLES GET THERE AT ALL, since the editor refuses them: not through it.
|
|
// They arrive by import, by bulk writes that skipped the per-edge probe, by
|
|
// concurrent adds that each saw an acyclic graph, and from rows written before
|
|
// the gate existed. That is why this role is a REPORT and not an assertion —
|
|
// finding one is not a bug in the writer that is running.
|
|
//
|
|
// Detecting is a READ. Nothing here records a history entry, fires a completion
|
|
// hook or changes a row. Result values are unspecified when error is non-nil.
|
|
type CycleDetector interface {
|
|
// DetectCycles reports every cycle in the blocking graph.
|
|
//
|
|
// An acyclic graph is an empty report and a nil error. There is no
|
|
// ErrNotFound and no refusal to classify: a question about a graph has an
|
|
// answer even when the answer is "none", and a caller warning after a write
|
|
// would otherwise have to tell an empty answer from a failure.
|
|
//
|
|
// A MEMBER THAT CANNOT BE HYDRATED DOES NOT FAIL THE CALL and does not
|
|
// shrink the path. Its CycleMember carries the id with a nil Issue and its
|
|
// Cycle is marked Partial. A report that failed outright on one unreadable
|
|
// row would tell a caller nothing about the other nine cycles, and a report
|
|
// that quietly dropped the row would tell it something false.
|
|
DetectCycles(ctx context.Context, req DetectCyclesRequest) (CycleReport, error)
|
|
}
|