beads/cmd/bd/wisp_gc_cascade_age_test.go
gascity-eddie[bot] b17005ad14
fix(wisp gc): apply the --age test to cascade children (follow-up to #5219) (#7599)
* fix(wisp gc): apply the --age test to cascade children

`bd mol wisp gc --age` promised, in its own help text, that a wisp counts as
abandoned when it "has not been updated within --age AND is not closed".
Parents were held to that contract; children reached through the cascade were
not. A child was deleted purely because something it transitively depended on
was old, so `--age` meant nothing for children at all.

Raising the threshold is not a workaround: with `--age 720h`, a step created a
moment ago is still destroyed when its parent is older than 720 hours.

Observed blast radius: a molecule slung seconds earlier went down with all nine
of its steps — 43 beads in a single run — and the agent's hook emptied
instantly. Two rigs of three were hit; the third survived only because a stop
order reached it first.

Steps already picked up have been covered by `isProtectedWisp` since #4430, but
a freshly created step is still `open`, and `open` maps to CategoryActive, which
that guard deliberately does not protect. This closes the remaining path.

Tests: cascade deletion of a stale parent no longer takes a fresh child, and
raising --age does not save one either.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(wisp gc): stop re-cascading at delete time; pin the age contract in the proxied test

The integration test update Steve asked for surfaced that the selection fix
alone was incomplete: findAbandonedWisps now respects --age for cascade
children, but both delete paths re-derived the cascade at delete time and
swept fresh children past that filter anyway:

- embedded path: deleteBatch was called with cascade=true
- proxied-server path: DeleteIssuesParams{Cascade: true} re-expanded via
  FindAllDependents in the domain layer

Both now delete exactly the set findAbandonedWisps selected — the selection
is the single place the --age contract lives.

Test cascade_sweeps_dependent_step_wisps is reshaped per review into
cascade_respects_age_for_dependent_step_wisps: a second child backdated past
the threshold IS swept (cascade still collects genuinely abandoned children),
the fresh child is absent from deleted AND still present in the wisps table
(the table-level check is what caught the delete-time re-cascade).

Verified against the shared dolt container (BEADS_TEST_PROXIED_SERVER=1):
TestProxiedServerWispGC all four subtests pass; TestWispGC* unit tests pass.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(wisp gc): age cascade children with wispIsAbandoned

Adopting #5219 onto main, which landed two changes after this PR was
written:

- #7246 (fixes #7236) moved the parents' age check onto
  wispIsAbandoned, so --age 0s still collects a wisp whose DATETIME(0)
  updated_at rounded up to half a second into the future. The PR's child
  check kept the raw now.Sub(updated_at) <= threshold skip, which
  re-opens #7236 for cascade children: under --age 0s a step closed in
  the same second as the gc was left behind, orphaned, while its
  abandoned parent was deleted. Children now take the parents'
  predicate, so "the same --age contract as parents" holds; positive
  thresholds behave exactly as before.
  TestWispGCCascadeChildAgesAtStoragePrecision pins it at storage
  precision and fails on the raw comparison.
- #5735 had already turned the delete-time cascade off on both gc
  routes (GH#4394), so the PR's second commit now carries only its
  proxied-test reshape. Main's delete-site comments gain that commit's
  reason alongside GH#4394: a cascade there would also sweep fresh
  children past the --age filter.

Also lists the PR's new wisp_gc_cascade_age_test.go in cmd/bd/BUILD.bazel,
which gazelle requires.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: mayor <6847071@gmail.com>
Co-authored-by: AB <6847071@gmail.com>

* docs(wisp gc): document the cascade's age policy; test it with a closed child

Review fixes for #5219, apply-fixes iteration 1.

- The 'bd mol wisp gc' help and the CHANGELOG now say what happens to
  the dependents of an abandoned wisp. They are deleted with it only if
  they meet --age themselves and are not live work, closed ones included
  even without --all. A dependent that is too young is spared, and both
  delete routes drop its edge to the deleted wisp, so an open one is
  collected once it ages out and a closed one is left for --all,
  --closed or bd purge: without --all the parent scan skips closed
  wisps.
- A comment by the child loop in findAbandonedWisps says dependents are
  exempt from the parent scan's not-closed clause, so a change that
  aligns the two loops does not quietly leave an abandoned molecule's
  finished steps behind.
- TestWispGCCascadeRespectsAge and the proxied subtest
  cascade_respects_age_for_dependent_step_wisps close their stale child.
  An open one was collected by the parent scan, so both passed with the
  cascade disabled. With the child closed, a mutant that skips every
  cascade child fails both.

docs/CLI_REFERENCE.md and docs/cli-reference/ are not regenerated: they
are built from the v1.2.2 pin in docs/cli-docs.pin.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: mayor <6847071@gmail.com>
Co-authored-by: AB <6847071@gmail.com>

---------

Co-authored-by: mayor <6847071@gmail.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com>
2026-10-16 09:49:28 +00:00

219 lines
7.9 KiB
Go

package main
import (
"context"
"testing"
"time"
"github.com/steveyegge/beads/internal/types"
)
// cascadeAgeReader is a minimal molReader covering only the calls
// findAbandonedWisps makes. The embedded nil interface makes any other call
// panic loudly rather than return a silent zero value.
type cascadeAgeReader struct {
molReader
issues []*types.Issue
children map[string]bool
}
func (r *cascadeAgeReader) SearchIssues(context.Context, string, types.IssueFilter) ([]*types.Issue, error) {
return r.issues, nil
}
func (r *cascadeAgeReader) GetBlockedIssues(context.Context, types.WorkFilter) ([]*types.BlockedIssue, error) {
return nil, nil
}
func (r *cascadeAgeReader) GetCustomStatusesDetailed(context.Context) ([]types.CustomStatus, error) {
return nil, nil
}
func (r *cascadeAgeReader) IsInfraTypeCtx(context.Context, types.IssueType) bool { return false }
func (r *cascadeAgeReader) FindWispDependentsRecursive(context.Context, []string) (map[string]bool, error) {
return r.children, nil
}
func (r *cascadeAgeReader) GetIssuesByIDs(_ context.Context, ids []string) ([]*types.Issue, error) {
want := make(map[string]bool, len(ids))
for _, id := range ids {
want[id] = true
}
var out []*types.Issue
for _, issue := range r.issues {
if want[issue.ID] {
out = append(out, issue)
}
}
return out, nil
}
// TestWispGCCascadeRespectsAge is the regression test for hq-k27y.
//
// `bd mol wisp gc --age` selected abandoned parents by age and then pulled in
// their transitive wisp dependents with no age test at all. A step created
// seconds ago was therefore destroyed because something it depended on was old.
//
// The consequence was not a stray bead: a patrol molecule slung moments earlier
// went down with all nine of its steps — 43 beads in one run — and the agent's
// hook emptied instantly. Two rigs of three were hit; the third survived only
// because a stop order reached it first.
//
// It also made the flag misleading in a way that punishes the obvious reaction:
// raising --age does not make the command safer, because the child's own age is
// never consulted. That is asserted separately below.
//
// GH#4430 already protects a step that has been picked up (in_progress/blocked/
// hooked map to CategoryWIP). A freshly created step is still `open`, and open
// maps to CategoryActive, which that guard deliberately does not protect — so
// the fresh-child path stayed open until this check.
func TestWispGCCascadeRespectsAge(t *testing.T) {
now := time.Now()
const threshold = time.Hour
staleParent := &types.Issue{
ID: "gc-stale-parent",
Status: types.StatusOpen,
UpdatedAt: now.Add(-24 * time.Hour),
}
// The molecule the patrol is working right now: created seconds ago,
// not yet picked up, so still open.
freshChild := &types.Issue{
ID: "gc-fresh-child",
Status: types.StatusOpen,
UpdatedAt: now.Add(-2 * time.Second),
}
// A child that really is abandoned must still be collected — the cascade
// exists for a reason and the fix must not disable it. It is closed so
// that only the cascade can reach it: without --all the parent scan passes
// over closed wisps, so an open stale child would be collected even with
// the cascade switched off.
staleChild := &types.Issue{
ID: "gc-stale-child",
Status: types.StatusClosed,
UpdatedAt: now.Add(-48 * time.Hour),
}
r := &cascadeAgeReader{
issues: []*types.Issue{staleParent, freshChild, staleChild},
children: map[string]bool{"gc-fresh-child": true, "gc-stale-child": true},
}
got, err := findAbandonedWisps(context.Background(), r, false, threshold, nil)
if err != nil {
t.Fatalf("findAbandonedWisps: %v", err)
}
collected := make(map[string]bool, len(got))
for _, issue := range got {
collected[issue.ID] = true
}
if collected["gc-fresh-child"] {
t.Errorf("fresh child %q was collected: a wisp updated %v ago must survive --age %v regardless of its parent's age (hq-k27y); collected=%v",
freshChild.ID, now.Sub(freshChild.UpdatedAt), threshold, collected)
}
if !collected["gc-stale-parent"] {
t.Errorf("stale parent %q must still be collected; collected=%v", staleParent.ID, collected)
}
if !collected["gc-stale-child"] {
t.Errorf("stale child %q must still be collected — the cascade must keep working for genuinely abandoned children; collected=%v", staleChild.ID, collected)
}
}
// TestWispGCRaisingAgeDoesNotSaveFreshChild pins the property that made the
// defect worse than it looked: before the fix, no value of --age protected a
// fresh child, so the natural mitigation ("use a bigger threshold") did
// nothing. After the fix a larger threshold is strictly more protective.
func TestWispGCRaisingAgeDoesNotSaveFreshChild(t *testing.T) {
now := time.Now()
for _, threshold := range []time.Duration{time.Hour, 24 * time.Hour, 720 * time.Hour} {
parent := &types.Issue{
ID: "gc-ancient-parent",
Status: types.StatusOpen,
UpdatedAt: now.Add(-2 * threshold),
}
child := &types.Issue{
ID: "gc-newborn",
Status: types.StatusOpen,
UpdatedAt: now.Add(-time.Second),
}
r := &cascadeAgeReader{
issues: []*types.Issue{parent, child},
children: map[string]bool{"gc-newborn": true},
}
got, err := findAbandonedWisps(context.Background(), r, false, threshold, nil)
if err != nil {
t.Fatalf("findAbandonedWisps(--age %v): %v", threshold, err)
}
for _, issue := range got {
if issue.ID == "gc-newborn" {
t.Errorf("--age %v still collected a wisp created 1s ago; the threshold must apply to cascade children", threshold)
}
}
}
}
// TestWispGCCascadeChildAgesAtStoragePrecision holds cascade children to the
// parents' age predicate, wispIsAbandoned, at Dolt's DATETIME(0) precision
// (#7236). A step closed at 12:00:00.7 is stored as 12:00:01, so a gc at
// 12:00:00.9 reads it 100ms in the future. --age 0s must still collect it with
// its stale parent; the raw now.Sub(updated_at) <= threshold skip that #7236
// replaced for parents reads -100ms and misses it, orphaning the step once its
// parent is deleted. --age 1h must spare it at that instant and collect it two
// hours later.
//
// The step is closed because under --age 0s the parent scan already collects
// every wisp it sees that is not closed, protected or an infra type, so only a
// wisp the scan passes over, such as a closed step without --all, reaches the
// cascade's own age check.
func TestWispGCCascadeChildAgesAtStoragePrecision(t *testing.T) {
base := time.Date(2026, 10, 10, 12, 0, 0, 0, time.UTC)
parent := &types.Issue{
ID: "gc-stale-parent",
Status: types.StatusOpen,
UpdatedAt: base.Add(-24 * time.Hour),
}
step := &types.Issue{
ID: "gc-closed-step",
Status: types.StatusClosed,
UpdatedAt: base.Add(700 * time.Millisecond).Round(time.Second), // 12:00:01
}
old := wispGCNow
t.Cleanup(func() { wispGCNow = old })
for _, tc := range []struct {
now time.Time
threshold time.Duration
wantStep bool
}{
{base.Add(900 * time.Millisecond), 0, true},
{base.Add(900 * time.Millisecond), time.Hour, false},
{base.Add(2 * time.Hour), time.Hour, true},
} {
wispGCNow = func() time.Time { return tc.now }
r := &cascadeAgeReader{
issues: []*types.Issue{parent, step},
children: map[string]bool{step.ID: true},
}
got, err := findAbandonedWisps(context.Background(), r, false, tc.threshold, nil)
if err != nil {
t.Fatalf("findAbandonedWisps(--age %s): %v", tc.threshold, err)
}
collected := make(map[string]bool, len(got))
for _, issue := range got {
collected[issue.ID] = true
}
if !collected[parent.ID] {
t.Errorf("findAbandonedWisps(--age %s) at %s: stale parent %q not collected; collected=%v",
tc.threshold, tc.now.Format("15:04:05.000"), parent.ID, collected)
}
if collected[step.ID] != tc.wantStep {
t.Errorf("findAbandonedWisps(--age %s) at %s, closed step updated_at 12:00:01: collected=%v, want %v",
tc.threshold, tc.now.Format("15:04:05.000"), collected[step.ID], tc.wantStep)
}
}
}