Repository navigation
Copy fork history without stalling the server - #7249
Merged
Merged
Conversation
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Human comments
What was wrong
copyForkSourceHistorycopied a fork's inherited history in one immediate transaction on the event loop.copyStoredThreadEventsInTransactionhandled each row from JS:On a real dev server, forking an imported copy of d5ej4e2gtv (39,486 inherited rows, 74 MB) blocked a concurrent
GET /api/v1/projectsfor 4.6–5.7 s. Found in the Nov 7 timeline audit (S7).What changed
Cheaper copy (
@bb/dbcopyStoredThreadEventsInTransaction)StoredEventRowMetadata, a stored row withoutdata). Rows are copied inside SQLite with batchedINSERT … SELECTstatements keyed by source id, so payloads never cross into JS. A missing source row fails the copy.item/completedoutputs 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.copyRetainedEventOutputs) and search segments (upsertThreadSearchSegmentBatch) are copied with one set-based statement per batch.listStoredEventRowMetadatalists rows without payloads.Sliced copy (
copyForkSourceHistory, now async)thread-createawaits it before the first dispatch, as before.All-or-nothing across crashes
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.409 fork_history_copying.409 fork_history_changed.discardUnstartedThread.interrupted-fork-history-copies) deletes any fork still marked through that same path.pending(displaystarting), never as ready.events-appendednotification at the end refreshes it.No schema change: the mark lives in the existing
threads.startup_contextJSON. No wire, CLI or SDK changes.How you verified
Real server (
pnpm start:worktreeon a fresh dev data dir)env -u BB_CLI -u BB_SERVER_URL pnpm bb:dev thread fork).GET /api/v1/projectsevery ~5 ms during the fork.createdAtof 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.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.POST /api/v1/threads/<fork>/sendduring the copy returned409 fork_history_copyingwhilebb thread showreportedpending. 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: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:
tagexcluded)Tests added, all failing before:
packages/db/test/data/retained-event-outputs.test.tsapps/server/test/services/threads/thread-fork-history.test.tsdiscardInterruptedForkHistoryCopiesdeletes it, and the fork's timeline returns 404.Commands:
🤖 Generated with Claude Code