Skip to content

Move archived threads to cold storage from Storage & retention, with a thread.delete_finalize hook, export and import - #7107

Merged
ymichael merged 16 commits into
mainfrom
bb/cold-history-tier
Nov 23, 2026
Merged

ymichael merged 16 commits into
mainfrom
bb/cold-history-tier

Conversation

@ymichael

@ymichael ymichael commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

bb.db grows without bound. Archiving hides a thread but keeps every event row, index entry and page, and on the maintainer's install 99% of the events in a 10.9 GB database belong to archived threads. Storage & retention's delete-after is the only way out, and it loses the history. Reports of 4–11.6 GB databases: #5730, #5005, #6835, #5270, #5192.

What changed

Archived threads can move out of bb.db into cold storage (files) and come back later. Core adds one mechanism, a hook that lets a plugin hold the end of a thread's delete, plus the thread file format, export and import. Deciding which threads to move, keeping the files, and restoring them is plugin policy, and lives in the Storage & retention plugin.

  • thread.delete_finalize hook (bb.experimental_hooks.on("thread.delete_finalize", …)). Deleting a thread hides it, then the thread-purge sweep removes its rows. The sweep asks the hook before it starts on a thread. The context is { threadId, projectId }.
    • proceed lets the removal start. wait keeps the rows, and core asks again about every 10 seconds and after every restart.
    • A throw, a timeout or an unknown answer counts as wait. During a plugin reload the old instance is already disposed, so its answer fails and counts as wait too.
    • A disabled or uninstalled plugin is not asked, so its threads are removed without a copy.
    • Nothing is removed while the startup load pass is still registering plugins (PluginHookProvider.isLoadingPlugins), so a restart can't remove a thread before its plugin is back.
    • Core asks until the removal starts. Migration 0168_thread_purge_started adds thread_purges.started_at, set at that point, and core never asks about that thread again.
    • A thread a plugin is waiting on is skipped for the rest of that pass, so it doesn't block the deletes queued behind it.
    • recheck("thread.delete_finalize") schedules nothing, since every pass already asks.
  • Export and import (GET /threads/:id/export, POST /threads/import, SDK threads.experimental_export / experimental_import, bb thread export / import). One zstd JSONL file per thread: a header line, the thread's rows (thread, plugin metadata, tabs, prompt history, search segments, outline, dynamic context file states), every event in order with its retained outputs, and its attachments. A seek table sits in a skippable frame.
    • Export also works on a deleted thread until its removal starts, and answers 409 thread_being_purged after that. It holds the removal while it runs.
    • Import only brings back a deleted thread. It answers 409 thread_exists for a thread that still exists and never touches it.
    • Import recreates the thread in a fixed order. The thread row goes in hidden with a purge queued, then its rows, attachments and events. One transaction then unhides it, cancels the purge and restarts an archived thread's archive clock. An import that fails or is cut off is cleaned up by that purge; no separate recovery state is needed.
    • A recreated thread counts as still having its storage (storage_deleted_at is cleared), so deleting it later still deletes its host storage. It is queued for pruning. Links to environments and sections that aren't on this server are dropped, and so are links to threads that aren't on this server or are deleted when the import finishes, so a deleted thread's purge never waits on a restored one.
    • Import claims the attachments it reuses before restoring them, so attachment GC can't delete them mid-import.
    • Import also answers 409 while the thread is still being deleted or while another import or export of it runs, 404 when the project isn't on this server, and 400 for a file it can't read: a damaged seek table or frame, missing attachment parts, rows from another thread or project, or a thread row that won't insert. It reads every format version from 1 up to its own and refuses only newer ones.
  • Storage & retention plugin: cold storage. The "Move archived threads to cold storage" policy (coldStoreAfterDays; bb storage retention --cold-store-after <days|never>) moves archived, unpinned, idle threads that no other thread points at, 50 per hourly run.
    • A move refuses a thread that a live thread points at as parent, source or lifecycle owner, and names those threads. bb's delete takes children and lifecycle dependents along, and only the moved thread gets a file, so moving a parent would otherwise remove its children for good. The hourly run and bb storage cold-store share this check. The move's delete passes childThreadsConfirmed: false, so a child created after the check makes bb refuse the delete.
    • A move records the thread in the plugin's SQLite database (metadata and the threads it points at as parent, source or lifecycle owner), then calls threads.delete. Moving a thread that already has an entry resets it, so the plugin always writes a fresh file.
    • On thread.delete_finalize the plugin answers wait and exports in the background. It writes the file to its own folder, <dataDir>/plugins/bb--storage-retention/cold-storage/<threadId>.jsonl.zst (via a .partial file and a rename), records its size, then answers proceed. Each file is an ordinary thread file, so bb thread import <file> also brings it back.
    • The panel shows cold storage as one row, like a machine: thread count, total size, when the last thread moved and how many are still moving. It appears once something is stored or the policy is on. Clicking it opens its own page (storage/cold-storage, with an "All storage" back link) with a title search and the list, 50 rows at a time. "Show 50 more" pages by a {storedAt, threadId} cursor and appends, so it stays stable while threads move in and out. A change reloads only the first page plus totals and merges them into what's shown; reloads are debounced, so an hourly run moving 50 threads causes one. Each row has Restore and Delete. Restore first brings back the cold-stored threads the thread points at, so those links survive, then calls threads.experimental_import and removes the file.
    • New CLI commands: bb storage cold-store, cold-list (--search, --limit, --after <threadId>), restore and cold-delete.
    • New RPC methods: coldThreads({projectId, search, limit, after}), which returns threads, hasMore, totalCount, totalBytes, movingCount and lastStoredAt, plus restoreColdThread, which returns {threadId, restoredThreadIds}, and deleteColdThread. Search matches titles literally (% and _ are escaped).
    • A move whose delete fails is forgotten at once. A move whose thread was removed without a copy (the plugin was off) is forgotten on the next run, with a warning. An entry whose thread is back in bb (brought back with bb thread import, or by a Restore cut off before its cleanup) is dropped on the next run, and Restore on it only drops it.
  • Removed from the earlier version of this PR: the core saved_threads table, the thread-save sweep and its startup recovery, the /threads/:id/save and /saved-threads routes, the SDK experimental_save / listSaved / restoreSaved / deleteSaved methods, bb thread save and bb thread saved, the Settings → Archived threads section, the savedThreads experiment, and import merging into a live thread.
  • Other changes:
    • @get-bb/plugin-sdk goes to 0.6.189 for the hook types, and the plugin requires it.
    • No HOST_DAEMON_PROTOCOL_VERSION change.
    • The purge sweep keeps the shared startPacedRun pacer.
  • Docs: api_to_audit.md (the hook entry and the export/import entry), system-overview.md, bb guide thread-lifecycle, the plugin-authoring backend-sdk.md and backend-events.md, the Plugin Guide "Delete finalize hook" card, the bb-cli command index, and the plugin README and skill.

What users see today

  • Nothing changes for anyone who doesn't use the new pieces. Deleting a thread behaves as before; the plugin only answers wait for threads it is moving.
  • bb thread export / bb thread import are available to everyone. In the SDK they're experimental_ methods.
  • Storage & retention shows a new "Move archived threads to cold storage" policy, which defaults to Never, and a Cold storage row that appears only once something has been moved or the policy is on.

How you verified

  • apps/server/test/threads/thread-files.test.ts (17 tests):

    • export writes the whole thread, its metadata and attachments;
    • a deleted thread comes back byte-for-byte, with metadata, attachments, dynamic context file states, a fresh archivedAt, storageDeletedAt cleared and pruning work queued;
    • the timeline is identical after export, removal and import;
    • an import of a thread that still exists gets 409 thread_exists and leaves its rows untouched;
    • bad files, a newer format version and a missing project are rejected;
    • missing attachment parts, rows from another project and an out-of-bounds seek table get 400 and recreate nothing (these two tests fail on the code before that fix);
    • an import into a thread being deleted gets 409, then recreates it once removed;
    • concurrent imports give 200 and 409;
    • the thread is never visible with missing events;
    • a half-imported thread is removed once its import is gone;
    • an unreadable attachment fails the export;
    • an import drops links to a thread that is still being deleted, and that thread's purge then finishes (fails on the code before that fix: the link was kept and the owner's row stayed hidden forever).
  • Hook tests in the same file:

    • a plugin waits, exports the deleted thread, proceeds, and the copy re-imports;
    • a throw or an invalid answer counts as wait;
    • threads queued behind a waiting one are still removed;
    • nothing is removed while plugins are loading;
    • no second ask once a removal has started, and export then answers 409;
    • no removal starts while an export holds it.

    Disabling the hook gate and the loading gate makes four of these fail.

  • Storage & retention (retention.test.ts):

    • cold storage selection;
    • the full flow with a fake host: the sweep deletes the thread, the hook waits, the file lands in the plugin's cold-storage/ folder with the exported bytes, the hook proceeds, restore calls import with those bytes and removes the file;
    • an export that fails keeps waiting and retries;
    • a failed delete and an abandoned move are both forgotten;
    • moving a thread again after it was brought back outside the plugin writes a fresh file, and an entry whose thread is back is dropped;
    • bb storage cold-store refuses a parent while a child, a fork (source) or a lifecycle dependent still points at it, deletes nothing, and moves it once they're gone (this test fails on the code before that fix);
    • restoring a child first restores its cold-stored parent, and restoring a thread that is already back only drops its entry;
    • cursor paging through moving rows, stored rows and rows with the same storedAt returns every row exactly once, with the right totals, moving count and last move time, and a search for 100%_ matches only that literal title.
  • Database: tests for thread file rows and for nextThreadPurge returning startedAt. The migration rewind helper gains rewindThreadPurgeStartedColumn. Query-cost cases cover getThreadPurge, markThreadPurgeStarted and the thread-file queries.

  • Locally: typecheck and lint for the changed packages; tests pass for db (724), plugin-sdk (440), the plugin (110), Plugin Guide, bb-guide, the CLI, and the server's thread-file, dispatch-hook, periodic-sweep and queue-drain tests.

  • Real server (pnpm start:worktree, source CLI), on an archived Codex thread with 18 events:

    • bb thread import of its export while it still existed answered 409: Thread … already exists. Only a deleted thread can be imported.
    • bb storage cold-store --thread … --yes answered moving. The rows were gone from bb.db within 20 s, and cold-storage/thr_….jsonl.zst (3,765 bytes) was on disk, with no file data in the plugin database.
    • bb storage cold-list listed it as stored.
    • Clicking Restore in the panel's Cold storage section showed "Thread restored". /timeline was byte-identical to before, all 18 events were back, and the file and its row were gone.
    • With 3,000 extra rows seeded into the plugin database:
      • the main panel showed one Cold storage row, "3,001 threads · Last moved 17m ago · 576.4 MB", with no list;
      • clicking it opened …/storage/cold-storage with 50 rows and "3,001 threads · 576.4 MB";
      • five "Show 50 more" clicks gave 300 unique rows with no error (the old list failed after 200);
      • searching "thread 42 —" gave "1 match", and clearing the search brought back the first 50;
      • moving "one" from the CLI while the page was open put it on top and raised the count to 3,002;
      • Restore removed its row and dropped the count to 3,001;
      • "All storage" went back to the main panel;
      • loading each page 6 times while sampling section positions every 10 ms: both go from blank to their final layout in one step, with nothing shifting afterwards.
    • After the review fixes:
      • moved a thread, brought it back with bb thread import, renamed it and moved it again: a fresh file was written, and restoring it kept the new title (before the fix, the old file was kept and the rename was lost);
      • the imported thread had storage_deleted_at NULL;
      • moved a child and then its parent, then restored the child: restoredThreadIds was [parent, child] and the child's parent_thread_id was intact;
      • importing a file with one corrupted byte answered 400: Thread file frame at 193 failed its checksum.
    • Cold-storing a parent with a child: before the fix, bb storage cold-store --thread <parent> --yes moved the parent and the child was purged from bb.db with no file (missing from cold-list, 404 on bb thread show). After it, the command exits 1 with Thread … can't move to cold storage while other threads point at it as their parent, source or lifecycle owner: thr_…. Move or delete those first., and both threads stay. Moving the child and then the parent stores both.

AGENT GENERATED

🤖 Generated with Claude Code

@ymichael
ymichael force-pushed the bb/cold-history-tier branch 2 times, most recently from 3d43c1a to 09bbad6 Compare November 6, 2026 05:50
@ymichael ymichael changed the title Move archived and idle threads' event history into compressed archive files Move archived and idle threads' history into thread files, with thread export and import Nov 6, 2026
@ymichael
ymichael force-pushed the bb/cold-history-tier branch from a7cf447 to 1266310 Compare November 6, 2026 08:02
@ymichael ymichael changed the title Move archived and idle threads' history into thread files, with thread export and import Save archived threads to thread files and remove them from bb.db, with restore, export and import Nov 6, 2026
ymichael added a commit that referenced this pull request Nov 6, 2026
## Human comments

## What was wrong

Background sweeps could get stuck on one bad item or one hung call. Each
periodic job had its own error boundary, but the runner only saw whole
jobs. Inside a job, each loop decided for itself what one failing item
meant, and most got it wrong:

- **One failure ended the pass**, and the same item came up first again
10 s later, so it blocked every item behind it:
- **Deleted threads and archived teardown.** Neither loop in the
lifecycle sweep had a per-thread `try`. One archived thread whose saved
startup context fails its strict parse stopped every later teardown and
every deleted-thread finalization.
- **Event pruning** caught the error and rethrew it. The failed policy's
cursor rolled back and was picked first again, so one thread could
freeze all four pruning policies.
- **Turn-start deadline:** one throwing thread stopped the threads after
it.
- **Completed output migration:** one failing target blocked the targets
after it.
  - **Startup recovery:** one failing step skipped the steps after it.
- **One hung call stopped a job for good.** A job still running is
skipped on every later pass, and nothing bounded these waits:
  - plugin schedules waited on each schedule with no timeout;
- environment provisioning can wait on daemon commands with a 24 h
timeout;
  - the environment lifecycle waited for every teardown at once.
- **Plugin schedule rows for unloaded plugins** stayed due and could
fill the 100-row batch.

## What changed

**One runner for every periodic job.** `PeriodicSweepJob` is now just a
name, a cadence, `background`, and `sweep(deps, now)`, which returns an
item sweep. There is no other kind of job.

- **The runner** (`apps/server/src/services/system/item-sweep.ts`) takes
`list({ excludedKeys })`, a stable `key`, `process`, and `concurrency`.
It runs each item behind its own boundary:
- A failure is written to the new `sweep_item_failures` table (sweep,
item key, attempts, first failure, retry time, last error), and the
remaining items still run.
- The item is left out until its retry time: 1 minute, doubling to 1
hour, counted from the pass, or from when it failed if it ran past the
60 s detach. `list` receives the excluded keys so `LIMIT` queries can
leave them out in SQL.
  - Each failure logs a warning; from the fifth attempt on, an error.
- A success clears the record. A record whose item hasn't been listed
for an hour past its retry time is dropped. Startup drops records of
sweeps that no longer exist.
- It stops waiting for any item after 60 s, skips it while still running
(also in an overlapping pass of the same sweep, such as the event-driven
and periodic queue wakes), and records its outcome when it settles.
  - It runs up to `concurrency` items at once and yields every 8 ms.
- A `background` job doesn't hold up the rest of the pass and is skipped
on later passes until it finishes.
- **Three constructors for three shapes:**
  - `defineItemSweep`: a list read once per pass;
- `defineScanSweep`: a cursor scan that lists again after each batch
until nothing new comes back. It never processes a key twice in a pass
and leaves out keys that failed earlier in the pass;
  - `defineSingleItemSweep`: one bulk statement or maintenance pass.
- **Every job's items:**
- environment provisioning, thread provisioning, archived-thread
teardown and deleted-thread finalization (the last two split out of
`thread-provisioning-orphan-cleanup`);
  - turn-start deadline; project deletion;
  - plugin schedules, which now list only loaded plugins' rows;
  - environment teardowns, with unbounded concurrency;
- machines, as two sweeps: a removal request per machine, and the
machine sweep itself, which runs in the background as before;
- the four queued-message wakes, on both the periodic and the
event-driven path. Each message's own retry and exhausted state stays
inside `process`;
- thread-storage orphan cleanup, one item per host, in the background as
before;
- attachment backfill and orphan prune, one project per pass. The
runner's records replace the backfill's own `error` column and 60 s
skip. The column stays in the schema, unused, because migration tests
rewind and rerun every later migration and a plain `DROP COLUMN` can't
run twice;
- completed output migration, one item per target, each with an equal
share of the 64-advance budget;
- event pruning, a scan sweep whose items are each policy's next thread
(`<policy>:<thread>`). `pickThreadPruningThread` commits the choice in
its own transaction before any pruning, so a failure lands on that
thread through the runner, and the next pick moves past it until its
retry time;
- single-item sweeps for the bulk prunes, the two claim and owner
releases, and database and plugin-database maintenance.
- **Deleted on the way:** the hand-written failure handling in the
pruning sweep, `ThreadPruningAdvanceError`, `skipThreadPruningThread`,
`advanceThreadPruningPolicy`, the backfill's own retry skip, and the
storage orphans' `runningHostIds`.
- **Startup recovery** runs each step behind its own boundary.
- **Migration `0153_sweep_item_failures`**, idempotent. No
`HOST_DAEMON_PROTOCOL_VERSION` change.
- **Docs:** `docs/system-overview.md` (Background sweeps) and
`docs/events-table-pruning.md`.
- **Order:** this lands before #7184. That PR rebases next and records
purge failures through this runner instead of its own columns. #7107
follows.

Known limits, unchanged from `main`:
- A row that always fails inside one output-migration target keeps that
target backing off, with error logs, rather than being skipped.
- If stopping a run fails after the turn-start deadline appended its
error event, the retry appends another. Backoff now spaces those out.
- A one-off failure in a bulk job (such as the machine-auth prune) now
waits a minute before the retry, instead of 10 s.

## How you verified

- `apps/server/test/system/item-sweep.test.ts`:
  - a failing item doesn't stop the items after it;
- it is recorded, excluded until exactly 60 s later, retried, and
cleared on success;
- delays double (60 s, 120 s, 240 s, 480 s, 960 s), with one error log
on the fifth failure;
- an unlisted record is kept until an hour past its retry time, then
dropped;
- with two hung items and one quick one, the pass returns at 60 s rather
than earlier or later; the hung items are skipped while in flight, and a
rejection 10 minutes later is recorded with its retry time counted from
that rejection;
- when two passes of one sweep overlap, an item the other pass is
running isn't started again.
- `apps/server/test/system/periodic-sweep-jobs.test.ts`:
- every job name is unique and matches the name of the item sweep it
runs, so failure records line up;
- a deleted thread whose finalization throws no longer stops another
deleted thread from being removed. On `main`, the whole sweep rejects.
- `apps/server/test/system/thread-pruning-sweep.test.ts`:
- with a trigger making deletes fail for one thread, the other thread is
pruned in the same pass. The broken thread records `turn-diffs:<id>`
with 1 attempt, isn't retried before its retry time, is pruned
afterwards, and the record clears;
- the existing pruning tests (busy threads, mid-visit busy, rotation and
budget, overrun, notifications after a failed batch) pass on the scan
sweep.
- **Local runs:**
  - `@bb/server` and `@bb/db` typecheck pass.
- `@bb/server` tests in `test/system`, `test/services`, `test/threads`,
`test/public`, `test/server-move`, `test/internal`, `test/hosts`,
`test/projects`, `test/environments` and `test/machines` pass: 3,205 of
3,206. The exception, `public-host-management` "revoke the removed
host's cloud machine", fails locally because the `connect` plugin's
frontend build can't resolve `@bb/domain`. It passes in CI, and this PR
doesn't touch plugins.
- The full `@bb/db` suite passes (660), including the migration-rewind
tests.
- **Overhead,** measured on a scrubbed copy of a real `bb.db`: one pass
costs 29 µs with no items, 32 µs with 10 and 75 µs with 100. That's
about 0.3 ms per 10 s across the 9 items jobs.

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 6, 2026
…ner (#7184)

## Human comments

## What was wrong

Deleting a thread ends with one `DELETE FROM threads` that cascades to
every event, search segment and prompt history row, in one transaction
on the server's main thread. On a scrubbed copy of a heavy install (3.9
GB `bb.db`), deleting its 40 largest deletable threads (406k events) one
by one blocked the server for 250 ms per thread at the median and 1,554
ms at worst. Storage retention's delete-after policy and project
deletion take the same path, so deleting many old threads stalls bb
again and again. It is also the delete step the cold tier (#7107) needs.

## What changed

Deleting a thread now finishes through a paced background sweep on the
shared item sweep runner from #7190. Nothing changes for users: a thread
disappears from lists, search and the sidebar the moment it is marked
deleted, as before.

- **Queue.** Where `finalizeStoppedThreadInTransaction` used to call
`deleteThread`, it now inserts the thread into a new `thread_purges`
table (`thread_id`, `requested_at`). The row cascades away with the
thread, so the queue needs no cleanup. The deleted-thread finalization
sweep skips threads already queued.
- **Sweep.** `thread-purge` is a `background` job in
`PERIODIC_SWEEP_JOBS`, built with `defineScanSweep`. It lists the oldest
queued thread that no longer owns lifecycle dependents, so owners still
go after their dependents. It then deletes that thread in steps, each
one immediate transaction:
  1. the next events, 64 rows or 512 KB, always at least one row;
2. then search segments, prompt history and attachment links, 128 rows
at a time;
  3. then the thread row, through the existing `deleteThread`.

Steps run in 10 ms slices. After each slice the sweep rests 9× as long
while a client is connected or a thread is running, and 1× otherwise. A
run stops after 30 seconds, or when a server move freezes the DB, and
the next pass continues. That keeps each item well under the runner's
60-second detach. A new delete starts at the next pass, at most 10 s
later.
- **Failures** go through the runner. A thread whose step throws has its
transaction rolled back. It gets a `sweep_item_failures` row and is left
out until its retry time (1 minute, doubling to at most 1 hour), while
other threads keep going. It stays queued and hidden and is never
dropped.
- **Migration `0154_thread_purges`** adds the table and its
`requested_at` index, idempotently. No `HOST_DAEMON_PROTOCOL_VERSION`
change; no app, CLI or contract change.
- `docs/system-overview.md` describes the queue.

## How you verified

- `packages/db/test/data/thread-purges.test.ts`:
- events are deleted in row- and byte-capped batches, an oversized event
alone, then prompt history in `maxRows` batches;
  - the thread row is never touched, and other threads' events stay;
- the queue takes the oldest request first, skips excluded threads, and
holds an owner until the threads it owns are gone.
- `apps/server/test/threads/thread-purge.test.ts`:
- after `DELETE /threads/:id`, the thread keeps its events and returns
404 until the sweep deletes them;
- with a trigger making one thread's deletes fail, the next thread is
still deleted. The failing thread records attempt 1 with a retry 60 s
later, is skipped at +59.999 s, and is deleted at +60 s with its failure
record cleared.
- Existing tests in 8 files (13 call sites) that expected the row gone
right after a sweep or route now drain the queue with the
`runThreadPurges` helper, which runs the production sweep.
- Locally:
  - `@bb/db` passes, 662 tests;
- `@bb/server` passes 3,935 of 3,936, the one failure being
`public-host-management`, which fails only locally on the connect plugin
build;
  - typecheck and lint pass.
- **Real server** (`pnpm start:worktree`, fresh data dir, driven with
the source `bb` CLI):
- deleting a thread hides it at once, and its rows are gone within one
pass;
  - deleting an owner removes its lifecycle dependent and sidebar child;
- a 30k-event, 57 MB thread was purged in about 3 s, during which `GET
/api/v1/threads` stayed at p50 3.1 ms, max 16.4 ms;
- a failing purge backs off while the next thread is deleted, and
retries 60 s later;
  - a restart mid-purge resumes;
  - project deletion completes;
  - the only server warning was the intended failure.
- **Bench:** the 40 largest deletable threads on a fresh scrubbed
heavy.db copy each run (405,939 events):

  | Path | Event loop | Wall time |
  |---|---|---|
| `main`: one cascade per thread | blocks of 250 ms median, 1,554 ms max
| 13.2 s, all blocking |
  | Paced, idle (rest 1×) | p99 25.9 ms, max 46 ms | 41.6 s |
  | Paced, busy (rest 9×) | p99 5.9 ms, max 116 ms | 232 s |

Timed one at a time, steps take 1.3 ms at p50, 26.8 ms at p99 and 72 ms
at most, and 24 s in all. The busy maximum is one outlier that includes
a WAL auto-checkpoint inside a commit, which any write on the main
thread can hit today. The bench script and DB copies stayed in thread
storage and were deleted.

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/cold-history-tier branch 2 times, most recently from ce3dd24 to 2b5526f Compare November 6, 2026 23:23
@ymichael ymichael changed the title Save archived threads to thread files and remove them from bb.db, with restore, export and import Save threads to thread files and remove them from bb.db, with restore, export and import Nov 6, 2026
@ymichael
ymichael force-pushed the bb/cold-history-tier branch 3 times, most recently from c43ce82 to 54c65b1 Compare November 19, 2026 00:09
@github-actions github-actions Bot closed this Nov 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

This is an automated message. We have closed this pull request because it has been open for more than two weeks.

@ymichael ymichael reopened this Nov 19, 2026
@ymichael ymichael changed the title Save threads to thread files and remove them from bb.db, with restore, export and import Save archived threads to files from Storage & retention, with a thread.purge hook, export and import Nov 19, 2026
@ymichael
ymichael force-pushed the bb/cold-history-tier branch from 47d8bd8 to 4893108 Compare November 19, 2026 22:00
@ymichael ymichael changed the title Save archived threads to files from Storage & retention, with a thread.purge hook, export and import Move archived threads to cold storage from Storage & retention, with a thread.delete_finalize hook, export and import Nov 19, 2026
@ymichael
ymichael force-pushed the bb/cold-history-tier branch 5 times, most recently from c63cd85 to a4908ed Compare November 23, 2026 21:55
ymichael and others added 3 commits November 23, 2026 14:04
…d.purge hook, export and import

Core gains a thread.purge plugin hook that lets a plugin hold a deleted
thread's purge until it answers proceed, plus thread file export and
import. The Storage & retention plugin uses them to save archived threads
to files in its own database, then delete them from bb.db, and to restore
them later.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…te_finalize, and keep cold storage in files

- Import no longer merges events into a thread that still exists; it answers
  409 thread_exists and only recreates a deleted thread.
- The thread.purge hook is now thread.delete_finalize, named for the delete
  it finishes rather than core's internal purge sweep.
- Storage & retention calls the feature cold storage (policy, panel, CLI and
  RPC names) and writes each thread file to its own folder instead of a
  BLOB in its database.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The panel's Cold storage section now shows the five most recent threads,
the total count and size of what is stored, and a title search. Show more
fetches the next 50 by cursor and appends them, instead of re-fetching
everything with a growing limit, which failed past the RPC's 200-row cap.
A change reloads only the first page and merges it into what is already
shown, and is debounced so a burst of moves causes one reload. Search
matches titles literally, and `bb storage cold-list` gains `--after` and
reports the same totals.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael and others added 13 commits November 23, 2026 14:04
The Storage & retention panel shows cold storage as one row, like a
machine: thread count, total size, when the last thread moved and how
many are still moving. Clicking it opens storage/cold-storage, which has
the search, 50-row pages, and Restore and Delete. The list RPC reports
movingCount and lastStoredAt alongside the totals.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The summary row was fetched on its own 200 ms after the rest of the panel
rendered, then pushed every section below it down. It now loads in the
panel's initial data and only live updates are debounced. The cold storage
page renders once its first page of threads is in, like a machine page, so
its header no longer jumps when bb's panel title bar mounts a moment after
the plugin on a fresh load.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t, and reject damaged thread files

- Moving a thread to cold storage again resets its entry, so the plugin writes
  a fresh file instead of letting bb remove a thread it only has an old copy of.
  Entries for threads that are back in bb (restored with bb thread import, or a
  restore cut off before its cleanup) are dropped by the hourly run and by
  Restore.
- Restore first brings back the cold-stored threads a thread points at as
  parent, source or lifecycle owner, so those links survive, and returns
  restoredThreadIds.
- Import clears storage_deleted_at, so deleting a restored thread later still
  deletes its host storage, and queues pruning work for it.
- Thread files also carry dynamic context file states.
- Import reads every format version up to its own, requires the thread row to
  insert, and answers 400 for damaged seek tables, frames, missing attachment
  parts and rows from another project instead of failing with a 500.
- Import pins attachments it reuses before restoring them, so attachment GC
  can't delete them mid-import, and an attachment path outside the project no
  longer leaves a stray row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bb storage cold-store deleted the thread with childThreadsConfirmed, and
bb's delete takes every thread linked to it as a child or lifecycle
dependent along. Only the thread itself got a cold storage entry, so
thread.delete_finalize let bb purge those children with no file: they
were gone for good. The hourly run already skipped such threads, but the
CLI did not check.

Moving a thread now refuses while a live thread points at it as parent,
source or lifecycle owner, naming those threads, for the CLI and the
hourly run alike. The delete no longer confirms child threads, so a
child created after that check makes bb refuse the delete instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… finish

Import kept a parent, source or lifecycle owner link to any thread row that
existed, including one deleted and waiting for its purge. Core never removes
a thread that another thread names as its lifecycle owner, so that purge
deleted the owner's events and left its hidden row behind for good, and the
owner could no longer be imported. The import's final transaction now keeps
a thread link only when the linked thread is live.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/cold-history-tier branch from a4908ed to 3628aee Compare November 23, 2026 22:08
@ymichael
ymichael merged commit 264df35 into main Nov 23, 2026
55 checks passed
@ymichael
ymichael deleted the bb/cold-history-tier branch November 23, 2026 22:25
ymichael added a commit that referenced this pull request Nov 23, 2026
## Human comments

## What was wrong

#7107 merged at 22:25:17 with plugin SDK 0.6.189. #7955 had been rebased
and bumped to 0.6.189 a few minutes earlier, while that number was still
free, and squash-merged at 22:26:18. Git saw its version line as
identical to main's, so the squash left `package.json` and
`plugin-sdk-version.ts` alone. Main now ships #7955's SDK additions
(`experimental_useThread`, `ExperimentalThreadState`,
`ExperimentalThread`, the segment `toggleRef`/`collapseRef`, and the
`renderSlot({ threads })` harness support) under the same 0.6.189 that
#7107 already used, so one version number names two different SDK
surfaces.

## What changed

- `node scripts/bump-plugin-sdk.mjs 0.6.190`:
`packages/plugin-sdk/package.json` and
`packages/domain/src/plugin-sdk-version.ts`.
- `docs/api_to_audit.md`: the two lines #7955 added that name its
required version ("Requires SDK 0.6.189" under `experimental_useThread`,
and the `toggleRef`/`collapseRef` note under thread context segments)
now say 0.6.190. The other 0.6.189 reference,
`plugins/storage-retention`'s `bbPluginSdk: ">=0.6.189"`, belongs to
#7107 and stays.

## How you verified

- `node .github/workflows/check-plugin-sdk-version.mjs` and `node
.github/workflows/check-version-lockstep.mjs` pass locally.
- `pnpm exec turbo run typecheck test --filter=@bb/domain
--filter=@get-bb/plugin-sdk` passes.

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
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