feat(dep): detect cycles through tracks edges (#6148)
* 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>
This commit is contained in:
parent
da89d21813
commit
12b19a6df7
18 changed files with 1263 additions and 68 deletions
|
|
@ -75,11 +75,11 @@ type SQLStatement struct {
|
|||
Args []any
|
||||
}
|
||||
|
||||
// RunCycleDetectorReportsNoCycleForAnAcyclicSubgraph pins cycledetector.go:135
|
||||
// RunCycleDetectorReportsNoCycleForAnAcyclicSubgraph pins cycledetector.go:171
|
||||
// from the empty side: an acyclic graph is an empty report and a nil error,
|
||||
// with no ErrNotFound to classify. The nil-slice half IS asserted globally —
|
||||
// that one is a property of the answer, not of the workspace
|
||||
// (cycledetector.go:78).
|
||||
// (cycledetector.go:108).
|
||||
func RunCycleDetectorReportsNoCycleForAnAcyclicSubgraph(t *testing.T, ctx context.Context, fixture CycleDetectorFixture) {
|
||||
t.Helper()
|
||||
first := fixture.IssuePrefix + "-acyclic-a"
|
||||
|
|
@ -98,10 +98,10 @@ func RunCycleDetectorReportsNoCycleForAnAcyclicSubgraph(t *testing.T, ctx contex
|
|||
}
|
||||
|
||||
// RunCycleDetectorFindsADurableCycleRotatedToItsLowestID pins the shape of a
|
||||
// found cycle: members in EDGE ORDER (cycledetector.go:48-50), rotated so the
|
||||
// lowest id comes first (cycledetector.go:52-58), the closing edge implied
|
||||
// found cycle: members in EDGE ORDER (cycledetector.go:78-80), rotated so the
|
||||
// lowest id comes first (cycledetector.go:82-88), the closing edge implied
|
||||
// rather than repeated, and Partial false when every member was described
|
||||
// (cycledetector.go:63).
|
||||
// (cycledetector.go:93).
|
||||
//
|
||||
// The three ids are seeded so that the edge order and the sorted order are NOT
|
||||
// the same sequence, which is what makes the rotation assertion say something.
|
||||
|
|
@ -138,8 +138,8 @@ func RunCycleDetectorFindsADurableCycleRotatedToItsLowestID(t *testing.T, ctx co
|
|||
}
|
||||
}
|
||||
|
||||
// RunCycleDetectorReportsTheSameCyclesEveryRun pins cycledetector.go:52-58 and
|
||||
// :91-92: two calls against an unchanged database must agree, id for id and
|
||||
// RunCycleDetectorReportsTheSameCyclesEveryRun pins cycledetector.go:82-88 and
|
||||
// :126-127: two calls against an unchanged database must agree, id for id and
|
||||
// cycle for cycle.
|
||||
//
|
||||
// It compares the WHOLE report rather than the case's own cycle: the walk used
|
||||
|
|
@ -175,7 +175,7 @@ func RunCycleDetectorReportsTheSameCyclesEveryRun(t *testing.T, ctx context.Cont
|
|||
}
|
||||
|
||||
// RunCycleDetectorMergesTheDurableAndEphemeralPlanes pins
|
||||
// cycledetector.go:120-122: the two dependency planes are one graph, so a cycle
|
||||
// cycledetector.go:156-158: the two dependency planes are one graph, so a cycle
|
||||
// that runs issue → wisp → issue is found. This is the clause a single-table
|
||||
// read passes every other case and fails here.
|
||||
func RunCycleDetectorMergesTheDurableAndEphemeralPlanes(t *testing.T, ctx context.Context, fixture CycleDetectorFixture) {
|
||||
|
|
@ -198,10 +198,12 @@ func RunCycleDetectorMergesTheDurableAndEphemeralPlanes(t *testing.T, ctx contex
|
|||
}
|
||||
}
|
||||
|
||||
// RunCycleDetectorFollowsOnlyBlockingEdges pins cycledetector.go:110-119: the
|
||||
// RunCycleDetectorFollowsOnlyBlockingEdges pins cycledetector.go:145-154: the
|
||||
// walk follows `blocks` and `conditional-blocks`, and nothing else — not
|
||||
// `waits-for`, whose gate semantics make a mutual wait legitimate, and not
|
||||
// `parent-child`, which the ADD-time gate does walk.
|
||||
// `waits-for`, whose gate semantics make a mutual wait legitimate, not
|
||||
// `parent-child`, which the ADD-time gate does walk, and not `tracks`, on the
|
||||
// DEFAULT (zero-value) request. IncludeTracks's own widened walk is pinned
|
||||
// separately by RunCycleDetectorIncludeTracks*, below.
|
||||
//
|
||||
// The conditional-blocks half is asserted in the same case as the exclusions on
|
||||
// purpose: a body narrowed to `blocks` alone would pass an exclusion-only case,
|
||||
|
|
@ -217,6 +219,7 @@ func RunCycleDetectorFollowsOnlyBlockingEdges(t *testing.T, ctx context.Context,
|
|||
{types.DepWaitsFor, "wait", false},
|
||||
{types.DepParentChild, "kid", false},
|
||||
{types.DepRelated, "rel", false},
|
||||
{types.DepTracks, "trk", false},
|
||||
} {
|
||||
first := fmt.Sprintf("%s-edge-%s-a", fixture.IssuePrefix, test.slug)
|
||||
second := fmt.Sprintf("%s-edge-%s-b", fixture.IssuePrefix, test.slug)
|
||||
|
|
@ -236,8 +239,87 @@ func RunCycleDetectorFollowsOnlyBlockingEdges(t *testing.T, ctx context.Context,
|
|||
}
|
||||
}
|
||||
|
||||
// RunCycleDetectorReportsAnHonestPartial pins cycledetector.go:140-144 and
|
||||
// :24-33 against real storage: a member the database cannot describe keeps its
|
||||
// RunCycleDetectorIncludeTracksIgnoresAPureTracksLoop pins
|
||||
// DetectCyclesRequest.IncludeTracks's own guard: widening the walk to `tracks`
|
||||
// must not resurrect the PR #4933 false-positive shape, where ordinary
|
||||
// convoy/tracking topology with no scheduling edge at all got reported as a
|
||||
// cycle. A loop made entirely of `tracks` edges stays silent even with
|
||||
// IncludeTracks set.
|
||||
func RunCycleDetectorIncludeTracksIgnoresAPureTracksLoop(t *testing.T, ctx context.Context, fixture CycleDetectorFixture) {
|
||||
t.Helper()
|
||||
first := fixture.IssuePrefix + "-trkloop-a"
|
||||
second := fixture.IssuePrefix + "-trkloop-b"
|
||||
seedCycleDetectorIssue(t, ctx, fixture, first)
|
||||
seedCycleDetectorIssue(t, ctx, fixture, second)
|
||||
seedCycleDetectorEdges(t, ctx, fixture, false,
|
||||
cycleDetectorEdge{Source: first, Target: second, Type: types.DepTracks},
|
||||
cycleDetectorEdge{Source: second, Target: first, Type: types.DepTracks})
|
||||
|
||||
report := cycleDetectorReportIncludingTracks(t, ctx, fixture)
|
||||
if found := cycleDetectorTouching(report, first, second); len(found) > 0 {
|
||||
t.Errorf("a mutual tracks-only pair produced %v under IncludeTracks, want none: a cycle needs at least one scheduling edge", found)
|
||||
}
|
||||
}
|
||||
|
||||
// RunCycleDetectorIncludeTracksFindsTheMoleculeRootShape pins the gc-818bx
|
||||
// deadlock this option exists to surface: a molecule root that
|
||||
// blocks-depends on its own entry step, which tracks-depends back to the
|
||||
// root. Neither edge alone is a cycle; the shape only closes across both edge
|
||||
// types, which is exactly what the default (blocks-only) walk cannot see.
|
||||
func RunCycleDetectorIncludeTracksFindsTheMoleculeRootShape(t *testing.T, ctx context.Context, fixture CycleDetectorFixture) {
|
||||
t.Helper()
|
||||
root := fixture.IssuePrefix + "-molroot"
|
||||
step := fixture.IssuePrefix + "-molstep"
|
||||
seedCycleDetectorIssue(t, ctx, fixture, root)
|
||||
seedCycleDetectorIssue(t, ctx, fixture, step)
|
||||
seedCycleDetectorEdges(t, ctx, fixture, false,
|
||||
cycleDetectorEdge{Source: root, Target: step, Type: types.DepBlocks},
|
||||
cycleDetectorEdge{Source: step, Target: root, Type: types.DepTracks})
|
||||
|
||||
// The default request must still see nothing: the closing edge is a
|
||||
// tracks edge, outside the base walk.
|
||||
if found := cycleDetectorTouching(cycleDetectorReport(t, ctx, fixture), root, step); len(found) > 0 {
|
||||
t.Errorf("the default request reported %v; IncludeTracks defaults to false and must leave the base walk unchanged", found)
|
||||
}
|
||||
|
||||
cycle := cycleDetectorFind(t, cycleDetectorReportIncludingTracks(t, ctx, fixture), root, step)
|
||||
assertCycleDetectorPath(t, cycle, root, step)
|
||||
}
|
||||
|
||||
// RunCycleDetectorIncludeTracksWalksEachEdgeInItsStoredDirection pins the
|
||||
// direction of the widened graph, which the two-node cases above cannot: a
|
||||
// two-node cycle reads the same reversed once it is rotated to its lowest id.
|
||||
// This loop has three nodes in edge order a, c, b. Reversed it is a, b, c, the
|
||||
// same member set in the other order, so a graph builder that stored
|
||||
// depends_on_id -> issue_id would still find exactly one cycle here and fail
|
||||
// only on the path.
|
||||
//
|
||||
// The blocks edge sits in the middle of the loop and the closing edges are
|
||||
// tracks, so the default request must see nothing.
|
||||
func RunCycleDetectorIncludeTracksWalksEachEdgeInItsStoredDirection(t *testing.T, ctx context.Context, fixture CycleDetectorFixture) {
|
||||
t.Helper()
|
||||
a := fixture.IssuePrefix + "-trkdir-a"
|
||||
b := fixture.IssuePrefix + "-trkdir-b"
|
||||
c := fixture.IssuePrefix + "-trkdir-c"
|
||||
for _, id := range []string{a, b, c} {
|
||||
seedCycleDetectorIssue(t, ctx, fixture, id)
|
||||
}
|
||||
// a -> c -> b -> a.
|
||||
seedCycleDetectorEdges(t, ctx, fixture, false,
|
||||
cycleDetectorEdge{Source: a, Target: c, Type: types.DepTracks},
|
||||
cycleDetectorEdge{Source: c, Target: b, Type: types.DepBlocks},
|
||||
cycleDetectorEdge{Source: b, Target: a, Type: types.DepTracks})
|
||||
|
||||
if found := cycleDetectorTouching(cycleDetectorReport(t, ctx, fixture), a, b, c); len(found) > 0 {
|
||||
t.Errorf("the default request reported %v; two of the three edges are tracks, outside the base walk", found)
|
||||
}
|
||||
|
||||
cycle := cycleDetectorFind(t, cycleDetectorReportIncludingTracks(t, ctx, fixture), a, b, c)
|
||||
assertCycleDetectorPath(t, cycle, a, c, b)
|
||||
}
|
||||
|
||||
// RunCycleDetectorReportsAnHonestPartial pins cycledetector.go:176-180 and
|
||||
// :54-63 against real storage: a member the database cannot describe keeps its
|
||||
// place on the path, carries no issue, and marks the cycle. The previous body
|
||||
// dropped the member, so this three-node cycle came back as a TWO-node cycle and
|
||||
// looked complete.
|
||||
|
|
@ -272,7 +354,7 @@ func RunCycleDetectorReportsAnHonestPartial(t *testing.T, ctx context.Context, f
|
|||
}
|
||||
}
|
||||
|
||||
// RunCycleDetectorCountsAWhollyUndescribableCycle pins cycledetector.go:81-85:
|
||||
// RunCycleDetectorCountsAWhollyUndescribableCycle pins cycledetector.go:111-115:
|
||||
// a cycle no member of which can be described is still IN the report, so the
|
||||
// count cannot shrink because rows went missing. Under the previous body this
|
||||
// cycle produced nothing at all, so `bd dep cycles` printed a smaller number and
|
||||
|
|
@ -297,7 +379,7 @@ func RunCycleDetectorCountsAWhollyUndescribableCycle(t *testing.T, ctx context.C
|
|||
}
|
||||
}
|
||||
|
||||
// RunCycleDetectorWritesNothing pins cycledetector.go:130-131: detecting is a
|
||||
// RunCycleDetectorWritesNothing pins cycledetector.go:166-167: detecting is a
|
||||
// read. It is asserted on the history log rather than on a row read-back
|
||||
// because every versioned unit of work in this tree ends in a Dolt commit, so a
|
||||
// sweep that took a write transaction would show up here even when it changed
|
||||
|
|
@ -433,6 +515,17 @@ func cycleDetectorReport(t *testing.T, ctx context.Context, fixture CycleDetecto
|
|||
return report
|
||||
}
|
||||
|
||||
// cycleDetectorReportIncludingTracks is cycleDetectorReport with
|
||||
// IncludeTracks set, for the cases pinning that option's own widened walk.
|
||||
func cycleDetectorReportIncludingTracks(t *testing.T, ctx context.Context, fixture CycleDetectorFixture) publicops.CycleReport {
|
||||
t.Helper()
|
||||
report, err := fixture.Detector.DetectCycles(ctx, publicops.DetectCyclesRequest{IncludeTracks: true})
|
||||
if err != nil {
|
||||
t.Fatalf("DetectCycles: %v", err)
|
||||
}
|
||||
return report
|
||||
}
|
||||
|
||||
// cycleDetectorPaths renders a report as id paths, which is what the
|
||||
// determinism case compares.
|
||||
func cycleDetectorPaths(report publicops.CycleReport) [][]string {
|
||||
|
|
|
|||
|
|
@ -205,6 +205,9 @@ var roleContractCases = []roleContract{
|
|||
RunCycleDetectorReportsTheSameCyclesEveryRun,
|
||||
RunCycleDetectorMergesTheDurableAndEphemeralPlanes,
|
||||
RunCycleDetectorFollowsOnlyBlockingEdges,
|
||||
RunCycleDetectorIncludeTracksIgnoresAPureTracksLoop,
|
||||
RunCycleDetectorIncludeTracksFindsTheMoleculeRootShape,
|
||||
RunCycleDetectorIncludeTracksWalksEachEdgeInItsStoredDirection,
|
||||
RunCycleDetectorReportsAnHonestPartial,
|
||||
RunCycleDetectorCountsAWhollyUndescribableCycle,
|
||||
RunCycleDetectorWritesNothing,
|
||||
|
|
|
|||
|
|
@ -1365,7 +1365,9 @@ var depCyclesCmd = &cobra.Command{
|
|||
|
||||
// Both routes, one body: the only difference between them is which
|
||||
// accessor answers, and that is inside openCycleDetector.
|
||||
return runDepCycles()
|
||||
includeTracks, _ := cmd.Flags().GetBool("include-tracks")
|
||||
limit, _ := cmd.Flags().GetInt("limit")
|
||||
return runDepCycles(includeTracks, limit)
|
||||
},
|
||||
}
|
||||
|
||||
|
|
@ -1668,6 +1670,23 @@ func init() {
|
|||
depListCmd.Flags().String("direction", "down", "Direction: 'down' (dependencies), 'up' (dependents)")
|
||||
depListCmd.Flags().StringP("type", "t", "", "Filter by dependency type (e.g., tracks, blocks, parent-child)")
|
||||
|
||||
// Widens the report, never narrows it: every cycle the default walk finds is
|
||||
// kept, and cycles that close through tracks edges are added. A loop made
|
||||
// only of tracks edges is still not reported, but that is the only thing
|
||||
// the guard excludes: a tracks loop fuses a component and every scheduling
|
||||
// edge inside it is then reported, so a tracks-dense workspace can print
|
||||
// many cycles here even where the default walk prints none — hence
|
||||
// --limit. See issueops.DetectCyclesRequest.IncludeTracks.
|
||||
depCyclesCmd.Flags().Bool("include-tracks", false, "Also walk 'tracks' edges: reports every cycle the default walk finds plus cycles that close through a tracks edge, never a loop made only of tracks edges (diagnostic for molecule-root deadlocks hidden by tracks-only propagation)")
|
||||
// Caps the RENDERED list only, and on BOTH walks: this does not consult
|
||||
// --include-tracks, so it bounds the default invocation's rendering too.
|
||||
// The widened walk is what makes the cap necessary rather than what scopes
|
||||
// it — bounded by the scheduling-edge count, not by the number of
|
||||
// deadlocks, so a tracks-dense workspace can report more cycles than a
|
||||
// reader can use. The printed total stays the whole report's and --json is
|
||||
// never truncated.
|
||||
depCyclesCmd.Flags().Int("limit", 50, "Maximum cycles to print (0 = no limit); the reported total is always the whole count, and --json is never truncated")
|
||||
|
||||
// Issue ID completions for dep subcommands
|
||||
depAddCmd.ValidArgsFunction = issueIDCompletion
|
||||
depRemoveCmd.ValidArgsFunction = issueIDCompletion
|
||||
|
|
|
|||
|
|
@ -36,13 +36,34 @@ func proxiedCycleDetector() (issueops.CycleDetector, error) {
|
|||
return src.CycleDetector()
|
||||
}
|
||||
|
||||
// runDepCycles is the whole of `bd dep cycles` on both routes.
|
||||
func runDepCycles() error {
|
||||
// runDepCycles is the whole of `bd dep cycles` on both routes. includeTracks
|
||||
// widens the walk per issueops.DetectCyclesRequest.IncludeTracks; the default
|
||||
// invocation leaves it false and the walk unchanged.
|
||||
//
|
||||
// limit caps how many cycles are PRINTED, and nothing else: 0 prints them all.
|
||||
// THE CAP IS UNCONDITIONAL — it does not consult includeTracks, so it bounds
|
||||
// the default walk's rendering too, and plain `bd dep cycles` now prints at most
|
||||
// 50 cycles where before this change it printed every one. The widened walk is
|
||||
// what makes the cap necessary rather than what scopes it: that walk is bounded
|
||||
// by the scheduling-edge count and not by the number of deadlocks (see that
|
||||
// field's BOUND), so a tracks-dense workspace can hold a correct report longer
|
||||
// than anyone can read. Capping both walks by one rule is the deliberate
|
||||
// choice — an operator can predict one rendering rule, and a --limit that
|
||||
// silently did nothing without a second flag would be the worse surprise. It
|
||||
// also matches --limit in list/search/stale/find_duplicates, which cap
|
||||
// unconditionally.
|
||||
//
|
||||
// It stays a rendering cap rather than a narrower request on EITHER walk:
|
||||
// CycleReport.Cycles promises to omit no cycle, and a --json consumer diffing
|
||||
// two snapshots needs the whole of it. So the count this prints is always the
|
||||
// whole report's, the truncation says how much it held back, and the --json
|
||||
// branch below is never capped.
|
||||
func runDepCycles(includeTracks bool, limit int) error {
|
||||
detector, err := openCycleDetector()
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
report, err := detector.DetectCycles(rootCtx, issueops.DetectCyclesRequest{})
|
||||
report, err := detector.DetectCycles(rootCtx, issueops.DetectCyclesRequest{IncludeTracks: includeTracks})
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
|
|
@ -59,7 +80,11 @@ func runDepCycles() error {
|
|||
}
|
||||
|
||||
fmt.Printf("\n%s Found %d dependency cycles:\n\n", ui.RenderFail("⚠"), len(report.Cycles))
|
||||
for i, cycle := range report.Cycles {
|
||||
shown := report.Cycles
|
||||
if limit > 0 && len(shown) > limit {
|
||||
shown = shown[:limit]
|
||||
}
|
||||
for i, cycle := range shown {
|
||||
if missing := unknownCycleMembers(cycle); missing > 0 {
|
||||
fmt.Printf("%d. Cycle involving (%d of %d members have no record in this database):\n",
|
||||
i+1, missing, len(cycle.Members))
|
||||
|
|
@ -71,6 +96,10 @@ func runDepCycles() error {
|
|||
}
|
||||
fmt.Println()
|
||||
}
|
||||
if len(shown) < len(report.Cycles) {
|
||||
fmt.Printf("... and %d more not shown. The count above is the whole report; use --limit 0 to print all of it.\n\n",
|
||||
len(report.Cycles)-len(shown))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package main
|
|||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"runtime"
|
||||
|
|
@ -33,7 +34,7 @@ func TestDepCyclesNamesTheMembersItCannotDescribe(t *testing.T) {
|
|||
{ID: "bd-c", Issue: &types.Issue{ID: "bd-c", Title: "Gamma"}},
|
||||
{ID: "bd-ghost"},
|
||||
}},
|
||||
}})
|
||||
}}, 0)
|
||||
})
|
||||
|
||||
if !strings.Contains(out, "Found 2 dependency cycles") {
|
||||
|
|
@ -55,7 +56,7 @@ func TestDepCyclesNamesTheMembersItCannotDescribe(t *testing.T) {
|
|||
|
||||
func TestDepCyclesSaysNothingIsWrongForACleanWorkspace(t *testing.T) {
|
||||
out := captureCycleStdout(t, func() {
|
||||
printCycleReportForTest(t, issueops.CycleReport{Cycles: []issueops.Cycle{}})
|
||||
printCycleReportForTest(t, issueops.CycleReport{Cycles: []issueops.Cycle{}}, 0)
|
||||
})
|
||||
if !strings.Contains(out, "No dependency cycles detected") {
|
||||
t.Errorf("a clean workspace did not say so:\n%s", out)
|
||||
|
|
@ -124,8 +125,9 @@ func TestCycleWarningIsSilentWithoutCycles(t *testing.T) {
|
|||
}
|
||||
|
||||
// printCycleReportForTest drives `bd dep cycles`'s human rendering with a
|
||||
// report, through the same role the command uses.
|
||||
func printCycleReportForTest(t *testing.T, report issueops.CycleReport) {
|
||||
// report, through the same role the command uses. limit is the rendering cap
|
||||
// runDepCycles takes; 0 prints the whole report.
|
||||
func printCycleReportForTest(t *testing.T, report issueops.CycleReport, limit int) {
|
||||
t.Helper()
|
||||
previousStore := store
|
||||
previousJSON := jsonOutput
|
||||
|
|
@ -136,11 +138,183 @@ func printCycleReportForTest(t *testing.T, report issueops.CycleReport) {
|
|||
jsonOutput = previousJSON
|
||||
}()
|
||||
|
||||
if err := runDepCycles(); err != nil {
|
||||
if err := runDepCycles(false, limit); err != nil {
|
||||
t.Fatalf("runDepCycles: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDepCyclesFlagRegistration pins the --include-tracks flag itself: it
|
||||
// exists on the command, is a bool, and defaults to false so an invocation
|
||||
// with no flag leaves the base (blocks/conditional-blocks-only) walk
|
||||
// unchanged.
|
||||
func TestDepCyclesFlagRegistration(t *testing.T) {
|
||||
flag := depCyclesCmd.Flags().Lookup("include-tracks")
|
||||
if flag == nil {
|
||||
t.Fatal("depCyclesCmd has no --include-tracks flag")
|
||||
}
|
||||
if flag.Value.Type() != "bool" {
|
||||
t.Errorf("--include-tracks is a %s, want bool", flag.Value.Type())
|
||||
}
|
||||
if flag.DefValue != "false" {
|
||||
t.Errorf("--include-tracks defaults to %q, want \"false\"", flag.DefValue)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDepCyclesLimitFlagRegistration pins the rendering cap: an int flag whose
|
||||
// default is not 0, so any workspace dense enough to report more cycles than a
|
||||
// reader can use gets a readable diagnostic without the operator having to know
|
||||
// the flag exists. This pins only the REGISTRATION; the "registered default"
|
||||
// arm of TestDepCyclesTruncatesTheRenderedListButNotTheCount is what exercises
|
||||
// the value through the renderer.
|
||||
func TestDepCyclesLimitFlagRegistration(t *testing.T) {
|
||||
flag := depCyclesCmd.Flags().Lookup("limit")
|
||||
if flag == nil {
|
||||
t.Fatal("depCyclesCmd has no --limit flag")
|
||||
}
|
||||
if flag.Value.Type() != "int" {
|
||||
t.Errorf("--limit is a %s, want int", flag.Value.Type())
|
||||
}
|
||||
if flag.DefValue == "0" {
|
||||
t.Error("--limit defaults to 0 (no limit), so the default invocation is unbounded; it exists to bound the default rendering")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDepCyclesTruncatesTheRenderedListButNotTheCount pins the cap's contract.
|
||||
// --include-tracks is bounded by the scheduling-edge count and not by the number
|
||||
// of real deadlocks, so the printed LIST is capped — but the reported total stays
|
||||
// the whole report's and the truncation announces itself, because a diagnostic
|
||||
// that quietly dropped rows would understate the very problem it exists to show.
|
||||
func TestDepCyclesTruncatesTheRenderedListButNotTheCount(t *testing.T) {
|
||||
var report issueops.CycleReport
|
||||
for i := range 5 {
|
||||
id := fmt.Sprintf("bd-%d", i)
|
||||
report.Cycles = append(report.Cycles, issueops.Cycle{Members: []issueops.CycleMember{
|
||||
{ID: id, Issue: &types.Issue{ID: id, Title: "Cycle " + id}},
|
||||
}})
|
||||
}
|
||||
|
||||
t.Run("capped", func(t *testing.T) {
|
||||
out := captureCycleStdout(t, func() { printCycleReportForTest(t, report, 2) })
|
||||
if !strings.Contains(out, "Found 5 dependency cycles") {
|
||||
t.Errorf("the total is not the whole report's; a cap must not shrink the count:\n%s", out)
|
||||
}
|
||||
for _, shown := range []string{"bd-0", "bd-1"} {
|
||||
if !strings.Contains(out, shown) {
|
||||
t.Errorf("%s is inside the cap but was not printed:\n%s", shown, out)
|
||||
}
|
||||
}
|
||||
for _, held := range []string{"bd-2", "bd-3", "bd-4"} {
|
||||
if strings.Contains(out, held) {
|
||||
t.Errorf("%s is past the cap but was printed anyway:\n%s", held, out)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(out, "and 3 more not shown") {
|
||||
t.Errorf("the truncation is silent, so a reader cannot tell the list is partial:\n%s", out)
|
||||
}
|
||||
if !strings.Contains(out, "--limit 0") {
|
||||
t.Errorf("the truncation does not name the way to print the rest:\n%s", out)
|
||||
}
|
||||
})
|
||||
|
||||
// The uncapped arm is what proves the cap is doing the work above, rather
|
||||
// than the fixture or the renderer dropping cycles on its own.
|
||||
t.Run("no limit", func(t *testing.T) {
|
||||
out := captureCycleStdout(t, func() { printCycleReportForTest(t, report, 0) })
|
||||
for _, id := range []string{"bd-0", "bd-1", "bd-2", "bd-3", "bd-4"} {
|
||||
if !strings.Contains(out, id) {
|
||||
t.Errorf("--limit 0 held back %s:\n%s", id, out)
|
||||
}
|
||||
}
|
||||
if strings.Contains(out, "not shown") {
|
||||
t.Errorf("--limit 0 announced a truncation it did not make:\n%s", out)
|
||||
}
|
||||
})
|
||||
|
||||
// Both arms above drive an explicit limit, so the value that actually SHIPS
|
||||
// would otherwise be pinned only by TestDepCyclesLimitFlagRegistration's
|
||||
// "not 0" assertion — a registration property, not a behavior. This arm
|
||||
// reads the default off the command and renders past it, so it keeps
|
||||
// exercising whatever the command registers. Ids are fixed-width so that
|
||||
// "past the cap" cannot match as a prefix of an id inside it.
|
||||
t.Run("registered default", func(t *testing.T) {
|
||||
registered, err := depCyclesCmd.Flags().GetInt("limit")
|
||||
if err != nil {
|
||||
t.Fatalf("reading the registered --limit default: %v", err)
|
||||
}
|
||||
if registered <= 0 {
|
||||
t.Fatalf("the registered --limit default is %d, so this arm would cap nothing", registered)
|
||||
}
|
||||
|
||||
var big issueops.CycleReport
|
||||
for i := range registered + 3 {
|
||||
id := fmt.Sprintf("bd-big-%03d", i)
|
||||
big.Cycles = append(big.Cycles, issueops.Cycle{Members: []issueops.CycleMember{
|
||||
{ID: id, Issue: &types.Issue{ID: id, Title: "Cycle " + id}},
|
||||
}})
|
||||
}
|
||||
|
||||
out := captureCycleStdout(t, func() { printCycleReportForTest(t, big, registered) })
|
||||
if want := fmt.Sprintf("Found %d dependency cycles", registered+3); !strings.Contains(out, want) {
|
||||
t.Errorf("the registered default shrank the count; want %q:\n%s", want, out)
|
||||
}
|
||||
if last := fmt.Sprintf("bd-big-%03d", registered-1); !strings.Contains(out, last) {
|
||||
t.Errorf("%s is the last cycle inside the registered default but was not printed:\n%s", last, out)
|
||||
}
|
||||
if first := fmt.Sprintf("bd-big-%03d", registered); strings.Contains(out, first) {
|
||||
t.Errorf("%s is past the registered default but was printed anyway:\n%s", first, out)
|
||||
}
|
||||
if !strings.Contains(out, "and 3 more not shown") {
|
||||
t.Errorf("the registered default truncated silently:\n%s", out)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestRunDepCyclesThreadsIncludeTracks pins dep_cycles.go's one line of real
|
||||
// logic for this option: the includeTracks parameter lands on
|
||||
// DetectCyclesRequest.IncludeTracks unchanged, in both directions.
|
||||
func TestRunDepCyclesThreadsIncludeTracks(t *testing.T) {
|
||||
for _, includeTracks := range []bool{false, true} {
|
||||
recorder := &recordingCycleStore{}
|
||||
previousStore := store
|
||||
previousJSON := jsonOutput
|
||||
store = recorder
|
||||
jsonOutput = false
|
||||
func() {
|
||||
defer func() {
|
||||
store = previousStore
|
||||
jsonOutput = previousJSON
|
||||
}()
|
||||
if err := runDepCycles(includeTracks, 0); err != nil {
|
||||
t.Fatalf("runDepCycles(%v): %v", includeTracks, err)
|
||||
}
|
||||
}()
|
||||
|
||||
if recorder.gotRequest.IncludeTracks != includeTracks {
|
||||
t.Errorf("runDepCycles(%v) called DetectCycles with IncludeTracks=%v",
|
||||
includeTracks, recorder.gotRequest.IncludeTracks)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// recordingCycleStore is a store whose cycle detector remembers the last
|
||||
// request it was asked to detect, so the flag-threading test can look inside
|
||||
// runDepCycles rather than only at its rendered output.
|
||||
type recordingCycleStore struct {
|
||||
storage.DoltStorage
|
||||
gotRequest issueops.DetectCyclesRequest
|
||||
}
|
||||
|
||||
func (s *recordingCycleStore) CycleDetector() (issueops.CycleDetector, error) {
|
||||
return &recordingCycleDetector{store: s}, nil
|
||||
}
|
||||
|
||||
type recordingCycleDetector struct{ store *recordingCycleStore }
|
||||
|
||||
func (d *recordingCycleDetector) DetectCycles(_ context.Context, req issueops.DetectCyclesRequest) (issueops.CycleReport, error) {
|
||||
d.store.gotRequest = req
|
||||
return issueops.CycleReport{}, nil
|
||||
}
|
||||
|
||||
// fixedCycleStore is a store whose only real method is the cycle accessor. It
|
||||
// embeds the interface, so any other method the command reached for would panic
|
||||
// rather than quietly answering zero — which is the assertion that `bd dep
|
||||
|
|
|
|||
|
|
@ -84,7 +84,7 @@ func (emptyDeps) GetIssueDependencyRecords(context.Context, []string) (map[strin
|
|||
// DetectCycleReport answers for a workspace with no cycles. Without it the
|
||||
// promoted method on the embedded nil interface panics, and the provider-backed
|
||||
// cycle route would 500 through the panic recovery rather than answering.
|
||||
func (emptyDeps) DetectCycleReport(context.Context) (issueops.CycleReport, error) {
|
||||
func (emptyDeps) DetectCycleReport(context.Context, issueops.DetectCyclesRequest) (issueops.CycleReport, error) {
|
||||
return issueops.CycleReport{Cycles: []issueops.Cycle{}}, nil
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -30,11 +30,11 @@ type cycleDetector struct{ store *DoltStore }
|
|||
|
||||
var _ issueops.CycleDetector = (*cycleDetector)(nil)
|
||||
|
||||
func (c *cycleDetector) DetectCycles(ctx context.Context, _ issueops.DetectCyclesRequest) (issueops.CycleReport, error) {
|
||||
func (c *cycleDetector) DetectCycles(ctx context.Context, req issueops.DetectCyclesRequest) (issueops.CycleReport, error) {
|
||||
var report issueops.CycleReport
|
||||
err := c.store.withReadTx(ctx, func(tx *sql.Tx) error {
|
||||
var err error
|
||||
report, err = storeops.DetectCycleReportInTx(ctx, tx)
|
||||
report, err = storeops.DetectCycleReportInTx(ctx, tx, req)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -35,6 +35,15 @@ func TestCycleDetectorContract(t *testing.T) {
|
|||
t.Run("FollowsOnlyBlockingEdges", func(t *testing.T) {
|
||||
conformance.RunCycleDetectorFollowsOnlyBlockingEdges(t, ctx, fixture)
|
||||
})
|
||||
t.Run("IncludeTracksIgnoresAPureTracksLoop", func(t *testing.T) {
|
||||
conformance.RunCycleDetectorIncludeTracksIgnoresAPureTracksLoop(t, ctx, fixture)
|
||||
})
|
||||
t.Run("IncludeTracksFindsTheMoleculeRootShape", func(t *testing.T) {
|
||||
conformance.RunCycleDetectorIncludeTracksFindsTheMoleculeRootShape(t, ctx, fixture)
|
||||
})
|
||||
t.Run("IncludeTracksWalksEachEdgeInItsStoredDirection", func(t *testing.T) {
|
||||
conformance.RunCycleDetectorIncludeTracksWalksEachEdgeInItsStoredDirection(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ReportsAnHonestPartial", func(t *testing.T) {
|
||||
conformance.RunCycleDetectorReportsAnHonestPartial(t, ctx, fixture)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -950,8 +950,8 @@ func (r *dependencySQLRepositoryImpl) DetectCycles(ctx context.Context) ([][]*ty
|
|||
return out, nil
|
||||
}
|
||||
|
||||
func (r *dependencySQLRepositoryImpl) DetectCycleReport(ctx context.Context) (publicops.CycleReport, error) {
|
||||
out, err := issueops.DetectCycleReportInTx(ctx, r.runner)
|
||||
func (r *dependencySQLRepositoryImpl) DetectCycleReport(ctx context.Context, req publicops.DetectCyclesRequest) (publicops.CycleReport, error) {
|
||||
out, err := issueops.DetectCycleReportInTx(ctx, r.runner, req)
|
||||
if err != nil {
|
||||
return publicops.CycleReport{}, fmt.Errorf("db: DependencySQLRepository.DetectCycleReport: %w", err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -161,8 +161,9 @@ type DependencySQLRepository interface {
|
|||
// DetectCycleReport answers the same walk in the shape issueops.CycleDetector
|
||||
// publishes: canonically ordered, and carrying every member of a cycle
|
||||
// whether or not this database can describe it. DetectCycles above is the
|
||||
// lossy legacy shape.
|
||||
DetectCycleReport(ctx context.Context) (issueops.CycleReport, error)
|
||||
// lossy legacy shape. req.IncludeTracks widens the walk; see
|
||||
// issueops.DetectCyclesRequest.
|
||||
DetectCycleReport(ctx context.Context, req issueops.DetectCyclesRequest) (issueops.CycleReport, error)
|
||||
|
||||
GetTree(ctx context.Context, rootID string, opts DepTreeOpts) ([]*types.TreeNode, error)
|
||||
// WalkDependencyTree answers the tree walk in the shape issueops.TreeWalker
|
||||
|
|
@ -206,7 +207,7 @@ type DependencyUseCase interface {
|
|||
DetectCycles(ctx context.Context) ([][]*types.Issue, error)
|
||||
// DetectCycleReport is the shape issueops.CycleDetector publishes; see the
|
||||
// repository method of the same name.
|
||||
DetectCycleReport(ctx context.Context) (issueops.CycleReport, error)
|
||||
DetectCycleReport(ctx context.Context, req issueops.DetectCyclesRequest) (issueops.CycleReport, error)
|
||||
|
||||
GetDependencyTree(ctx context.Context, rootID string, opts DepTreeOpts) ([]*types.TreeNode, error)
|
||||
// WalkDependencyTree is the shape issueops.TreeWalker publishes; see the
|
||||
|
|
@ -643,8 +644,8 @@ func (u *dependencyUseCaseImpl) DetectCycles(ctx context.Context) ([][]*types.Is
|
|||
return out, nil
|
||||
}
|
||||
|
||||
func (u *dependencyUseCaseImpl) DetectCycleReport(ctx context.Context) (issueops.CycleReport, error) {
|
||||
out, err := u.depRepo.DetectCycleReport(ctx)
|
||||
func (u *dependencyUseCaseImpl) DetectCycleReport(ctx context.Context, req issueops.DetectCyclesRequest) (issueops.CycleReport, error) {
|
||||
out, err := u.depRepo.DetectCycleReport(ctx, req)
|
||||
if err != nil {
|
||||
return issueops.CycleReport{}, fmt.Errorf("DetectCycleReport: %w", err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,11 +31,11 @@ type cycleDetector struct{ store *EmbeddedDoltStore }
|
|||
|
||||
var _ issueops.CycleDetector = (*cycleDetector)(nil)
|
||||
|
||||
func (c *cycleDetector) DetectCycles(ctx context.Context, _ issueops.DetectCyclesRequest) (issueops.CycleReport, error) {
|
||||
func (c *cycleDetector) DetectCycles(ctx context.Context, req issueops.DetectCyclesRequest) (issueops.CycleReport, error) {
|
||||
var report issueops.CycleReport
|
||||
err := c.store.withConn(ctx, false, func(tx *sql.Tx) error {
|
||||
var err error
|
||||
report, err = storeops.DetectCycleReportInTx(ctx, tx)
|
||||
report, err = storeops.DetectCycleReportInTx(ctx, tx, req)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -39,6 +39,15 @@ func TestCycleDetectorContract(t *testing.T) {
|
|||
t.Run("FollowsOnlyBlockingEdges", func(t *testing.T) {
|
||||
conformance.RunCycleDetectorFollowsOnlyBlockingEdges(t, ctx, fixture)
|
||||
})
|
||||
t.Run("IncludeTracksIgnoresAPureTracksLoop", func(t *testing.T) {
|
||||
conformance.RunCycleDetectorIncludeTracksIgnoresAPureTracksLoop(t, ctx, fixture)
|
||||
})
|
||||
t.Run("IncludeTracksFindsTheMoleculeRootShape", func(t *testing.T) {
|
||||
conformance.RunCycleDetectorIncludeTracksFindsTheMoleculeRootShape(t, ctx, fixture)
|
||||
})
|
||||
t.Run("IncludeTracksWalksEachEdgeInItsStoredDirection", func(t *testing.T) {
|
||||
conformance.RunCycleDetectorIncludeTracksWalksEachEdgeInItsStoredDirection(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ReportsAnHonestPartial", func(t *testing.T) {
|
||||
conformance.RunCycleDetectorReportsAnHonestPartial(t, ctx, fixture)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package issueops
|
|||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
|
|
@ -11,8 +12,9 @@ import (
|
|||
// The cycle REPORT: the shared body behind issueops.CycleDetector on all three
|
||||
// backends, split into a pure half and a transactional half so the part that
|
||||
// decides what the answer MEANS is testable without a database.
|
||||
// CanonicalCyclePaths holds the determinism ruling and BuildCycles the
|
||||
// honest-partial one; both are pinned in cycle_report_test.go.
|
||||
// CanonicalCyclePaths holds the determinism ruling, CanonicalMixedCyclePaths
|
||||
// the IncludeTracks widening, and BuildCycles the honest-partial one; all
|
||||
// three are pinned in cycle_report_test.go.
|
||||
|
||||
// CanonicalCyclePaths returns the cycles of a blocking graph as id paths, in a
|
||||
// canonical form: each path rotated so its lowest id comes first, and the paths
|
||||
|
|
@ -80,6 +82,248 @@ func CanonicalCyclePaths(graph map[string][]string) [][]string {
|
|||
return cycles
|
||||
}
|
||||
|
||||
// CanonicalMixedCyclePaths reports the qualifying cycles of a graph that also
|
||||
// carries `tracks` edges (MixedCycleEdge.Scheduling false). A cycle qualifies
|
||||
// only when at least one of its edges is a scheduling edge.
|
||||
//
|
||||
// THE REPORT IS THE UNION, deduplicated by canonical rotation, of two sets:
|
||||
//
|
||||
// 1. CanonicalCyclePaths over the scheduling edges alone, which is exactly
|
||||
// the report the default request produces on the same data.
|
||||
// 2. For every scheduling edge from -> to whose endpoints share a strongly
|
||||
// connected component of the mixed graph, the cycle that edge closes with
|
||||
// the shortest return path from `to` back to `from` over edges of either
|
||||
// kind (closeMixedCycle).
|
||||
//
|
||||
// Set 1 makes the widened report a SUPERSET of the default report. Set 2 alone
|
||||
// would not: the default walk records the depth-first tree path behind each
|
||||
// back edge, which need not be the shortest return path of any edge on it. And
|
||||
// sampling one cycle per component instead would drop real deadlocks, because
|
||||
// tracks edges can fuse separate blocks-only deadlocks into one component.
|
||||
//
|
||||
// Set 2 finds the cycles that need a tracks edge, the shape this exists for: a
|
||||
// molecule root that blocks-depends (transitively) on its own entry step,
|
||||
// which tracks-depends back to the root. Every internal edge of a strongly
|
||||
// connected component lies on a cycle, so each such scheduling edge closes one,
|
||||
// and a scheduling edge outside every component lies on no cycle at all.
|
||||
//
|
||||
// BOUND: at most one cycle per scheduling edge inside a component plus one per
|
||||
// default-walk cycle, so never more than twice the distinct scheduling edges.
|
||||
// That is the whole of the volume guarantee, and it counts EDGES, not
|
||||
// deadlocks. A cycle made only of tracks edges is never reported, which rules
|
||||
// out the pure-tracks shape AppendMixedCycleGraphInTx documents and nothing
|
||||
// beyond it: one tracks-only loop fuses its whole neighborhood into a single
|
||||
// component, after which every scheduling edge inside is on a cycle and is
|
||||
// reported, however acyclic the scheduling edges are on their own. So the
|
||||
// exclusion does not keep the report small on a tracks-dense graph — the edge
|
||||
// count does, which is why this walk is opt-in and why `bd dep cycles`
|
||||
// truncates its rendering.
|
||||
//
|
||||
// COST: one breadth-first search per distinct scheduling-edge target inside a
|
||||
// component, confined to that component, and shared by every edge into that
|
||||
// target. On a component of V nodes and E edges that is O(V(V+E)). A search per
|
||||
// edge was O(E(V+E)), and on a dense tangle E grows with the square of V.
|
||||
//
|
||||
// Nodes, adjacency lists, components, and return paths are all ordered, so the
|
||||
// answer depends only on the graph, not on Go map or SQL row order. The error
|
||||
// is a broken internal invariant (see closeMixedCycle), never a property of
|
||||
// the data.
|
||||
func CanonicalMixedCyclePaths(graph map[string][]MixedCycleEdge) ([][]string, error) {
|
||||
adjacency := make(map[string][]MixedCycleEdge, len(graph))
|
||||
nodeSet := make(map[string]struct{}, len(graph))
|
||||
for node, edges := range graph {
|
||||
nodeSet[node] = struct{}{}
|
||||
scheduling := make(map[string]bool, len(edges))
|
||||
for _, edge := range edges {
|
||||
nodeSet[edge.To] = struct{}{}
|
||||
scheduling[edge.To] = scheduling[edge.To] || edge.Scheduling
|
||||
}
|
||||
targets := make([]string, 0, len(scheduling))
|
||||
for to := range scheduling {
|
||||
targets = append(targets, to)
|
||||
}
|
||||
slices.Sort(targets)
|
||||
deduped := make([]MixedCycleEdge, 0, len(targets))
|
||||
for _, to := range targets {
|
||||
deduped = append(deduped, MixedCycleEdge{To: to, Scheduling: scheduling[to]})
|
||||
}
|
||||
adjacency[node] = deduped
|
||||
}
|
||||
nodes := make([]string, 0, len(nodeSet))
|
||||
plain := make(map[string][]string, len(nodeSet))
|
||||
schedulingOnly := make(map[string][]string, len(nodeSet))
|
||||
for node := range nodeSet {
|
||||
nodes = append(nodes, node)
|
||||
for _, edge := range adjacency[node] {
|
||||
plain[node] = append(plain[node], edge.To)
|
||||
if edge.Scheduling {
|
||||
schedulingOnly[node] = append(schedulingOnly[node], edge.To)
|
||||
}
|
||||
}
|
||||
}
|
||||
slices.Sort(nodes)
|
||||
|
||||
cycles := CanonicalCyclePaths(schedulingOnly)
|
||||
for _, component := range mixedStronglyConnectedComponents(adjacency, nodes) {
|
||||
closed, err := closeComponentSchedulingEdges(adjacency, plain, component)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cycles = append(cycles, closed...)
|
||||
}
|
||||
slices.SortFunc(cycles, slices.Compare)
|
||||
return slices.CompactFunc(cycles, slices.Equal), nil
|
||||
}
|
||||
|
||||
// closeComponentSchedulingEdges closes every scheduling edge inside one strongly
|
||||
// connected component, which is set 2 of CanonicalMixedCyclePaths.
|
||||
//
|
||||
// The edges are grouped by target, so one shortestPathTree rooted at a target
|
||||
// closes every edge into it. Only one tree is held at a time.
|
||||
func closeComponentSchedulingEdges(adjacency map[string][]MixedCycleEdge, plain map[string][]string, component []string) ([][]string, error) {
|
||||
members := make(map[string]bool, len(component))
|
||||
for _, node := range component {
|
||||
members[node] = true
|
||||
}
|
||||
sources := make(map[string][]string, len(component))
|
||||
for _, from := range component {
|
||||
for _, edge := range adjacency[from] {
|
||||
if edge.Scheduling && members[edge.To] {
|
||||
sources[edge.To] = append(sources[edge.To], from)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var cycles [][]string
|
||||
for _, to := range component {
|
||||
if len(sources[to]) == 0 {
|
||||
continue
|
||||
}
|
||||
tree := shortestPathTree(plain, members, to)
|
||||
for _, from := range sources[to] {
|
||||
cycle, err := closeMixedCycle(tree, from, to)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cycles = append(cycles, cycle)
|
||||
}
|
||||
}
|
||||
return cycles, nil
|
||||
}
|
||||
|
||||
// shortestPathTree is the breadth-first tree over graph from start, confined to
|
||||
// members: tree[n] is the node before n on a shortest path from start, and
|
||||
// tree[start] is start. Neighbors are taken in their stored order, so the path
|
||||
// to any node is the one reachPath returns for the same start and goal. The
|
||||
// search runs past the first goal so that every goal can share it.
|
||||
//
|
||||
// Confining the search to a strongly connected component loses no path between
|
||||
// two of its members. A node that start reaches, and that reaches back into the
|
||||
// component, is itself in the component, so a search that leaves the component
|
||||
// never comes back to it.
|
||||
func shortestPathTree(graph map[string][]string, members map[string]bool, start string) map[string]string {
|
||||
tree := map[string]string{start: start}
|
||||
queue := []string{start}
|
||||
for len(queue) > 0 {
|
||||
node := queue[0]
|
||||
queue = queue[1:]
|
||||
for _, next := range graph[node] {
|
||||
if _, seen := tree[next]; seen || !members[next] {
|
||||
continue
|
||||
}
|
||||
tree[next] = node
|
||||
queue = append(queue, next)
|
||||
}
|
||||
}
|
||||
return tree
|
||||
}
|
||||
|
||||
// closeMixedCycle returns the canonical cycle the edge from -> to closes: from,
|
||||
// followed by the shortest path from `to` back to `from`, read out of tree, the
|
||||
// shortestPathTree rooted at `to`.
|
||||
//
|
||||
// The caller passes only edges inside one strongly connected component, with
|
||||
// the tree rooted at the edge's target, so the tree always reaches `from`. When
|
||||
// it does not, or the climb ends at a different root, the invariant is broken,
|
||||
// and that is returned as an error rather than a panic: the caller is a read
|
||||
// that `bd dep cycles --include-tracks` runs, and a crash there would hide every
|
||||
// other cycle behind a stack trace.
|
||||
func closeMixedCycle(tree map[string]string, from, to string) ([]string, error) {
|
||||
// Climbing from `from` to the root gives the return path backwards.
|
||||
backwards := []string{from}
|
||||
for at := from; at != to; {
|
||||
parent, reached := tree[at]
|
||||
if !reached || parent == at {
|
||||
return nil, fmt.Errorf("mixed cycle graph: edge %s -> %s lies in a strongly connected component but has no return path", from, to)
|
||||
}
|
||||
at = parent
|
||||
backwards = append(backwards, at)
|
||||
}
|
||||
cycle := make([]string, 0, len(backwards))
|
||||
cycle = append(cycle, from)
|
||||
for i := len(backwards) - 1; i > 0; i-- {
|
||||
cycle = append(cycle, backwards[i])
|
||||
}
|
||||
return rotateToLowest(cycle), nil
|
||||
}
|
||||
|
||||
// mixedStronglyConnectedComponents returns Tarjan components with both their
|
||||
// members and the component list sorted. Targets without outgoing edges are in
|
||||
// nodes too, so singleton sinks remain part of the traversal even though they
|
||||
// can never qualify on their own.
|
||||
func mixedStronglyConnectedComponents(adjacency map[string][]MixedCycleEdge, nodes []string) [][]string {
|
||||
nextIndex := 0
|
||||
index := make(map[string]int, len(nodes))
|
||||
lowlink := make(map[string]int, len(nodes))
|
||||
onStack := make(map[string]bool, len(nodes))
|
||||
stack := make([]string, 0, len(nodes))
|
||||
components := make([][]string, 0)
|
||||
|
||||
var visit func(string)
|
||||
visit = func(node string) {
|
||||
nextIndex++
|
||||
index[node] = nextIndex
|
||||
lowlink[node] = nextIndex
|
||||
stack = append(stack, node)
|
||||
onStack[node] = true
|
||||
|
||||
for _, edge := range adjacency[node] {
|
||||
neighbor := edge.To
|
||||
if index[neighbor] == 0 {
|
||||
visit(neighbor)
|
||||
lowlink[node] = min(lowlink[node], lowlink[neighbor])
|
||||
} else if onStack[neighbor] {
|
||||
lowlink[node] = min(lowlink[node], index[neighbor])
|
||||
}
|
||||
}
|
||||
|
||||
if lowlink[node] != index[node] {
|
||||
return
|
||||
}
|
||||
component := make([]string, 0)
|
||||
for {
|
||||
last := len(stack) - 1
|
||||
member := stack[last]
|
||||
stack = stack[:last]
|
||||
onStack[member] = false
|
||||
component = append(component, member)
|
||||
if member == node {
|
||||
break
|
||||
}
|
||||
}
|
||||
slices.Sort(component)
|
||||
components = append(components, component)
|
||||
}
|
||||
|
||||
for _, node := range nodes {
|
||||
if index[node] == 0 {
|
||||
visit(node)
|
||||
}
|
||||
}
|
||||
slices.SortFunc(components, slices.Compare)
|
||||
return components
|
||||
}
|
||||
|
||||
// rotateToLowest returns a copy of a cycle path rotated so its lowest id comes
|
||||
// first, preserving edge order. The members of a cycle are distinct — the path
|
||||
// it is taken from is a simple path — so the lowest id is unique and names
|
||||
|
|
@ -133,19 +377,33 @@ func BuildCycles(paths [][]string, hydrate func(id string) *types.Issue) []publi
|
|||
|
||||
// DetectCycleReportInTx is the whole read: build the blocking graph across both
|
||||
// planes, canonicalize it, and hydrate what it can. It reads the same two tables
|
||||
// and the same two edge types DetectCyclesInTx reads, because it is the same
|
||||
// question.
|
||||
func DetectCycleReportInTx(ctx context.Context, tx DBTX) (publicops.CycleReport, error) {
|
||||
graph := make(map[string][]string)
|
||||
if err := AppendBlockingGraphInTx(ctx, tx, cycleDetectionTables(), graph); err != nil {
|
||||
return publicops.CycleReport{}, err
|
||||
}
|
||||
// and, by default, the same two edge types DetectCyclesInTx reads, because it
|
||||
// is the same question. req.IncludeTracks answers a wider question instead —
|
||||
// see DetectCyclesRequest and CanonicalMixedCyclePaths.
|
||||
func DetectCycleReportInTx(ctx context.Context, tx DBTX, req publicops.DetectCyclesRequest) (publicops.CycleReport, error) {
|
||||
hydrate := func(id string) *types.Issue {
|
||||
// The error is deliberately not distinguished from a miss: both mean the
|
||||
// same thing to the answer, that this database did not describe the node.
|
||||
issue, _ := GetIssueInTx(ctx, tx, id)
|
||||
return issue
|
||||
}
|
||||
|
||||
if req.IncludeTracks {
|
||||
graph := make(map[string][]MixedCycleEdge)
|
||||
if err := AppendMixedCycleGraphInTx(ctx, tx, cycleDetectionTables(), graph); err != nil {
|
||||
return publicops.CycleReport{}, err
|
||||
}
|
||||
paths, err := CanonicalMixedCyclePaths(graph)
|
||||
if err != nil {
|
||||
return publicops.CycleReport{}, err
|
||||
}
|
||||
return publicops.CycleReport{Cycles: BuildCycles(paths, hydrate)}, nil
|
||||
}
|
||||
|
||||
graph := make(map[string][]string)
|
||||
if err := AppendBlockingGraphInTx(ctx, tx, cycleDetectionTables(), graph); err != nil {
|
||||
return publicops.CycleReport{}, err
|
||||
}
|
||||
return publicops.CycleReport{
|
||||
Cycles: BuildCycles(CanonicalCyclePaths(graph), hydrate),
|
||||
}, nil
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package issueops
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"maps"
|
||||
"math/rand"
|
||||
"reflect"
|
||||
|
|
@ -195,3 +196,479 @@ func TestBuildCyclesLeavesACompleteCycleUnmarked(t *testing.T) {
|
|||
t.Error("Partial = true for a fully described cycle")
|
||||
}
|
||||
}
|
||||
|
||||
// The IncludeTracks widening: CanonicalMixedCyclePaths adds `tracks` edges to
|
||||
// the walk but must report a cycle only when a scheduling (blocks/
|
||||
// conditional-blocks) edge is also on it. This is the gc-818bx guard: the
|
||||
// shape it exists to surface is a molecule root that blocks-depends
|
||||
// (transitively) on its own entry step, which tracks-depends back to the
|
||||
// root, without reporting the pure-tracks loops that a
|
||||
// tracks-in-the-plain-walk change reported when it caused the "thousands of
|
||||
// cycles" regression and had to revert (ordinary convoy topology loops
|
||||
// constantly through tracks alone). That requirement is NECESSARY AND NOT
|
||||
// SUFFICIENT: it excludes the pure-tracks loop only, and
|
||||
// TestCanonicalMixedCyclePathsBoundsAFusedMoleculeByItsSchedulingEdges pins
|
||||
// what it leaves standing.
|
||||
|
||||
// TestCanonicalMixedCyclePathsIgnoresAPureTracksLoop pins the regression
|
||||
// guard directly: a loop made entirely of tracks edges — the shape a convoy
|
||||
// and its tracked issues form routinely — must not be reported.
|
||||
func TestCanonicalMixedCyclePathsIgnoresAPureTracksLoop(t *testing.T) {
|
||||
graph := map[string][]MixedCycleEdge{
|
||||
"a": {{To: "b"}},
|
||||
"b": {{To: "c"}},
|
||||
"c": {{To: "a"}},
|
||||
}
|
||||
if got := mustMixedCyclePaths(t, graph); len(got) != 0 {
|
||||
t.Errorf("pure-tracks loop reported %v, want no cycles: tracks-only convoy topology is not a deadlock", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCanonicalMixedCyclePathsBoundsAFusedMoleculeByItsSchedulingEdges pins
|
||||
// what the "at least one scheduling edge" requirement does NOT buy, the
|
||||
// direction TestCanonicalMixedCyclePathsKeepsDeadlocksATracksEdgeFuses leaves
|
||||
// open. That test fuses two REAL deadlocks and checks neither is lost; this one
|
||||
// fuses none at all. The single tracks edge from an entry step back to its root
|
||||
// pulls the whole molecule into one strongly connected component, and every
|
||||
// scheduling edge inside a component lies on a cycle — so a strictly acyclic
|
||||
// blocks chain, which the default walk reports nothing for, still yields one
|
||||
// cycle per blocks edge. The requirement excludes a PURE tracks loop and
|
||||
// nothing else, which is why the guarantee on this walk is the BOUND (here 9,
|
||||
// inside twice the 9 distinct scheduling edges) and never a count of real
|
||||
// deadlocks.
|
||||
func TestCanonicalMixedCyclePathsBoundsAFusedMoleculeByItsSchedulingEdges(t *testing.T) {
|
||||
const steps = 10
|
||||
graph := map[string][]MixedCycleEdge{}
|
||||
schedulingOnly := map[string][]string{}
|
||||
for i := range steps {
|
||||
step := fmt.Sprintf("step-%03d", i)
|
||||
// root -tracks-> step: the stored direction of a convoy's edge to an
|
||||
// issue it tracks.
|
||||
graph["root"] = append(graph["root"], MixedCycleEdge{To: step})
|
||||
if i == 0 {
|
||||
continue
|
||||
}
|
||||
// A strictly ACYCLIC blocks chain down the steps. Nothing here closes.
|
||||
previous := fmt.Sprintf("step-%03d", i-1)
|
||||
graph[step] = append(graph[step], MixedCycleEdge{To: previous, Scheduling: true})
|
||||
schedulingOnly[step] = append(schedulingOnly[step], previous)
|
||||
}
|
||||
// The entry step tracks back to the root: one edge, and the only cycle in
|
||||
// the graph runs through it.
|
||||
graph["step-000"] = append(graph["step-000"], MixedCycleEdge{To: "root"})
|
||||
|
||||
if plain := CanonicalCyclePaths(schedulingOnly); len(plain) != 0 {
|
||||
t.Fatalf("the blocks chain alone reported %v, want none: this fixture only measures fusion while its scheduling edges are acyclic", plain)
|
||||
}
|
||||
|
||||
schedulingEdges := steps - 1
|
||||
if got := mustMixedCyclePaths(t, graph); len(got) != schedulingEdges {
|
||||
t.Errorf("a tracks-fused molecule over an ACYCLIC blocks chain reported %d cycles, want %d — one per scheduling edge inside the fused component: %v",
|
||||
len(got), schedulingEdges, got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCanonicalMixedCyclePathsFindsTheMoleculeRootShape pins the case gc-818bx
|
||||
// exists for: a root that blocks-depends (transitively) on its own entry
|
||||
// step, closed by a tracks edge back to the root. Neither
|
||||
// CanonicalCyclePaths (no tracks edge at all) nor a plain-tracks walk (no
|
||||
// scheduling requirement) would report this correctly — the former misses it
|
||||
// entirely, the latter would drown it in every other tracks loop.
|
||||
func TestCanonicalMixedCyclePathsFindsTheMoleculeRootShape(t *testing.T) {
|
||||
graph := map[string][]MixedCycleEdge{
|
||||
"root": {{To: "step", Scheduling: true}},
|
||||
"step": {{To: "root"}}, // tracks edge closing the loop
|
||||
}
|
||||
got := mustMixedCyclePaths(t, graph)
|
||||
want := [][]string{{"root", "step"}}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("cycles = %v, want %v: a blocks edge plus a closing tracks edge is exactly the deadlock this option surfaces", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCanonicalMixedCyclePathsFindsASchedulingCycleAfterATracksOnlyBackEdge
|
||||
// pins the edge-labelled DFS trap from the exact-head review of gc-818bx. A
|
||||
// global visited set can first close and ignore the tracks-only a-b loop, then
|
||||
// miss the qualifying a-c-b-a loop because b is visited but no longer on the
|
||||
// active path when c reaches it.
|
||||
func TestCanonicalMixedCyclePathsFindsASchedulingCycleAfterATracksOnlyBackEdge(t *testing.T) {
|
||||
graph := map[string][]MixedCycleEdge{
|
||||
"a": {
|
||||
{To: "b"},
|
||||
{To: "c", Scheduling: true},
|
||||
},
|
||||
"b": {{To: "a"}},
|
||||
"c": {{To: "b"}},
|
||||
}
|
||||
|
||||
got := mustMixedCyclePaths(t, graph)
|
||||
want := [][]string{{"a", "c", "b"}}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("cycles = %v, want %v: a tracks-only back edge must not hide a different cycle containing a scheduling edge", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCanonicalMixedCyclePathsStillFindsAPureSchedulingCycle keeps parity with
|
||||
// CanonicalCyclePaths for the case that needs no tracks edge at all.
|
||||
func TestCanonicalMixedCyclePathsStillFindsAPureSchedulingCycle(t *testing.T) {
|
||||
graph := map[string][]MixedCycleEdge{
|
||||
"a": {{To: "b", Scheduling: true}},
|
||||
"b": {{To: "a", Scheduling: true}},
|
||||
}
|
||||
got := mustMixedCyclePaths(t, graph)
|
||||
want := [][]string{{"a", "b"}}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("cycles = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCanonicalMixedCyclePathsAcceptsASchedulingEdgeAnywhereOnTheLoop checks
|
||||
// that the requirement is "at least one scheduling edge on the cycle", not
|
||||
// specifically on the closing edge — a longer chain where the blocks edge
|
||||
// sits in the middle must still be reported.
|
||||
func TestCanonicalMixedCyclePathsAcceptsASchedulingEdgeAnywhereOnTheLoop(t *testing.T) {
|
||||
graph := map[string][]MixedCycleEdge{
|
||||
"a": {{To: "b"}}, // tracks
|
||||
"b": {{To: "c", Scheduling: true}}, // blocks, in the middle of the loop
|
||||
"c": {{To: "a"}}, // tracks, closes the loop
|
||||
}
|
||||
got := mustMixedCyclePaths(t, graph)
|
||||
want := [][]string{{"a", "b", "c"}}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("cycles = %v, want %v: a scheduling edge anywhere on the loop must qualify it, not only the closing edge", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCanonicalMixedCyclePathsSelfLoop mirrors
|
||||
// TestCanonicalCyclePathsFindsSelfLoopsAndReportsNoneForAnAcyclicGraph for the
|
||||
// mixed graph: a self-loop qualifies exactly when its own edge is scheduling.
|
||||
func TestCanonicalMixedCyclePathsSelfLoop(t *testing.T) {
|
||||
if got := mustMixedCyclePaths(t, map[string][]MixedCycleEdge{"a": {{To: "a", Scheduling: true}}}); !reflect.DeepEqual(got, [][]string{{"a"}}) {
|
||||
t.Errorf("blocking self-loop = %v, want [[a]]", got)
|
||||
}
|
||||
if got := mustMixedCyclePaths(t, map[string][]MixedCycleEdge{"a": {{To: "a"}}}); len(got) != 0 {
|
||||
t.Errorf("tracks-only self-loop = %v, want no cycles", got)
|
||||
}
|
||||
if got := mustMixedCyclePaths(t, nil); len(got) != 0 {
|
||||
t.Errorf("empty graph produced %v, want no cycles", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCanonicalMixedCyclePathsCollapsesParallelEdgesByOringScheduling mirrors
|
||||
// TestCanonicalCyclePathsCollapsesParallelEdges: two rows for the same pair of
|
||||
// nodes — one a tracks edge, one blocking — must collapse to one edge that is
|
||||
// scheduling, not fall out of the requirement because the dedup happened to
|
||||
// keep the tracks-flavored copy.
|
||||
func TestCanonicalMixedCyclePathsCollapsesParallelEdgesByOringScheduling(t *testing.T) {
|
||||
graph := map[string][]MixedCycleEdge{
|
||||
"a": {{To: "b"}, {To: "b", Scheduling: true}},
|
||||
"b": {{To: "a"}},
|
||||
}
|
||||
got := mustMixedCyclePaths(t, graph)
|
||||
want := [][]string{{"a", "b"}}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("cycles = %v, want %v: a duplicated edge where either copy is scheduling must count as scheduling", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// mustMixedCyclePaths runs CanonicalMixedCyclePaths and fails the test on its
|
||||
// error, which only a broken internal invariant can produce.
|
||||
func mustMixedCyclePaths(t *testing.T, graph map[string][]MixedCycleEdge) [][]string {
|
||||
t.Helper()
|
||||
paths, err := CanonicalMixedCyclePaths(graph)
|
||||
if err != nil {
|
||||
t.Fatalf("CanonicalMixedCyclePaths: %v", err)
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
// TestCloseMixedCycleReportsAMissingReturnPathAsAnError pins the invariant
|
||||
// breach as an error rather than a panic. CanonicalMixedCyclePaths cannot
|
||||
// reach it (it only closes edges inside a strongly connected component, from a
|
||||
// tree rooted at the edge's target), so the helper is exercised directly: once
|
||||
// with an edge that has no way back, and once with a tree rooted elsewhere,
|
||||
// where the climb must stop instead of looping at the wrong root.
|
||||
func TestCloseMixedCycleReportsAMissingReturnPathAsAnError(t *testing.T) {
|
||||
everyone := map[string]bool{"a": true, "b": true, "c": true}
|
||||
oneWay := map[string][]string{"a": {"b"}}
|
||||
if cycle, err := closeMixedCycle(shortestPathTree(oneWay, everyone, "b"), "a", "b"); err == nil || cycle != nil {
|
||||
t.Fatalf("closeMixedCycle = %v, %v; want nil and an error: b cannot reach a", cycle, err)
|
||||
}
|
||||
if cycle, err := closeMixedCycle(shortestPathTree(oneWay, everyone, "a"), "a", "b"); err == nil || cycle != nil {
|
||||
t.Fatalf("closeMixedCycle from a tree rooted at a = %v, %v; want nil and an error", cycle, err)
|
||||
}
|
||||
|
||||
triangle := map[string][]string{"a": {"c"}, "c": {"b"}, "b": {"a"}}
|
||||
cycle, err := closeMixedCycle(shortestPathTree(triangle, everyone, "b"), "c", "b")
|
||||
if err != nil {
|
||||
t.Fatalf("closeMixedCycle on a real cycle: %v", err)
|
||||
}
|
||||
if want := []string{"a", "c", "b"}; !slices.Equal(cycle, want) {
|
||||
t.Errorf("closeMixedCycle = %v, want %v: the edge, then its return path, rotated to the lowest id", cycle, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCanonicalMixedCyclePathsKeepsDeadlocksATracksEdgeFuses is the #6148
|
||||
// review reproduction. a<->b and c<->d are two separate blocks deadlocks; the
|
||||
// tracks edges b->c and d->a fuse them into ONE strongly connected component.
|
||||
// A widening option must not shrink the answer: both deadlocks the default
|
||||
// walk reports are still reported.
|
||||
func TestCanonicalMixedCyclePathsKeepsDeadlocksATracksEdgeFuses(t *testing.T) {
|
||||
plain := map[string][]string{"a": {"b"}, "b": {"a"}, "c": {"d"}, "d": {"c"}}
|
||||
mixed := map[string][]MixedCycleEdge{
|
||||
"a": {{To: "b", Scheduling: true}},
|
||||
"b": {{To: "a", Scheduling: true}, {To: "c"}},
|
||||
"c": {{To: "d", Scheduling: true}},
|
||||
"d": {{To: "c", Scheduling: true}, {To: "a"}},
|
||||
}
|
||||
want := CanonicalCyclePaths(plain)
|
||||
if !reflect.DeepEqual(want, [][]string{{"a", "b"}, {"c", "d"}}) {
|
||||
t.Fatalf("default walk = %v, want [[a b] [c d]]: the fixture no longer says what this test claims", want)
|
||||
}
|
||||
got := mustMixedCyclePaths(t, mixed)
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("widened = %v, want %v: tracks edges fusing two deadlocks into one component must not drop either", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCanonicalMixedCyclePathsReportsTheChordTheDefaultWalkMisses pins the
|
||||
// example CycleReport.Cycles documents. On a -> b -> c -> a plus the chord
|
||||
// a -> c, the default walk crosses a -> c after c is finished and reports only
|
||||
// a-b-c. The widened report keeps a-b-c and adds a-c, which the chord closes by
|
||||
// its shortest return path, even with no tracks edge in the graph.
|
||||
func TestCanonicalMixedCyclePathsReportsTheChordTheDefaultWalkMisses(t *testing.T) {
|
||||
if got, want := CanonicalCyclePaths(map[string][]string{"a": {"b", "c"}, "b": {"c"}, "c": {"a"}}), [][]string{{"a", "b", "c"}}; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("default walk = %v, want %v: the documented example no longer holds", got, want)
|
||||
}
|
||||
got := mustMixedCyclePaths(t, map[string][]MixedCycleEdge{
|
||||
"a": {{To: "b", Scheduling: true}, {To: "c", Scheduling: true}},
|
||||
"b": {{To: "c", Scheduling: true}},
|
||||
"c": {{To: "a", Scheduling: true}},
|
||||
})
|
||||
if want := [][]string{{"a", "b", "c"}, {"a", "c"}}; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("widened = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCanonicalMixedCyclePathsIsASupersetOfTheDefaultReport checks the
|
||||
// widening promise over generated graphs rather than one fixture: on the same
|
||||
// data, every cycle CanonicalCyclePaths reports on the scheduling edges alone
|
||||
// is also in the widened report. Each widened cycle must also be a real cycle
|
||||
// carrying a scheduling edge, stay within the documented size bound, and not
|
||||
// move when the edge rows arrive in a different order.
|
||||
func TestCanonicalMixedCyclePathsIsASupersetOfTheDefaultReport(t *testing.T) {
|
||||
type rawEdge struct {
|
||||
from, to string
|
||||
scheduling bool
|
||||
}
|
||||
ids := []string{"a", "b", "c", "d", "e", "f"}
|
||||
rng := rand.New(rand.NewSource(6148))
|
||||
widenedBeyondDefault := 0
|
||||
for trial := range 600 {
|
||||
n := 2 + rng.Intn(len(ids)-1)
|
||||
edges := make([]rawEdge, 0, 3*n)
|
||||
for range rng.Intn(3 * n) {
|
||||
edges = append(edges, rawEdge{ids[rng.Intn(n)], ids[rng.Intn(n)], rng.Intn(2) == 0})
|
||||
}
|
||||
|
||||
build := func(order []rawEdge) (map[string][]string, map[string][]MixedCycleEdge) {
|
||||
plain := map[string][]string{}
|
||||
mixed := map[string][]MixedCycleEdge{}
|
||||
for _, e := range order {
|
||||
mixed[e.from] = append(mixed[e.from], MixedCycleEdge{To: e.to, Scheduling: e.scheduling})
|
||||
if e.scheduling {
|
||||
plain[e.from] = append(plain[e.from], e.to)
|
||||
}
|
||||
}
|
||||
return plain, mixed
|
||||
}
|
||||
plain, mixed := build(edges)
|
||||
want := CanonicalCyclePaths(plain)
|
||||
got := mustMixedCyclePaths(t, mixed)
|
||||
|
||||
for _, cycle := range want {
|
||||
if !slices.ContainsFunc(got, func(c []string) bool { return slices.Equal(c, cycle) }) {
|
||||
t.Fatalf("trial %d, edges %v: default cycle %v is missing from the widened report %v (default report %v)",
|
||||
trial, edges, cycle, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
scheduling := map[[2]string]bool{}
|
||||
for _, e := range edges {
|
||||
key := [2]string{e.from, e.to}
|
||||
scheduling[key] = scheduling[key] || e.scheduling
|
||||
}
|
||||
schedulingEdges := 0
|
||||
for _, isScheduling := range scheduling {
|
||||
if isScheduling {
|
||||
schedulingEdges++
|
||||
}
|
||||
}
|
||||
if bound := schedulingEdges + len(want); len(got) > bound {
|
||||
t.Fatalf("trial %d, edges %v: widened report has %d cycles, above the bound %d (scheduling edges + default cycles)",
|
||||
trial, edges, len(got), bound)
|
||||
}
|
||||
if len(got) < len(want) {
|
||||
t.Fatalf("trial %d: widened report %v is smaller than the default %v", trial, got, want)
|
||||
}
|
||||
if len(got) > len(want) && len(want) > 0 {
|
||||
widenedBeyondDefault++
|
||||
}
|
||||
for _, cycle := range got {
|
||||
if len(slices.Compact(slices.Sorted(slices.Values(cycle)))) != len(cycle) {
|
||||
t.Fatalf("trial %d, edges %v: widened cycle %v repeats a member", trial, edges, cycle)
|
||||
}
|
||||
hasScheduling := false
|
||||
for i, from := range cycle {
|
||||
isScheduling, ok := scheduling[[2]string{from, cycle[(i+1)%len(cycle)]}]
|
||||
if !ok {
|
||||
t.Fatalf("trial %d, edges %v: widened cycle %v uses %s -> %s, which is not an edge",
|
||||
trial, edges, cycle, from, cycle[(i+1)%len(cycle)])
|
||||
}
|
||||
hasScheduling = hasScheduling || isScheduling
|
||||
}
|
||||
if !hasScheduling {
|
||||
t.Fatalf("trial %d, edges %v: widened cycle %v is made only of tracks edges", trial, edges, cycle)
|
||||
}
|
||||
}
|
||||
|
||||
shuffled := slices.Clone(edges)
|
||||
rng.Shuffle(len(shuffled), func(i, j int) { shuffled[i], shuffled[j] = shuffled[j], shuffled[i] })
|
||||
_, reordered := build(shuffled)
|
||||
if again := mustMixedCyclePaths(t, reordered); !reflect.DeepEqual(again, got) {
|
||||
t.Fatalf("trial %d: the same edges in another order produced %v, want %v", trial, again, got)
|
||||
}
|
||||
}
|
||||
if widenedBeyondDefault == 0 {
|
||||
t.Fatal("no generated graph had a widened report larger than a non-empty default one; the generator is not exercising mixed cycles")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCanonicalMixedCyclePathsIsIndependentOfMapOrder mirrors
|
||||
// TestCanonicalCyclePathsIsIndependentOfMapOrder against the mixed walk: it is
|
||||
// a separate implementation and must earn the same determinism guarantee
|
||||
// independently.
|
||||
func TestCanonicalMixedCyclePathsIsIndependentOfMapOrder(t *testing.T) {
|
||||
type rawEdge struct {
|
||||
from, to string
|
||||
scheduling bool
|
||||
}
|
||||
edges := []rawEdge{
|
||||
{"a", "b", true}, {"b", "c", false}, {"c", "a", false},
|
||||
{"c", "d", true}, {"d", "b", false},
|
||||
{"e", "f", false}, {"f", "e", false},
|
||||
{"a", "e", true}, {"g", "a", false}, {"g", "f", false},
|
||||
}
|
||||
|
||||
rng := rand.New(rand.NewSource(1))
|
||||
var first [][]string
|
||||
for attempt := range 40 {
|
||||
shuffled := slices.Clone(edges)
|
||||
rng.Shuffle(len(shuffled), func(i, j int) { shuffled[i], shuffled[j] = shuffled[j], shuffled[i] })
|
||||
|
||||
graph := map[string][]MixedCycleEdge{}
|
||||
for _, edge := range shuffled {
|
||||
graph[edge.from] = append(graph[edge.from], MixedCycleEdge{To: edge.to, Scheduling: edge.scheduling})
|
||||
}
|
||||
|
||||
got := mustMixedCyclePaths(t, graph)
|
||||
if attempt == 0 {
|
||||
first = got
|
||||
continue
|
||||
}
|
||||
if !reflect.DeepEqual(got, first) {
|
||||
t.Fatalf("run %d produced %v, run 0 produced %v: the same graph must produce the same report", attempt, got, first)
|
||||
}
|
||||
}
|
||||
if len(first) == 0 {
|
||||
t.Fatal("the fixture graph has qualifying cycles; the detector found none")
|
||||
}
|
||||
}
|
||||
|
||||
// TestShortestPathTreeClosesEachEdgeAsAPerEdgeSearchDid pins the shared search
|
||||
// to the answer it replaced. Over generated graphs, every edge inside a strongly
|
||||
// connected component is closed from one tree per target, confined to the
|
||||
// component, and compared with reachPath run from scratch for that one edge over
|
||||
// the whole graph. Ties between equally short return paths must break the same
|
||||
// way too, or the report would change.
|
||||
func TestShortestPathTreeClosesEachEdgeAsAPerEdgeSearchDid(t *testing.T) {
|
||||
ids := []string{"a", "b", "c", "d", "e", "f", "g"}
|
||||
rng := rand.New(rand.NewSource(61482))
|
||||
closedEdges := 0
|
||||
for trial := range 400 {
|
||||
n := 2 + rng.Intn(len(ids)-1)
|
||||
// The normalization CanonicalMixedCyclePaths applies: sorted,
|
||||
// deduplicated targets, and every target is a node.
|
||||
plain := map[string][]string{}
|
||||
nodeSet := map[string]bool{}
|
||||
for range rng.Intn(3 * n) {
|
||||
from, to := ids[rng.Intn(n)], ids[rng.Intn(n)]
|
||||
plain[from] = append(plain[from], to)
|
||||
nodeSet[from], nodeSet[to] = true, true
|
||||
}
|
||||
adjacency := map[string][]MixedCycleEdge{}
|
||||
for from, targets := range plain {
|
||||
slices.Sort(targets)
|
||||
plain[from] = slices.Compact(targets)
|
||||
for _, to := range plain[from] {
|
||||
adjacency[from] = append(adjacency[from], MixedCycleEdge{To: to, Scheduling: true})
|
||||
}
|
||||
}
|
||||
|
||||
for _, component := range mixedStronglyConnectedComponents(adjacency, slices.Sorted(maps.Keys(nodeSet))) {
|
||||
members := map[string]bool{}
|
||||
for _, node := range component {
|
||||
members[node] = true
|
||||
}
|
||||
for _, to := range component {
|
||||
tree := shortestPathTree(plain, members, to)
|
||||
for _, from := range component {
|
||||
if !slices.Contains(plain[from], to) {
|
||||
continue
|
||||
}
|
||||
got, err := closeMixedCycle(tree, from, to)
|
||||
if err != nil {
|
||||
t.Fatalf("trial %d, graph %v: edge %s -> %s: %v", trial, plain, from, to, err)
|
||||
}
|
||||
back := reachPath(plain, to, from)
|
||||
want := rotateToLowest(append([]string{from}, back[:len(back)-1]...))
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("trial %d, graph %v: edge %s -> %s closes as %v, a per-edge search gave %v",
|
||||
trial, plain, from, to, got, want)
|
||||
}
|
||||
closedEdges++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if closedEdges == 0 {
|
||||
t.Fatal("no generated graph had an edge inside a component; the generator is not exercising the search")
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkCanonicalMixedCyclePathsDenseTangle is the worst case a review of
|
||||
// #6148 named: a blocks edge i -> j for every pair of n issues with i < j, and
|
||||
// one tracks edge from the last issue back to the first, which makes all n a
|
||||
// single strongly connected component. It holds n(n-1)/2 scheduling edges but
|
||||
// only n-1 distinct edge targets.
|
||||
func BenchmarkCanonicalMixedCyclePathsDenseTangle(b *testing.B) {
|
||||
const n = 80
|
||||
ids := make([]string, n)
|
||||
for i := range ids {
|
||||
ids[i] = fmt.Sprintf("n%03d", i)
|
||||
}
|
||||
graph := make(map[string][]MixedCycleEdge, n)
|
||||
for i := range n {
|
||||
for j := i + 1; j < n; j++ {
|
||||
graph[ids[i]] = append(graph[ids[i]], MixedCycleEdge{To: ids[j], Scheduling: true})
|
||||
}
|
||||
}
|
||||
graph[ids[n-1]] = append(graph[ids[n-1]], MixedCycleEdge{To: ids[0]})
|
||||
|
||||
b.ResetTimer()
|
||||
for range b.N {
|
||||
if _, err := CanonicalMixedCyclePaths(graph); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -120,6 +120,69 @@ func appendDependencyGraphInTx(ctx context.Context, tx DBTX, depTables []string,
|
|||
return nil
|
||||
}
|
||||
|
||||
// MixedCycleEdge is one edge in the widened graph AppendMixedCycleGraphInTx
|
||||
// builds: a neighbor plus whether the edge that reaches it is a blocking
|
||||
// (scheduling) edge, as opposed to a `tracks` edge kept only to complete a
|
||||
// path. CanonicalMixedCyclePaths uses the flag to require a blocking edge on
|
||||
// every cycle it reports.
|
||||
type MixedCycleEdge struct {
|
||||
To string
|
||||
Scheduling bool
|
||||
}
|
||||
|
||||
// AppendMixedCycleGraphInTx adds blocks, conditional-blocks, and tracks
|
||||
// dependency edges from the given tables on tx into graph, tagging each edge
|
||||
// scheduling or not. It is the edge set behind
|
||||
// issueops.DetectCyclesRequest.IncludeTracks: wide enough to see a molecule
|
||||
// root's `tracks` edge back to its own entry step. Every edge keeps its stored
|
||||
// direction, issue_id -> depends_on_id, exactly as in the blocks-only graph.
|
||||
//
|
||||
// CanonicalMixedCyclePaths turns this graph into a report that holds every
|
||||
// cycle the default blocks-only walk finds on the same rows, plus cycles that
|
||||
// need a tracks edge to close. A cycle made ENTIRELY of tracks edges is never
|
||||
// reported: ordinary convoy topology loops constantly through tracks alone,
|
||||
// and reporting every one of those loops is the "thousands of cycles"
|
||||
// regression a previous change to the plain (blocks-only) walk caused and had
|
||||
// to revert. That exclusion covers the pure-tracks shape and nothing more: a
|
||||
// tracks loop still fuses a component, and every scheduling edge inside a
|
||||
// fused component is reported, so this walk is bounded by the scheduling-edge
|
||||
// count rather than by the number of real deadlocks. See
|
||||
// CanonicalMixedCyclePaths's BOUND.
|
||||
//
|
||||
//nolint:gosec // G201: depTable is hardcoded to "dependencies" or "wisp_dependencies"
|
||||
func AppendMixedCycleGraphInTx(ctx context.Context, tx DBTX, depTables []string, graph map[string][]MixedCycleEdge) error {
|
||||
for _, depTable := range depTables {
|
||||
rows, err := tx.QueryContext(ctx, fmt.Sprintf(`
|
||||
SELECT issue_id, %s AS depends_on_id, type
|
||||
FROM %s
|
||||
`, DepTargetExpr, depTable))
|
||||
if err != nil {
|
||||
return fmt.Errorf("mixed cycle graph: query %s: %w", depTable, err)
|
||||
}
|
||||
for rows.Next() {
|
||||
var issueID, dependsOnID, depType string
|
||||
if err := rows.Scan(&issueID, &dependsOnID, &depType); err != nil {
|
||||
_ = rows.Close()
|
||||
return fmt.Errorf("mixed cycle graph: scan %s: %w", depTable, err)
|
||||
}
|
||||
// The backend conformance cases are this switch's pin: the
|
||||
// package tests build their graphs by hand, so only
|
||||
// RunCycleDetectorIncludeTracks* reads a row through it.
|
||||
switch types.DependencyType(depType) {
|
||||
case types.DepBlocks, types.DepConditionalBlocks:
|
||||
graph[issueID] = append(graph[issueID], MixedCycleEdge{To: dependsOnID, Scheduling: true})
|
||||
case types.DepTracks:
|
||||
graph[issueID] = append(graph[issueID], MixedCycleEdge{To: dependsOnID})
|
||||
}
|
||||
}
|
||||
_ = rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return fmt.Errorf("mixed cycle graph: rows %s: %w", depTable, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CycleThroughEdgesInGraph reports a rendered cycle that traverses
|
||||
// one of the new edges (issueID -> dependsOnID pairs), or "" when no new edge
|
||||
// lies on a cycle. An edge u -> v is on a cycle exactly when u is reachable
|
||||
|
|
|
|||
|
|
@ -40,8 +40,8 @@ var _ publicops.CycleDetector = (*cycleDetector)(nil)
|
|||
// rows that were on the cycle, rather than the rows that exist by the time the
|
||||
// second query runs. The two store-backed bodies get the same property from
|
||||
// their own read transaction.
|
||||
func (c *cycleDetector) DetectCycles(ctx context.Context, _ publicops.DetectCyclesRequest) (publicops.CycleReport, error) {
|
||||
func (c *cycleDetector) DetectCycles(ctx context.Context, req publicops.DetectCyclesRequest) (publicops.CycleReport, error) {
|
||||
return RunTxRead(ctx, c.provider, func(ctx context.Context, uw UnitOfWork) (publicops.CycleReport, error) {
|
||||
return uw.DependencyUseCase().DetectCycleReport(ctx)
|
||||
return uw.DependencyUseCase().DetectCycleReport(ctx, req)
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -36,6 +36,15 @@ func TestCycleDetectorContract(t *testing.T) {
|
|||
t.Run("FollowsOnlyBlockingEdges", func(t *testing.T) {
|
||||
conformance.RunCycleDetectorFollowsOnlyBlockingEdges(t, ctx, fixture)
|
||||
})
|
||||
t.Run("IncludeTracksIgnoresAPureTracksLoop", func(t *testing.T) {
|
||||
conformance.RunCycleDetectorIncludeTracksIgnoresAPureTracksLoop(t, ctx, fixture)
|
||||
})
|
||||
t.Run("IncludeTracksFindsTheMoleculeRootShape", func(t *testing.T) {
|
||||
conformance.RunCycleDetectorIncludeTracksFindsTheMoleculeRootShape(t, ctx, fixture)
|
||||
})
|
||||
t.Run("IncludeTracksWalksEachEdgeInItsStoredDirection", func(t *testing.T) {
|
||||
conformance.RunCycleDetectorIncludeTracksWalksEachEdgeInItsStoredDirection(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ReportsAnHonestPartial", func(t *testing.T) {
|
||||
conformance.RunCycleDetectorReportsAnHonestPartial(t, ctx, fixture)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -8,16 +8,61 @@ import (
|
|||
|
||||
// DetectCyclesRequest asks for the whole blocking graph's cycles.
|
||||
//
|
||||
// It carries NOTHING, and the empty struct is the honest shape rather than a
|
||||
// placeholder. A cycle is a property of the graph as a whole: there is no
|
||||
// predicate that narrows it, because 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 flags for the same reason.
|
||||
// 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.
|
||||
//
|
||||
// It exists as a type so that a later option — a bound on how much of the graph
|
||||
// is walked, say — is a new field rather than a new method or a changed
|
||||
// signature, which is what every other role's request buys.
|
||||
type DetectCyclesRequest struct{}
|
||||
// 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.
|
||||
//
|
||||
|
|
@ -78,18 +123,23 @@ type CycleReport struct {
|
|||
// Cycles is the canonical, sorted set. It is empty — never nil — when the
|
||||
// graph is acyclic.
|
||||
//
|
||||
// ITS LENGTH IS THE TOTAL, 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.
|
||||
// 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 detector records one cycle per
|
||||
// back edge of a depth-first walk, so two cycles sharing every node but one
|
||||
// edge may be reported as one. What IS promised is that the slice is empty
|
||||
// exactly when the graph is acyclic, and that the same graph always yields
|
||||
// the same slice.
|
||||
// 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"`
|
||||
}
|
||||
|
||||
|
|
@ -115,7 +165,8 @@ type CycleReport struct {
|
|||
// 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".
|
||||
// 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
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue