Skip to content

Confine daemon storage to collections and import through the daemon - #276

Merged
Stephen Belanger (Qard) merged 42 commits into
mainfrom
design/sqlite-journal-collections
Nov 17, 2026
Merged

Stephen Belanger (Qard) merged 42 commits into
mainfrom
design/sqlite-journal-collections

Conversation

@Qard

@Qard Stephen Belanger (Qard) commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

Third in the stack that splits this work. #289 (translator state) and #291 (imports through the daemon) have merged into main; #287 (expiry and retention) is stacked on this PR.

Daemon storage now lives entirely in bt-daemon/src/collections, the only module that uses SQLite. Each source session has one database holding two concrete collections:

  • Events. Capture inserts redacted events and acknowledges a hook only after the insert commits. Translation reads them in order. Each input event's complete output (SpanOps, span metadata, root candidates and the translator's saved state) is stored in the same transaction that removes the event. Nothing reaches a route before that commits, and a failed handoff retries without translating again.
  • SpanOps. Each route has a durable head and removes ops from its view once the backend accepts them. An op is deleted once every route has passed it. The collection also owns the live feed routes read from.

One translation row records the translated boundary, op tail, translator state, root candidates and source failure. Translator state is each translator serialized through a shared TranslatorState impl: it holds only what later events still need, such as open spans and transcript offsets.

Translator state (#289) and importing through the daemon (#291) are separate PRs below this one in the stack. This PR replaces the storage that both of them use.

Capture is idempotent within the retention window. The same event captured again for the same route, such as a repeated import or a hook retried across a daemon handover, is acknowledged and recorded once. A Muse export imported after live capture updates the spans the live session already completed.

Bounded storage:

  • Delivered ops are deleted immediately; consumed events are deleted in the handoff.
  • Sessions may never end, so hourly cleanup expires, after 7 days without use, capture identities, origins of ended spans, abandoned tool and ended root state, and heads that were registered for output but never subscribed (for example a route whose credentials never resolve). Live routes, and subscribed heads held by a reported failure, are kept.
  • A session that owes nothing is deleted after 7 days without activity, measured inside the database. So is one whose output no destination ever subscribed to.

Upgrades:

  • Main's schema-6 SpanOp tables convert in place into the translation row. Ops an earlier daemon published for a partly translated input are kept and that input is translated again, so its published part may be delivered a second time under the same span IDs.
  • NDJSON journals are imported at their original positions, then deleted. Input every route had delivered according to legacy delivery checkpoints is marked translated, so the translator rebuilds its state from it without publishing. When routes were acknowledged unevenly, the route that was further ahead may receive that range again under the same span IDs. Legacy delivery-ledger/ directories are deleted.

Tests inspect storage and inject faults through a typed storage_inspect API behind a test-support feature, and contain no SQL. Import tests run against an in-process daemon.

Behavior changes covered by updated tests:

  • A Claude subagent transcript is now read in full. Before, the parent transcript's byte bound was also applied to the subagent file, which cut off the subagent's last model call.
  • A re-import into a live session no longer re-inserts its root span.

Validation on macOS: the full Rust suite with all features (716 passed, 14 ignored installed-agent tests), Clippy across all targets with warnings denied under both default and all features, and formatting checks. The ignored muse_attach test, which needs an installed Muse binary, was not run.

🤖 Generated with Claude Code

@Qard
Stephen Belanger (Qard) force-pushed the design/sqlite-journal-collections branch from 8b7c73e to 779dacd Compare November 11, 2026 12:34
@Qard Stephen Belanger (Qard) changed the title Design persistent collections for draining trace journals Drain trace journals through persistent collections Nov 11, 2026
@Qard
Stephen Belanger (Qard) marked this pull request as ready for review November 11, 2026 12:34
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-11T12:37:56.883300Z 779dacd Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 779dacd9ad

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "Codex (@codex) review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "Codex (@codex) address that feedback".

Comment thread bt-daemon/src/server/maintenance.rs Resolved
All storage now goes through bt-daemon/src/collections. A shared per-session
store owns the only SQLite connection, schema migration and removal. Capture
inserts into EventCollection, translation moves events into SpanOps in one
transaction, and each route removes SpanOps from its view on delivery.

JournalWriter and the NDJSON readers are gone. Legacy journals are read only
to import them at their original byte positions, then deleted.

Retention now measures recorded pipeline activity rather than file times,
so restarts that reopen every database no longer keep stale sessions alive.
A cold session that owes nothing, or whose output no destination subscribed
to, is removed.

Tests use a typed inspection and fault-injection API instead of SQL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Transcript import is now a daemon client. It starts or upgrades the daemon
as hook capture does, captures every synthesized event over one connection,
and finishes each session with import.finish, which flushes or finalizes its
routes and reports their root span and distinct span count. A rewritten
transcript restarts translation with import.reset. Imports and hooks share
one pipeline and one session store.

The delivery ledger and its NDJSON log, JSON checkpoint, origins index and
lock files are gone, along with its last SQLite use outside collections.
SpanOp heads already acknowledge delivery and translation stamps stored
origins. Legacy ledger directories are deleted. Capture is idempotent while
a session's storage exists, so repeating an import records nothing twice.
Muse completions that arrive after a live preview update the completed span.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Qard Stephen Belanger (Qard) changed the title Drain trace journals through persistent collections Confine daemon storage to collections and import through the daemon Nov 11, 2026
Translation used to open a batch, write ops in separate transactions that
routes could already deliver, and remove the input event only in a later
commit, with per-ordinal receipts to repair a crash in between. Now an
input's complete output, metadata, root candidates and translator
continuation are stored in the same transaction that removes the event.
Nothing is published live until that commits, and a failed handoff retries
without translating again. A legacy delivery checkpoint is applied in the
same transaction. Inputs a released daemon left partly published are
completed without redelivering their recorded prefix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Atomic event-to-SpanOp handoff makes per-input batches, publication
receipts and separate root and checkpoint tables unnecessary. One
translation row now records the translated boundary, op tail,
continuation, root candidates and source failure; schema 7 converts a
released channel's tables into it. The collection also owns the live
feed and replay window, so SpanJournal and its pass-through methods are
gone. Legacy delivery checkpoints are converted during import instead
of flowing through translation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…pper

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every translator stored its state as its own serde serialization; a
blanket impl now provides that once, and only wrappers forward to their
inner translator.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Input migrated from main below the translated boundary only rebuilds
  translator state, so it no longer keeps a delivered session from
  collection. Neither do root candidates still waiting for work.
- Bytes a legacy journal reserved without importing a record, such as a
  trailing delivery checkpoint, are translated as input with no output,
  so the boundary reaches the event tail and lifecycle controls append.
- Hourly cleanup expires, after the 7-day retention, capture identities,
  origins of ended spans, abandoned tool and ended root state, and heads
  registered for output that no delivery ever subscribed to. Live routes
  and subscribed heads held by a failure are kept.
- Saved OpenCode 2 content parts restore exactly, and floats round-trip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Capture, control appends and the test-only append shared one insert.
append(record, after) now covers them: event records are recorded once
per capture identity, and `after` keeps a control from being ordered
ahead of work translation has not seen. Legacy import and its boundary
reservation become one import call.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- EventCollection::append takes anything convertible into a record.
- Event appends return SourcePosition instead of an identical type.
- Stored ops and root candidates (de)serialize through StoredOp with
  From/TryFrom, without re-encoding through raw bytes.
- Translator state is a raw JSON value, so wrappers embed it directly.
- BackendAuth derives Default; BindingChanged derives its error.
- Legacy import reuses the event identity snapshot helpers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A Json<T> column type replaces encoding and decoding JSON columns by
hand, and a One extension on Connection replaces repeated single-value
query_row closures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Events and controls are stored as their own JSON values beside a
control flag, so no tag is injected into or looked up in the value. Only
the legacy NDJSON reader still recognizes the old tag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Ports #278's route detachment to SpanOps: a stopped route's head is held at
the largest position, owes nothing and never resumes. The in-process import
path #278 also changed no longer exists; imports reach the same consumer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Stephen Belanger (Qard) added a commit that referenced this pull request Nov 13, 2026
Merges the updated base, keeping stalled-route expiry alongside route
detachment (a detached head is never behind, so never stalled).

Retention is now an optional --retention-hours flag that falls back to
BT_TRACE_RETENTION_HOURS read through crate::env, then 168 hours, instead
of Clap's env attribute. An unusable value is reported and ignored. Daemon
tuning variables are declared in env.rs and AGENTS.md describes them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every translator is now serializable, and AgentTranslator requires a new
TranslatorState trait with a blanket implementation for serde types. A
translator's saved state is everything it still needs from events it has
consumed to translate later ones, so a later pipeline can persist it
instead of replaying those events.

Sink-only row fields that wire JSON omits are preserved through a shared
SinkFields codec, which the stored SpanOp codec now also uses. serde_json
round-trips floats exactly so restored state matches what was saved.
OpenCode v2 message parts the translator does not model are kept as raw
JSON rather than rejected.

A test resumes every agent's native stream from saved state after each
event and requires output identical to an uninterrupted run; the shared
native streams now include an OpenCode v2 session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Transcript import is now a daemon client. It starts or upgrades the daemon
as hook capture does, captures every synthesized event over one connection,
and finishes each session with import.finish, which flushes or finalizes
its routes and reports their root span and distinct span count. A rewritten
transcript restarts translation with import.reset, a Reset control stored
in the journal so replay resets the translator at the same point. Imports
and hooks share one pipeline.

With the daemon the only process that delivers, the delivery ledger and its
cross-process locks, NDJSON log, checkpoint and origins index are gone.
Translation already stamps stored origins; tags are deduplicated while
routed rows are prepared. Legacy ledger directories are deleted. A legacy
delivery checkpoint now advances its route's head past the output it
covered and discards origins rebuilt for those spans, which the ledger
previously did by remembering completed spans.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This branch already contained its own translator-state and import changes,
so conflicts take this branch's side. Keeps #289's save-and-restore test
for every agent alongside this branch's recovery tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Qard
Stephen Belanger (Qard) changed the base branch from main to design/import-through-daemon November 16, 2026 10:58
Match the crate's convention: derives name Serialize and Deserialize
through a use serde import rather than serde:: paths.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…sign/import-through-daemon

# Conflicts:
#	bt-daemon/src/transcript_import/pipeline.rs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Imports shared the live session's translator, so importing a session into a
new destination delivered almost none of its history, and repeating a Claude
import opened new turns and a new trace for the same work.

Each import run now captures into its own daemon-side session (the native id
with a per-run suffix) with its own journal, storage and delivery, while
translation, span metadata, sinks and span plugins use the native session id.
A run therefore reproduces the native session's deterministic ids and
delivers every span to its destination. Repeating an import re-delivers its
rows under the same ids; an older import may replace newer content on spans
it shares with what a destination already holds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Each import run's translator uses the native session's namespace here too,
while its events and ops live in the run's own session storage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Each import run is its own session now, so it records its events.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…-daemon

# Conflicts:
#	bt-daemon/src/transcript_import/pipeline.rs
Base automatically changed from design/import-through-daemon to main November 16, 2026 15:58
#291 landed as c4e25c9, whose tree matches the #291 head this branch already
merged, so every conflict keeps this branch's side.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Both sides added import.finish and import.reset; keep this branch's copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The event and SpanOp collections shared one database and connection but
were separate types, so callers kept joining them back together. They are
now one SessionStorage handle, and one session row replaces the
event_state and translation rows.

- A single status() read replaces about a dozen one-column getters.
- One expire() transaction covers capture identities, span metadata and
  stuck heads.
- Event and op reads share one size-limited batch reader. Event records
  are now decoded inside the storage call instead of one thread hop each.
- Head reads return one Head, and route matching uses one helper.
- Every mutation runs in a write transaction, so bind's check and set can
  no longer interleave with another writer.
- Schema upgrades live in upgrade.rs and legacy NDJSON import in
  legacy.rs, so events.rs and span_ops.rs hold only current-schema logic.
- pipeline/journal.rs is renamed cursor.rs, and SpanOp gains
  row()/row_mut().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- SessionStorage is the store itself rather than a wrapper around it,
  and owns finding (`all`) and deleting (`remove`) session databases.
- Reads return the live feed's Record type; StoredRecord is gone.
- continuation() replaces checkpoint(), whose boundary status() already
  reports.
- complete() no longer treats a session with no routes as incomplete.
  Its only production caller collected such sessions anyway.
- Startup recovery no longer groups one session's records by source
  session, since a session database holds exactly one.
- The daemon's open-storage map and storage_for() are named for what they
  hold, and rpc.rs no longer splits one impl block in two.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Inspector::continuation() returns only the saved state, as the daemon's
API does. Its only caller that needed the boundary, delivered(), now
reads it in its own query.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
EventReader implements futures::Stream instead of hand-written next()
and next_event() methods. Callers use TryStreamExt (try_next, map_ok,
try_collect), and events() is a try_filter_map that skips controls. A
reader still ends at the end of its range and continues after extend().

The connection uses parking_lot's Mutex, which has no poisoning to
handle, and head matching uses rusqlite's query_and_then iterator.

futures was already in the dependency tree and is now a direct
dependency.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Status, Head, HeldRoute and the inspector's Head derive Deserialize and
  are read by column name through one select() helper, instead of
  positional row.get(n) mapping. Status reports source and session_id,
  with owner() pairing them.
- The registry of open databases is a weak_table::WeakValueHashMap, so
  expired entries no longer need manual upgrading and pruning.

serde_rusqlite 0.40 is the release built on rusqlite 0.37.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
serde_rusqlite tracks rusqlite, so this moves it from 0.40 to the current
0.44. Since rusqlite 0.38, u64 columns need the fallible_uint feature;
values above i64::MAX fail at runtime, as they already did. Every
position stored fits, up to DETACHED, which is i64::MAX.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Main's #293 stored attachments in the SpanOp journal that this branch
replaces, so they are ported into session storage:

- The translation handoff captures inline media as attachments. Routes
  receive their bytes live; storage keeps one copy per digest, counted
  per op and deleted with the last op that references it.
- Reads load each op's attachments and count their bytes toward the
  batch size.
- Main's attachment tables are schema 7. Session storage becomes schema
  8, so databases written by main upgrade through both.
- Main's attachment tests use the session storage API, and a new test
  upgrades a schema-7 database with an attachment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Qard
Stephen Belanger (Qard) merged commit 9d46494 into main Nov 17, 2026
27 of 29 checks passed
@Qard
Stephen Belanger (Qard) deleted the design/sqlite-journal-collections branch November 17, 2026 15:21
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.

2 participants