Skip to content

Copy fork history without stalling the server - #7249

Merged
ymichael merged 2 commits into
mainfrom
bb/fork-history-copy-thr_mb7ipbhx2t
Nov 9, 2026
Merged

ymichael merged 2 commits into
mainfrom
bb/fork-history-copy-thr_mb7ipbhx2t

Conversation

@ymichael

@ymichael ymichael commented Nov 7, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

copyForkSourceHistory copied a fork's inherited history in one immediate transaction on the event loop. copyStoredThreadEventsInTransaction handled each row from JS:

  1. read it with its full payload
  2. re-insert it with a one-off drizzle statement
  3. copy its retained outputs with another statement
  4. parse its payload for search indexing

On a real dev server, forking an imported copy of d5ej4e2gtv (39,486 inherited rows, 74 MB) blocked a concurrent GET /api/v1/projects for 4.6–5.7 s. Found in the Nov 7 timeline audit (S7).

What changed

Cheaper copy (@bb/db copyStoredThreadEventsInTransaction)

  • It now takes row metadata (StoredEventRowMetadata, a stored row without data). Rows are copied inside SQLite with batched INSERT … SELECT statements keyed by source id, so payloads never cross into JS. A missing source row fails the copy.
  • Rows that need JS still read their payload:
    • item/completed outputs whose stored size is over the truncation threshold go through the normal insert path, so legacy untruncated outputs are still truncated into a retained output.
    • Requests are still read for attachment ownership.
    • Request and message rows are still read for search segments.
  • Retained outputs (copyRetainedEventOutputs) and search segments (upsertThreadSearchSegmentBatch) are copied with one set-based statement per batch.
  • listStoredEventRowMetadata lists rows without payloads.

Sliced copy (copyForkSourceHistory, now async)

  • The selection reads metadata in 2,000-row pages.
  • The copy runs in time-bounded slices: 10-row batches, ~8 ms per immediate transaction, yielding to the event loop between slices. SQLite alone needs ~0.6 s to write d5ej4e2gtv's rows, so a single atomic transaction can't be short.
  • thread-create awaits it before the first dispatch, as before.

All-or-nothing across crashes

  • A fork that will copy history is created with historyCopy: "copying" in its pending startup context, in the same insert as the thread row. The last slice clears the mark in its own transaction, or a separate transaction clears it when there is nothing to copy.
  • While the mark is set:
    • Dispatch refuses the fork with 409 fork_history_copying.
    • Each slice requires the mark, an undeleted fork, and an unchanged latest sequence, otherwise it fails with 409 fork_history_changed.
    • Any copy failure deletes the fork through the existing create-failure path, now discardUnstartedThread.
  • The startup recovery sweep (interrupted-fork-history-copies) deletes any fork still marked through that same path.
  • What a client sees mid-copy:
    • The fork is listed with status pending (display starting), never as ready.
    • Its timeline shows a growing prefix of the inherited history.
    • A send gets the 409.
    • The usual events-appended notification at the end refreshes it.

No schema change: the mark lives in the existing threads.startup_context JSON. No wire, CLI or SDK changes.

How you verified

Real server (pnpm start:worktree on a fresh dev data dir)

  • Setup: imported d5ej4e2gtv's row and 75,019 events from my snapshot clone and attached a dev environment, then forked through the source CLI (env -u BB_CLI -u BB_SERVER_URL pnpm bb:dev thread fork).
  • Measurement: a probe timed GET /api/v1/projects every ~5 ms during the fork.
build concurrent request during the fork copy window
base p50 2–4 ms, max 4,646–5,685 ms (3 runs) one blocking transaction
this PR p50 6–8 ms, p99 ~55 ms, max 59–61 ms (2 runs) 5.3–7.2 s, server responsive
  • Parity: a fix fork and a base fork of the same source had identical rows (39,486, every column except ids), search segments (4,530), retained outputs, and outline (2,280 items). The latest timeline window (144 rows) matched except the createdAt of the provider-start error appended afterwards. Every fork, base and fix alike, later fails to start because the imported provider session doesn't exist on this machine.
  • Crash: I SIGKILLed the server while a fork held 8,020 of 39,486 rows with the mark set. The launcher restarted it, and the boot sweep logged Deleted forks whose history copy the previous server process left unfinished (discarded: 1). The fork then returned 404 to the API and CLI and was not listed.
  • Dispatch guard: POST /api/v1/threads/<fork>/send during the copy returned 409 fork_history_copying while bb thread show reported pending. The fork then completed normally.

Snapshot A/B (in-process, 2–3 alternating pairs, median of 3, load avg 8–17). "Longest block" is the maximum event-loop delay (monitorEventLoopDelay) during the copy:

source thread copied rows longest block ms (before → after) total copy ms (before → after)
d5ej4e2gtv 39,486 3463 → 36 3461 → 2565
6e9knccemi 11,008 1023 → 17 1022 → 728
u738kqjs29 5,525 797 → 21 796 → 390
ymhw6pktq4 4,667 618 → 17 615 → 345
kdrbtee92b 4,699 384 → 18 382 → 311
y6xhxw8t8w 4,411 548 → 17 546 → 292

Parity covered 45 threads (the 12 audit threads plus 40 recent threads with ≥1,000 events), 129,826 copied rows. The following were identical between base and fix:

  • forked rows (ids mapped to sequences)
  • retained outputs, search segments, attachment ownership and pruning-work rows
  • the fork's app timeline (cursor decoded, random-id tag excluded)
  • the fork's outline

Tests added, all failing before:

  • packages/db/test/data/retained-event-outputs.test.ts
    • 300 ordinary rows plus a retained output and a legacy untruncated output copy in fewer than 20 statements (608 before), with matching rows and the legacy output truncated into a retained output.
    • A missing source row fails the copy and copies nothing.
  • apps/server/test/services/threads/thread-fork-history.test.ts
    • The copy runs in slices that let the event loop run, matches the source, and clears the mark.
    • A write to the fork mid-copy fails it.
    • A crash simulated between slices leaves a marked partial fork; discardInterruptedForkHistoryCopies deletes it, and the fork's timeline returns 404.
    • A send to a marked fork returns 409 and appends nothing.

Commands:

pnpm exec turbo run typecheck lint --filter=@bb/db --filter=@bb/server
pnpm exec turbo run test --filter=@bb/db --filter=@bb/server -- test/public/public-thread-fork.test.ts test/services/threads/thread-fork-history.test.ts test/data/retained-event-outputs.test.ts test/data/events.test.ts test/data/event-ingestion-work.test.ts test/data/threads.test.ts test/threads/thread-create-seed-without-run.test.ts

AGENT GENERATED

🤖 Generated with Claude Code

ymichael and others added 2 commits November 7, 2026 13:00
Forking a thread copied its inherited history in one immediate
transaction on the event loop: every row was read into JS with its full
payload, re-inserted with a one-off statement, its retained outputs
copied with another, and its payload parsed for search indexing. Forking
d5ej4e2gtv (39.5k inherited rows) blocked the server for ~3 s.

Copy rows inside SQLite with batched INSERT ... SELECT statements keyed
by source id, so payloads never cross into JS. Only rows that need JS
still read their payload: completed outputs over the truncation size go
through the normal insert path, and requests and messages are read for
attachment ownership and search segments. Retained outputs are copied
with one set-based statement per batch.

SQLite alone needs ~0.6 s to write d5ej4e2gtv's rows, so the copy now
runs in time-bounded slices (25-row batches, ~20 ms per transaction)
that yield to the event loop, and selection reads metadata in 2,000-row
pages. The fork is new and undispatched while it copies; each slice
checks nothing else wrote to it, and any failure deletes the fork as
before. Readers in between see a prefix of the inherited history.

Snapshot A/B (3 alternating pairs, load avg 5-20), longest event-loop
block / total copy:
- d5ej4e2gtv (39,486 rows): 2995 -> 51-64 ms / 2993 -> 2098 ms
- u738kqjs29 (5,525 rows): 640 -> 27 ms / 639 -> 289 ms
- 6e9knccemi (11,008 rows): 803 -> 38 ms / 800 -> 576 ms
Forked rows, retained outputs, search segments, attachment ownership,
pruning work, timeline and outline are identical across 45 threads
(129,826 rows).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Slicing the copy meant a server crash mid-copy left an undispatched fork
holding part of the source history, and nothing cleaned it up.

A fork that will copy history is now created with historyCopy: "copying"
in its pending startup context, in the same insert as the thread row. The
last copy slice clears the mark in its own transaction. Until then:
- dispatch refuses the fork with 409 fork_history_copying;
- each slice requires the mark, so a fork deleted mid-copy stops copying;
- the startup recovery sweep deletes any fork still marked, through the
  same path a failed create uses.

Also batch each slice's search segments into one upsert, and shrink
slices to 10-row batches within ~8 ms so a concurrent request waits less.

Real server (pnpm start:worktree, imported d5ej4e2gtv, 39,486 copied rows,
fork through the source CLI), concurrent GET /api/v1/projects during the
copy: base max 4.6-5.7 s; after p50 6-8 ms, p99 ~55 ms, max ~60 ms. A
SIGKILL mid-copy left a marked fork with 8,020 rows; the restarted
server's boot sweep deleted it. Snapshot A/B longest event-loop block:
d5ej4e2gtv 3463 -> 36 ms, u738kqjs29 797 -> 21 ms; rows, retained
outputs, search segments, timeline and outline identical on 45 threads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael marked this pull request as ready for review November 9, 2026 18:26
@ymichael
ymichael merged commit 78e0e28 into main Nov 9, 2026
33 checks passed
@ymichael
ymichael deleted the bb/fork-history-copy-thr_mb7ipbhx2t branch November 9, 2026 18:31
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