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>
This commit is contained in:
gascity-eddie[bot] 2026-10-16 09:49:28 +00:00 • committed by GitHub
commit b17005ad14
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 284 additions and 17 deletions

View file

@ -718,6 +718,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
negative duration and fails, even though `--age 0s`'s own contract is
that every wisp qualifies. `ageThreshold <= 0` now bypasses the clock
comparison entirely (#7236).
- **`bd mol wisp gc` no longer deletes a fresh step because a wisp it
depends on is abandoned.** The GC applied `--age` only to the wisps it
selected directly, then deleted their dependents at any age as long as
they were not live work, so a step created seconds earlier went with an
old wisp it depended on, and raising `--age` did not help. A dependent
now has to meet `--age` itself, by the same rule as the wisp it depends
on (including the #7236 rounding fix). One that is too young is spared
and loses its edge to the deleted wisp: an open one is collected once it
ages out, a closed one is left for `--all`, `--closed` or `bd purge`,
since without `--all` the GC reaches a closed wisp only as the dependent
of an abandoned one (#5219).
- `bd create --parent` works on the HTTP backend: the create role mints the
`<parent>.<n>` child id (and inherits the parent's labels) inside the
create on every route, instead of the CLI reserving it through a raw

View file

@ -1277,6 +1277,7 @@ go_test(
"where_test.go",
"wisp_abandoned_test.go",
"wisp_gc_active_embedded_test.go",
"wisp_gc_cascade_age_test.go",
"wisp_gc_purge_closed_embedded_test.go",
"wisp_proxied_integration_test.go",
"wisp_test.go",

View file

@ -621,6 +621,12 @@ A wisp is considered abandoned if:
are age-reclaimable. If the blocked set or the custom-status list cannot be
read, the GC aborts rather than risk reclaiming live steps.
Wisps that depend on an abandoned wisp are deleted with it, closed ones
included even without --all, but only if they too haven't been updated in
--age duration and are not live work. A dependent that is too young is
spared and loses its edge to the deleted wisp: an open one is collected once
it ages out, a closed one only by --all, --closed or 'bd purge'.
Abandoned wisps are deleted without creating a digest. Use 'bd mol squash'
if you want to preserve a summary before garbage collection.
@ -810,10 +816,11 @@ func runWispGC(cmd *cobra.Command, args []string) error {
ids[i] = issue.ID
}
// Cascade must stay OFF here too. findAbandonedWisps has already expanded
// dependents and kept only the unprotected ones, so a deleteBatch cascade
// would re-expand from that set to ALL transitive dependents — including
// blocked/in-progress steps that isProtectedWisp just excluded (GH#4394's
// protection is only enforced in the pre-filter; cascade bypasses it).
// dependents and kept only the unprotected ones that meet --age, so a
// deleteBatch cascade would re-expand from that set to ALL transitive
// dependents — including blocked/in-progress steps that isProtectedWisp
// just excluded (GH#4394's protection is only enforced in the pre-filter;
// cascade bypasses it) and fresh steps the --age check just spared.
// Without cascade the list is deleted exactly as filtered and live
// dependents are orphaned (edges dropped, is_blocked recomputed).
if err := deleteBatch(nil, ids, true, false, false, jsonOutput, false, nil, "wisp gc"); err != nil {
@ -912,6 +919,9 @@ func findAbandonedWisps(ctx context.Context, r molReader, cleanAll bool, ageThre
for _, issue := range abandoned {
abandonedSet[issue.ID] = true
}
// Dependents skip the parent scan's not-closed clause: an
// abandoned molecule's finished steps go with it, even without
// --all.
for _, child := range childIssues {
if abandonedSet[child.ID] {
continue
@ -922,6 +932,12 @@ func findAbandonedWisps(ctx context.Context, r molReader, cleanAll bool, ageThre
if isProtectedWisp(child, blockedSet, protectedStatuses) {
continue
}
// Children are held to the same --age contract as parents. One
// spared here is detached when its parent is deleted, so a
// closed one is left for --all, --closed or bd purge.
if !wispIsAbandoned(now, child.UpdatedAt, ageThreshold) {
continue
}
abandoned = append(abandoned, child)
}
}

View file

@ -0,0 +1,219 @@
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)
}
}
}

View file

@ -263,21 +263,29 @@ func TestProxiedServerWispGC(t *testing.T) {
}
})
t.Run("cascade_sweeps_dependent_step_wisps", func(t *testing.T) {
t.Run("cascade_respects_age_for_dependent_step_wisps", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "wgc")
parentWisp := bdProxiedCreate(t, bd, p.dir, "Abandoned parent wisp", "--ephemeral")
childWisp := bdProxiedCreate(t, bd, p.dir, "Fresh child wisp", "--ephemeral")
staleChild := bdProxiedCreate(t, bd, p.dir, "Stale child wisp", "--ephemeral")
freshChild := bdProxiedCreate(t, bd, p.dir, "Fresh child wisp", "--ephemeral")
// Closed so that only the cascade can collect it: without --all the
// parent scan passes over closed wisps.
if out, err := bdProxiedRun(t, bd, p.dir, "close", staleChild.ID); err != nil {
t.Fatalf("bd close: %v\n%s", err, out)
}
db := openProxiedDB(t, p)
if _, err := db.Exec(
"INSERT INTO wisp_dependencies (id, issue_id, depends_on_wisp_id, type, created_at, created_by) VALUES (UUID(), ?, ?, ?, NOW(), 'test')",
childWisp.ID, parentWisp.ID, "blocks"); err != nil {
t.Fatalf("plant child->parent wisp edge: %v", err)
for _, childID := range []string{staleChild.ID, freshChild.ID} {
if _, err := db.Exec(
"INSERT INTO wisp_dependencies (id, issue_id, depends_on_wisp_id, type, created_at, created_by) VALUES (UUID(), ?, ?, ?, NOW(), 'test')",
childID, parentWisp.ID, "blocks"); err != nil {
t.Fatalf("plant child->parent wisp edge: %v", err)
}
}
if _, err := db.Exec("UPDATE wisps SET updated_at = ? WHERE id = ?",
time.Now().UTC().Add(-2*time.Hour), parentWisp.ID); err != nil {
t.Fatalf("backdate parent wisp: %v", err)
if _, err := db.Exec("UPDATE wisps SET updated_at = ? WHERE id IN (?, ?)",
time.Now().UTC().Add(-2*time.Hour), parentWisp.ID, staleChild.ID); err != nil {
t.Fatalf("backdate parent and stale child wisps: %v", err)
}
out, err := bdProxiedRun(t, bd, p.dir, "mol", "wisp", "gc", "--age", "1h", "--json")
@ -297,8 +305,19 @@ func TestProxiedServerWispGC(t *testing.T) {
if !cleaned[parentWisp.ID] {
t.Errorf("expected abandoned parent %s cleaned", parentWisp.ID)
}
if !cleaned[childWisp.ID] {
t.Errorf("expected dependent child %s cascaded even though it's not itself old", childWisp.ID)
if !cleaned[staleChild.ID] {
t.Errorf("expected stale dependent child %s cascaded", staleChild.ID)
}
if cleaned[freshChild.ID] {
t.Errorf("fresh child %s must survive gc despite stale parent, deleted: %v", freshChild.ID, got.Deleted)
}
var count int
if err := db.QueryRow("SELECT COUNT(*) FROM wisps WHERE id = ?", freshChild.ID).Scan(&count); err != nil {
t.Fatalf("query fresh child wisp: %v", err)
}
if count != 1 {
t.Errorf("expected fresh child %s to remain in wisps table", freshChild.ID)
}
})

View file

@ -182,8 +182,9 @@ func runWispGCProxiedServer(ctx context.Context, dryRun bool, ageThreshold time.
res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (domain.DeleteIssuesResult, string, error) {
// Cascade must stay OFF: findAbandonedWisps already expanded dependents
// and kept only unprotected ones; a cascade here re-expands to ALL
// transitive dependents, bypassing that protection (GH#4394).
// and kept only unprotected ones that meet --age; a cascade here
// re-expands to ALL transitive dependents, bypassing that protection
// (GH#4394) and sweeping fresh children past the --age filter.
// Mirrors runWispGC in wisp.go.
res, err := uw.IssueUseCase().DeleteIssues(ctx, domain.DeleteIssuesParams{
IDs: ids,