* 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>
404 lines
14 KiB
Go
404 lines
14 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"runtime"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
"github.com/steveyegge/beads/issueops"
|
|
)
|
|
|
|
// The rendering half of `bd dep cycles` and of the post-add warning, driven
|
|
// directly with a report rather than through a database.
|
|
//
|
|
// These need no store and no server: they pin the one thing the conformance
|
|
// contract and the HTTP tests cannot see, which is what a human reads. The
|
|
// partial phrasing exists only here — a member with no row behind it used to be
|
|
// dropped, so there was nothing to print.
|
|
|
|
func TestDepCyclesNamesTheMembersItCannotDescribe(t *testing.T) {
|
|
out := captureCycleStdout(t, func() {
|
|
printCycleReportForTest(t, issueops.CycleReport{Cycles: []issueops.Cycle{
|
|
{Members: []issueops.CycleMember{
|
|
{ID: "bd-a", Issue: &types.Issue{ID: "bd-a", Title: "Alpha"}},
|
|
{ID: "bd-b", Issue: &types.Issue{ID: "bd-b", Title: "Beta"}},
|
|
}},
|
|
{Partial: true, Members: []issueops.CycleMember{
|
|
{ID: "bd-c", Issue: &types.Issue{ID: "bd-c", Title: "Gamma"}},
|
|
{ID: "bd-ghost"},
|
|
}},
|
|
}}, 0)
|
|
})
|
|
|
|
if !strings.Contains(out, "Found 2 dependency cycles") {
|
|
t.Errorf("output does not report both cycles:\n%s", out)
|
|
}
|
|
if !strings.Contains(out, "bd-a: Alpha") || !strings.Contains(out, "bd-b: Beta") {
|
|
t.Errorf("a fully described cycle lost a title:\n%s", out)
|
|
}
|
|
if !strings.Contains(out, "1 of 2 members have no record in this database") {
|
|
t.Errorf("the partial cycle is not marked as partial:\n%s", out)
|
|
}
|
|
if !strings.Contains(out, "bd-ghost") {
|
|
t.Errorf("the undescribable member is missing from the path; it used to be dropped:\n%s", out)
|
|
}
|
|
if !strings.Contains(out, "no record in this database") {
|
|
t.Errorf("the undescribable member has no description at all, leaving a bare id and a blank:\n%s", out)
|
|
}
|
|
}
|
|
|
|
func TestDepCyclesSaysNothingIsWrongForACleanWorkspace(t *testing.T) {
|
|
out := captureCycleStdout(t, func() {
|
|
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)
|
|
}
|
|
}
|
|
|
|
// TestCycleWarningSpellsTheWholePathIncludingUndescribableMembers pins the
|
|
// post-add warning both dep-add routes and `bd link` print. It is spelled from
|
|
// the member IDS, so a node with no row behind it still appears.
|
|
func TestCycleWarningSpellsTheWholePathIncludingUndescribableMembers(t *testing.T) {
|
|
origStderr := os.Stderr
|
|
r, w, err := os.Pipe()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
os.Stderr = w
|
|
defer func() { os.Stderr = origStderr }()
|
|
|
|
printCycleWarnings([]issueops.Cycle{{Partial: true, Members: []issueops.CycleMember{
|
|
{ID: "bd-a", Issue: &types.Issue{ID: "bd-a"}},
|
|
{ID: "bd-ghost"},
|
|
{ID: "bd-c", Issue: &types.Issue{ID: "bd-c"}},
|
|
}}})
|
|
|
|
_ = w.Close()
|
|
var buf bytes.Buffer
|
|
if _, err := io.Copy(&buf, r); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
_ = r.Close()
|
|
|
|
out := buf.String()
|
|
// The closing edge is drawn by repeating the first member, so the path
|
|
// reads as a cycle rather than as a chain.
|
|
if !strings.Contains(out, "bd-a → bd-ghost → bd-c → bd-a") {
|
|
t.Errorf("cycle path is not the whole rotated path closed on itself:\n%s", out)
|
|
}
|
|
if !strings.Contains(out, "Run 'bd dep cycles' for detailed analysis.") {
|
|
t.Errorf("the warning does not point at the detailed command:\n%s", out)
|
|
}
|
|
}
|
|
|
|
// TestCycleWarningIsSilentWithoutCycles keeps the sweep from printing a header
|
|
// over an empty list on every successful `bd dep add`.
|
|
func TestCycleWarningIsSilentWithoutCycles(t *testing.T) {
|
|
origStderr := os.Stderr
|
|
r, w, err := os.Pipe()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
os.Stderr = w
|
|
defer func() { os.Stderr = origStderr }()
|
|
|
|
printCycleWarnings(nil)
|
|
|
|
_ = w.Close()
|
|
var buf bytes.Buffer
|
|
if _, err := io.Copy(&buf, r); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
_ = r.Close()
|
|
|
|
if buf.Len() != 0 {
|
|
t.Errorf("an empty sweep wrote to stderr:\n%s", buf.String())
|
|
}
|
|
}
|
|
|
|
// printCycleReportForTest drives `bd dep cycles`'s human rendering with a
|
|
// 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
|
|
store = &fixedCycleStore{report: report}
|
|
jsonOutput = false
|
|
defer func() {
|
|
store = previousStore
|
|
jsonOutput = previousJSON
|
|
}()
|
|
|
|
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
|
|
// cycles` opens nothing but the role. The detector is a separate type because
|
|
// the store's LEGACY surface already carries a DetectCycles with a different
|
|
// signature.
|
|
type fixedCycleStore struct {
|
|
storage.DoltStorage
|
|
report issueops.CycleReport
|
|
}
|
|
|
|
func (s *fixedCycleStore) CycleDetector() (issueops.CycleDetector, error) {
|
|
return fixedCycleDetector{report: s.report}, nil
|
|
}
|
|
|
|
type fixedCycleDetector struct{ report issueops.CycleReport }
|
|
|
|
func (d fixedCycleDetector) DetectCycles(context.Context, issueops.DetectCyclesRequest) (issueops.CycleReport, error) {
|
|
return d.report, nil
|
|
}
|
|
|
|
func captureCycleStdout(t *testing.T, run func()) string {
|
|
t.Helper()
|
|
origStdout := os.Stdout
|
|
r, w, err := os.Pipe()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
// Drain concurrently: a synchronous drain deadlocks once the command
|
|
// writes more than the 64KiB pipe buffer, and it cannot run at all when
|
|
// run() exits via Goexit.
|
|
done := make(chan string, 1)
|
|
go func() {
|
|
var b bytes.Buffer
|
|
_, _ = io.Copy(&b, r)
|
|
done <- b.String()
|
|
}()
|
|
|
|
os.Stdout = w
|
|
restored := false
|
|
restore := func() string {
|
|
if restored {
|
|
return ""
|
|
}
|
|
restored = true
|
|
_ = w.Close() // unblocks the drain goroutine
|
|
os.Stdout = origStdout // ALWAYS runs, including on Goexit/panic
|
|
out := <-done
|
|
_ = r.Close()
|
|
return out
|
|
}
|
|
defer restore()
|
|
|
|
run()
|
|
|
|
return restore()
|
|
}
|
|
|
|
// TestCaptureCycleStdoutRestoresOnFatal pins be-gh02: a callback that Goexits
|
|
// must still leave os.Stdout restored. Before the fix this left os.Stdout as an
|
|
// orphaned pipe whose read end the GC finalizer later closed, making every
|
|
// subsequent write in the binary fail with "write |1: broken pipe".
|
|
//
|
|
// The leaking callback runs on a manually created goroutine that calls
|
|
// runtime.Goexit() directly rather than a t.Run subtest calling t.Fatal: the
|
|
// unwind-and-run-deferred-calls mechanism is identical, but this keeps the test
|
|
// itself green instead of always reporting a deliberately-failed subtest.
|
|
func TestCaptureCycleStdoutRestoresOnFatal(t *testing.T) {
|
|
real := os.Stdout
|
|
done := make(chan struct{})
|
|
go func() {
|
|
defer close(done)
|
|
_ = captureCycleStdout(t, func() {
|
|
runtime.Goexit()
|
|
})
|
|
}()
|
|
<-done
|
|
|
|
if os.Stdout != real {
|
|
os.Stdout = real
|
|
t.Fatalf("captureCycleStdout leaked os.Stdout after a Goexit")
|
|
}
|
|
if _, err := os.Stdout.Write(nil); err != nil {
|
|
t.Fatalf("os.Stdout unusable after capture: %v", err)
|
|
}
|
|
}
|