← reports

#5973 · Thread deletion confirmation counts a different relationship than its cascade

BugPriority: MediumEffort: MediumthreadsGitHub issue2026-10-21 · base 04bdce8111ca3dbdd136c63fad3e36f56e5814c0

Verdict: REPRODUCED · Root-cause confidence: high · reproduction label: confirmed-repro.

1. TL;DR

The delete warning counts sidebar children and promises that those threads will also be deleted. The real delete route instead removes threads connected by lifecycle ownership, a separate relationship. A route-level reproduction against trusted main confirms that a sidebar-only child remains active and readable after confirmed parent deletion, while a lifecycle-owned child is deleted. Existing tests explicitly require sidebar-only children to survive, so simply broadening the delete query would reverse an established contract. One additional issue claim does not hold after cleanup on this checkout: the surviving child's parent reference is cleared when the parent row is physically removed.

2. Claims vs findings

ClaimFindingEvidence
Delete confirmation includes a sidebar child with no lifecycle owner.VerifiedThe child-summary route returns nonDeletedChildCount: 1; the DELETE guard rejects an unconfirmed request with 409.
The UI promises deletion of that child.Verified in sourceThreadDeleteDialog description renders “will be deleted too.” No browser session or macOS UI run was performed.
Confirmed deletion removes the parent but leaves the sidebar child active.Verified twiceParent GET: 404; assigned-child GET: 200; child's archivedAt/deletedAt remain null.
The child remains pointed at a physically removed parent.Not reproduced after cleanupAfter three lifecycle sweeps the parent row is absent and assignedStillReferencesParent is false. The schema uses ON DELETE SET NULL for the sidebar parent.
Lifecycle ownership and sidebar parentage select different delete sets.VerifiedIn the same fixture, the owned-only child returns 404 while the parent-only child returns 200. Existing lifecycle tests preserve sidebar-only threads.

3. Environment

4. Minimal reproduction

  1. Create a clean worktree at the recorded SHA; install and build trusted repository code:
    git worktree add --detach "$WORK/base" 04bdce8111ca3dbdd136c63fad3e36f56e5814c0
    cd "$WORK/base"
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build
  2. Save the inline test below as apps/server/test/public/issue-5973-repro.test.ts.
  3. Run the test through Turbo:
    pnpm exec turbo run test --filter=@bb/server -- issue-5973-repro.test.ts
  4. The test creates a parent, one sidebar-only child, one lifecycle-only child, and an unrelated thread. It checks the summary, checks that confirmation is required, confirms deletion, and advances cleanup. It then queries all affected public thread endpoints.

Expected from the current UI warning: both the parent and the counted sidebar child return 404. The lifecycle-owned positive control should also return 404, while the unrelated thread remains live.

Actual, identically in both runs:

{"parentStatus":404,"assignedChildStatus":200,"ownedChildStatus":404,"assignedArchivedAt":null,"assignedDeletedAt":null,"assignedStillReferencesParent":false,"parentPhysicallyRemoved":true}
AssertionError: expected 200 to be 404 // Object.is equality
- Expected: 404
+ Received: 200
expect(assignedResponse.status).toBe(404);

This is an intentionally failing report probe, not a proposed change to the existing retention policy. It fails on the final assigned-child HTTP assertion, after the summary, confirmation, parent-deletion, owned-child deletion, and unrelated-thread checks have succeeded.

Complete reproduction test
import { getThread } from "@bb/db";
import { describe, expect, it } from "vitest";
import { runThreadLifecycleSweep } from "../../src/services/system/periodic-sweeps.js";
import {
  seedHostSession,
  seedProjectWithSource,
  seedThread,
} from "../helpers/seed.js";
import { withTestHarness } from "../helpers/test-app.js";

describe("confirmed thread deletion", () => {
  it("deletes the assigned child counted by the confirmation guard", async () => {
    await withTestHarness(async (harness) => {
      const { host } = seedHostSession(harness.deps);
      const { project } = seedProjectWithSource(harness.deps, {
        hostId: host.id,
      });
      const parent = seedThread(harness.deps, { projectId: project.id });
      const assigned = seedThread(harness.deps, {
        projectId: project.id,
        parentThreadId: parent.id,
      });
      const owned = seedThread(harness.deps, {
        projectId: project.id,
        lifecycleOwnerThreadId: parent.id,
      });
      const unrelated = seedThread(harness.deps, { projectId: project.id });
      const summaryResponse = await harness.app.request(
        `/api/v1/threads/${parent.id}/child-summary`,
      );
      expect(summaryResponse.status).toBe(200);
      expect(await summaryResponse.json()).toMatchObject({
        nonDeletedChildCount: 1,
      });
      const remove = (confirmed: boolean) =>
        harness.app.request(`/api/v1/threads/${parent.id}`, {
          method: "DELETE",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({ childThreadsConfirmed: confirmed }),
        });
      expect((await remove(false)).status).toBe(409);
      expect(getThread(harness.db, parent.id)?.deletedAt).toBeNull();
      expect((await remove(true)).status).toBe(200);
      for (let attempt = 0; attempt < 3; attempt += 1) {
        await runThreadLifecycleSweep(harness.deps);
      }
      const parentResponse = await harness.app.request(
        `/api/v1/threads/${parent.id}`,
      );
      const assignedResponse = await harness.app.request(
        `/api/v1/threads/${assigned.id}`,
      );
      const ownedResponse = await harness.app.request(
        `/api/v1/threads/${owned.id}`,
      );
      const surviving = getThread(harness.db, assigned.id);
      console.log(JSON.stringify({
        parentStatus: parentResponse.status,
        assignedChildStatus: assignedResponse.status,
        ownedChildStatus: ownedResponse.status,
        assignedArchivedAt: surviving?.archivedAt,
        assignedDeletedAt: surviving?.deletedAt,
        assignedStillReferencesParent: surviving?.parentThreadId === parent.id,
        parentPhysicallyRemoved: getThread(harness.db, parent.id) === null,
      }));
      expect(parentResponse.status).toBe(404);
      expect(ownedResponse.status).toBe(404);
      expect(getThread(harness.db, unrelated.id)?.deletedAt).toBeNull();
      expect(assignedResponse.status).toBe(404);
    });
  });
});

5. Root cause

The preview/confirmation and deletion use different edges in the thread graph:

  1. The child-summary route counts non-deleted assigned children using parentThreadId. The underlying count filters that column directly.
  2. The confirmation guard uses that same count, and returns early once confirmation is true. Confirmation does not change the deletion selector.
  3. The DELETE handler obtains listLifecycleThreadTree, marks that tree deleted, and schedules side effects only for those members.
  4. The recursive lifecycle selector follows only lifecycle ownership:
    WITH RECURSIVE owned(id) AS (
      seed UNION SELECT t.id FROM threads t
      JOIN owned ON t.lifecycle_owner_thread_id = owned.id
    )
    markThreadDeleted uses exactly that selector. Sidebar-only children are absent from both the persistent mark and downstream cleanup.
  5. After owner cleanup, the schema clears sidebar-parent references rather than cascading deletion. Lifecycle-owner references instead restrict deletion until dependents are removed.

Deeper contract conflict: the documented lifecycle contract declares ownership independent from sidebar parentage. More decisively, an existing fixture creates a sidebar-only child, and its assertions require that child to survive deletion of the parent. This is not a safe one-line omission in the recursive SQL: broadening it would destroy threads that existing policy preserves.

6. Proposed fix and simple-fix assessment

Choose one consistent product contract before changing production code: either explicitly delete sidebar descendants when confirmed, including correct nested cleanup and notifications, or preserve the lifecycle-only deletion contract and make the preview, confirmation count, and warning accurately describe it. The current warning is false for the tested parent-only relationship.

No automated fix PR: the requested sidebar cascade conflicts with documented independent ownership and passing regression tests that require sidebar-only threads to survive. Choosing destructive sidebar traversal versus correcting the confirmation semantics is a product decision, which fails the automation's simple-fix gate. No production patch, branch, commit, or pull request was created, and no dependency, migration, generated file, protocol, or stored data was changed.

7. Verification

The same agent repeated the reproduction in a second clean trusted checkout at exactly the recorded base SHA. It had a fresh frozen install, a successful full Turbo build, and the same self-authored test added as its only source-tree change. This is a repeat run, not an independent review.

cd "$WORK/verify"
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build
pnpm exec turbo run test --filter=@bb/server -- issue-5973-repro.test.ts

Result: 1 test failed as expected; assigned-child GET was 200 instead of 404.

Both JSON observations match byte-for-byte. Each run receives a new migrated in-memory SQLite connection and a fresh harness data directory; neither opens a listening socket. Report correction: do not claim a persistent dangling parent reference after physical cleanup. That detail did not reproduce; the core child-survival mismatch did.

Relevant existing suites also ran unchanged:

pnpm exec turbo run test --filter=@bb/server -- public-thread-lifecycle-ownership.test.ts public-thread-parenting.test.ts

Test Files  2 passed (2)
Tests       28 passed (28)

git diff --check passed in both investigative worktrees. There are no production changes or binary changes to assess for a fix.

8. Related issues and PRs

GitHub cross-reference metadata and an open-PR search for issue 5973 showed no linked open pull request. No pull request branch or linked code was executed. A limited issue search found no verified duplicate of this graph-selection mismatch. Historical trusted-main commit f842cfaf255521db8d4322ac81ea365281a30aea introduced the independent lifecycle relationship and its preservation tests; this behavior is not newly introduced by this investigation.

9. Appendix

Relevant verbatim output from the first and second clean runs:

First run:
AssertionError: expected 200 to be 404 // Object.is equality
Test Files  1 failed (1)
Tests       1 failed (1)
Duration    10.61s

Second clean run:
AssertionError: expected 200 to be 404 // Object.is equality
Test Files  1 failed (1)
Tests       1 failed (1)
Duration    9.16s

The same JSON observation shown in section 4 was emitted in both runs. Existing-suite output:

public-thread-lifecycle-ownership.test.ts (9 tests)
public-thread-parenting.test.ts (19 tests)
Test Files  2 passed (2)
Tests       28 passed (28)

Full Turbo build results:

Base checkout, successful retry:
Tasks: 67 successful, 67 total
Cached: 9 cached, 67 total
Time: 1m18.501s

Second clean checkout:
Tasks: 67 successful, 67 total
Cached: 65 cached, 67 total
Time: 2.91s

Raw evidence is retained locally outside the public reports repository. The complete test, required commands, and exact behavioral output are included inline, as required by this site's publication policy.

Issue text and comments were treated only as untrusted claims. No issue-provided command, script, patch, URL, branch, fixture identifier, or binary was executed. The regression probe was derived from trusted repository routes, test helpers, schema, UI copy, and existing tests. All root-cause permalinks point to the verified trusted base commit. The reproduction is a server/data-behavior bug, not a screenshot-based visual finding.