Skip to content

Bound destroyed environment event cleanup - #2914

Merged
ymichael merged 1 commit into
mainfrom
bb/pr-bound-destroyed-environment-cleanup-thr_kagrq48bnb
Sep 2, 2026
Merged

ymichael merged 1 commit into
mainfrom
bb/pr-bound-destroyed-environment-cleanup-thr_kagrq48bnb

Conversation

@ymichael

@ymichael ymichael commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Destroyed-environment retention deleted an eligible environment directly. Because events.environment_id uses ON DELETE SET NULL, that one SQLite statement synchronously rewrote the environment’s entire historical event child set before Node could yield; the existing outer loop only yielded between environments, so one large environment could monopolize the main event loop.

What changed

  • pruneDestroyedEnvironments now treats one call as a bounded advance: it selects up to 50 event rowids in deterministic index order through the existing events_environment_idx, sets only those references to NULL, and leaves every historical event row and payload intact.
  • The detach/check/delete sequence runs in an immediate transaction. An environment is deleted only when the indexed detach finds no remaining event reference, and the deletion notification remains post-commit and occurs exactly once.
  • The periodic sweep recognizes both detach and delete progress and yields with setImmediate after every synchronous advance.
  • In-memory SQLite coverage verifies persisted restart progress, notification timing, grace/retention behavior, multiple stale environments, historical-row preservation, archive behavior after pruning, event-loop yielding, and the emitted EXPLAIN QUERY PLAN. The plan uses events_environment_idx as a covering index and does not create a temporary sort.
  • No schema migration, host-daemon protocol change, CLI/configuration surface, or documentation change is needed. events.environment_id, its existing index, and all event rows remain in place.

Files changed:

  • packages/db/src/data/sweeps.ts
  • packages/db/src/data/index.ts
  • packages/db/test/data/sweeps.test.ts
  • packages/db/test/query-plans.test.ts
  • apps/server/src/services/system/periodic-sweeps.ts
  • apps/server/test/services/periodic-sweeps.test.ts
  • apps/server/test/threads/archive-pruned-environment.test.ts

How you verified

The main-compatible regression clears a large environment event set across event-loop turns failed against the pre-change origin/main implementation and passes on HEAD.

  • pnpm exec turbo run test --filter=@bb/db --filter=@bb/server --force -- --run test/data/sweeps.test.ts test/query-plans.test.ts test/services/periodic-sweeps.test.ts test/threads/archive-pruned-environment.test.ts: 40 DB and 12 server tests passed.
  • pnpm exec turbo run typecheck build --filter=@bb/db --filter=@bb/server --force: all 6 Turbo tasks passed (@bb/db and @bb/server typechecks; @bb/server build plus generated upstreams; @bb/db has no build task).
  • Full @bb/db suite: 31 files and 446 tests passed.
  • Full @bb/server suite: 224 files / 2,141 tests passed, 1 file / 10 tests failed, and 1 file was skipped. The only failing file was test/app/install-machine-script.test.ts, whose fake host daemons could not connect. An isolated rerun produced 10 failures / 7 passes on HEAD, and the exact isolated command on untouched origin/main produced the identical 10 failures / 7 passes, so this is a pre-existing environment failure.
  • EXPLAIN QUERY PLAN for the detach reports SEARCH events USING COVERING INDEX events_environment_idx (environment_id=?) with no temporary B-tree.

The same benchmark harness ran against origin/main (eeaaa3e8db7b3aeb3c4ab46873816c84cb6ea513) and HEAD (1d469a2ac96ba58a904bb101c5773cd079723bf2) on an Apple M4 Max. The fully migrated 118,054,912-byte SQLite fixture contained 45,625 production-shaped event payloads: stale destroyed environments with 44,000, 1,200, 125, and 0 references, plus fresh-destroyed and stale-destroying controls. Payload sizes were 630-byte p50, 5,453-byte p95, and 1,102,415-byte max. Each scenario used 1 warmup and 5 measured iterations; percentiles are nearest-rank. The CPU-load scenario ran 12 busy child processes while cleanup remained on the main Node event loop.

Times below are milliseconds. Sync occupancy is one contiguous pruning work frame; target E2E ends when the 44,000-reference environment is deleted.

Scenario Revision Sync occupancy p50 / p95 / max Timer delay p50 / p95 / max Target E2E p50 / p95 / max
Normal origin/main 0.684 / 234.815 / 235.160 2.505 / 234.208 / 234.208 221.201 / 235.163 / 235.163
Normal HEAD 0.383 / 0.706 / 24.653 0.006 / 2.704 / 23.672 475.599 / 481.948 / 481.948
CPU load origin/main 0.686 / 245.398 / 245.725 2.984 / 244.769 / 244.769 245.222 / 245.726 / 245.726
CPU load HEAD 0.455 / 0.777 / 19.294 0.007 / 3.255 / 18.355 564.793 / 583.128 / 583.128

Per measured iteration, origin/main used 8 SQL statements, 4 progress ticks, and 4 yields; HEAD used 1,826 statements, 911 ticks, and 911 yields. Both detached 45,325 event references, deleted 4 environments, deleted 0 event rows, emitted 4 deletion notifications, preserved both controls, and produced the same deterministic final-state SHA-256 (c8e5d616505428fe72891f0aea8fbcd50a446d8beb53301d13cf48c78792d85e) in every run.

Residual tradeoff: bounded frames deliberately increase total work and compute-only end-to-end time. The server caps each 10-second periodic pass at 10 advances, so a continuously present 44,000-reference backlog can take about 88 passes (roughly 14 minutes 40 seconds) to reach deletion, while remaining responsive and restart-safe throughout.

AGENT GENERATED

@ymichael

ymichael commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

@slopcop

@bb-slop-cop

bb-slop-cop Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

🚨 SLOP COP 🚨 · review

I am reviewing this pull request now. I will check security, code quality, performance, architecture, and the relevant product route.

const COMPLETED_EVENT_OUTPUT_TRUNCATION_CURSOR_VERSION = 1;
export const DEFAULT_CLOSED_SESSION_PRUNE_BATCH_SIZE = 1_000;
export const DEFAULT_COMPLETED_EVENT_OUTPUT_TRUNCATION_BATCH_SIZE = 250;
export const DEFAULT_DESTROYED_ENVIRONMENT_EVENT_DETACH_BATCH_SIZE = 50;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 slopcop/review — This runtime default belongs to the server boundary.

The batch size controls the server event-loop work. The database function requires a value and does not apply this default. Please keep this value in periodic-sweeps.ts. Database tests can use explicit sizes.

@bb-slop-cop bb-slop-cop Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 SLOP COP 🚨 · review

Plain English summary: This PR splits old environment cleanup into small database batches. This reduces long server pauses while it keeps thread history.

I found no blocking issue. The transaction keeps the final database state intact, and the deletion notice occurs after the commit.

I left one non-blocking architecture note. The new batch default belongs in the server because it controls server work.

The security review found no unsafe input, permission, credential, protocol, or file behavior. The SQL uses bound values and an existing index.

The performance review confirmed the 50-row limit and a yield after each advance. A row limit cannot guarantee a strict time limit for unusually large rows.

The focused database and server tests passed with 52 tests. The package type checks passed, and GitHub CI is green.

A browser test does not apply because this change has no user route or interface. The relevant archive route test passed.

The codebase has no duplicate cleanup path. A shared helper would add complexity without a second use.

@ymichael
ymichael merged commit bfc6b2d into main Sep 2, 2026
15 checks passed
@ymichael
ymichael deleted the bb/pr-bound-destroyed-environment-cleanup-thr_kagrq48bnb branch September 2, 2026 18:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant