diff --git a/bt-daemon/Cargo.lock b/bt-daemon/Cargo.lock index 0b42583e..161d6f8a 100644 --- a/bt-daemon/Cargo.lock +++ b/bt-daemon/Cargo.lock @@ -335,11 +335,13 @@ dependencies = [ "base64 0.22.1", "braintrust-api-client", "braintrust-sdk-rust", + "bt-daemon", "bytes", "chrono", "clap", "file-rotate", "fs2", + "futures", "libc", "mime_guess", "muse-code-sdk", @@ -352,6 +354,7 @@ dependencies = [ "semver", "serde", "serde_json", + "serde_rusqlite", "sha2", "sysinfo", "tempfile", @@ -361,6 +364,7 @@ dependencies = [ "tracing-subscriber", "url", "uuid", + "weak-table", "windows-sys 0.61.2", "wiremock", "zstd", @@ -756,12 +760,6 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" -[[package]] -name = "foldhash" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" - [[package]] name = "foldhash" version = "0.2.0" @@ -961,12 +959,9 @@ dependencies = [ [[package]] name = "hashbrown" -version = "0.15.5" +version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" -dependencies = [ - "foldhash 0.1.5", -] +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" [[package]] name = "hashbrown" @@ -976,16 +971,16 @@ checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" dependencies = [ "allocator-api2", "equivalent", - "foldhash 0.2.0", + "foldhash", ] [[package]] name = "hashlink" -version = "0.10.0" +version = "0.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" +checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" dependencies = [ - "hashbrown 0.15.5", + "hashbrown 0.17.1", ] [[package]] @@ -1359,9 +1354,9 @@ checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" [[package]] name = "libsqlite3-sys" -version = "0.35.0" +version = "0.39.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "133c182a6a2c87864fe97778797e46c7e999672690dc9fa3ee8e241aa4a9c13f" +checksum = "14a5f01b87b92705d07b433c06f96cbc764637d81a0bffb5734ce17cf0f9a2b3" dependencies = [ "cc", "pkg-config", @@ -1937,11 +1932,20 @@ dependencies = [ "cc", ] +[[package]] +name = "rsqlite-vfs" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353b74f9810d5b085b6c42c9d86a5f0fdb795553235cdd48753b32e3809d18a7" +dependencies = [ + "thiserror", +] + [[package]] name = "rusqlite" -version = "0.37.0" +version = "0.41.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "165ca6e57b20e1351573e3729b958bc62f0e48025386970b6e4d29e7a7e71f3f" +checksum = "da9bba6f3506135e120a6586df05be18b48d18896600646a4bec8f993d91a594" dependencies = [ "bitflags", "fallible-iterator", @@ -1949,6 +1953,7 @@ dependencies = [ "hashlink", "libsqlite3-sys", "smallvec", + "sqlite-wasm-rs", ] [[package]] @@ -2190,6 +2195,16 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "serde_rusqlite" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "554f7555174fb6e1b86062e62fa7c086e88513d4067bc106ffba2db7b24fcca2" +dependencies = [ + "rusqlite", + "serde_core", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -2288,6 +2303,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "sqlite-wasm-rs" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cd504cecbfe7eef649988840f9a6cb768d11085efec138f8e99f160632d867" +dependencies = [ + "cc", + "rsqlite-vfs", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -2376,18 +2401,18 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.19" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09a43598840e33d5b0331f38c5e30d13bb11c11210a4b58f0d9b18a5a5eefcd9" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "2.0.19" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43cbfe0cf76104d42a574802844187e84a305e531ed54455f11fbde0f10541cd" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", @@ -2798,6 +2823,16 @@ dependencies = [ "web-sys", ] +[[package]] +name = "weak-table" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eba2ec791141b0bf4db542f6b038a8f9310cee33e076cb181245780b09a24ff" +dependencies = [ + "cfg-if", + "hashbrown 0.16.1", +] + [[package]] name = "web-sys" version = "0.3.103" diff --git a/bt-daemon/Cargo.toml b/bt-daemon/Cargo.toml index 24ab5c5f..9328cc3a 100644 --- a/bt-daemon/Cargo.toml +++ b/bt-daemon/Cargo.toml @@ -11,6 +11,8 @@ description = "Embeddable Braintrust coding-agent tracing daemon." default = [] # Standalone development/test binary. Production embeds the library in `bt`. cli = [] +# Storage inspection and fault injection for this crate's integration tests. +test-support = [] [[bin]] name = "bt-daemon" @@ -34,6 +36,7 @@ async-trait = "0.1" chrono = "0.4" clap = { version = "4", features = ["derive", "env"] } fs2 = "0.4" +futures = { version = "0.3", default-features = false, features = ["std"] } regex = "1" rquickjs = "0.12.2" rquickjs-serde = "0.6.1" @@ -50,13 +53,16 @@ tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] } uuid = { version = "1", features = ["v4", "v5"] } url = "2" -rusqlite = { version = "0.37", features = ["bundled"] } +rusqlite = { version = "0.41", features = ["bundled", "fallible_uint"] } +serde_rusqlite = "0.44" +weak-table = "0.4" file-rotate = "0.8" [target.'cfg(windows)'.dependencies] windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_System_Threading"] } [dev-dependencies] +bt-daemon = { path = ".", features = ["test-support"] } axum = "0.8" bytes = "1" reqwest = { version = "0.12", default-features = false, features = ["json", "stream"] } diff --git a/bt-daemon/docs/protocol.md b/bt-daemon/docs/protocol.md index 23ea0333..7c88dc6d 100644 --- a/bt-daemon/docs/protocol.md +++ b/bt-daemon/docs/protocol.md @@ -65,9 +65,9 @@ not found, `-32602` invalid params, `-32603` internal); application errors use ### Ordering & delivery A capture adapter sends `event.log` as a **request** and waits only for the raw -event and any transcript high-water reference to be flushed to the daemon's -journal. The daemon then queues correlation, translation, and reporting on its -own workers. Per-session journal appends are serialized, and the daemon keeps +event and any transcript high-water reference to be committed to the daemon's +session storage. The daemon then queues correlation, translation, and reporting on its +own workers. Per-session captures are serialized, and the daemon keeps derived processing ordered without making the hook wait for it. Subprocess shims may exit as soon as they receive the response; long-lived in-process clients use the same request boundary. @@ -109,7 +109,7 @@ The hot path. Params are the **Envelope** (see below). Request result: { "accepted": true } ``` `accepted: true` means the raw capture is durably recorded in the source -journal. It does not mean authentication, correlation, translation, session +session's storage. It does not mean authentication, correlation, translation, session queueing, or Braintrust delivery has completed. Those steps run out-of-band; errors are surfaced via `status.get`. Before correlating a new session, the daemon settles previously dispatched parent events. Command-hook correlation @@ -118,7 +118,7 @@ process. This discovery window ends after five seconds or three events, whicheve comes first; insufficient evidence falls back to the original standalone route. A timer enforces the deadline even if no further events arrive. Pending sessions remain visible in status with a nonzero `queued` count and an -explanation in `last_error`. On restart, uncheckpointed journal entries are +explanation in `last_error`. On restart, captured events not yet delivered are queued again automatically. Explicit status and flush requests act as daemon-worker barriers, but hook capture never does. @@ -287,10 +287,10 @@ version, `context.span_origin..version` is its coding-agent `source_version`, and `context.span_origin.bt.version` is the daemon version at span creation. `` is the canonical name, such as `codex` or `claude-code`, not a literal `agent` key. Unknown plugin and agent versions are explicit JSON -`null`; they never fall back to another component's version. Translation -records each snapshot in the session's SpanOp storage when its span is created, -before delivery; later updates, resume, and replay reuse it unchanged, even -across upgrades. +`null`; they never fall back to another component's version. The +session's storage records each snapshot when its span is created, before +delivery; later updates, resume, and replay reuse it unchanged, even across +upgrades. New spans capture new snapshots instead of inheriting the root's versions. Provisional roots retain their original snapshot while waiting for work. An unmaterialized span replayed for a new destination uses its @@ -394,8 +394,8 @@ Field notes: ### Redaction -Live credentials returned by the host provider are **never** written to the -journal, logs, status, or RPC response. Envelopes journal only their non-secret +Live credentials returned by the host provider are **never** written to +session storage, logs, status, or RPC response. Stored envelopes keep only their non-secret `route`, allowing restart recovery to resolve a fresh lease. Span plugins read an environment snapshot captured inside their daemon worker process; it is not part of the envelope or journal schema. @@ -417,15 +417,15 @@ part of the envelope or journal schema. zero active sessions and empty queues. - **Session retirement.** A delivery pipeline with no traffic for `--session-idle-timeout` (default 300 s) and an empty queue is flushed and - dropped: its translator state, sink handles, credential lease, and journal + dropped: its translator state, sink handles, credential lease, and storage handle are released rather than held for the daemon's lifetime. A later - event rebuilds it from the journal, and deterministic span ids merge the + event resumes it from session storage, and deterministic span ids merge the re-emitted rows. This matters because the idle exit above requires *every* session to be quiet, which for a continuously active user never happens. - **Version handover.** `initialize` compares versions. Older clients use a newer compatible daemon. A newer client sends `daemon.shutdown`; the old daemon quiesces and drains before acknowledging, then the client spawns its - daemon. In-flight session state is rebuilt from the journal. This makes + daemon. In-flight session state resumes from session storage. This makes upgrades monotonic instead of allowing mixed-version clients to repeatedly replace each other. @@ -435,17 +435,18 @@ Transcript import and hook capture share one pipeline. The `import [project_logs: | experiment:]` command locates the selected agent's native transcript and captures synthetic lifecycle events with the daemon, which -journals, translates and delivers them like hook events (see `import.finish`). -Each import run captures into its own daemon-side session, separate from the -native session's live capture and from earlier imports, and translates the -native session from fresh state under the native session's identity. It -therefore reproduces the native session's deterministic span ids and delivers -every span to its destination, including one that already received the session -elsewhere. Importing a session again re-delivers its rows under the same ids; -an import older than what a destination already holds may replace newer -content on the spans they share. Recovery replays the journal to rebuild state -and may idempotently re-emit rows under their original deterministic ids. -`--parent +translates and delivers them like hook events (see `import.finish`). Each +import run captures into its own daemon-side session, separate from the native +session's live capture and from earlier imports, and translates the native +session from fresh state under the native session's identity. It therefore +reproduces the native session's deterministic span ids and delivers every span +to its destination, including one that already received the session elsewhere. +Importing a session again re-delivers its rows under the same ids; an import +older than what a destination already holds may replace newer content on the +spans they share. Within one session, capture is idempotent while its storage +exists: the same event captured again for the same route, such as a hook +retried across a daemon handover, is acknowledged without being recorded +twice. `--parent ` attaches it below an exported span and is mutually exclusive with an object destination. @@ -460,7 +461,7 @@ inherited environment marker makes installed Braintrust plugin hooks no-op for that managed child, while a private hook flag authorizes the injected hook process. Codex does not bypass hook trust: the user reviews the injected hook once through `/hooks`, and Codex reuses its hash-based trust while the definition is unchanged. -The resulting native hook events follow the regular journal, translator, and +The resulting native hook events follow the regular capture, translator, and sink path; transcript tailing remains specific to `import --attach`. The managed child inherits a non-secret invocation-settings value containing `trace_to_braintrust: true` and its immutable `SessionRoute`. This overrides the @@ -468,45 +469,42 @@ persistent setup route only within that process tree. Other agent processes continue using setup settings, and concurrent managed runs can select distinct profiles, organizations, and destinations while sharing one daemon. -- **Journal (WAL).** Every accepted event is appended (auth-redacted) to - `/journal/----.ndjson` before/at - enqueue — one journal file per source and session_id, shared across every - route that session has opened. The sanitized session_id keeps only its tail - when the name would exceed 255 bytes; the stable id keeps names distinct. - `data_dir` defaults to `$XDG_STATE_HOME/braintrust/bt-daemon` or +- **Session storage.** Each source session has one SQLite database, + `/pipeline/.sqlite`, shared by every route that session + has opened. `data_dir` defaults to `$XDG_STATE_HOME/braintrust/bt-daemon` or `$HOME/.braintrust/state/bt-daemon` on Unix, and - `%LOCALAPPDATA%\Braintrust\bt-daemon` on Windows. On restart the daemon - rebuilds each route's unfinished correlation state independently, replaying - only the journal entries whose delivery route matches that pipeline into a - fresh translator. Span plugin paths are ignored for this comparison so raw - events can be replayed through the current plugin chain. The resulting rows - may be resubmitted to repair delivery - interrupted by a crash, but their deterministic ids target the same backend - rows and must never create duplicate spans, and a route never receives - another route's rows. Replay streams the journal and is bounded to the - bytes recorded before the replaying session was created, so recovering a - long session costs no more memory than running it. The journal itself is - never capped or truncated — dropping entries would silently cost recovery - fidelity — so its size is governed by writing each transcript byte once - (below) and by GC after 7 days. + `%LOCALAPPDATA%\Braintrust\bt-daemon` on Windows. Capture inserts each + accepted event (auth-redacted) before acknowledging it. Translation removes + consumed events in the same transaction that stores their SpanOps and the + translator's continuation, so a crash either keeps the event or keeps its + output, never neither. Each route has a durable head; a SpanOp is removed + once every route has delivered it. Deterministic ids mean a route resuming + after a crash may resubmit rows that target the same backend rows, never + duplicate spans, and a route never receives another route's rows. What + remains after delivery is only the continuation and small per-span metadata + a resumed session needs; storage of a session that owes nothing is deleted + once it has been inactive for 7 days. Activity is recorded by capture, + translation and delivery, never by opening storage. NDJSON journals written + by earlier daemons are read only to import them, at their original + positions, and are then deleted; their delivery ledgers are deleted. - **Transcript mirrors.** Claude transcript files are external mutable state, so a lifecycle event must stay replayable after the agent rewrites the path it came from. The daemon appends new transcript bytes to `/transcripts/.jsonl` — one mirror per - (session_id, transcript path) — and the journal entry carries only + (session_id, transcript path) — and the captured event carries only `_bt_transcript_mirror: {path, mirror, through}`. `through` is the mirror's high-water offset at acceptance, which bounds replay to exactly the bytes - the live run saw. Storing each byte once keeps a journal proportional to a + the live run saw. Storing each byte once keeps captured input proportional to a session's transcript rather than to its transcript times its turn count. Entries written before mirroring instead carry the whole transcript inline as `_bt_transcript_snapshot`, which translators still accept. Mirrors are - GC'd after 7 days like the journal. -- **Managed-run acceptance records.** Alongside the journal, each accepted + GC'd after 7 days once no retained session references them. +- **Managed-run acceptance records.** Alongside session storage, each accepted event that carries a `managed_run_id` also appends `{session_id, route}` to `/managed-runs/.ndjson`. `managed_run.flush` reads this record when the daemon that accepted the events has since restarted or idle-exited, so flush accounting for a child process tree survives a daemon - generation change. GC'd after 7 days like the journal. + generation change. GC'd after 7 days. - **Deterministic span ids.** Translators derive span ids as UUIDv5 over stable keys (`session_id`, `turn_id`, `call_id`, …) so a replayed re-emit merges server-side (`_is_merge`) instead of duplicating. diff --git a/bt-daemon/src/collections/events.rs b/bt-daemon/src/collections/events.rs new file mode 100644 index 00000000..12b568fa --- /dev/null +++ b/bt-daemon/src/collections/events.rs @@ -0,0 +1,370 @@ +//! Captured input for one source session. Capture inserts a redacted event and +//! acknowledges it only after the insert commits. Translation reads records in +//! order and removes them in the same transaction that stores their output. +//! +//! Record IDs grow by each record's encoded size, so IDs imported from a legacy +//! NDJSON journal keep their original byte boundaries and input budgets still +//! measure bytes. Removal never renumbers later records. +use super::store::{read_batch, Json, One, SessionStorage, NOW_MS}; +use crate::pipeline::input::{PipelineControl, SourcePosition}; +use crate::wire::RedactedEnvelope; +use futures::{future::BoxFuture, ready, Stream, TryStreamExt}; +use rusqlite::params; +use sha2::{Digest, Sha256}; +use std::{ + collections::VecDeque, + pin::Pin, + task::{Context, Poll}, +}; + +const READ_RECORDS: usize = 32; +const READ_BYTES: usize = 256 * 1024; +/// Payload fields the daemon adds to record what it captured alongside an event. +const CAPTURE_REFERENCES: [&str; 3] = [ + "_bt_claude_transcript_mirrors", + "_bt_transcript_mirror", + "_bt_transcript_replay", +]; +/// Payload fields that identify on-disk state the session still references. +const IDENTITY_PAYLOAD: [&str; 3] = [ + "transcript_path", + "agent_transcript_path", + "_bt_transcript_mirror", +]; + +#[derive(Debug)] +// Keep event records inline on the read path; the capture completeness bit +// makes this enum just exceed Clippy's size threshold. +#[allow(clippy::large_enum_variant)] +pub(crate) enum EventRecord { + Event(RedactedEnvelope), + Control(PipelineControl), +} + +impl From<&crate::wire::Envelope> for EventRecord { + fn from(env: &crate::wire::Envelope) -> Self { + Self::Event(env.redacted()) + } +} + +impl From for EventRecord { + fn from(control: PipelineControl) -> Self { + Self::Control(control) + } +} + +#[derive(Debug)] +pub(crate) struct EventEntry { + pub id: u64, + pub record: EventRecord, +} + +/// A record as stored: its kind, and the event or control as JSON. +#[derive(PartialEq)] +pub(super) struct Stored { + pub control: bool, + pub value: Vec, +} + +impl TryFrom<&EventRecord> for Stored { + type Error = serde_json::Error; + fn try_from(record: &EventRecord) -> serde_json::Result { + Ok(match record { + EventRecord::Event(event) => Self { + control: false, + value: serde_json::to_vec(event)?, + }, + EventRecord::Control(control) => Self { + control: true, + value: serde_json::to_vec(control)?, + }, + }) + } +} + +impl TryFrom<&Stored> for EventRecord { + type Error = serde_json::Error; + fn try_from(stored: &Stored) -> serde_json::Result { + Ok(if stored.control { + Self::Control(serde_json::from_slice(&stored.value)?) + } else { + Self::Event(serde_json::from_slice(&stored.value)?) + }) + } +} + +impl SessionStorage { + /// Append a record and return the ID range it occupies. The caller may + /// acknowledge it once this returns: it is durable and visible to + /// translation. Returns `None` when nothing was appended: + /// - an event already captured, such as a re-import or a capture retried + /// across a daemon handover, is acknowledged without a second record; + /// - with `after`, a record lands only if nothing else has since `after`, + /// so a control is never ordered ahead of work translation has not seen. + pub async fn append( + &self, + record: impl Into, + after: Option, + ) -> anyhow::Result> { + let mut record = record.into(); + let capture = match &mut record { + EventRecord::Event(event) => { + let capture = (digest(event)?, identity(event)); + compact_pi_payload(event); + Some(capture) + } + EventRecord::Control(_) => None, + }; + let stored = Stored::try_from(&record)?; + self.write(move |tx| { + let tail: u64 = tx.one("SELECT event_tail FROM session WHERE id=1", [])?; + if after.is_some_and(|after| tail > after) { + return Ok(None); + } + let Some((digest, mut identity)) = capture else { + return insert(tx, stored).map(Some); + }; + if tx.execute( + &format!("INSERT OR IGNORE INTO captured(digest,at_ms) VALUES(?,{NOW_MS})"), + [digest], + )? == 0 + { + return Ok(None); + } + let previous: Option> = + tx.one("SELECT identity FROM session WHERE id=1", [])?; + if let Some(Json(previous)) = previous { + retain_references(&mut identity, &previous); + } + let appended = insert(tx, stored)?; + tx.execute( + "UPDATE session SET identity=? WHERE id=1", + [Json(&identity)], + )?; + Ok(Some(appended)) + }) + .await + } + + /// The latest captured event with only state-referencing payload fields. + pub async fn identity(&self) -> anyhow::Result> { + self.run(|db| { + let identity: Option> = + db.one("SELECT identity FROM session WHERE id=1", [])?; + Ok(identity.map(|Json(identity)| identity)) + }) + .await + } + + /// Lazily read records with IDs in `(after, through]`. Reading never + /// changes membership; only a committed translation removes records. + pub fn read(&self, after: u64, through: u64) -> EventReader { + EventReader { + storage: self.clone(), + position: after, + through, + buffer: VecDeque::new(), + fetch: None, + } + } +} + +/// What identifies one capture of a native event. Route and capture context +/// are part of it: hooks may deliver one native event to several +/// destinations, each as its own capture. Daemon-added transcript references +/// describe the capture, not the native event. +fn digest(event: &RedactedEnvelope) -> anyhow::Result> { + let mut payload = event.payload.clone(); + if let Some(payload) = payload.as_object_mut() { + for key in CAPTURE_REFERENCES { + payload.remove(key); + } + } + Ok(Sha256::digest(serde_json::to_vec(&( + &event.event, + event.ts_ms, + &payload, + &event.route, + &event.capture, + ))?) + .to_vec()) +} + +/// Keep on-disk references an earlier identity recorded that `identity` omits. +pub(super) fn retain_references(identity: &mut RedactedEnvelope, previous: &RedactedEnvelope) { + if let (Some(payload), Some(old)) = ( + identity.payload.as_object_mut(), + previous.payload.as_object(), + ) { + for key in IDENTITY_PAYLOAD { + if let (false, Some(value)) = (payload.contains_key(key), old.get(key)) { + payload.insert(key.into(), value.clone()); + } + } + } +} + +/// The event with only the payload fields that reference on-disk state. +pub(super) fn identity(event: &RedactedEnvelope) -> RedactedEnvelope { + let mut identity = event.clone(); + identity.payload = serde_json::Value::Object( + IDENTITY_PAYLOAD + .iter() + .filter_map(|key| Some(((*key).into(), event.payload.get(*key)?.clone()))) + .collect(), + ); + identity +} + +fn insert(tx: &rusqlite::Transaction<'_>, stored: Stored) -> anyhow::Result { + let before: u64 = tx.one("SELECT event_tail FROM session WHERE id=1", [])?; + let through = before + .checked_add(stored.value.len() as u64 + 1) + .filter(|id| *id <= i64::MAX as u64) + .ok_or_else(|| anyhow::anyhow!("event ID overflow"))?; + tx.execute( + "INSERT INTO events(id,control,value) VALUES(?,?,?)", + params![through, stored.control, stored.value], + )?; + tx.execute("UPDATE session SET event_tail=? WHERE id=1", [through])?; + super::store::touch(tx)?; + Ok(SourcePosition { before, through }) +} + +type Batch = VecDeque<(u64, serde_json::Result)>; + +/// An ordered stream of the event records in a range, fetched in batches. +/// It ends at the end of the range; [`extend`](Self::extend) lets it +/// continue as later records arrive. +pub(crate) struct EventReader { + storage: SessionStorage, + position: u64, + through: u64, + /// Each fetched record decoded, or why it could not be. + buffer: Batch, + fetch: Option>>, +} + +impl EventReader { + /// The ID of the last record read. + pub fn position(&self) -> u64 { + self.position + } + + pub fn extend(&mut self, through: u64) { + self.through = self.through.max(through); + } + + /// The native events, skipping controls. + pub fn events(self) -> impl Stream> { + self.try_filter_map(|entry| async move { + Ok(match entry.record { + EventRecord::Event(event) => Some(event), + EventRecord::Control(_) => None, + }) + }) + } + + fn fetch(&self) -> BoxFuture<'static, anyhow::Result> { + let (storage, after, through) = (self.storage.clone(), self.position, self.through); + Box::pin(async move { + let batch = storage + .run(move |db| { + read_batch( + db, + "SELECT id,control,value FROM events WHERE id>? AND id<=? ORDER BY id LIMIT ?", + params![after, through, READ_RECORDS], + READ_BYTES, + std::time::Duration::MAX, + |row| { + let stored = Stored { + control: row.get(1)?, + value: row.get(2)?, + }; + let size = stored.value.len(); + Ok((size, (row.get(0)?, EventRecord::try_from(&stored)))) + }, + ) + }) + .await?; + Ok(batch.into()) + }) + } +} + +impl Stream for EventReader { + type Item = anyhow::Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = &mut *self; + if this.buffer.is_empty() && this.position < this.through { + let fetch = match this.fetch.take() { + Some(fetch) => fetch, + None => this.fetch(), + }; + let fetch = this.fetch.insert(fetch); + let batch = ready!(fetch.as_mut().poll(cx)); + this.fetch = None; + this.buffer = match batch { + Ok(batch) => batch, + Err(error) => return Poll::Ready(Some(Err(error))), + }; + } + let Some((id, record)) = this.buffer.pop_front() else { + return Poll::Ready(None); + }; + Poll::Ready(Some(match record { + Ok(record) => { + this.position = id; + Ok(EventEntry { id, record }) + } + Err(error) => { + // Leave the position at the last good record, so a retry + // reads the undecodable record again. + this.buffer.clear(); + Err(anyhow::Error::new(error).context(format!("event record {id}"))) + } + })) + } +} + +/// Drop Pi payload fields the translator never reads before they reach disk. +fn compact_pi_payload(event: &mut RedactedEnvelope) { + if event.source != "pi" { + return; + } + let Some(native) = event + .payload + .get_mut("event") + .and_then(serde_json::Value::as_object_mut) + else { + return; + }; + match event.event.as_str() { + "before_provider_request" => { + // The translator records only the allowlisted request + // configuration and tool definitions, never the prompt or messages. + if let Some(payload) = native.get_mut("payload") { + *payload = serde_json::Value::Object(crate::translate::pi_request_config(payload)); + } + } + "agent_end" => { + // The translator only consumes willRetry from this lifecycle event. + native.remove("messages"); + } + "message_update" => { + // Pi repeats the progressively growing assistant message on every + // streaming update. Translation only needs the update type to mark + // time-to-first-token; the completed message arrives separately. + native.remove("message"); + if let Some(update) = native + .get_mut("assistantMessageEvent") + .and_then(serde_json::Value::as_object_mut) + { + update.retain(|key, _| key == "type"); + } + native.retain(|key, _| key == "type" || key == "assistantMessageEvent"); + } + _ => {} + } +} diff --git a/bt-daemon/src/collections/inspect.rs b/bt-daemon/src/collections/inspect.rs new file mode 100644 index 00000000..110cbccd --- /dev/null +++ b/bt-daemon/src/collections/inspect.rs @@ -0,0 +1,278 @@ +//! Test support: inspect session storage and inject storage faults through a +//! typed interface, so tests outside this module never contain SQL. +#![allow(dead_code, reason = "Different test suites use different inspectors.")] +use super::store::{Json, One}; +use rusqlite::Connection; +use serde_json::Value; +use std::path::{Path, PathBuf}; + +/// A storage write that can be made to fail. +#[derive(Clone, Copy, Debug)] +pub enum Fault { + /// The handoff of an input's translation and continuation. + Handoff, + InsertOps, + AdvanceHead, + RemoveEvents, +} + +impl Fault { + fn trigger(self) -> (&'static str, &'static str) { + match self { + Self::Handoff => ("fault_handoff", "BEFORE UPDATE OF through ON session"), + Self::InsertOps => ("fault_insert_ops", "BEFORE INSERT ON ops"), + Self::AdvanceHead => ("fault_head", "BEFORE UPDATE OF position ON heads"), + Self::RemoveEvents => ("fault_remove_events", "BEFORE DELETE ON events"), + } + } +} + +/// Stored record kinds that can be counted. +#[derive(Clone, Copy, Debug)] +pub enum Table { + Events, + Ops, + Heads, + Origins, +} + +impl Table { + fn name(self) -> &'static str { + match self { + Self::Events => "events", + Self::Ops => "ops", + Self::Heads => "heads", + Self::Origins => "origins", + } + } +} + +/// One route's durable delivery head. +#[derive(Debug, Clone, serde::Deserialize)] +pub struct Head { + pub position: u64, + pub failure: Option, + /// Corrected settings recorded for a held head. + #[serde(deserialize_with = "super::store::json_or_null")] + pub settings: Option, +} + +/// The database file holding one source session. +pub fn session_path(data_dir: &Path, source: &str, session_id: &str) -> PathBuf { + super::session::session_path(data_dir, source, session_id) +} + +/// A separate connection to a session database, independent of the daemon's. +pub struct Inspector(Connection); + +impl Inspector { + /// Open (creating at the current schema if needed) a session database. + pub fn open(path: &Path) -> anyhow::Result { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + Ok(Self(super::store::open_connection(path)?)) + } + + pub fn session(data_dir: &Path, source: &str, session_id: &str) -> anyhow::Result { + Self::open(&session_path(data_dir, source, session_id)) + } + + /// Open without creating or upgrading anything; `None` if it is absent. + pub fn existing(path: &Path) -> Option { + let db = + Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY).ok()?; + db.busy_timeout(std::time::Duration::from_secs(1)).ok()?; + Some(Self(db)) + } + + pub fn count(&self, table: Table) -> u64 { + self.0 + .one(&format!("SELECT count(*) FROM {}", table.name()), []) + .unwrap_or(0) + } + + /// Event records awaiting translation, decoded as JSON. + pub fn events(&self) -> Vec { + let Ok(mut query) = self.0.prepare("SELECT value FROM events ORDER BY id") else { + return Vec::new(); + }; + let Ok(rows) = query.query_map([], |r| r.get::<_, Vec>(0)) else { + return Vec::new(); + }; + rows.filter_map(|row| serde_json::from_slice(&row.ok()?).ok()) + .collect() + } + + /// Encoded SpanOp records in publication order. + pub fn op_records(&self) -> Vec> { + let Ok(mut query) = self.0.prepare("SELECT value FROM ops ORDER BY position") else { + return Vec::new(); + }; + let Ok(rows) = query.query_map([], |r| r.get::<_, Vec>(0)) else { + return Vec::new(); + }; + rows.filter_map(Result::ok).collect() + } + + pub fn identity(&self) -> Option { + let Json(identity) = self + .0 + .one("SELECT identity FROM session WHERE id=1", []) + .ok()?; + Some(identity) + } + + /// The translator continuation saved with the last handed-over input. + pub fn continuation(&self) -> Option { + let Json(continuation) = self + .0 + .one("SELECT continuation FROM session WHERE id=1", []) + .ok()?; + Some(continuation) + } + + /// The reference count of each stored attachment. + pub fn attachment_refs(&self) -> Vec { + super::store::select::<(u64,)>( + &self.0, + "SELECT refs FROM attachment_blobs ORDER BY digest", + [], + ) + .map(|rows| rows.into_iter().map(|(refs,)| refs).collect()) + .unwrap_or_default() + } + + pub fn heads(&self) -> Vec { + super::store::select(&self.0, "SELECT position, failure, settings FROM heads", []) + .unwrap_or_default() + } + + /// The position of the last published SpanOp. + pub fn published_tail(&self) -> u64 { + self.0 + .one("SELECT op_tail FROM session WHERE id=1", []) + .unwrap_or(0) + } + + /// Heads that are failed or behind the published tail. + pub fn held_heads(&self) -> u64 { + self.0 + .one( + "SELECT count(*) FROM heads WHERE failure IS NOT NULL + OR position<(SELECT op_tail FROM session WHERE id=1)", + [], + ) + .unwrap_or(0) + } + + /// All captured input is translated and every head has delivered. + pub fn delivered(&self) -> bool { + self.0 + .one( + "SELECT continuation IS NOT NULL AND through>=event_tail FROM session WHERE id=1", + [], + ) + .unwrap_or(false) + && self.held_heads() == 0 + } + + pub fn inject(&self, fault: Fault) -> anyhow::Result<()> { + let (name, when) = fault.trigger(); + self.0.execute_batch(&format!( + "CREATE TRIGGER IF NOT EXISTS {name} {when} BEGIN SELECT RAISE(FAIL,'injected {name}'); END;" + ))?; + Ok(()) + } + + pub fn clear(&self, fault: Fault) -> anyhow::Result<()> { + self.0 + .execute_batch(&format!("DROP TRIGGER IF EXISTS {}", fault.trigger().0))?; + Ok(()) + } + + /// Make event records in `(after, through]` undecodable. + pub fn corrupt_events(&self, after: u64, through: u64) -> anyhow::Result<()> { + self.0.execute( + "UPDATE events SET value=x'78' WHERE id>? AND id<=?", + [after, through], + )?; + Ok(()) + } + + pub fn corrupt_checkpoint(&self) -> anyhow::Result<()> { + self.0 + .execute_batch("UPDATE session SET continuation=x'78' WHERE id=1")?; + Ok(()) + } + + /// Make every activity the session recorded `by` older. + pub fn age(&self, by: std::time::Duration) -> anyhow::Result<()> { + let by = i64::try_from(by.as_millis())?; + for statement in [ + "UPDATE session SET active_ms=active_ms-?", + "UPDATE captured SET at_ms=at_ms-?", + "UPDATE origins SET ended_ms=ended_ms-?", + "UPDATE span_state SET touched_ms=touched_ms-?", + "UPDATE heads SET progress_ms=progress_ms-?", + ] { + self.0.execute(statement, [by])?; + } + Ok(()) + } + + /// Register a delivery head at the start, as a route subscribed before + /// any output existed. + pub fn add_head(&self, route: &impl serde::Serialize) -> anyhow::Result<()> { + self.0.execute( + &format!( + "INSERT OR IGNORE INTO heads(route,position,progress_ms) VALUES (?,0,{})", + super::store::NOW_MS + ), + [serde_json::to_string(route)?], + )?; + Ok(()) + } + + /// Record input through `through` as translated, as an earlier daemon + /// left it, without a continuation. + pub fn set_translated(&self, through: u64) -> anyhow::Result<()> { + self.0 + .execute("UPDATE session SET through=? WHERE id=1", [through])?; + Ok(()) + } + + /// Return every head to the start and clear failures. + pub fn rewind_heads(&self) -> anyhow::Result<()> { + self.0 + .execute("UPDATE heads SET position=0,failure=NULL", [])?; + Ok(()) + } + + /// Mark the database as written by a different storage schema. + pub fn set_schema_version(&self, version: u32) -> anyhow::Result<()> { + self.0 + .execute_batch(&format!("PRAGMA user_version={version}"))?; + Ok(()) + } + + /// Undo [`Self::set_schema_version`]. + pub fn restore_schema_version(&self) -> anyhow::Result<()> { + self.set_schema_version(super::store::SCHEMA) + } + + pub fn checkpoint_wal(&self) -> anyhow::Result<()> { + self.0.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")?; + Ok(()) + } + + /// Copy the database, as a crash-consistent snapshot, to `to`. + pub fn backup(&self, to: &Path) -> anyhow::Result<()> { + self.0.execute( + "VACUUM INTO ?", + [to.to_str() + .ok_or_else(|| anyhow::anyhow!("backup path is not UTF-8"))?], + )?; + Ok(()) + } +} diff --git a/bt-daemon/src/collections/legacy.rs b/bt-daemon/src/collections/legacy.rs new file mode 100644 index 00000000..60853be3 --- /dev/null +++ b/bt-daemon/src/collections/legacy.rs @@ -0,0 +1,403 @@ +//! Read-only migration of NDJSON event journals written before collections. +//! +//! Records are imported at their original byte boundaries, so translation +//! positions recorded by an older daemon remain valid. Delivery checkpoints are +//! not imported: input every route had delivered is instead marked translated, +//! so the translator rebuilds its state from it without publishing it again. A +//! journal file is deleted only after every record it contributes has been +//! committed. +use super::events::{EventRecord, Stored}; +use super::store::{Json, SessionStorage}; +use crate::journal::{journal_dir, journal_path, source_journal_path}; +use crate::wire::{RedactedEnvelope, SessionRoute}; +use anyhow::Context; +use rusqlite::{params, OptionalExtension}; +use serde::Deserialize; +use std::collections::BTreeSet; +use std::collections::HashMap; +use std::path::Path; +use tokio::io::AsyncBufReadExt; + +const IMPORT_RECORDS: usize = 1024; +const IMPORT_BYTES: usize = 8 * 1024 * 1024; +const PI_MESSAGES_DELTA: &str = "_bt_messages_delta"; + +/// Import any legacy journals that hold records for this source session. +pub(super) async fn import_session( + data_dir: &Path, + source: &str, + session_id: &str, + events: &SessionStorage, +) -> anyhow::Result<()> { + let unqualified = journal_path(data_dir, session_id); + if unqualified + .file_name() + .is_some_and(|name| name.len() <= crate::journal::MAX_FILE_NAME_BYTES) + && tokio::fs::try_exists(&unqualified).await? + { + import_unqualified(data_dir, &unqualified).await?; + } + let qualified = source_journal_path(data_dir, source, session_id); + if tokio::fs::try_exists(&qualified).await? { + import_file(&qualified, source, events, None).await?; + tokio::fs::remove_file(&qualified).await?; + } + Ok(()) +} + +/// Import every legacy journal in the data directory. Failures leave that +/// file in place for a later attempt without blocking other sessions. +pub(crate) async fn import_all(data_dir: &Path) { + let Ok(mut entries) = tokio::fs::read_dir(journal_dir(data_dir)).await else { + return; + }; + while let Ok(Some(entry)) = entries.next_entry().await { + let path = entry.path(); + if path.extension().is_none_or(|ext| ext != "ndjson") { + continue; + } + let result = async { + let owners = sessions(&path).await?; + if owners.is_empty() { + // Nothing was ever acknowledged from a file without events. + tokio::fs::remove_file(&path).await?; + } + for (source, session_id) in owners { + SessionStorage::open(data_dir, &source, &session_id).await?; + } + anyhow::Ok(()) + } + .await; + if let Err(error) = result { + tracing::warn!(%error, path = %path.display(), "legacy journal migration is held"); + } + } + // Leave no empty legacy directory behind. + let _ = tokio::fs::remove_dir(journal_dir(data_dir)).await; +} + +/// A pre-qualification journal holds every source observed for one native +/// session id. Split it into each source's collection, then remove it. +async fn import_unqualified(data_dir: &Path, path: &Path) -> anyhow::Result<()> { + // Only the first source recorded for a native session keeps the old + // span-id namespace: that daemon had one actor per native session. + let mut owner = None; + let mut reader = Reader::open(path).await?; + while let Some((_, line)) = reader.next().await? { + if let Line::Record(EventRecord::Event(event)) = line { + owner.get_or_insert_with(|| { + crate::translate::canonical_source_name(&event.source).to_owned() + }); + } + } + for (source, session_id) in sessions(path).await? { + // An older daemon copied this file into a qualified journal on first + // use and appended there. That copy is the authoritative superset. + if tokio::fs::try_exists(source_journal_path(data_dir, &source, &session_id)).await? { + let events = SessionStorage::claim(data_dir, &source, &session_id).await?; + events + .import( + Vec::new(), + Some(Imported { + identity: None, + namespace: Some(owner.as_deref() == Some(source.as_str())), + through: 0, + delivered: 0, + }), + ) + .await?; + continue; + } + let events = SessionStorage::claim(data_dir, &source, &session_id).await?; + import_file( + path, + &source, + &events, + Some(owner.as_deref() == Some(source.as_str())), + ) + .await?; + } + tokio::fs::remove_file(path).await?; + Ok(()) +} + +async fn sessions(path: &Path) -> anyhow::Result> { + let mut sessions = BTreeSet::new(); + let mut reader = Reader::open(path).await?; + while let Some((_, line)) = reader.next().await? { + if let Line::Record(EventRecord::Event(event)) = line { + sessions.insert(( + crate::translate::canonical_source_name(&event.source).to_owned(), + event.session_id, + )); + } + } + Ok(sessions) +} + +async fn import_file( + path: &Path, + source: &str, + events: &SessionStorage, + namespace: Option, +) -> anyhow::Result<()> { + let mut reader = Reader::open(path).await?; + // Each route that captured events, and the latest checkpoint it delivered. + let mut routes: Vec = Vec::new(); + let mut delivered: HashMap = HashMap::new(); + let mut batch = Vec::new(); + let mut bytes = 0; + let mut identity: Option = None; + while let Some((through, line)) = reader.next().await? { + let record = match line { + Line::Record(record) => record, + Line::Checkpoint(checkpoint) => { + let key = serde_json::to_string(&checkpoint.route)?; + let entry = delivered.entry(key).or_default(); + *entry = (*entry).max(checkpoint.through); + continue; + } + }; + match &record { + EventRecord::Event(event) => { + if crate::translate::canonical_source_name(&event.source) != source { + continue; + } + if let Some(route) = &event.route { + if !routes.iter().any(|known| known.same_route(route)) { + routes.push(route.clone()); + } + } + let mut latest = super::events::identity(event); + if let Some(previous) = &identity { + super::events::retain_references(&mut latest, previous); + } + identity = Some(latest); + } + EventRecord::Control(_) => {} + } + let stored = Stored::try_from(&record)?; + bytes += stored.value.len(); + batch.push((through, stored)); + if batch.len() >= IMPORT_RECORDS || bytes >= IMPORT_BYTES { + events.import(std::mem::take(&mut batch), None).await?; + bytes = 0; + } + } + // Input is delivered only through the point every route had delivered. + let delivered = routes + .iter() + .map(|route| { + let key = serde_json::to_string(route)?; + anyhow::Ok(delivered.get(&key).copied().unwrap_or(0)) + }) + .collect::>>()? + .into_iter() + .min() + .unwrap_or(0); + events + .import( + batch, + Some(Imported { + identity, + namespace, + through: reader.position, + delivered, + }), + ) + .await +} + +/// What a fully imported legacy file implies about its session. +struct Imported { + /// The latest event, with only state-referencing payload fields. + identity: Option, + /// Whether this source keeps the pre-qualification span-id namespace. + namespace: Option, + /// The file's length, the boundary for new records. + through: u64, + /// Input every route had delivered, already translated. + delivered: u64, +} + +impl SessionStorage { + /// Import legacy records at their original byte boundaries. Retrying is + /// idempotent. The last batch of a file carries what the file implies + /// about the session as a whole. + async fn import( + &self, + records: Vec<(u64, Stored)>, + finished: Option, + ) -> anyhow::Result<()> { + self.write(move |tx| { + let mut tail = 0; + for (id, stored) in records { + anyhow::ensure!( + id <= i64::MAX as u64, + "legacy position exceeds storage range" + ); + let prior = tx + .query_row("SELECT control,value FROM events WHERE id=?", [id], |r| { + Ok(Stored { + control: r.get(0)?, + value: r.get(1)?, + }) + }) + .optional()?; + match prior { + Some(prior) => { + anyhow::ensure!(prior == stored, "legacy record changed during migration") + } + None => { + tx.execute( + "INSERT INTO events(id,control,value) VALUES(?,?,?)", + params![id, stored.control, stored.value], + )?; + } + } + tail = tail.max(id); + } + if let Some(finished) = &finished { + tail = tail.max(finished.through); + } + tx.execute( + "UPDATE session SET event_tail=max(event_tail,?) WHERE id=1", + [tail], + )?; + let Some(finished) = finished else { + return Ok(()); + }; + tx.execute( + "UPDATE session SET identity=coalesce(?,identity), + legacy_namespace=coalesce(?,legacy_namespace) WHERE id=1", + params![finished.identity.as_ref().map(Json), finished.namespace], + )?; + // Input every route had delivered is translated, unless this + // session already has SpanOp history. The translator rebuilds + // its state from it without publishing it. + tx.execute( + "UPDATE session SET through=? WHERE id=1 AND through=0 AND op_tail=0", + [finished.delivered], + )?; + Ok(()) + }) + .await + } +} + +/// A delivery acknowledgement written by a daemon before SpanOp storage. +#[derive(Deserialize)] +struct Checkpoint { + route: SessionRoute, + through: u64, +} + +#[allow(clippy::large_enum_variant, reason = "One line is read at a time.")] +enum Line { + Record(EventRecord), + Checkpoint(Checkpoint), +} + +/// Streaming NDJSON reader. An incomplete final line was never acknowledged +/// to capture and is not imported. +struct Reader { + lines: tokio::io::BufReader, + position: u64, + pi_context: Vec, +} + +impl Reader { + async fn open(path: &Path) -> anyhow::Result { + Ok(Self { + lines: tokio::io::BufReader::new(tokio::fs::File::open(path).await?), + position: 0, + pi_context: Vec::new(), + }) + } + + async fn next(&mut self) -> anyhow::Result> { + loop { + let mut line = Vec::new(); + let read = self.lines.read_until(b'\n', &mut line).await?; + if read == 0 || line.last() != Some(&b'\n') { + return Ok(None); + } + self.position += read as u64; + let text = std::str::from_utf8(&line)?.trim(); + if text.is_empty() { + continue; + } + let context = || format!("legacy journal offset {}", self.position); + let value: serde_json::Value = serde_json::from_str(text)?; + if value + .get("_bt_record_type") + .and_then(serde_json::Value::as_str) + == Some("delivery_checkpoint") + { + let checkpoint = serde_json::from_value(value).map_err(anyhow::Error::from); + return Ok(Some(( + self.position, + Line::Checkpoint(checkpoint.with_context(context)?), + ))); + } + // Legacy journals tag controls and leave events untagged. + let control = value + .get("_bt_record_type") + .and_then(serde_json::Value::as_str) + == Some("pipeline_control"); + let mut record = if control { + serde_json::from_value(value).map(EventRecord::Control) + } else { + serde_json::from_value(value).map(EventRecord::Event) + } + .with_context(context)?; + if let EventRecord::Event(event) = &mut record { + expand_pi_payload(event, &mut self.pi_context)?; + } + return Ok(Some((self.position, Line::Record(record)))); + } + } +} + +/// Older journals stored Pi context as a delta against the previous context. +fn expand_pi_payload( + event: &mut RedactedEnvelope, + previous: &mut Vec, +) -> anyhow::Result<()> { + if event.source != "pi" || event.event != "context" { + return Ok(()); + } + let Some(native) = event + .payload + .get_mut("event") + .and_then(serde_json::Value::as_object_mut) + else { + return Ok(()); + }; + let Some(delta) = native.remove(PI_MESSAGES_DELTA) else { + if let Some(messages) = native.get("messages").and_then(serde_json::Value::as_array) { + *previous = messages.clone(); + } + return Ok(()); + }; + let common_prefix = delta + .get("common_prefix") + .and_then(serde_json::Value::as_u64) + .and_then(|value| usize::try_from(value).ok()) + .ok_or_else(|| anyhow::anyhow!("invalid Pi context common prefix"))?; + anyhow::ensure!( + common_prefix <= previous.len(), + "Pi context common prefix exceeds prior context" + ); + let suffix = delta + .get("suffix") + .and_then(serde_json::Value::as_array) + .ok_or_else(|| anyhow::anyhow!("invalid Pi context suffix"))?; + previous.truncate(common_prefix); + previous.extend(suffix.iter().cloned()); + native.insert( + "messages".into(), + serde_json::Value::Array(previous.clone()), + ); + Ok(()) +} diff --git a/bt-daemon/src/collections/mod.rs b/bt-daemon/src/collections/mod.rs new file mode 100644 index 00000000..64b41ebb --- /dev/null +++ b/bt-daemon/src/collections/mod.rs @@ -0,0 +1,23 @@ +//! Durable pipeline storage. This module is the only owner of SQLite: callers +//! see one [`SessionStorage`] per source session, holding concrete collections of +//! events and SpanOps. They read records in order and remove them once the +//! next stage owns their data or they are irrelevant. +//! +//! Translation transfers events to SpanOps in one transaction; each route +//! removes SpanOps from its view once the backend accepts them. Storage of a +//! session that has met every obligation is deleted. +mod events; +#[cfg(any(test, feature = "test-support"))] +pub mod inspect; +mod legacy; +mod session; +mod span_ops; +mod store; +#[cfg(test)] +mod tests; +mod upgrade; + +pub(crate) use events::{EventReader, EventRecord}; +pub(crate) use span_ops::{metadata_only, BindingChanged, HeldRoute, Translated, DETACHED}; +pub(crate) use store::is_corruption; +pub(crate) use store::SessionStorage; diff --git a/bt-daemon/src/collections/session.rs b/bt-daemon/src/collections/session.rs new file mode 100644 index 00000000..c8b2ac83 --- /dev/null +++ b/bt-daemon/src/collections/session.rs @@ -0,0 +1,272 @@ +//! One source session's database: its event collection, its SpanOp +//! collection, and the single row that records how far each has progressed. +//! Everything that spans both collections, such as handing an input's +//! translation over or deciding the session owes nothing, lives here. +use super::span_ops::{ + decode_roots, detach_attachments, encode_roots, prune, save_metadata, store_attachments, + Translated, +}; +use super::store::{select, One, SessionStorage, NOW_MS}; +use crate::pipeline::live::{Record, SharedOp}; +use crate::translate::SpanOp; +use rusqlite::params; +use std::{ + collections::BTreeMap, + path::{Path, PathBuf}, + time::Duration, +}; + +/// How far a session has progressed, read in one query. +#[derive(Debug, Clone, serde::Deserialize)] +pub(crate) struct Status { + /// The source that owns this database, once claimed. + pub source: Option, + pub session_id: Option, + /// The ID of the last event record ever inserted, including removed records. + pub event_tail: u64, + /// The last input whose translation has been handed over. + pub translated_through: u64, + /// The position of the last committed op. + pub op_tail: u64, + /// Whether this source kept the pre-qualification span-id namespace. + pub legacy_namespace: bool, + /// A translation failure recorded for recovery. + pub source_failure: Option, + /// Time since capture, translation or delivery last made progress. + #[serde(deserialize_with = "millis")] + pub idle_for: Duration, +} + +impl Status { + /// The source and native session this database belongs to. + pub fn owner(&self) -> Option<(String, String)> { + self.source.clone().zip(self.session_id.clone()) + } +} + +fn millis<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result { + ::deserialize(deserializer).map(Duration::from_millis) +} + +/// The database file for one source session. +pub(crate) fn session_path(data_dir: &Path, source: &str, session_id: &str) -> PathBuf { + data_dir.join("pipeline").join(format!( + "{}.sqlite", + crate::ids::session_storage_id(source, session_id) + )) +} + +impl SessionStorage { + /// Every session database in the data directory, after importing legacy journals. + pub async fn all(data_dir: &Path) -> anyhow::Result> { + super::legacy::import_all(data_dir).await; + let mut sessions = Vec::new(); + match tokio::fs::read_dir(data_dir.join("pipeline")).await { + Ok(mut entries) => { + while let Some(entry) = entries.next_entry().await? { + let path = entry.path(); + let session = path + .file_stem() + .and_then(|stem| stem.to_str()) + .is_some_and(|stem| uuid::Uuid::parse_str(stem).is_ok()); + if session && path.extension().is_some_and(|ext| ext == "sqlite") { + sessions.push(path); + } + } + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error.into()), + } + sessions.sort(); + Ok(sessions) + } + + /// Open the session, first importing any legacy NDJSON journal for it. A + /// legacy file is deleted only after its records are committed here. + pub async fn open(data_dir: &Path, source: &str, session_id: &str) -> anyhow::Result { + let source = crate::translate::canonical_source_name(source).to_owned(); + let session = Self::claim(data_dir, &source, session_id).await?; + super::legacy::import_session(data_dir, &source, session_id, &session).await?; + Ok(session) + } + + /// Open the session database without legacy import, recording its owner. + pub(super) async fn claim( + data_dir: &Path, + source: &str, + session_id: &str, + ) -> anyhow::Result { + let session = Self::at(&session_path(data_dir, source, session_id)).await?; + let (source, session_id) = (source.to_owned(), session_id.to_owned()); + session + .write(move |tx| { + tx.execute( + "UPDATE session SET source=?, session_id=? WHERE id=1 AND source IS NULL", + params![source, session_id], + )?; + Ok(()) + }) + .await?; + Ok(session) + } + + pub async fn status(&self) -> anyhow::Result { + self.run(|db| { + select( + db, + &format!( + "SELECT source, session_id, event_tail, through AS translated_through, + op_tail, legacy_namespace, failure AS source_failure, + max(0,{NOW_MS}-active_ms) AS idle_for FROM session WHERE id=1" + ), + [], + )? + .pop() + .ok_or_else(|| anyhow::anyhow!("session row is missing")) + }) + .await + } + + /// The translator continuation saved with the last handed-over input. + pub async fn continuation(&self) -> anyhow::Result>> { + self.run(|db| Ok(db.one("SELECT continuation FROM session WHERE id=1", [])?)) + .await + } + + /// Root candidates still waiting for work. + pub async fn root_candidates(&self) -> anyhow::Result>> { + self.run(|db| { + let bytes: Option> = db.one("SELECT roots FROM session WHERE id=1", [])?; + bytes.map_or_else(|| Ok(BTreeMap::new()), |bytes| decode_roots(&bytes)) + }) + .await + } + + pub async fn set_source_failure(&self, failure: Option) -> anyhow::Result<()> { + self.write(move |tx| { + tx.execute("UPDATE session SET failure=? WHERE id=1", [failure])?; + Ok(()) + }) + .await + } + + /// Hand one input event's complete translation to delivery in a single + /// transaction: store its ops, metadata, root candidates and translator + /// continuation, and remove the consumed events through `input`. Routes + /// then receive the original op instances. An input that is already + /// handed over is left unchanged. Returns the published tail. + /// + /// Inline media become attachments: routes receive them with their bytes, + /// and storage keeps one copy of each until no op references it. + pub async fn commit_translation(&self, mut translated: Translated) -> anyhow::Result { + let encoded = translated + .ops + .iter_mut() + .map(|op| { + let (value, blobs) = detach_attachments(op)?; + Ok((value, blobs, super::metadata_only(op))) + }) + .collect::>>()?; + let roots = encode_roots(&translated.roots)?; + let (input, observation, state) = + (translated.input, translated.observation, translated.state); + let (tail, positions) = self + .write(move |tx| { + let (through, tail): (u64, u64) = + tx.query_row("SELECT through,op_tail FROM session WHERE id=1", [], |r| { + Ok((r.get(0)?, r.get(1)?)) + })?; + if input <= through { + return Ok((tail, Vec::new())); + } + let mut positions = Vec::with_capacity(encoded.len()); + for (value, blobs, metadata) in encoded { + save_metadata(tx, &metadata, observation)?; + let bytes = blobs.iter().fold(value.len(), |bytes, blob| { + bytes.saturating_add(blob.data.len()) + }); + tx.execute("INSERT INTO ops(value) VALUES (?)", [value])?; + let position = tx.last_insert_rowid() as u64; + store_attachments(tx, position, &blobs)?; + positions.push((position, bytes)); + } + let new_tail = positions.last().map_or(tail, |(position, _)| *position); + if !positions.is_empty() { + // Heads that had caught up start waiting for this output now. + tx.execute( + &format!("UPDATE heads SET progress_ms={NOW_MS} WHERE position>=?"), + [tail], + )?; + } + tx.execute( + "UPDATE session SET through=?, op_tail=?, roots=?, + continuation=coalesce(?,continuation) WHERE id=1", + params![input, new_tail, roots, state], + )?; + tx.execute("DELETE FROM events WHERE id<=?", [input])?; + prune(tx)?; + super::store::touch(tx)?; + Ok((new_tail, positions)) + }) + .await?; + let records = positions + .into_iter() + .zip(translated.ops) + .map(|((position, bytes), op)| Record { + position, + bytes, + op: SharedOp::new(op), + }); + self.channel().publish(tail, records).await; + Ok(tail) + } + + /// Every obligation is met: all captured input is translated and every + /// route has delivered every op. Root candidates still waiting for work + /// and input retained only to rebuild translator state are not owed. + pub async fn complete(&self) -> anyhow::Result { + self.run(|db| { + Ok(db.one( + "SELECT NOT EXISTS(SELECT 1 FROM heads WHERE failure IS NOT NULL OR position=s.event_tail + FROM session s WHERE id=1", + [], + )?) + }) + .await + } + + /// Expire what a live session no longer uses once `retention` passes: + /// capture identities, metadata of spans that ended or were never + /// completed, and heads that were registered for output but never + /// subscribed (such as a route whose credentials never resolved) and have + /// owed it that long. Ops no remaining head needs are then deleted. A + /// subscribed head held by a failure is kept for recovery, and so is every + /// route named in `live`, which has an active delivery. + pub async fn expire(&self, retention: Duration, live: Vec) -> anyhow::Result<()> { + let retention = i64::try_from(retention.as_millis()).unwrap_or(i64::MAX); + self.write(move |tx| { + let cutoff: i64 = tx.one(&format!("SELECT {NOW_MS}-?"), [retention])?; + tx.execute("DELETE FROM captured WHERE at_ms(0))?; + rows.collect::, _>>()? + }; + for route in stuck.into_iter().filter(|route| !live.contains(route)) { + tracing::warn!(%route, "undelivered output expired for a route that never subscribed"); + tx.execute("DELETE FROM heads WHERE route=?", [route])?; + } + prune(tx) + }) + .await + } +} diff --git a/bt-daemon/src/collections/span_ops.rs b/bt-daemon/src/collections/span_ops.rs new file mode 100644 index 00000000..473dbedd --- /dev/null +++ b/bt-daemon/src/collections/span_ops.rs @@ -0,0 +1,717 @@ +//! Translated SpanOps for one source session, with one durable head per route. +//! +//! Routes receive ops live, or read them back after a gap. A route removes +//! ops from its view by advancing its head once a destination accepts them, +//! and an op is deleted when every route has passed it. +use super::store::{json, json_or_null, read_batch, select, Json, One, SessionStorage, NOW_MS}; +use crate::{ + attachments::Attachment, + pipeline::live::{Multiplexer, Receiver, Record, SharedOp, BYTE_BUDGET, WINDOW}, + translate::{OriginSnapshot, SinkFields, SpanOp, SpanRow, SpanType}, + wire::{SessionConfig, SessionRoute}, +}; +use rusqlite::{params, Connection, OptionalExtension}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{collections::BTreeMap, sync::Arc}; +use tokio::sync::watch; + +#[derive(Debug, thiserror::Error)] +#[error("credential resolution changed the durable head's pinned backend or organization")] +pub(crate) struct BindingChanged; + +/// The head position of a detached route. SQLite integers are signed, so this +/// is the largest position a head can hold; it is past every SpanOp. +pub(crate) const DETACHED: u64 = i64::MAX as u64; + +/// Explicit codec preserves fields intentionally omitted from wire/plugin JSON. +#[derive(Serialize, Deserialize)] +pub(super) struct StoredOp { + version: u32, + op: Op, + #[serde(flatten)] + fields: SinkFields, +} + +impl<'a> From<&'a SpanOp> for StoredOp<&'a SpanOp> { + fn from(op: &'a SpanOp) -> Self { + Self { + version: 1, + op, + fields: SinkFields::of(op.row()), + } + } +} + +impl TryFrom> for SpanOp { + type Error = anyhow::Error; + fn try_from(mut stored: StoredOp) -> anyhow::Result { + anyhow::ensure!( + stored.version == 1, + "unsupported SpanOp codec {}", + stored.version + ); + stored.fields.restore(stored.op.row_mut()); + Ok(stored.op) + } +} + +impl StoredOp { + pub(super) fn encode(op: &SpanOp) -> anyhow::Result> { + Ok(serde_json::to_vec(&StoredOp::from(op))?) + } + pub(super) fn decode(bytes: &[u8]) -> anyhow::Result { + serde_json::from_slice::(bytes)?.try_into() + } +} + +pub(super) fn encode_roots( + roots: &BTreeMap>, +) -> anyhow::Result>> { + if roots.is_empty() { + return Ok(None); + } + let roots: BTreeMap<_, Vec>> = roots + .iter() + .map(|(id, ops)| (id, ops.iter().map(StoredOp::from).collect())) + .collect(); + Ok(Some(serde_json::to_vec(&roots)?)) +} + +pub(super) fn decode_roots(bytes: &[u8]) -> anyhow::Result>> { + serde_json::from_slice::>>>(bytes)? + .into_iter() + .map(|(id, ops)| { + let ops = ops.into_iter().map(SpanOp::try_from); + Ok((id, ops.collect::>()?)) + }) + .collect() +} + +/// The op as stored, with its attachments' bytes moved out: storage keeps one +/// copy of each attachment however many ops reference it. Inline media in the +/// op's input and output are captured as attachments first. +pub(super) fn detach_attachments(op: &mut SpanOp) -> anyhow::Result<(Vec, Vec)> { + let row = op.row_mut(); + for value in [&mut row.input, &mut row.output].into_iter().flatten() { + crate::attachments::capture(value, &mut row.attachments); + } + for attachment in &row.attachments { + anyhow::ensure!( + format!("{:x}", Sha256::digest(&attachment.data)) == attachment.digest, + "attachment digest does not match captured bytes" + ); + } + let mut stored = op.clone(); + let blobs = stored + .row_mut() + .attachments + .iter_mut() + .map(|attachment| Attachment { + data: std::mem::take(&mut attachment.data), + ..attachment.clone() + }) + .collect(); + Ok((StoredOp::encode(&stored)?, blobs)) +} + +/// Record that the op at `position` references each of `blobs`. A blob is +/// deleted with the last op that references it. +pub(super) fn store_attachments( + db: &Connection, + position: u64, + blobs: &[Attachment], +) -> anyhow::Result<()> { + for blob in blobs { + db.execute( + "INSERT OR IGNORE INTO attachment_blobs(digest,data,refs) VALUES (?,?,0)", + params![blob.digest, blob.data], + )?; + db.execute( + "INSERT OR IGNORE INTO operation_attachments(position,digest) VALUES (?,?)", + params![position, blob.digest], + )?; + } + Ok(()) +} + +fn load_attachments(db: &Connection, mut op: SpanOp) -> anyhow::Result { + for attachment in &mut op.row_mut().attachments { + attachment.data = db.one( + "SELECT data FROM attachment_blobs WHERE digest=?", + [&attachment.digest], + )?; + } + Ok(op) +} + +/// Metadata needed to restore correlation and provenance without retaining +/// conversation input/output after all delivery obligations are complete. +pub(crate) fn metadata_only(op: &SpanOp) -> SpanOp { + let row = op.row(); + let row = SpanRow { + span_id: row.span_id.clone(), + root_span_id: row.root_span_id.clone(), + parent_span_ids: row.parent_span_ids.clone(), + name: row.name.clone(), + span_type: row.span_type, + start_ms: row.start_ms, + end_ms: row.end_ms, + metadata: row.metadata.clone(), + origin: row.origin.clone(), + is_turn: row.is_turn, + ..Default::default() + }; + match op { + SpanOp::Insert(_) => SpanOp::Insert(row), + SpanOp::Merge(_) => SpanOp::Merge(row), + } +} + +pub(super) fn save_metadata(db: &Connection, op: &SpanOp, observation: bool) -> anyhow::Result<()> { + let row = op.row(); + if let Some(origin) = &row.origin { + db.execute( + "INSERT OR IGNORE INTO origins(span_id,value) VALUES (?,?)", + params![row.span_id, Json(origin)], + )?; + } + if row.end_ms.is_some() { + db.execute( + &format!("UPDATE origins SET ended_ms={NOW_MS} WHERE span_id=?"), + [&row.span_id], + )?; + } + if !observation { + return Ok(()); + } + if matches!(op, SpanOp::Insert(_)) + && (row.span_type == SpanType::Tool + || (row.span_type == SpanType::Task && row.span_id == row.root_span_id)) + { + let mut birth = metadata_only(op); + birth.row_mut().end_ms = None; + db.execute( + &format!( + "INSERT OR REPLACE INTO span_state(span_id,kind,value,end_ms,touched_ms) + VALUES (?,?,?,?,{NOW_MS})" + ), + params![ + row.span_id, + if row.span_type == SpanType::Tool { + "tool" + } else { + "root" + }, + StoredOp::encode(&birth)?, + row.end_ms + ], + )?; + } else { + db.execute( + &format!("UPDATE span_state SET end_ms=?, touched_ms={NOW_MS} WHERE span_id=?"), + params![row.end_ms, row.span_id], + )?; + } + db.execute( + "DELETE FROM span_state WHERE span_id=? AND kind='tool' AND end_ms IS NOT NULL", + [&row.span_id], + )?; + Ok(()) +} + +/// Delete ops every head has passed. +pub(super) fn prune(db: &Connection) -> anyhow::Result<()> { + db.execute( + "DELETE FROM ops WHERE position<=(SELECT min(position) FROM heads)", + [], + )?; + Ok(()) +} + +/// Heads selected by `filter` that are the same route as `route`, by key. +fn same_heads(db: &Connection, filter: &str, route: &SessionRoute) -> anyhow::Result> { + let mut query = db.prepare(&format!("SELECT route FROM heads WHERE {filter}"))?; + let matching = query.query_and_then([], |r| { + let key: String = r.get(0)?; + let head: SessionRoute = serde_json::from_str(&key)?; + anyhow::Ok(head.same_route(route).then_some(key)) + })?; + matching.filter_map(Result::transpose).collect() +} + +/// One input event's complete translation. +#[derive(Clone, Default)] +pub(crate) struct Translated { + pub input: u64, + /// Whether the ops are native observations; retirement output is not. + pub observation: bool, + pub ops: Vec, + /// Root candidates still waiting for work after this input. + pub roots: BTreeMap>, + /// The translator continuation after this input. + pub state: Option>, +} + +/// A head that is held by a failure and may accept corrected settings. +#[derive(serde::Deserialize)] +pub(crate) struct HeldRoute { + /// The stored route, exactly as it keys its head. + key: String, + #[serde(deserialize_with = "json")] + pub route: SessionRoute, + pub failure: String, + #[serde(deserialize_with = "json_or_null")] + pub settings: Option, +} + +/// One route's durable delivery head. +#[derive(serde::Deserialize)] +pub(crate) struct Head { + pub position: u64, + pub failure: Option, + /// Corrected settings recorded for a held head. + #[serde(deserialize_with = "json_or_null")] + pub settings: Option, +} + +/// A route's head and its feed of ops committed after subscribing. +pub(crate) struct Subscriber { + pub position: u64, + pub live: Receiver, + /// The position of the last committed op. + pub published: watch::Receiver, +} + +type ReplayWindow = Vec<(u64, std::sync::Weak, usize)>; + +/// In-memory delivery state shared by every handle on one session database. +pub(super) struct Channel { + published: watch::Sender, + live: Multiplexer, + replay: tokio::sync::Mutex, + #[cfg(test)] + payload_reads: std::sync::atomic::AtomicU64, +} + +impl Channel { + pub fn new(tail: u64) -> Self { + Self { + published: watch::channel(tail).0, + live: Multiplexer::default(), + replay: Default::default(), + #[cfg(test)] + payload_reads: Default::default(), + } + } + + /// Advertise durable ops to routes: the tail first, so routes can drain + /// the bounded live feed (or read storage) while it is being filled. + pub async fn publish(&self, tail: u64, records: impl IntoIterator) { + self.published.send_replace(tail); + for record in records { + self.live.publish(record).await; + } + } +} + +impl SessionStorage { + /// Stored ops after `after`, bounded by bytes and elapsed decode time. + pub async fn read_after( + &self, + after: u64, + budget: usize, + window: std::time::Duration, + ) -> anyhow::Result> { + self.run(move |db| { + read_batch( + db, + "SELECT position,value FROM ops WHERE position>? ORDER BY position", + [after], + budget, + window, + |row| { + let value = row.get_ref(1)?.as_blob()?; + let op = load_attachments(db, StoredOp::decode(value)?)?; + let size = op + .row() + .attachments + .iter() + .fold(value.len(), |size, attachment| { + size.saturating_add(attachment.data.len()) + }); + let position = row.get(0)?; + Ok(( + size, + Record { + position, + op: SharedOp::new(op), + bytes: size, + }, + )) + }, + ) + }) + .await + } + + /// Ops after `after` for a route that fell behind the live feed. One + /// weakly held window is shared by all routes, so no decoded payload + /// stays alive solely because of this cache. + pub async fn recover_after(&self, after: u64) -> anyhow::Result> { + let mut cache = self.channel().replay.lock().await; + if cache + .first() + .is_some_and(|(position, _, _)| *position <= after + 1) + && cache + .last() + .is_some_and(|(position, _, _)| *position > after) + { + let shared = cache + .iter() + .filter(|(position, _, _)| *position > after) + .map(|(position, op, bytes)| { + Some(Record { + position: *position, + op: SharedOp::from_arc(op.upgrade()?), + bytes: *bytes, + }) + }) + .collect::>>(); + if let Some(shared) = shared { + return Ok(shared); + } + } + let records = self.read_after(after, BYTE_BUDGET, WINDOW).await?; + #[cfg(test)] + self.channel() + .payload_reads + .fetch_add(records.len() as u64, std::sync::atomic::Ordering::Relaxed); + *cache = records + .iter() + .map(|record| (record.position, record.op.downgrade(), record.bytes)) + .collect(); + Ok(records) + } + + /// Create the route's head if needed. A new head starts after ops that + /// every existing route has already removed. + pub async fn subscribe(&self, route: &SessionRoute) -> anyhow::Result { + let live = self.channel().live.subscribe(); + let key = serde_json::to_string(route)?; + let candidate = route.clone(); + let position = self + .write(move |tx| { + // Auth can register a named-profile obligation before learning + // its stable ID. Move that unresolved placeholder to the resolved + // identity instead of leaving a second head that can never run. + if candidate.auth.profile_id.is_some() { + for alias in same_heads(tx, "binding IS NULL", &candidate)? { + let previous: SessionRoute = serde_json::from_str(&alias)?; + if alias != key && previous.auth.profile_id.is_none() { + tx.execute( + "UPDATE OR IGNORE heads SET route=? WHERE route=?", + params![key, alias], + )?; + tx.execute("DELETE FROM heads WHERE route=?", [alias])?; + } + } + } + tx.execute( + &format!( + "INSERT OR IGNORE INTO heads(route,position,progress_ms) VALUES (?,coalesce( + (SELECT min(position)-1 FROM ops),(SELECT op_tail FROM session WHERE id=1)), + {NOW_MS})" + ), + [&key], + )?; + tx.execute("UPDATE heads SET subscribed=1 WHERE route=?", [&key])?; + Ok(tx.one("SELECT position FROM heads WHERE route=?", [key])?) + }) + .await?; + Ok(Subscriber { + position, + live, + published: self.channel().published.subscribe(), + }) + } + + /// Register a delivery obligation for new output without backfilling. + pub async fn register(&self, route: &SessionRoute) -> anyhow::Result<()> { + let key = serde_json::to_string(route)?; + let candidate = route.clone(); + self.write(move |tx| { + if same_heads(tx, "1", &candidate)?.is_empty() { + tx.execute( + &format!( + "INSERT OR IGNORE INTO heads(route,position,progress_ms) + VALUES (?,(SELECT op_tail FROM session WHERE id=1),{NOW_MS})" + ), + [key], + )?; + } + Ok(()) + }) + .await + } + + /// Whether `route` has delivered every op translated from input through `input`. + pub async fn route_complete(&self, route: &SessionRoute, input: u64) -> anyhow::Result { + let route = route.clone(); + self.run(move |db| { + let through: u64 = db.one("SELECT through FROM session WHERE id=1", [])?; + Ok(through >= input + && !same_heads( + db, + "failure IS NULL AND position>=(SELECT op_tail FROM session WHERE id=1)", + &route, + )? + .is_empty()) + }) + .await + } + + pub async fn origins_for( + &self, + spans: Vec, + ) -> anyhow::Result>> { + if spans.is_empty() { + return Ok(BTreeMap::new()); + } + self.run(move |db| { + let mut query = db.prepare_cached("SELECT value FROM origins WHERE span_id=?")?; + let mut origins = BTreeMap::new(); + for span in spans { + if let Some(Json(origin)) = query.query_row([&span], |r| r.get(0)).optional()? { + origins.insert(span, origin); + } + } + Ok(origins) + }) + .await + } + + /// Births of open tools and roots, each followed by its terminal update. + pub async fn observations(&self) -> anyhow::Result> { + self.run(|db| { + let mut query = db.prepare("SELECT value,end_ms FROM span_state ORDER BY rowid")?; + let rows = query.query_map([], |r| { + Ok((r.get::<_, Vec>(0)?, r.get::<_, Option>(1)?)) + })?; + let mut result = Vec::new(); + for row in rows { + let (bytes, end) = row?; + let op = StoredOp::decode(&bytes)?; + let terminal = end.map(|end_ms| { + let mut terminal = op.row().clone(); + terminal.end_ms = Some(end_ms); + SpanOp::Merge(terminal) + }); + result.push(op); + result.extend(terminal); + } + Ok(result) + }) + .await + } + + pub async fn routes(&self) -> anyhow::Result> { + self.run(|db| { + let mut query = db.prepare("SELECT route FROM heads ORDER BY route")?; + let routes = query + .query_map([], |r| r.get::<_, Json>(0))? + .map(|route| Ok(route?.0)) + .collect(); + routes + }) + .await + } + + pub async fn head(&self, route: &str) -> anyhow::Result> { + let route = route.to_owned(); + self.run(move |db| { + Ok(select( + db, + "SELECT position, failure, settings FROM heads WHERE route=?", + [route], + )? + .pop()) + }) + .await + } + + /// The route's corrected settings, or the route itself if it has none. + pub async fn route_settings(&self, route: &SessionRoute) -> anyhow::Result { + let head = self.head(&serde_json::to_string(route)?).await?; + Ok(head + .and_then(|head| head.settings) + .unwrap_or_else(|| route.clone())) + } + + pub async fn set_failure(&self, route: &str, failure: Option) -> anyhow::Result<()> { + let route = route.to_owned(); + self.write(move |tx| { + tx.execute( + "UPDATE heads SET failure=? WHERE route=?", + params![failure, route], + )?; + Ok(()) + }) + .await + } + + /// Tokens can change; a durable head's backend and organization cannot. + pub async fn bind(&self, route: &str, config: &SessionConfig) -> anyhow::Result<()> { + let route = route.to_owned(); + let binding = serde_json::to_string(&serde_json::json!({ + "api_url": config.auth.api_url.as_deref().unwrap_or("https://api.braintrust.dev"), + "org_id":config.auth.org_id,"org_name":config.auth.org_name, + }))?; + self.write(move |tx| { + let previous: Option = + tx.one("SELECT binding FROM heads WHERE route=?", [&route])?; + match previous { + Some(previous) => anyhow::ensure!(previous == binding, BindingChanged), + None => { + tx.execute( + "UPDATE heads SET binding=? WHERE route=?", + params![binding, route], + )?; + } + } + Ok(()) + }) + .await + } + + /// Atomically replace settings of held heads selected by `correct`, which + /// returns the corrected route for a held head it can unblock. + pub async fn reconfigure_held( + &self, + through: u64, + correct: impl Fn(&HeldRoute) -> Option + Send + 'static, + ) -> anyhow::Result> { + self.write(move |tx| { + let held: Vec = select( + tx, + "SELECT route AS key, route, failure, settings FROM heads + WHERE failure IS NOT NULL AND settings_through anyhow::Result<()> { + let route = route.to_string(); + self.write(move |tx| { + tx.execute( + "UPDATE heads SET position=?, failure=NULL WHERE route=?", + params![DETACHED, route], + )?; + prune(tx) + }) + .await + } + + /// Remove ops through `through` from the route's view. The head must not + /// skip unresolved ops before `expected`. Ops every route has passed are + /// deleted. Returns the head after the update. + pub async fn remove_through( + &self, + route: &str, + expected: u64, + through: u64, + ) -> anyhow::Result { + let route = route.to_owned(); + self.write(move |tx| { + let head: u64 = tx.one("SELECT position FROM heads WHERE route=?", [&route])?; + if head >= through { + return Ok(head); + } + anyhow::ensure!(head >= expected, "completion cannot skip unresolved input"); + tx.execute( + &format!( + "UPDATE heads SET position=?, failure=NULL, progress_ms={NOW_MS} WHERE route=?" + ), + params![through, route], + )?; + prune(tx)?; + super::store::touch(tx)?; + Ok(through) + }) + .await + } +} + +#[cfg(test)] +impl SessionStorage { + /// Stored ops decoded for assertions. + pub async fn stored(&self) -> Vec { + self.read_after(0, usize::MAX, std::time::Duration::MAX) + .await + .unwrap() + .into_iter() + .map(|record| record.op.as_ref().clone()) + .collect() + } + + pub fn payload_reads(&self) -> u64 { + self.channel() + .payload_reads + .load(std::sync::atomic::Ordering::Relaxed) + } + + /// Commit native output for `input` with no continuation. + pub async fn translated(&self, input: u64, ops: Vec) -> anyhow::Result { + self.commit_translation(Translated { + input, + observation: true, + ops, + ..Default::default() + }) + .await + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn codec_preserves_aggregate_watermarks_and_reads_older_records() { + let mut op = SpanOp::Insert(SpanRow { + span_id: "root".into(), + late_merge_key: Some("late".into()), + ..SpanRow::default() + }); + let version = crate::translate::LateMergeVersion { + ts_ms: 123, + native_id: Some("turn".into()), + }; + op.row_mut().late_merge_version = Some(version.clone()); + let encoded = StoredOp::encode(&op).unwrap(); + let decoded = StoredOp::decode(&encoded).unwrap(); + assert_eq!(decoded.row().late_merge_version, Some(version)); + let mut legacy: serde_json::Value = serde_json::from_slice(&encoded).unwrap(); + legacy.as_object_mut().unwrap().remove("late_merge_version"); + let decoded = StoredOp::decode(&serde_json::to_vec(&legacy).unwrap()).unwrap(); + assert!(decoded.row().late_merge_version.is_none()); + assert!(serde_json::to_value(&op).unwrap()["Insert"] + .get("late_merge_version") + .is_none()); + } +} diff --git a/bt-daemon/src/collections/store.rs b/bt-daemon/src/collections/store.rs new file mode 100644 index 00000000..c168ef54 --- /dev/null +++ b/bt-daemon/src/collections/store.rs @@ -0,0 +1,314 @@ +//! The only owner of SQLite connections. +use parking_lot::Mutex; +use rusqlite::{ + types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef}, + Connection, Params, +}; +use std::{ + collections::HashMap, + path::{Path, PathBuf}, + sync::{Arc, LazyLock, Weak}, +}; +use weak_table::WeakValueHashMap; + +/// Schema 1-7 belong to the original SpanOp channel; 7 added attachment +/// blobs. Schema 8 adds the event collection, replacing NDJSON capture, and +/// one session row that makes each event-to-SpanOp handoff a single +/// transaction. +pub(super) const SCHEMA: u32 = 8; + +/// The current time in milliseconds, as SQL. +pub(super) const NOW_MS: &str = "CAST(unixepoch('subsec') * 1000 AS INTEGER)"; + +/// Databases with a live handle in this process. +static OPEN: LazyLock>>> = + LazyLock::new(Default::default); +/// Files whose last handle is still compacting and closing its connection. +static CLOSING: LazyLock>> = LazyLock::new(Default::default); + +struct Inner { + path: PathBuf, + connection: Mutex>, + channel: super::span_ops::Channel, +} + +impl Drop for Inner { + fn drop(&mut self) { + *CLOSING.lock().entry(self.path.clone()).or_default() += 1; + self.close(); + let mut closing = CLOSING.lock(); + if let Some(count) = closing.get_mut(&self.path) { + *count -= 1; + if *count == 0 { + closing.remove(&self.path); + } + } + } +} + +impl Inner { + fn close(&mut self) { + if let Some(connection) = self.connection.get_mut().take() { + // Reclaim a bounded number of free pages and leave no WAL behind. + if let Err(error) = connection + .execute_batch("PRAGMA incremental_vacuum(256); PRAGMA wal_checkpoint(TRUNCATE)") + { + tracing::warn!(%error, path = %self.path.display(), "session storage could not be compacted on close"); + } + if let Err((_, error)) = connection.close() { + tracing::warn!(%error, path = %self.path.display(), "session storage did not close cleanly"); + } + } + } +} + +/// One source session's database. Every handle on the same file shares one +/// connection, so a transfer between its collections is a single local +/// transaction and closing the last handle releases the file. +#[derive(Clone)] +pub(crate) struct SessionStorage(Arc); + +impl SessionStorage { + /// Open (or share) the database at `path`, creating and upgrading its + /// schema, without claiming it for a source session. + pub async fn at(path: &Path) -> anyhow::Result { + let path = normalize(path).await?; + if let Some(storage) = Self::shared(&path) { + return Ok(storage); + } + let opened = path.clone(); + let (connection, tail) = tokio::task::spawn_blocking(move || { + let db = open_connection(&opened)?; + let tail = db.one("SELECT op_tail FROM session WHERE id=1", [])?; + anyhow::Ok((db, tail)) + }) + .await??; + let mut open = OPEN.lock(); + // A concurrent opener may have published the same file meanwhile. + if let Some(inner) = open.get(&path) { + drop(connection); + return Ok(Self(inner)); + } + let inner = Arc::new(Inner { + path: path.clone(), + connection: Mutex::new(Some(connection)), + channel: super::span_ops::Channel::new(tail), + }); + open.insert(path, inner.clone()); + Ok(Self(inner)) + } + + /// Live delivery state shared by every handle on this database. + pub(super) fn channel(&self) -> &super::span_ops::Channel { + &self.0.channel + } + + fn shared(path: &Path) -> Option { + OPEN.lock().get(path).map(Self) + } + + pub(super) async fn run( + &self, + operation: impl FnOnce(&mut Connection) -> anyhow::Result + Send + 'static, + ) -> anyhow::Result { + let inner = self.0.clone(); + tokio::task::spawn_blocking(move || { + let mut connection = inner.connection.lock(); + operation( + connection + .as_mut() + .ok_or_else(|| anyhow::anyhow!("session storage is closed"))?, + ) + }) + .await? + } + + /// Hold the storage lock, blocking every operation until released. + #[cfg(test)] + pub fn lock_storage(&self) -> impl Drop + '_ { + self.0.connection.lock() + } + + /// One immediate transaction: writers acquire the lock before reading. + pub(super) async fn write( + &self, + operation: impl FnOnce(&rusqlite::Transaction<'_>) -> anyhow::Result + Send + 'static, + ) -> anyhow::Result { + self.run(move |db| { + let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; + let result = operation(&tx)?; + tx.commit()?; + Ok(result) + }) + .await + } + + /// Delete a session database and its sidecars only if no handle is open + /// in this process. Holding the registry lock keeps a concurrent open + /// from racing it. + pub async fn remove(path: &Path) -> anyhow::Result { + let path = normalize(path).await?; + let open = OPEN.lock(); + if open.contains_key(&path) || CLOSING.lock().contains_key(&path) { + return Ok(false); + } + for suffix in ["", "-wal", "-shm"] { + let mut file = path.clone().into_os_string(); + file.push(suffix); + match std::fs::remove_file(&file) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error.into()), + } + } + Ok(true) + } +} + +async fn normalize(path: &Path) -> anyhow::Result { + let parent = path + .parent() + .ok_or_else(|| anyhow::anyhow!("storage path has no parent"))?; + let name = path + .file_name() + .ok_or_else(|| anyhow::anyhow!("storage path has no file name"))?; + tokio::fs::create_dir_all(parent).await?; + Ok(tokio::fs::canonicalize(parent).await?.join(name)) +} + +pub(super) fn open_connection(path: &Path) -> anyhow::Result { + let db = Connection::open(path)?; + db.busy_timeout(std::time::Duration::from_secs(5))?; + // Concurrent WAL transitions can return BUSY without invoking SQLite's + // busy handler. Retry initialization before any schema transaction starts. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + loop { + match db.execute_batch( + "PRAGMA auto_vacuum=INCREMENTAL; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; + PRAGMA journal_size_limit=1048576; BEGIN IMMEDIATE;", + ) { + Ok(()) => break, + Err(error) + if error.sqlite_error_code() == Some(rusqlite::ErrorCode::DatabaseBusy) + && std::time::Instant::now() < deadline => + { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + Err(error) => return Err(error.into()), + } + } + match super::upgrade::migrate(&db) { + Ok(()) => db.execute_batch("COMMIT")?, + Err(error) => { + let _ = db.execute_batch("ROLLBACK"); + return Err(error); + } + } + Ok(db) +} + +/// A column holding a JSON-encoded value, stored as text. +pub(super) struct Json(pub T); + +impl FromSql for Json { + fn column_result(value: ValueRef<'_>) -> FromSqlResult { + serde_json::from_slice(value.as_bytes()?) + .map(Json) + .map_err(|error| FromSqlError::Other(Box::new(error))) + } +} + +impl ToSql for Json { + fn to_sql(&self) -> rusqlite::Result> { + serde_json::to_string(&self.0) + .map(ToSqlOutput::from) + .map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error))) + } +} + +/// Field deserializer for a JSON-encoded text column. +pub(super) fn json<'de, D: serde::Deserializer<'de>, T: serde::de::DeserializeOwned>( + deserializer: D, +) -> Result { + let text = ::deserialize(deserializer)?; + serde_json::from_str(&text).map_err(serde::de::Error::custom) +} + +/// Field deserializer for a nullable JSON-encoded text column. +pub(super) fn json_or_null<'de, D: serde::Deserializer<'de>, T: serde::de::DeserializeOwned>( + deserializer: D, +) -> Result, D::Error> { + let text = as serde::Deserialize>::deserialize(deserializer)?; + text.map(|text| serde_json::from_str(&text).map_err(serde::de::Error::custom)) + .transpose() +} + +/// Every row `sql` selects, deserialized by column name. +pub(super) fn select( + db: &Connection, + sql: &str, + params: impl Params, +) -> anyhow::Result> { + let mut statement = db.prepare_cached(sql)?; + let rows = serde_rusqlite::from_rows::(statement.query(params)?); + Ok(rows.collect::>()?) +} + +/// Read the first column of the one row a query selects. +pub(super) trait One { + fn one(&self, sql: &str, params: impl Params) -> rusqlite::Result; +} + +impl One for Connection { + fn one(&self, sql: &str, params: impl Params) -> rusqlite::Result { + self.query_row(sql, params, |row| row.get(0)) + } +} + +/// Storage errors that will not succeed on retry without changing the data. +pub(crate) fn is_corruption(error: &anyhow::Error) -> bool { + error.downcast_ref::().is_some_and(|error| { + matches!(error, rusqlite::Error::SqliteFailure(code, _) + if matches!(code.code, rusqlite::ErrorCode::DatabaseCorrupt | rusqlite::ErrorCode::NotADatabase)) + }) +} + +/// Record pipeline progress. Opening or inspecting storage never counts as +/// activity, so retention measures how long the session has been cold. +pub(super) fn touch(tx: &Connection) -> rusqlite::Result<()> { + tx.execute( + &format!("UPDATE session SET active_ms={NOW_MS} WHERE id=1"), + [], + ) + .map(|_| ()) +} + +/// Read records in order until they reach `budget` bytes or `window` elapses, +/// always returning at least one. `decode` builds each record from its row +/// and reports its size in bytes. +pub(super) fn read_batch( + db: &Connection, + sql: &str, + params: impl Params, + budget: usize, + window: std::time::Duration, + mut decode: impl FnMut(&rusqlite::Row<'_>) -> anyhow::Result<(usize, R)>, +) -> anyhow::Result> { + let mut statement = db.prepare_cached(sql)?; + let mut rows = statement.query(params)?; + let started = std::time::Instant::now(); + let mut records = Vec::new(); + let mut bytes: usize = 0; + while let Some(row) = rows.next()? { + let (size, record) = decode(row)?; + if !records.is_empty() && bytes.saturating_add(size) > budget { + break; + } + bytes = bytes.saturating_add(size); + records.push(record); + if bytes >= budget || started.elapsed() >= window { + break; + } + } + Ok(records) +} diff --git a/bt-daemon/src/collections/tests.rs b/bt-daemon/src/collections/tests.rs new file mode 100644 index 00000000..0a23e3b3 --- /dev/null +++ b/bt-daemon/src/collections/tests.rs @@ -0,0 +1,377 @@ +//! Storage behavior shared by the concrete collections. +use super::inspect::{Fault, Inspector, Table}; +use super::span_ops::Translated; +use super::*; +use crate::journal::{journal_path, source_journal_path}; +use crate::translate::{SpanOp, SpanRow}; +use crate::wire::Envelope; +use futures::TryStreamExt; +use serde_json::json; + +fn event(source: &str, session: &str, name: &str, payload: serde_json::Value) -> Envelope { + serde_json::from_value(json!({ + "source": source, "session_id": session, "event": name, "ts_ms": 1, + "payload": payload, + })) + .unwrap() +} + +fn line(value: &serde_json::Value) -> Vec { + let mut line = serde_json::to_vec(value).unwrap(); + line.push(b'\n'); + line +} + +async fn write_legacy(path: &std::path::Path, bytes: &[u8]) { + tokio::fs::create_dir_all(path.parent().unwrap()) + .await + .unwrap(); + tokio::fs::write(path, bytes).await.unwrap(); +} + +#[tokio::test] +async fn capture_stores_only_the_pi_fields_translation_reads() { + let temp = tempfile::tempdir().unwrap(); + let events = SessionStorage::open(temp.path(), "pi", "session") + .await + .unwrap(); + let marker = "growing-partial-marker".repeat(64); + events + .append( + &event( + "pi", + "session", + "message_update", + json!({"event": { + "type": "message_update", + "assistantMessageEvent": {"type": "text_delta", "partial": marker}, + "message": {"role": "assistant", "content": marker}, + }}), + ), + None, + ) + .await + .unwrap() + .unwrap(); + events + .append( + &event( + "pi", + "session", + "before_provider_request", + json!({"event": { + "type": "before_provider_request", + "payload": { + "system": "system-prompt-marker", + "messages": [{"role": "user", "content": "message-marker"}], + "tools": [{"name": "read", "input_schema": {"type": "object"}}], + "max_tokens": 1024, + }, + }}), + ), + None, + ) + .await + .unwrap() + .unwrap(); + let stored = Inspector::session(temp.path(), "pi", "session") + .unwrap() + .events(); + let text = serde_json::to_string(&stored).unwrap(); + for marker in [ + "growing-partial-marker", + "system-prompt-marker", + "message-marker", + ] { + assert!(!text.contains(marker), "{marker} reached storage"); + } + let tail = events.status().await.unwrap().event_tail; + let mut reader = std::pin::pin!(events.read(0, tail).events()); + let update = reader.try_next().await.unwrap().unwrap(); + assert_eq!( + update.payload.pointer("/event/assistantMessageEvent/type"), + Some(&json!("text_delta")) + ); + let request = reader.try_next().await.unwrap().unwrap(); + assert_eq!( + request.payload.pointer("/event/payload"), + Some(&json!({ + "max_tokens": 1024, + "tools": [{"type": "function", "function": { + "name": "read", "parameters": {"type": "object"}, + }}], + })) + ); +} + +#[tokio::test] +async fn legacy_import_keeps_byte_positions_expands_pi_history_and_deletes_the_file() { + let temp = tempfile::tempdir().unwrap(); + let path = source_journal_path(temp.path(), "pi", "session"); + let first = json!({"source":"pi","session_id":"session","event":"context","ts_ms":1, + "payload":{"event":{"type":"context","messages":[{"role":"user","content":"a"}]}}}); + let second = json!({"source":"pi","session_id":"session","event":"context","ts_ms":2, + "payload":{"event":{"type":"context","_bt_messages_delta":{ + "common_prefix":1,"suffix":[{"role":"user","content":"b"}]}}}}); + let mut bytes = line(&first); + let boundary = bytes.len() as u64; + bytes.extend(line(&second)); + // An unacknowledged partial append at the tail is not imported. + bytes.extend(b"{\"partial\":"); + write_legacy(&path, &bytes).await; + let events = SessionStorage::open(temp.path(), "pi", "session") + .await + .unwrap(); + assert!(!path.exists()); + let through = events.status().await.unwrap().event_tail; + assert_eq!(through, bytes.len() as u64 - 11); + let mut reader = events.read(0, through); + let entry = reader.try_next().await.unwrap().unwrap(); + assert_eq!(entry.id, boundary); + let entry = reader.try_next().await.unwrap().unwrap(); + let EventRecord::Event(context) = entry.record else { + panic!("expected an event") + }; + assert_eq!( + context.payload.pointer("/event/messages"), + Some(&json!([{"role":"user","content":"a"},{"role":"user","content":"b"}])) + ); + assert!(reader.try_next().await.unwrap().is_none()); + let appended = events + .append(&event("pi", "session", "context", json!({})), None) + .await + .unwrap() + .unwrap(); + assert_eq!(appended.before, through); +} + +#[tokio::test] +async fn an_unreadable_legacy_journal_is_retained_until_it_can_be_imported() { + let temp = tempfile::tempdir().unwrap(); + let path = source_journal_path(temp.path(), "debug", "session"); + let valid = + line(&json!({"source":"debug","session_id":"session","event":"e","ts_ms":1,"payload":{}})); + write_legacy(&path, &[valid.as_slice(), b"{broken}\n"].concat()).await; + assert!(SessionStorage::open(temp.path(), "debug", "session") + .await + .is_err()); + assert!(path.exists(), "a failed import keeps its source"); + write_legacy(&path, &valid).await; + let events = SessionStorage::open(temp.path(), "debug", "session") + .await + .unwrap(); + assert!(!path.exists()); + assert_eq!( + events.status().await.unwrap().event_tail, + valid.len() as u64 + ); +} + +#[tokio::test] +async fn a_session_only_journal_splits_by_source_and_keeps_its_namespace_owner() { + let temp = tempfile::tempdir().unwrap(); + let path = journal_path(temp.path(), "shared"); + let mut bytes = Vec::new(); + for source in ["codex", "claude"] { + bytes.extend(line( + &json!({"source":source,"session_id":"shared","event":"e", + "ts_ms":1,"payload":{},"route":{}}), + )); + } + write_legacy(&path, &bytes).await; + let codex = SessionStorage::open(temp.path(), "codex", "shared") + .await + .unwrap(); + assert!(!path.exists()); + let claude = SessionStorage::open(temp.path(), "claude-code", "shared") + .await + .unwrap(); + for (events, source, owner) in [(&codex, "codex", true), (&claude, "claude", false)] { + assert_eq!(events.status().await.unwrap().legacy_namespace, owner); + let tail = events.status().await.unwrap().event_tail; + let sources: Vec<_> = events + .read(0, tail) + .events() + .map_ok(|event| event.source) + .try_collect() + .await + .unwrap(); + assert_eq!(sources, [source]); + } +} + +#[tokio::test] +async fn storage_is_removed_only_after_its_last_handle_closes() { + let temp = tempfile::tempdir().unwrap(); + let events = SessionStorage::open(temp.path(), "debug", "session") + .await + .unwrap(); + events + .append(&event("debug", "session", "e", json!({})), None) + .await + .unwrap() + .unwrap(); + let path = super::inspect::session_path(temp.path(), "debug", "session"); + let ops = events.clone(); + drop(events); + assert!(!SessionStorage::remove(&path).await.unwrap()); + assert!(path.exists()); + drop(ops); + assert!(SessionStorage::remove(&path).await.unwrap()); + for suffix in ["", "-wal", "-shm"] { + let mut file = path.clone().into_os_string(); + file.push(suffix); + assert!(!std::path::Path::new(&file).exists(), "{suffix}"); + } +} + +#[tokio::test] +async fn input_is_removed_only_in_the_transaction_that_stores_its_output() { + let temp = tempfile::tempdir().unwrap(); + let events = SessionStorage::open(temp.path(), "debug", "session") + .await + .unwrap(); + let input = events + .append(&event("debug", "session", "e", json!({})), None) + .await + .unwrap() + .unwrap() + .through; + let translated = Translated { + input, + observation: true, + ops: vec![SpanOp::Insert(SpanRow { + span_id: "span".into(), + ..Default::default() + })], + roots: Default::default(), + state: Some(b"{}".to_vec()), + }; + let db = Inspector::session(temp.path(), "debug", "session").unwrap(); + db.inject(Fault::RemoveEvents).unwrap(); + assert!(events.commit_translation(translated.clone()).await.is_err()); + // Neither stage changed: the event remains and no output is visible. + let status = events.status().await.unwrap(); + assert_eq!(status.translated_through, 0); + assert_eq!(db.count(Table::Events), 1); + assert_eq!(db.count(Table::Ops), 0); + assert_eq!(status.op_tail, 0); + assert!(events.continuation().await.unwrap().is_none()); + db.clear(Fault::RemoveEvents).unwrap(); + let committed = events.commit_translation(translated.clone()).await.unwrap(); + assert_eq!(committed, 1); + assert_eq!(db.count(Table::Ops), 1); + assert_eq!(events.status().await.unwrap().translated_through, input); + assert_eq!(db.count(Table::Events), 0); + assert!(events.continuation().await.unwrap().is_some()); +} + +#[tokio::test] +async fn reopening_storage_does_not_count_as_activity() { + let temp = tempfile::tempdir().unwrap(); + let events = SessionStorage::open(temp.path(), "debug", "session") + .await + .unwrap(); + events + .append(&event("debug", "session", "e", json!({})), None) + .await + .unwrap() + .unwrap(); + drop(events); + let day = std::time::Duration::from_secs(24 * 60 * 60); + Inspector::session(temp.path(), "debug", "session") + .unwrap() + .age(day) + .unwrap(); + // Restart recovery reopens every session database. + let events = SessionStorage::open(temp.path(), "debug", "session") + .await + .unwrap(); + assert!(events.status().await.unwrap().idle_for >= day); + events + .append(&event("debug", "session", "later", json!({})), None) + .await + .unwrap() + .unwrap(); + assert!(events.status().await.unwrap().idle_for < day); +} + +#[tokio::test] +async fn a_live_session_expires_only_what_it_no_longer_uses() { + let retention = std::time::Duration::from_secs(7 * 24 * 60 * 60); + let temp = tempfile::tempdir().unwrap(); + let events = SessionStorage::open(temp.path(), "debug", "session") + .await + .unwrap(); + let mut captured = event("debug", "session", "e", json!({})); + captured.route = Some(Default::default()); + let input = events + .append(&captured, None) + .await + .unwrap() + .unwrap() + .through; + assert!(events.append(&captured, None).await.unwrap().is_none()); + let route = |name: &str| crate::wire::SessionRoute { + tags: [name.into()].into_iter().collect(), + ..Default::default() + }; + let delivered = events + .subscribe(&route("delivered")) + .await + .unwrap() + .position; + // A route registered for output whose delivery never starts. + events.register(&route("unsubscribed")).await.unwrap(); + let span = |id: &str, end_ms: Option| { + SpanOp::Insert(SpanRow { + span_id: id.into(), + root_span_id: id.into(), + span_type: crate::translate::SpanType::Tool, + end_ms, + origin: Some( + crate::translate::OriginSnapshot { + plugin_version: None, + source_version: None, + bt_version: "test".into(), + } + .into(), + ), + ..Default::default() + }) + }; + let tail = events + .commit_translation(Translated { + input, + observation: true, + ops: vec![span("ended", Some(2)), span("abandoned", None)], + roots: Default::default(), + state: Some(b"{}".to_vec()), + }) + .await + .unwrap(); + let key = serde_json::to_string(&route("delivered")).unwrap(); + events.remove_through(&key, delivered, tail).await.unwrap(); + let db = Inspector::session(temp.path(), "debug", "session").unwrap(); + assert_eq!( + db.count(Table::Ops), + 2, + "the unsubscribed head holds output" + ); + + db.age(retention + std::time::Duration::from_secs(60)) + .unwrap(); + let unsubscribed = serde_json::to_string(&route("unsubscribed")).unwrap(); + events.expire(retention, vec![unsubscribed]).await.unwrap(); + assert_eq!(db.count(Table::Heads), 2, "a live route is never expired"); + + events.expire(retention, Vec::new()).await.unwrap(); + assert_eq!(db.count(Table::Heads), 1); + assert_eq!(db.count(Table::Ops), 0); + assert_eq!(db.count(Table::Origins), 1, "an open span keeps its origin"); + assert!(events.observations().await.unwrap().is_empty()); + assert!( + events.append(&captured, None).await.unwrap().is_some(), + "an expired capture identity is recorded again" + ); +} diff --git a/bt-daemon/src/collections/upgrade.rs b/bt-daemon/src/collections/upgrade.rs new file mode 100644 index 00000000..5ce122fd --- /dev/null +++ b/bt-daemon/src/collections/upgrade.rs @@ -0,0 +1,485 @@ +//! Upgrades of session databases written by earlier daemons. Everything else +//! in this module works only with the current schema. +use super::span_ops::{save_metadata, StoredOp}; +use super::store::{NOW_MS, SCHEMA}; +use rusqlite::{Connection, OptionalExtension}; +use serde_json::value::RawValue; +use std::collections::BTreeMap; + +/// Schema 7: each attachment is stored once, however many ops reference it, +/// and deleted with the last op that does. +const ATTACHMENTS: &str = + "CREATE TABLE attachment_blobs(digest TEXT PRIMARY KEY, data BLOB NOT NULL, + refs INTEGER NOT NULL CHECK(refs>=0)); + CREATE TABLE operation_attachments(position INTEGER NOT NULL, digest TEXT NOT NULL, + PRIMARY KEY(position,digest)); + CREATE TRIGGER attachment_acquire AFTER INSERT ON operation_attachments BEGIN + UPDATE attachment_blobs SET refs=refs+1 WHERE digest=NEW.digest; END; + CREATE TRIGGER attachment_release AFTER DELETE ON operation_attachments BEGIN + UPDATE attachment_blobs SET refs=refs-1 WHERE digest=OLD.digest; + DELETE FROM attachment_blobs WHERE digest=OLD.digest AND refs=0; END; + CREATE TRIGGER operation_release AFTER DELETE ON ops BEGIN + DELETE FROM operation_attachments WHERE position=OLD.position; END;"; + +/// Read the version under the same write transaction as every upgrade, so a +/// concurrent opener cannot run a stale migration plan. +pub(super) fn migrate(db: &Connection) -> anyhow::Result<()> { + let version: u32 = db.query_row("PRAGMA user_version", [], |row| row.get(0))?; + anyhow::ensure!( + version <= SCHEMA, + "unsupported session storage schema {version}" + ); + if version < 3 { + db.execute_batch( + "CREATE TABLE IF NOT EXISTS batches ( + input INTEGER PRIMARY KEY, committed INTEGER NOT NULL DEFAULT 0, + observation INTEGER NOT NULL DEFAULT 1); + CREATE TABLE IF NOT EXISTS ops ( + position INTEGER PRIMARY KEY AUTOINCREMENT, + input INTEGER NOT NULL, value BLOB NOT NULL); + CREATE INDEX IF NOT EXISTS ops_input ON ops(input); + CREATE TABLE IF NOT EXISTS heads ( + route TEXT PRIMARY KEY, position INTEGER NOT NULL DEFAULT 0, + failure TEXT); + CREATE TABLE IF NOT EXISTS recovery (id INTEGER PRIMARY KEY CHECK(id=1),failure TEXT);", + )?; + if version == 1 { + db.execute_batch( + "ALTER TABLE batches ADD COLUMN observation INTEGER NOT NULL DEFAULT 1", + )?; + } + db.execute_batch("ALTER TABLE heads ADD COLUMN binding TEXT")?; + } + if version < 4 { + db.execute_batch( + "CREATE TABLE root_candidates (span_id TEXT PRIMARY KEY, value BLOB NOT NULL)", + )?; + } + if version < 5 { + db.execute_batch( + "ALTER TABLE heads ADD COLUMN settings TEXT; + ALTER TABLE heads ADD COLUMN settings_through INTEGER NOT NULL DEFAULT 0", + )?; + } + if version < 6 { + db.execute_batch( + "DELETE FROM ops WHERE input IN (SELECT input FROM batches WHERE committed=0); + CREATE TABLE receipts (input INTEGER NOT NULL, ordinal INTEGER NOT NULL, PRIMARY KEY(input,ordinal)); + CREATE TABLE publication (id INTEGER PRIMARY KEY CHECK(id=1), tail INTEGER NOT NULL, floor INTEGER NOT NULL); + INSERT INTO publication VALUES(1,(SELECT coalesce(max(position),0) FROM ops),0); + CREATE TABLE origins (span_id TEXT PRIMARY KEY, value TEXT NOT NULL); + CREATE TABLE span_state (span_id TEXT PRIMARY KEY, kind TEXT NOT NULL, value BLOB NOT NULL, end_ms INTEGER);", + )?; + } + if version < 7 { + db.execute_batch(ATTACHMENTS)?; + } + if version < 8 { + // One session row replaces per-input batches: an input is handed over + // in one transaction, so only ops a route could already see survive. + // A partly published input is translated again. + db.execute_batch(&format!( + "CREATE TABLE session(id INTEGER PRIMARY KEY CHECK(id=1), + source TEXT, session_id TEXT, identity BLOB, + legacy_namespace INTEGER NOT NULL DEFAULT 0, + active_ms INTEGER NOT NULL, event_tail INTEGER NOT NULL DEFAULT 0, + through INTEGER NOT NULL DEFAULT 0, op_tail INTEGER NOT NULL DEFAULT 0, + continuation BLOB, roots BLOB, failure TEXT); + INSERT INTO session(id,active_ms,through,op_tail,failure) VALUES(1,{NOW_MS}, + (SELECT coalesce(max(input),0) FROM batches WHERE committed=1), + (SELECT tail FROM publication WHERE id=1), + (SELECT failure FROM recovery WHERE id=1)); + DELETE FROM ops WHERE position>(SELECT op_tail FROM session);" + ))?; + migrate_roots(db)?; + // Metadata kept for a live session expires once it goes unused. + db.execute_batch(&format!( + "ALTER TABLE origins ADD COLUMN ended_ms INTEGER; + CREATE INDEX origins_ended ON origins(ended_ms); + ALTER TABLE span_state ADD COLUMN touched_ms INTEGER NOT NULL DEFAULT 0; + UPDATE span_state SET touched_ms={NOW_MS}; + ALTER TABLE heads ADD COLUMN progress_ms INTEGER NOT NULL DEFAULT 0; + ALTER TABLE heads ADD COLUMN subscribed INTEGER NOT NULL DEFAULT 0; + UPDATE heads SET progress_ms={NOW_MS}, subscribed=1;" + ))?; + if version < 6 { + // One bounded pass extracts the metadata a schema-5 channel kept + // only inside its stored ops. + extract_metadata(db)?; + } + db.execute_batch( + "DROP TABLE batches; DROP TABLE receipts; DROP TABLE root_candidates; + DROP TABLE publication; DROP TABLE recovery; + DROP INDEX ops_input; ALTER TABLE ops DROP COLUMN input; + CREATE TABLE events (id INTEGER PRIMARY KEY, control INTEGER NOT NULL, value BLOB NOT NULL); + CREATE TABLE captured (digest BLOB PRIMARY KEY, at_ms INTEGER NOT NULL) WITHOUT ROWID; + CREATE INDEX captured_at ON captured(at_ms);", + )?; + } + if version < SCHEMA { + // Opening an up-to-date store writes nothing, so it keeps its age. + db.execute_batch(&format!("PRAGMA user_version={SCHEMA}"))?; + } + Ok(()) +} + +/// A schema-5 channel kept span metadata only inside its stored ops. One +/// bounded pass extracts what recovery needs, then drops delivered ops. +fn extract_metadata(db: &Connection) -> anyhow::Result<()> { + let mut after = 0; + loop { + let record: Option<(u64, Vec, bool)> = db + .query_row( + "SELECT position,value,observation FROM ops JOIN batches USING(input) + WHERE position>? ORDER BY position LIMIT 1", + [after], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), + ) + .optional()?; + let Some((position, value, observation)) = record else { + break; + }; + save_metadata(db, &StoredOp::decode(&value)?, observation)?; + after = position; + } + super::span_ops::prune(db) +} + +/// A pre-collection channel stored each root candidate in its own row. +/// Translation now replaces them all in one value. +fn migrate_roots(db: &Connection) -> anyhow::Result<()> { + let mut roots = BTreeMap::>>::new(); + let mut query = db.prepare("SELECT span_id,value FROM root_candidates")?; + for row in query.query_map([], |r| { + Ok((r.get::<_, String>(0)?, r.get::<_, Vec>(1)?)) + })? { + let (id, value) = row?; + let ops: Vec> = serde_json::from_slice(&value)?; + let ops = ops + .into_iter() + .map(|op| Ok(RawValue::from_string(String::from_utf8(op)?)?)) + .collect::>>()?; + roots.insert(id, ops); + } + if !roots.is_empty() { + db.execute( + "UPDATE session SET roots=? WHERE id=1", + [serde_json::to_vec(&roots)?], + )?; + } + Ok(()) +} + +/// Upgrades from SpanOp channel schemas that predate collections. +#[cfg(test)] +mod tests { + use super::super::inspect::{Inspector, Table}; + use super::super::{BindingChanged, SessionStorage, Translated}; + use super::*; + use crate::pipeline::cursor::Cursor; + use crate::translate::{OriginSnapshot, SpanOp, SpanRow}; + use crate::wire::SessionRoute; + use rusqlite::params; + use std::sync::Arc; + + fn op(name: &str) -> SpanOp { + SpanOp::Insert(SpanRow { + span_id: name.into(), + name: name.into(), + late_merge_key: Some("late".into()), + turn_span_id: Some("turn".into()), + is_turn: true, + origin: Some( + OriginSnapshot { + plugin_version: Some("capture".into()), + source_version: None, + bt_version: "test".into(), + } + .into(), + ), + ..SpanRow::default() + }) + } + + fn route(name: &str) -> SessionRoute { + SessionRoute { + tags: [name.into()].into_iter().collect(), + ..SessionRoute::default() + } + } + + /// The SpanOp channel schema written by the last pre-collection release. + const SCHEMA_FIVE: &str = "CREATE TABLE batches(input INTEGER PRIMARY KEY, + committed INTEGER NOT NULL DEFAULT 0, observation INTEGER NOT NULL DEFAULT 1); + CREATE TABLE ops(position INTEGER PRIMARY KEY AUTOINCREMENT, + input INTEGER NOT NULL, value BLOB NOT NULL); + CREATE INDEX ops_input ON ops(input); + CREATE TABLE heads(route TEXT PRIMARY KEY, position INTEGER NOT NULL DEFAULT 0, + failure TEXT, binding TEXT, settings TEXT, settings_through INTEGER NOT NULL DEFAULT 0); + CREATE TABLE recovery(id INTEGER PRIMARY KEY CHECK(id=1), failure TEXT); + CREATE TABLE root_candidates(span_id TEXT PRIMARY KEY, value BLOB NOT NULL); + PRAGMA user_version=5;"; + + const SCHEMA_SIX: &str = "CREATE TABLE receipts(input INTEGER NOT NULL, + ordinal INTEGER NOT NULL, PRIMARY KEY(input,ordinal)); + CREATE TABLE publication(id INTEGER PRIMARY KEY CHECK(id=1), + tail INTEGER NOT NULL, floor INTEGER NOT NULL); + CREATE TABLE origins(span_id TEXT PRIMARY KEY, value TEXT NOT NULL); + CREATE TABLE span_state(span_id TEXT PRIMARY KEY, kind TEXT NOT NULL, + value BLOB NOT NULL, end_ms INTEGER); + PRAGMA user_version=6;"; + + #[tokio::test] + async fn schema_seven_attachments_survive_the_upgrade() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("upgrade.sqlite"); + let db = Connection::open(&path).unwrap(); + db.execute_batch(SCHEMA_FIVE).unwrap(); + db.execute_batch(SCHEMA_SIX).unwrap(); + db.execute_batch(ATTACHMENTS).unwrap(); + db.execute( + "INSERT INTO heads(route,position) VALUES(?,0)", + [serde_json::to_string(&route("a")).unwrap()], + ) + .unwrap(); + db.execute_batch( + "INSERT INTO batches(input,committed) VALUES(10,1); + INSERT INTO publication VALUES(1,1,0); + PRAGMA user_version=7;", + ) + .unwrap(); + let attachment = crate::attachments::Attachment::new( + "document.pdf".into(), + "application/pdf".into(), + b"pdf bytes".to_vec(), + ); + let mut stored = op("document"); + stored.row_mut().attachments = vec![crate::attachments::Attachment { + data: Vec::new(), + ..attachment.clone() + }]; + db.execute( + "INSERT INTO ops(input,value) VALUES(10,?)", + [StoredOp::encode(&stored).unwrap()], + ) + .unwrap(); + db.execute( + "INSERT INTO attachment_blobs(digest,data,refs) VALUES(?,?,0)", + params![attachment.digest, attachment.data], + ) + .unwrap(); + db.execute( + "INSERT INTO operation_attachments(position,digest) VALUES(1,?)", + [&attachment.digest], + ) + .unwrap(); + drop(db); + let upgraded = SessionStorage::at(&path).await.unwrap(); + let ops = upgraded.stored().await; + assert_eq!(ops[0].row().attachments[0].data, b"pdf bytes"); + assert_eq!(Inspector::open(&path).unwrap().attachment_refs(), [1]); + } + + #[tokio::test] + async fn schema_five_upgrade_reclaims_acknowledged_payloads_without_losing_provenance() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("upgrade.sqlite"); + let db = Connection::open(&path).unwrap(); + db.execute_batch(SCHEMA_FIVE).unwrap(); + db.execute( + "INSERT INTO heads(route,position) VALUES(?,1)", + [serde_json::to_string(&route("old")).unwrap()], + ) + .unwrap(); + db.execute_batch("INSERT INTO batches(input,committed) VALUES(10,1)") + .unwrap(); + db.execute( + "INSERT INTO ops(input,value) VALUES(10,?)", + [StoredOp::encode(&op("old")).unwrap()], + ) + .unwrap(); + drop(db); + let upgraded = SessionStorage::at(&path).await.unwrap(); + assert_eq!(upgraded.status().await.unwrap().op_tail, 1); + let origins = upgraded.origins_for(vec!["old".into()]).await.unwrap(); + assert_eq!(origins["old"].bt_version, "test"); + assert_eq!(Inspector::open(&path).unwrap().count(Table::Ops), 0); + assert!(upgraded.complete().await.unwrap()); + } + + #[tokio::test] + async fn schema_six_upgrade_keeps_only_published_ops_and_translation_state() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("upgrade.sqlite"); + let db = Connection::open(&path).unwrap(); + db.execute_batch(SCHEMA_FIVE).unwrap(); + db.execute_batch(SCHEMA_SIX).unwrap(); + db.execute( + "INSERT INTO heads(route,position) VALUES(?,0)", + [serde_json::to_string(&route("a")).unwrap()], + ) + .unwrap(); + // Input 10 committed; input 20 published one op, then the daemon + // stopped before storing or publishing the rest. + db.execute_batch( + "INSERT INTO batches(input,committed) VALUES(10,1),(20,0); + INSERT INTO receipts VALUES(20,0); + INSERT INTO publication VALUES(1,2,0); + INSERT INTO recovery VALUES(1,'held');", + ) + .unwrap(); + for (input, name) in [(10, "committed"), (20, "published"), (20, "unpublished")] { + db.execute( + "INSERT INTO ops(input,value) VALUES(?,?)", + params![input, StoredOp::encode(&op(name)).unwrap()], + ) + .unwrap(); + } + let root = serde_json::to_vec(&[StoredOp::encode(&op("root")).unwrap()]).unwrap(); + db.execute("INSERT INTO root_candidates VALUES('root',?)", [root]) + .unwrap(); + drop(db); + let upgraded = SessionStorage::at(&path).await.unwrap(); + let status = upgraded.status().await.unwrap(); + assert_eq!(status.translated_through, 10); + assert_eq!(status.op_tail, 2); + let names: Vec<_> = upgraded + .stored() + .await + .into_iter() + .map(|op| op.row().span_id.clone()) + .collect(); + assert_eq!(names, ["committed", "published"]); + assert_eq!(status.source_failure.as_deref(), Some("held")); + let roots = upgraded.root_candidates().await.unwrap(); + assert_eq!( + roots["root"][0].row().late_merge_key.as_deref(), + Some("late") + ); + assert!(upgraded.continuation().await.unwrap().is_none()); + } + + #[tokio::test] + async fn concurrent_opens_upgrade_one_schema_atomically() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("concurrent-upgrade.sqlite"); + let db = Connection::open(&path).unwrap(); + db.execute_batch("CREATE TABLE batches(input INTEGER PRIMARY KEY,committed INTEGER NOT NULL DEFAULT 0); PRAGMA user_version=1;").unwrap(); + drop(db); + let ready = Arc::new(tokio::sync::Barrier::new(8)); + let mut tasks = Vec::new(); + for _ in 0..8 { + let path = path.clone(); + let ready = ready.clone(); + tasks.push(tokio::spawn(async move { + ready.wait().await; + SessionStorage::at(&path).await + })); + } + let mut opened = Vec::new(); + for task in tasks { + opened.push(task.await.unwrap().unwrap()); + } + for session in opened { + assert_eq!(session.status().await.unwrap().op_tail, 0); + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn translation_begin_waits_for_a_concurrent_writer_before_reading() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("concurrent.sqlite"); + let session = SessionStorage::at(&path).await.unwrap(); + let mut peer = Connection::open(&path).unwrap(); + let transaction = peer + .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate) + .unwrap(); + transaction + .execute("UPDATE session SET through=10", []) + .unwrap(); + let begin = tokio::spawn(async move { + session.translated(10, vec![op("late")]).await.unwrap(); + session + }); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + let failed_early = begin.is_finished(); + transaction.commit().unwrap(); + begin.await.unwrap(); + assert_eq!( + Inspector::open(&path).unwrap().count(Table::Ops), + 0, + "a committed input must remain committed after waiting for its writer" + ); + assert!( + !failed_early, + "a read-before-write transaction must wait rather than fail to upgrade its snapshot" + ); + } + + #[tokio::test] + async fn preparatory_schema_upgrades_without_changing_committed_positions() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("old.sqlite"); + let db = Connection::open(&path).unwrap(); + db.execute_batch("CREATE TABLE batches(input INTEGER PRIMARY KEY,committed INTEGER NOT NULL DEFAULT 0); INSERT INTO batches VALUES(10,1); PRAGMA user_version=1;").unwrap(); + drop(db); + let session = SessionStorage::at(&path).await.unwrap(); + assert_eq!(session.status().await.unwrap().translated_through, 10); + session + .commit_translation(Translated { + input: 20, + ops: vec![op("retirement")], + ..Default::default() + }) + .await + .unwrap(); + assert!( + session.observations().await.unwrap().is_empty(), + "retirement output is not a native correlation observation" + ); + let mut route = Cursor::open(&session, &route("a")).await.unwrap(); + assert_eq!( + route.next_batch(8).await.unwrap().unwrap().value().len(), + 1, + "all published output still reaches durable delivery subscribers" + ); + } + + #[tokio::test] + async fn schema_two_heads_upgrade_and_keep_a_nonsecret_backend_binding() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("old.sqlite"); + let db = Connection::open(&path).unwrap(); + db.execute_batch("CREATE TABLE heads(route TEXT PRIMARY KEY,position INTEGER NOT NULL DEFAULT 0,failure TEXT); PRAGMA user_version=2;").unwrap(); + let route = route("canonical"); + let key = serde_json::to_string(&route).unwrap(); + db.execute("INSERT INTO heads(route,position) VALUES(?,7)", [&key]) + .unwrap(); + drop(db); + let session = SessionStorage::at(&path).await.unwrap(); + let mut config = route.with_auth(crate::wire::BackendAuth { + token: "secret-a".into(), + api_url: Some("https://one.test".into()), + app_url: None, + org_id: Some("org".into()), + org_name: None, + }); + session.bind(&key, &config).await.unwrap(); + config.auth.token = "secret-b".into(); + session.bind(&key, &config).await.unwrap(); + config.auth.api_url = Some("https://other.test".into()); + assert!(session + .bind(&key, &config) + .await + .unwrap_err() + .downcast_ref::() + .is_some()); + let restored = Cursor::open(&session, &route).await.unwrap(); + assert_eq!(restored.completed_position(), 7); + let binding: String = Connection::open(&path) + .unwrap() + .query_row("SELECT binding FROM heads", [], |r| r.get(0)) + .unwrap(); + assert!(!binding.contains("secret-")); + } +} diff --git a/bt-daemon/src/dispatch.rs b/bt-daemon/src/dispatch.rs index cda842a8..95092118 100644 --- a/bt-daemon/src/dispatch.rs +++ b/bt-daemon/src/dispatch.rs @@ -76,7 +76,7 @@ pub(crate) struct SessionOptions { pub route: crate::wire::SessionRoute, pub data_dir: PathBuf, pub translation: Arc, - pub input: crate::pipeline::journal::Cursor, + pub input: crate::pipeline::cursor::Cursor, pub auth_provider: Option>, } @@ -87,7 +87,7 @@ pub struct Session { pub counters: Arc, pub last_error: Arc>>, source_progress: Arc, - route_progress: crate::pipeline::journal::Progress, + route_progress: crate::pipeline::cursor::Progress, pub recovery: Arc>>, pub source_recovery: Arc>>, pub source_error: Arc>>, @@ -159,9 +159,9 @@ impl Session { } SessionMsg::Flush(reply) | SessionMsg::Finalize(reply) => { let kind = if finalize { - crate::journal::ControlKind::Finalize + crate::pipeline::input::ControlKind::Finalize } else { - crate::journal::ControlKind::Checkpoint + crate::pipeline::input::ControlKind::Checkpoint }; let target = producer.control(kind).await; let progress = progress.clone(); @@ -192,7 +192,7 @@ impl Session { let target = match target { Some(tail) => Some(tail), None if last => producer - .control(crate::journal::ControlKind::Retire) + .control(crate::pipeline::input::ControlKind::Retire) .await .ok(), None => None, @@ -626,7 +626,7 @@ mod tests { recovery: Arc::new(Mutex::new(None)), source_recovery: Arc::new(Mutex::new(None)), source_progress: Arc::new(crate::pipeline::translation::Progress::default()), - route_progress: crate::pipeline::journal::Progress::default(), + route_progress: crate::pipeline::cursor::Progress::default(), permalink: Arc::new(Mutex::new(None)), last_activity: Mutex::new(Instant::now()), }; diff --git a/bt-daemon/src/journal.rs b/bt-daemon/src/journal.rs index cf872e75..8ddcde93 100644 --- a/bt-daemon/src/journal.rs +++ b/bt-daemon/src/journal.rs @@ -1,20 +1,15 @@ -//! Per-session write-ahead journal. Every accepted event is appended -//! (auth-redacted) before the caller is acked, so a restarted daemon can -//! rebuild session state by replaying the journal through the translator. +//! On-disk naming for session state, and managed-run acceptance records. //! -//! Format: one [`RedactedEnvelope`] JSON value per line in -//! `/journal/----.ndjson`, where an -//! overlong sanitized session id keeps only its tail to fit one file name. -//! -//! Managed-run acceptance records live alongside the journals so a flush can -//! still tell which delivery pipelines a managed child produced after the -//! daemon that accepted them has restarted or idle-exited. +//! Captured events live in [`crate::collections`]. NDJSON journals written by +//! earlier daemons are only read there, to migrate them, and are then deleted. +//! Managed-run acceptance records remain separate so flush can discover +//! pipelines after the daemon that accepted them has restarted or idle-exited. use crate::wire::{BackendAuth, Envelope, RedactedEnvelope, SessionRoute}; use serde::{Deserialize, Serialize}; use std::collections::HashSet; use std::path::{Path, PathBuf}; -use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt}; +use tokio::io::AsyncWriteExt; pub fn journal_dir(data_dir: &Path) -> PathBuf { data_dir.join("journal") @@ -39,7 +34,7 @@ pub fn journal_path(data_dir: &Path, session_id: &str) -> PathBuf { journal_dir(data_dir).join(format!("{}.ndjson", sanitize(session_id))) } -/// Source-qualified journal path. The stable suffix prevents sanitized native +/// Source-qualified legacy journal path. The stable suffix prevents sanitized native /// ids such as `a/b` and `a_b` from aliasing the same file, so a session id /// too long for one file name keeps only its tail (Pi ids embed the session /// file path). Names that fit are unchanged, so existing journals still match. @@ -56,34 +51,6 @@ pub fn source_journal_path(data_dir: &Path, source: &str, session_id: &str) -> P journal_dir(data_dir).join(format!("{prefix}{session}{suffix}")) } -/// Return the source-qualified journal, copying the legacy session-only file -/// on first use so an upgrade retains replay history. The legacy file remains -/// untouched for rollback and is no longer appended after migration. -pub async fn ensure_source_journal( - data_dir: &Path, - source: &str, - session_id: &str, -) -> anyhow::Result { - let path = source_journal_path(data_dir, source, session_id); - if tokio::fs::metadata(&path).await.is_ok() { - return Ok(path); - } - let legacy = journal_path(data_dir, session_id); - // A legacy name too long for the filesystem was never written. - if legacy.file_name().map_or(0, |name| name.len()) > MAX_FILE_NAME_BYTES { - return Ok(path); - } - match tokio::fs::metadata(&legacy).await { - Ok(_) => { - tokio::fs::create_dir_all(journal_dir(data_dir)).await?; - tokio::fs::copy(&legacy, &path).await?; - } - Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} - Err(error) => return Err(error.into()), - } - Ok(path) -} - pub fn managed_run_dir(data_dir: &Path) -> PathBuf { data_dir.join("managed-runs") } @@ -147,48 +114,51 @@ pub async fn read_managed_run_keys(data_dir: &Path, managed_run_id: &str) -> Vec /// Recover the source omitted by pre-source-qualified managed-run records. /// Route matching avoids selecting an unrelated delivery pipeline when an old -/// session journal contains more than one destination. +/// session contained more than one destination. The source that owned the +/// legacy session namespace wins when several match. pub async fn legacy_journal_source( data_dir: &Path, session_id: &str, route: &SessionRoute, ) -> Option { - let path = journal_path(data_dir, session_id); - let through = JournalReader::recorded_len(&path).await; - let mut reader = JournalReader::open(&path, through).await.ok().flatten()?; - while let Ok(Some(entry)) = reader.next_entry().await { - if entry - .route - .as_ref() - .is_some_and(|candidate| candidate.same_route(route)) - { - return Some(entry.source); + let mut found = None; + for path in crate::collections::SessionStorage::all(data_dir) + .await + .ok()? + { + let Ok(storage) = crate::collections::SessionStorage::at(&path).await else { + continue; + }; + let Ok(status) = storage.status().await else { + continue; + }; + let Some((source, session)) = status.owner() else { + continue; + }; + if session != session_id { + continue; } - } - None -} - -/// Whether this source owned the session actor recorded by a pre-qualification -/// daemon. Only the first source recorded for a native session keeps the old -/// span-id namespace: the legacy daemon had one actor and one namespace per -/// native session even if its journal later received mixed-source events. -pub async fn legacy_journal_has_session( - data_dir: &Path, - canonical_source: &str, - session_id: &str, -) -> bool { - let path = journal_path(data_dir, session_id); - let through = JournalReader::recorded_len(&path).await; - let Ok(Some(mut reader)) = JournalReader::open(&path, through).await else { - return false; - }; - while let Ok(Some(entry)) = reader.next_entry().await { - let recorded_source = crate::translate::canonical_source_name(&entry.source); - if entry.session_id == session_id { - return recorded_source == canonical_source; + let recorded = storage + .identity() + .await + .ok() + .flatten() + .and_then(|identity| identity.route) + .is_some_and(|candidate| candidate.same_route(route)); + let registered = storage + .routes() + .await + .unwrap_or_default() + .iter() + .any(|candidate| candidate.same_route(route)); + if recorded || registered { + if status.legacy_namespace { + return Some(source); + } + found.get_or_insert(source); } } - false + found } /// Best-effort age-based collection of managed-run records, mirroring journal @@ -217,480 +187,6 @@ pub async fn gc_old_managed_runs(data_dir: &Path, max_age: std::time::Duration) } } -/// Append-only journal writer for one session. -pub struct JournalWriter { - file: tokio::fs::File, - position: u64, - pi_context: Vec, -} - -impl JournalWriter { - pub async fn open_path(path: &Path) -> anyhow::Result { - if let Some(dir) = path.parent() { - tokio::fs::create_dir_all(dir).await?; - } - let file = tokio::fs::OpenOptions::new() - .create(true) - .append(true) - .open(path) - .await?; - let position = file.metadata().await?.len(); - Ok(Self { - file, - position, - pi_context: Vec::new(), - }) - } - - pub(crate) fn position(&self) -> u64 { - self.position - } - - /// Append one redacted event and confirm its durable write before capture acknowledges it. - /// - /// The journal is a durability record and is never capped or truncated: - /// dropping entries would silently cost recovery fidelity. Its size is - /// bounded instead by writing each transcript byte once (see - /// [`crate::transcript_mirror`]) and by age-based GC, and replay reads it - /// as a stream so a large journal never becomes a large allocation. - pub async fn append(&mut self, env: &Envelope) -> anyhow::Result { - let mut redacted = env.redacted(); - compact_pi_payload(&mut redacted, &mut self.pi_context); - let mut line = serde_json::to_vec(&redacted)?; - line.push(b'\n'); - self.file.write_all(&line).await?; - self.file.flush().await?; - self.file.sync_data().await?; - self.position += line.len() as u64; - Ok(self.position) - } - - pub(crate) async fn append_control( - &mut self, - control: &PipelineControl, - ) -> anyhow::Result { - let mut value = serde_json::to_value(control)?; - value["_bt_record_type"] = "pipeline_control".into(); - let mut line = serde_json::to_vec(&value)?; - line.push(b'\n'); - self.file.write_all(&line).await?; - self.file.flush().await?; - self.file.sync_data().await?; - self.position += line.len() as u64; - Ok(self.position) - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct DeliveryCheckpointRecord { - #[serde(rename = "_bt_record_type")] - record_type: String, - route: SessionRoute, - through: u64, -} - -#[derive(Debug)] -// Keep event records inline on the journal read path; the added capture -// completeness bit makes this enum just exceed Clippy's size threshold. -#[allow(clippy::large_enum_variant)] -pub enum JournalRecord { - Event(RedactedEnvelope), - Control(PipelineControl), - DeliveryCheckpoint { route: SessionRoute, through: u64 }, -} - -#[derive(Debug, Clone, Copy, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum ControlKind { - Checkpoint, - Finalize, - Retire, - /// Discard translator state: the native source was rewritten. - Reset, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct PipelineControl { - pub kind: ControlKind, - pub bounds: std::collections::HashMap, -} - -#[derive(Debug)] -pub struct JournalRecordEntry { - pub record: JournalRecord, - /// Exclusive byte offset after this record in the journal. - pub through: u64, -} - -/// Streaming reader over one session's journal. -/// -/// Replay must never materialize a whole journal: the file is read line by -/// line so peak memory is one entry, not the entire recorded session. -pub struct JournalReader { - reader: tokio::io::BufReader>, - path: PathBuf, - line_no: usize, - position: u64, - pi_context: Vec, -} - -impl JournalReader { - pub(crate) fn position(&self) -> u64 { - self.position - } - - /// Rebuild decoder context before continuing at a saved record boundary. - pub(crate) async fn resume(path: &Path, position: u64, through: u64) -> anyhow::Result { - anyhow::ensure!(position <= through, "invalid recovery range"); - let mut reader = Self::open(path, through) - .await? - .ok_or_else(|| anyhow::anyhow!("recovery journal is missing"))?; - while reader.position < position { - anyhow::ensure!( - reader.next_record().await?.is_some(), - "recovery journal ended before its boundary" - ); - } - anyhow::ensure!(reader.position == position, "invalid recovery boundary"); - Ok(reader) - } - - /// Open a journal for streaming, reading at most `through` bytes. - /// - /// That bound is what keeps replay from consuming the very event that - /// triggered the session's creation: the caller records the journal's - /// length before appending, so the actor replays strictly what was - /// already recovered state, never the live event still on its way to the - /// queue. `Ok(None)` means the session has no journal yet. - pub async fn open(path: &Path, through: u64) -> anyhow::Result> { - let file = match tokio::fs::File::open(path).await { - Ok(file) => file, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), - Err(error) => return Err(error.into()), - }; - Ok(Some(Self { - reader: tokio::io::BufReader::new(file.take(through)), - path: path.to_path_buf(), - line_no: 0, - position: 0, - pi_context: Vec::new(), - })) - } - - /// The journal's current length, which is the bound a session created now - /// should replay through. A missing journal replays nothing. - pub async fn recorded_len(path: &Path) -> u64 { - tokio::fs::metadata(path) - .await - .map(|meta| meta.len()) - .unwrap_or(0) - } - - /// The next entry, or `None` at end of file. - pub async fn next_entry(&mut self) -> anyhow::Result> { - while let Some(entry) = self.next_record().await? { - if let JournalRecord::Event(env) = entry.record { - return Ok(Some(env)); - } - } - Ok(None) - } - - /// The next journal record, including delivery checkpoints written by a - /// previous daemon generation. - pub async fn next_record(&mut self) -> anyhow::Result> { - loop { - let mut bytes = Vec::new(); - let read = self.reader.read_until(b'\n', &mut bytes).await?; - if read == 0 { - return Ok(None); - } - self.position += read as u64; - self.line_no += 1; - let path = self.path.clone(); - let line_no = self.line_no; - let position = self.position; - let mut pi_context = std::mem::take(&mut self.pi_context); - let (pi_context, record) = tokio::task::spawn_blocking(move || { - let record = decode_record(&bytes, &path, line_no, position, &mut pi_context); - (pi_context, record) - }) - .await?; - self.pi_context = pi_context; - if let Some(record) = record? { - return Ok(Some(record)); - } - } - } - - pub(crate) fn extend(&mut self, through: u64) { - let buffered = self.reader.buffer().len() as u64; - self.reader - .get_mut() - .set_limit(through.saturating_sub(self.position + buffered)); - } - - /// The latest acknowledged event offset for `route` in the portion of the - /// journal being recovered. Older journals contain no checkpoints and - /// therefore retain their existing replay behavior. - pub async fn acknowledged_through(path: &Path, through: u64, route: &SessionRoute) -> u64 { - let Ok(Some(mut reader)) = Self::open(path, through).await else { - return 0; - }; - let mut acknowledged = 0; - while let Ok(Some(entry)) = reader.next_record().await { - if let JournalRecord::DeliveryCheckpoint { - route: candidate, - through, - } = entry.record - { - if candidate.same_route(route) { - acknowledged = acknowledged.max(through); - } - } - } - acknowledged - } -} - -fn decode_record( - bytes: &[u8], - path: &Path, - line_no: usize, - position: u64, - pi_context: &mut Vec, -) -> anyhow::Result> { - let line = std::str::from_utf8(bytes) - .map_err(|error| anyhow::anyhow!("journal {}:{}: {error}", path.display(), line_no))? - .trim(); - if line.is_empty() { - return Ok(None); - } - let value: serde_json::Value = serde_json::from_str(line) - .map_err(|error| anyhow::anyhow!("journal {}:{}: {error}", path.display(), line_no))?; - let record = if value - .get("_bt_record_type") - .and_then(serde_json::Value::as_str) - == Some("delivery_checkpoint") - { - let checkpoint: DeliveryCheckpointRecord = serde_json::from_value(value) - .map_err(|error| anyhow::anyhow!("journal {}:{}: {error}", path.display(), line_no))?; - JournalRecord::DeliveryCheckpoint { - route: checkpoint.route, - through: checkpoint.through, - } - } else if value - .get("_bt_record_type") - .and_then(serde_json::Value::as_str) - == Some("pipeline_control") - { - JournalRecord::Control(serde_json::from_value(value)?) - } else { - let mut event = serde_json::from_value(value) - .map_err(|error| anyhow::anyhow!("journal {}:{}: {error}", path.display(), line_no))?; - expand_pi_payload(&mut event, pi_context) - .map_err(|error| anyhow::anyhow!("journal {}:{}: {error}", path.display(), line_no))?; - JournalRecord::Event(event) - }; - Ok(Some(JournalRecordEntry { - record, - through: position, - })) -} - -const PI_MESSAGES_DELTA: &str = "_bt_messages_delta"; - -fn compact_pi_payload(event: &mut RedactedEnvelope, previous: &mut Vec) { - if event.source != "pi" { - return; - } - let Some(native) = event - .payload - .get_mut("event") - .and_then(serde_json::Value::as_object_mut) - else { - return; - }; - match event.event.as_str() { - "context" => { - let Some(messages) = native - .remove("messages") - .and_then(|messages| messages.as_array().cloned()) - else { - return; - }; - let common_prefix = previous - .iter() - .zip(&messages) - .take_while(|(left, right)| left == right) - .count(); - native.insert( - PI_MESSAGES_DELTA.into(), - serde_json::json!({ - "common_prefix": common_prefix, - "suffix": messages[common_prefix..], - }), - ); - *previous = messages; - } - "before_provider_request" => { - // The translator records only the allowlisted request - // configuration and tool definitions, never the prompt or messages. - if let Some(payload) = native.get_mut("payload") { - *payload = serde_json::Value::Object(crate::translate::pi_request_config(payload)); - } - } - "agent_end" => { - // The translator only consumes willRetry from this lifecycle event. - native.remove("messages"); - } - "message_update" => { - // Pi repeats the progressively growing assistant message on every - // streaming update. Translation only needs the update type to mark - // time-to-first-token; the completed message arrives separately in - // message_end. - native.remove("message"); - if let Some(update) = native - .get_mut("assistantMessageEvent") - .and_then(serde_json::Value::as_object_mut) - { - update.retain(|key, _| key == "type"); - } - native.retain(|key, _| key == "type" || key == "assistantMessageEvent"); - } - _ => {} - } -} - -fn expand_pi_payload( - event: &mut RedactedEnvelope, - previous: &mut Vec, -) -> anyhow::Result<()> { - if event.source != "pi" || event.event != "context" { - return Ok(()); - } - let Some(native) = event - .payload - .get_mut("event") - .and_then(serde_json::Value::as_object_mut) - else { - return Ok(()); - }; - let Some(delta) = native.remove(PI_MESSAGES_DELTA) else { - if let Some(messages) = native.get("messages").and_then(serde_json::Value::as_array) { - *previous = messages.clone(); - } - return Ok(()); - }; - let common_prefix = delta - .get("common_prefix") - .and_then(serde_json::Value::as_u64) - .and_then(|value| usize::try_from(value).ok()) - .ok_or_else(|| anyhow::anyhow!("invalid Pi context common prefix"))?; - anyhow::ensure!( - common_prefix <= previous.len(), - "Pi context common prefix exceeds prior context" - ); - let suffix = delta - .get("suffix") - .and_then(serde_json::Value::as_array) - .ok_or_else(|| anyhow::anyhow!("invalid Pi context suffix"))?; - previous.truncate(common_prefix); - previous.extend(suffix.iter().cloned()); - native.insert( - "messages".into(), - serde_json::Value::Array(previous.clone()), - ); - Ok(()) -} - -/// Best-effort age-based journal collection. A failed stat/remove is logged -/// and ignored; stale state must never prevent the daemon from serving hooks. -pub async fn gc_old_journals(data_dir: &Path, max_age: std::time::Duration) { - let dir = journal_dir(data_dir); - let Ok(mut entries) = tokio::fs::read_dir(&dir).await else { - return; - }; - let now = std::time::SystemTime::now(); - while let Ok(Some(entry)) = entries.next_entry().await { - let path = entry.path(); - if path.extension().and_then(|v| v.to_str()) != Some("ndjson") { - continue; - } - let old = entry - .metadata() - .await - .ok() - .and_then(|m| m.modified().ok()) - .and_then(|modified| now.duration_since(modified).ok()) - .is_some_and(|age| age > max_age); - let partition = path - .file_stem() - .and_then(|name| name.to_str()) - .and_then(|name| name.rsplit("--").next()); - let protected = match partition { - Some(id) => { - tokio::fs::try_exists(data_dir.join("pipeline").join(format!("{id}.sqlite"))) - .await - .unwrap_or(true) - } - None => false, - }; - if old && !protected && legacy_collectible(data_dir, &path).await { - if let Err(e) = tokio::fs::remove_file(&path).await { - tracing::warn!(path = %path.display(), "failed to remove stale journal: {e}"); - } - } - } -} - -// Pre-SpanOp journals can be collected only with explicit completion evidence. -// Unknown or uncheckpointed history stays available for migration/reconstruction. -async fn legacy_collectible(data_dir: &Path, path: &Path) -> bool { - let Ok(Some(mut reader)) = - JournalReader::open(path, JournalReader::recorded_len(path).await).await - else { - return false; - }; - let mut observed = std::collections::HashMap::::new(); - let mut completed = std::collections::HashMap::::new(); - loop { - match reader.next_record().await { - Ok(Some(entry)) => match entry.record { - JournalRecord::Event(event) => { - let partition = data_dir.join("pipeline").join(format!( - "{}.sqlite", - crate::ids::session_storage_id(&event.source, &event.session_id) - )); - if tokio::fs::try_exists(partition).await.unwrap_or(true) { - return false; - } - let Some(route) = event.route else { - return false; - }; - observed.insert( - serde_json::to_string(&route).unwrap_or_default(), - entry.through, - ); - } - JournalRecord::DeliveryCheckpoint { route, through } => { - completed - .entry(serde_json::to_string(&route).unwrap_or_default()) - .and_modify(|previous| *previous = (*previous).max(through)) - .or_insert(through); - } - JournalRecord::Control(_) => return false, - }, - Ok(None) => break, - Err(_) => return false, - } - } - !observed.is_empty() - && observed - .iter() - .all(|(route, through)| completed.get(route).copied().unwrap_or(0) >= *through) -} - /// Reconstruct a translator-usable [`Envelope`] from a redacted journal entry. /// The live token is gone (redacted), so `auth.token` is empty — fine for /// rebuilding translator state; the sink must be re-supplied live credentials @@ -725,173 +221,6 @@ pub fn envelope_from_redacted(r: RedactedEnvelope) -> Envelope { mod tests { use super::*; - fn pi_context(messages: Vec, ts_ms: i64) -> Envelope { - Envelope { - source: "pi".into(), - source_version: None, - plugin_version: None, - session_id: "pi-session".into(), - event: "context".into(), - ts_ms, - managed_run_id: None, - capture: None, - payload: serde_json::json!({"event":{"type":"context","messages":messages}}), - route: None, - config: None, - } - } - - #[tokio::test] - async fn pi_context_history_is_delta_encoded_and_replayed() { - let temp = tempfile::tempdir().unwrap(); - let path = temp.path().join("pi.ndjson"); - let mut writer = JournalWriter::open_path(&path).await.unwrap(); - let mut messages = Vec::new(); - let mut naive_bytes = 0usize; - for index in 0..20 { - messages.push(serde_json::json!({ - "role":"user", - "content": format!("{index}:{}", "x".repeat(4096)), - })); - let event = pi_context(messages.clone(), index); - naive_bytes += serde_json::to_vec(&event.redacted()).unwrap().len() + 1; - writer.append(&event).await.unwrap(); - } - let compacted = vec![ - serde_json::json!({"role":"compactionSummary","summary":"bounded"}), - serde_json::json!({"role":"user","content":"after"}), - ]; - let event = pi_context(compacted.clone(), 20); - naive_bytes += serde_json::to_vec(&event.redacted()).unwrap().len() + 1; - writer.append(&event).await.unwrap(); - drop(writer); - - let stored = tokio::fs::read(&path).await.unwrap(); - assert!( - stored.len() < naive_bytes / 3, - "Pi journal did not eliminate cumulative context copies: stored={} naive={naive_bytes}", - stored.len() - ); - assert!(!String::from_utf8_lossy(&stored).contains("\"messages\"")); - - let through = stored.len() as u64; - let mut reader = JournalReader::open(&path, through).await.unwrap().unwrap(); - let mut contexts = Vec::new(); - while let Some(entry) = reader.next_entry().await.unwrap() { - contexts.push( - entry - .payload - .pointer("/event/messages") - .and_then(serde_json::Value::as_array) - .cloned() - .unwrap(), - ); - } - assert_eq!(contexts.len(), 21); - assert_eq!(contexts[19].len(), 20); - assert_eq!(contexts[20], compacted); - } - - #[tokio::test] - async fn pi_streaming_updates_do_not_persist_growing_partial_messages() { - let temp = tempfile::tempdir().unwrap(); - let path = temp.path().join("pi.ndjson"); - let mut writer = JournalWriter::open_path(&path).await.unwrap(); - let marker = "growing-partial-marker".repeat(4096); - let event = Envelope { - source: "pi".into(), - source_version: None, - plugin_version: None, - session_id: "pi-session".into(), - event: "message_update".into(), - ts_ms: 1, - managed_run_id: None, - capture: None, - payload: serde_json::json!({ - "event": { - "type": "message_update", - "assistantMessageEvent": { - "type": "text_delta", - "partial": marker, - }, - "message": {"role": "assistant", "content": marker}, - } - }), - route: None, - config: None, - }; - writer.append(&event).await.unwrap(); - drop(writer); - - let stored = tokio::fs::read(&path).await.unwrap(); - assert!(!String::from_utf8_lossy(&stored).contains("growing-partial-marker")); - - let mut reader = JournalReader::open(&path, stored.len() as u64) - .await - .unwrap() - .unwrap(); - let replayed = reader.next_entry().await.unwrap().unwrap(); - assert_eq!( - replayed - .payload - .pointer("/event/assistantMessageEvent/type"), - Some(&serde_json::json!("text_delta")) - ); - } - - #[tokio::test] - async fn pi_provider_requests_persist_only_request_configuration() { - let temp = tempfile::tempdir().unwrap(); - let path = temp.path().join("pi.ndjson"); - let mut writer = JournalWriter::open_path(&path).await.unwrap(); - let event = Envelope { - source: "pi".into(), - source_version: None, - plugin_version: None, - session_id: "pi-session".into(), - event: "before_provider_request".into(), - ts_ms: 1, - managed_run_id: None, - capture: None, - payload: serde_json::json!({ - "event": { - "type": "before_provider_request", - "payload": { - "system": "system-prompt-marker", - "messages": [{"role": "user", "content": "message-marker"}], - "tools": [{"name": "read", "input_schema": {"type": "object"}}], - "max_tokens": 1024, - }, - } - }), - route: None, - config: None, - }; - writer.append(&event).await.unwrap(); - drop(writer); - - let stored = tokio::fs::read(&path).await.unwrap(); - let stored_text = String::from_utf8_lossy(&stored); - assert!(!stored_text.contains("system-prompt-marker")); - assert!(!stored_text.contains("message-marker")); - - let mut reader = JournalReader::open(&path, stored.len() as u64) - .await - .unwrap() - .unwrap(); - let replayed = reader.next_entry().await.unwrap().unwrap(); - assert_eq!( - replayed.payload.pointer("/event/payload"), - Some(&serde_json::json!({ - "max_tokens": 1024, - "tools": [{"type": "function", "function": { - "name": "read", - "parameters": {"type": "object"}, - }}], - })) - ); - } - #[test] fn pi_journaled_request_configuration_replays_unchanged() { let schema = serde_json::json!({"type": "object"}); @@ -923,37 +252,12 @@ mod tests { } } - #[tokio::test] - async fn source_journals_are_distinct_and_migrate_legacy_history() { - let temp = tempfile::tempdir().unwrap(); - let legacy = journal_path(temp.path(), "same/session"); - tokio::fs::create_dir_all(legacy.parent().unwrap()) - .await - .unwrap(); - tokio::fs::write(&legacy, b"legacy\n").await.unwrap(); - - let codex = ensure_source_journal(temp.path(), "codex", "same/session") - .await - .unwrap(); - let claude = ensure_source_journal(temp.path(), "claude-code", "same/session") - .await - .unwrap(); - assert_ne!(codex, claude); - assert_eq!(tokio::fs::read(&codex).await.unwrap(), b"legacy\n"); - assert_eq!(tokio::fs::read(&claude).await.unwrap(), b"legacy\n"); - assert_eq!(tokio::fs::read(&legacy).await.unwrap(), b"legacy\n"); - } - - #[tokio::test] - async fn long_session_ids_get_distinct_bounded_journals() { + #[test] + fn long_session_ids_get_distinct_bounded_journal_names() { let temp = tempfile::tempdir().unwrap(); let shared = "x".repeat(400); - let first = ensure_source_journal(temp.path(), "pi", &format!("a{shared}")) - .await - .unwrap(); - let second = ensure_source_journal(temp.path(), "pi", &format!("b{shared}")) - .await - .unwrap(); + let first = source_journal_path(temp.path(), "pi", &format!("a{shared}")); + let second = source_journal_path(temp.path(), "pi", &format!("b{shared}")); assert_ne!(first, second); for path in [&first, &second] { assert!(path.file_name().unwrap().len() <= MAX_FILE_NAME_BYTES); @@ -973,46 +277,39 @@ mod tests { async fn legacy_managed_run_records_recover_source_from_the_old_journal() { let temp = tempfile::tempdir().unwrap(); let route = SessionRoute::default(); - let mut writer = JournalWriter::open_path(&journal_path(temp.path(), "legacy")) + let path = journal_path(temp.path(), "legacy"); + tokio::fs::create_dir_all(path.parent().unwrap()) .await .unwrap(); - writer - .append(&Envelope { - source: "codex".into(), + let mut lines = String::new(); + for (source, ts_ms) in [("codex", 1), ("claude", 2)] { + let env = Envelope { + source: source.into(), source_version: None, plugin_version: None, session_id: "legacy".into(), event: "SessionStart".into(), - ts_ms: 1, + ts_ms, managed_run_id: None, payload: serde_json::json!({}), route: Some(route.clone()), config: None, capture: None, - }) - .await - .unwrap(); - writer - .append(&Envelope { - source: "claude".into(), - source_version: None, - plugin_version: None, - session_id: "legacy".into(), - event: "SessionStart".into(), - ts_ms: 2, - managed_run_id: None, - payload: serde_json::json!({}), - route: Some(route.clone()), - config: None, - capture: None, - }) - .await - .unwrap(); + }; + lines.push_str(&serde_json::to_string(&env.redacted()).unwrap()); + lines.push('\n'); + } + tokio::fs::write(&path, lines).await.unwrap(); assert_eq!( legacy_journal_source(temp.path(), "legacy", &route).await, Some("codex".into()) ); - assert!(legacy_journal_has_session(temp.path(), "codex", "legacy").await); - assert!(!legacy_journal_has_session(temp.path(), "claude-code", "legacy").await); + assert!(!path.exists()); + for (source, owner) in [("codex", true), ("claude-code", false)] { + let events = crate::collections::SessionStorage::open(temp.path(), source, "legacy") + .await + .unwrap(); + assert_eq!(events.status().await.unwrap().legacy_namespace, owner); + } } } diff --git a/bt-daemon/src/lib.rs b/bt-daemon/src/lib.rs index 726611b3..c2f79a9a 100644 --- a/bt-daemon/src/lib.rs +++ b/bt-daemon/src/lib.rs @@ -17,6 +17,7 @@ mod agents; mod args; mod client; mod codex_hooks; +mod collections; mod command_output; mod correlation; mod daemon_log; @@ -61,6 +62,10 @@ pub fn init_daemon_logging(data_dir: &std::path::Path, verbose: bool) -> bool { pub use client::{ flush_managed_run, flush_session, forward_envelope, run_status, shutdown_daemon, HostInfo, }; +/// Session storage inspection and fault injection for integration tests. +#[cfg(feature = "test-support")] +#[doc(hidden)] +pub use collections::inspect as storage_inspect; pub use command_output::{ AuthDiagnostic, DaemonDiagnostic, DaemonStatus, DoctorCommandOutput, ImportSummary, OutputFormat, SetupCommandOutput, StatusCommandOutput, StopCommandOutput, TraceCommandOutput, diff --git a/bt-daemon/src/pipeline/attachment_tests.rs b/bt-daemon/src/pipeline/attachment_tests.rs index 6d7c3247..05af5e4b 100644 --- a/bt-daemon/src/pipeline/attachment_tests.rs +++ b/bt-daemon/src/pipeline/attachment_tests.rs @@ -4,7 +4,7 @@ reason = "Test fixtures and assertions fail immediately on unexpected values." )] //! Exercise native agent translation through durable attachment capture and upload. -use super::journal::SpanJournal; +use crate::collections::SessionStorage; use crate::{ sink::{BraintrustSinkConfig, BraintrustSinkFactory, SinkFactory}, translate::{Registry, SessionCtx}, @@ -64,10 +64,10 @@ async fn upload(source: &str, events: Vec) -> Vec { .mount(&storage) .await; let tmp = tempfile::tempdir().unwrap(); - let journal = SpanJournal::open(&tmp.path().join("attachments.sqlite")) + let session = SessionStorage::at(&tmp.path().join("attachments.sqlite")) .await .unwrap(); - journal.register(&Default::default()).await.unwrap(); + session.register(&Default::default()).await.unwrap(); let mut translator = Registry::default_agents().create(source, "attachments"); let ctx = SessionCtx { session_id: "attachments".into(), @@ -75,28 +75,24 @@ async fn upload(source: &str, events: Vec) -> Vec { }; for (i, event) in events.iter().enumerate() { let input = i as u64 + 1; - journal.begin(input, true).await.unwrap(); let mut ops = translator.handle(event, &ctx).unwrap(); while let Some(more) = translator.drain_pending(&ctx).unwrap() { ops.extend(more); } - journal.append_live(input, &mut 0, &mut ops).await.unwrap(); - journal.commit(input).await.unwrap(); + session.translated(input, ops).await.unwrap(); } let input = events.len() as u64 + 1; - journal.begin(input, true).await.unwrap(); let mut ops = translator.finalize(&ctx).unwrap(); while let Some(more) = translator.drain_pending(&ctx).unwrap() { ops.extend(more); } - journal.append_live(input, &mut 0, &mut ops).await.unwrap(); - journal.commit(input).await.unwrap(); + session.translated(input, ops).await.unwrap(); let mut sink = BraintrustSinkFactory::new(BraintrustSinkConfig::default()) .create("attachments", source) .unwrap(); let config: SessionConfig = serde_json::from_value(json!({"auth":{"token":"test-key","org_id":"org","api_url":server.uri(),"app_url":server.uri()},"destination":{"type":"project_logs","project_name":"attachments"}})).unwrap(); sink.configure(&config); - for (_, op) in journal.read_after(0, 1000).await.unwrap() { + for op in session.stored().await { sink.emit(&[op]).await.unwrap(); } sink.flush().await.unwrap(); diff --git a/bt-daemon/src/pipeline/consumer.rs b/bt-daemon/src/pipeline/consumer.rs index 0ce9c785..c4b801c1 100644 --- a/bt-daemon/src/pipeline/consumer.rs +++ b/bt-daemon/src/pipeline/consumer.rs @@ -368,9 +368,9 @@ impl Consumer { mod tests { use super::*; use crate::{ - pipeline::journal::SpanJournal, translate::{SpanOp, SpanRow}, wire::BackendAuth, + {collections::SessionStorage, pipeline::cursor::Cursor}, }; use std::sync::atomic::{AtomicBool, AtomicU64}; @@ -456,11 +456,11 @@ mod tests { } } fn spawn( - cursor: crate::pipeline::journal::Cursor, + cursor: crate::pipeline::cursor::Cursor, options: ConsumerOptions, ) -> ( Arc, - crate::pipeline::journal::Progress, + crate::pipeline::cursor::Progress, Arc>>, ) { let subscription = cursor.into_input( @@ -485,12 +485,11 @@ mod tests { .await .unwrap(); } - async fn stored(journal: &SpanJournal) { - journal.begin(10, true).await.unwrap(); + async fn stored(journal: &SessionStorage) { journal - .append( + .translated( 10, - &[SpanOp::Insert(SpanRow { + vec![SpanOp::Insert(SpanRow { span_id: "one".into(), name: "one".into(), root_span_id: "one".into(), @@ -500,19 +499,18 @@ mod tests { ) .await .unwrap(); - journal.commit(10).await.unwrap(); } #[tokio::test] async fn transient_rejection_resubmits_consumed_batch_before_completing() { let tmp = tempfile::tempdir().unwrap(); - let journal = SpanJournal::open(&tmp.path().join("spans.sqlite")) + let journal = SessionStorage::at(&tmp.path().join("spans.sqlite")) .await .unwrap(); stored(&journal).await; let route = SessionRoute::default(); let record = Arc::new(Recording::default()); record.reject.store(true, Ordering::SeqCst); - let cursor = journal.subscribe(&route, 0).await.unwrap(); + let cursor = Cursor::open(&journal, &route).await.unwrap(); let opts = options(tmp.path(), &route, record.clone()); let subscription = cursor.into_input( opts.config.subscribe(), @@ -537,14 +535,15 @@ mod tests { assert_eq!(record.submitted.load(Ordering::SeqCst), 2); assert!(error.lock().is_none()); assert!(journal - .failure(&serde_json::to_string(&route).unwrap()) + .head(&serde_json::to_string(&route).unwrap()) .await .unwrap() + .and_then(|head| head.failure) .is_none()); consumer.shutdown().await; forward.abort(); let _ = forward.await; - journal.close().await.unwrap(); + drop(journal); } #[tokio::test] @@ -552,7 +551,7 @@ mod tests { let tmp = tempfile::tempdir().unwrap(); let plugin = tmp.path().join("redact.mjs"); std::fs::write(&plugin, "let calls=0; export default span => {if(calls++===0) {while(true){}} return {...span,name:'redacted'};}").unwrap(); - let journal = SpanJournal::open(&tmp.path().join("spans.sqlite")) + let journal = SessionStorage::at(&tmp.path().join("spans.sqlite")) .await .unwrap(); stored(&journal).await; @@ -563,7 +562,8 @@ mod tests { let record = Arc::new(Recording::default()); let opts = options(tmp.path(), &route, record.clone()); let recovery = opts.recovery.clone(); - let (consumer, progress, error) = spawn(journal.subscribe(&route, 0).await.unwrap(), opts); + let (consumer, progress, error) = + spawn(Cursor::open(&journal, &route).await.unwrap(), opts); wait_for(|| recovery.lock().is_some()).await; assert_eq!(progress.completed(), 0); assert_eq!(record.accepted.load(Ordering::SeqCst), 0); @@ -573,12 +573,13 @@ mod tests { assert!(error.lock().is_none()); assert!(recovery.lock().is_none()); assert!(journal - .failure(&serde_json::to_string(&route).unwrap()) + .head(&serde_json::to_string(&route).unwrap()) .await .unwrap() + .and_then(|head| head.failure) .is_none()); consumer.shutdown().await; - journal.close().await.unwrap(); + drop(journal); } struct Acknowledged(Arc); #[async_trait::async_trait] @@ -618,7 +619,7 @@ mod tests { #[tokio::test] async fn deferred_delivery_can_read_ahead_and_acknowledge_original_receipts() { let tmp = tempfile::tempdir().unwrap(); - let journal = SpanJournal::open(&tmp.path().join("spans.sqlite")) + let journal = SessionStorage::at(&tmp.path().join("spans.sqlite")) .await .unwrap(); let ops: Vec<_> = (0..129) @@ -632,14 +633,12 @@ mod tests { }) }) .collect(); - journal.begin(1, true).await.unwrap(); - journal.append(1, &ops).await.unwrap(); - journal.commit(1).await.unwrap(); + journal.translated(1, ops.clone()).await.unwrap(); let route = SessionRoute::default(); let record = Arc::new(Recording::default()); record.defer_until.store(129, Ordering::SeqCst); let (consumer, progress, _error) = spawn( - journal.subscribe(&route, 0).await.unwrap(), + Cursor::open(&journal, &route).await.unwrap(), options(tmp.path(), &route, record.clone()), ); wait_for(|| progress.completed() == 129).await; @@ -653,19 +652,21 @@ mod tests { async fn head_write_recovery_retries_only_completion() { let tmp = tempfile::tempdir().unwrap(); let path = tmp.path().join("spans.sqlite"); - let journal = SpanJournal::open(&path).await.unwrap(); + let journal = SessionStorage::at(&path).await.unwrap(); stored(&journal).await; let route = SessionRoute::default(); - let cursor = journal.subscribe(&route, 0).await.unwrap(); - let db = rusqlite::Connection::open(&path).unwrap(); - db.execute_batch("CREATE TRIGGER fail_head BEFORE UPDATE OF position ON heads BEGIN SELECT RAISE(FAIL,'injected head failure'); END;").unwrap(); + let cursor = Cursor::open(&journal, &route).await.unwrap(); + let db = crate::collections::inspect::Inspector::open(&path).unwrap(); + db.inject(crate::collections::inspect::Fault::AdvanceHead) + .unwrap(); let record = Arc::new(Recording::default()); let (consumer, progress, error) = spawn(cursor, options(tmp.path(), &route, record.clone())); wait_for(|| error.lock().is_some()).await; assert_eq!(progress.completed(), 0); assert_eq!(record.accepted.load(Ordering::SeqCst), 1); - db.execute_batch("DROP TRIGGER fail_head").unwrap(); + db.clear(crate::collections::inspect::Fault::AdvanceHead) + .unwrap(); wait_for(|| progress.completed() == 1).await; assert_eq!(record.submitted.load(Ordering::SeqCst), 1); assert_eq!(record.accepted.load(Ordering::SeqCst), 1); @@ -676,7 +677,7 @@ mod tests { let tmp = tempfile::tempdir().unwrap(); let plugin = tmp.path().join("plugin.mjs"); std::fs::write(&plugin, "export default () => {throw new Error('bad')}").unwrap(); - let journal = SpanJournal::open(&tmp.path().join("spans.sqlite")) + let journal = SessionStorage::at(&tmp.path().join("spans.sqlite")) .await .unwrap(); stored(&journal).await; @@ -687,17 +688,22 @@ mod tests { let key = serde_json::to_string(&route).unwrap(); let record = Arc::new(Recording::default()); let (consumer, _progress, error) = spawn( - journal.subscribe(&route, 0).await.unwrap(), + Cursor::open(&journal, &route).await.unwrap(), options(tmp.path(), &route, record.clone()), ); wait_for(|| error.lock().is_some()).await; consumer.shutdown().await; - let evidence = journal.failure(&key).await.unwrap().unwrap(); + let evidence = journal + .head(&key) + .await + .unwrap() + .and_then(|head| head.failure) + .unwrap(); assert!(!evidence.contains("never-persist-this")); // Restart with an ordinary channel between the durable source and the // same consumer. Historical failure gating belongs to the source. let opts = options(tmp.path(), &route, record.clone()); - let subscription = journal.subscribe(&route, 0).await.unwrap().into_input( + let subscription = Cursor::open(&journal, &route).await.unwrap().into_input( opts.config.subscribe(), opts.version.clone(), opts.error.clone(), @@ -719,11 +725,16 @@ mod tests { std::fs::write(&plugin, "export default span => span").unwrap(); wait_for(|| progress.completed() == 1).await; assert_eq!(record.accepted.load(Ordering::SeqCst), 1); - assert!(journal.failure(&key).await.unwrap().is_none()); + assert!(journal + .head(&key) + .await + .unwrap() + .and_then(|head| head.failure) + .is_none()); consumer.shutdown().await; forward.abort(); let _ = forward.await; - journal.close().await.unwrap(); + drop(journal); } struct RefreshAuth(Arc); #[async_trait::async_trait] @@ -751,7 +762,7 @@ mod tests { #[tokio::test] async fn stop_signal_detaches_only_its_route_without_reporting_failure() { let tmp = tempfile::tempdir().unwrap(); - let journal = SpanJournal::open(&tmp.path().join("spans.sqlite")) + let journal = SessionStorage::at(&tmp.path().join("spans.sqlite")) .await .unwrap(); let plugin = tmp.path().join("stop.mjs"); @@ -767,9 +778,9 @@ mod tests { let healthy_route = SessionRoute::default(); let stopped_record = Arc::new(Recording::default()); let healthy_record = Arc::new(Recording::default()); - let stopped_cursor = journal.subscribe(&stopped_route, 0).await.unwrap(); - let healthy_cursor = journal.subscribe(&healthy_route, 0).await.unwrap(); stored(&journal).await; + let stopped_cursor = Cursor::open(&journal, &stopped_route).await.unwrap(); + let healthy_cursor = Cursor::open(&journal, &healthy_route).await.unwrap(); let (stopped, stopped_progress, error) = spawn( stopped_cursor, options(tmp.path(), &stopped_route, stopped_record.clone()), @@ -779,16 +790,18 @@ mod tests { options(tmp.path(), &healthy_route, healthy_record.clone()), ); wait_for(|| { - stopped_progress.completed() == i64::MAX as u64 && healthy_progress.completed() == 1 + stopped_progress.completed() == crate::collections::DETACHED + && healthy_progress.completed() == 1 }) .await; assert!(error.lock().is_none()); assert_eq!(stopped_record.submitted.load(Ordering::SeqCst), 0); assert_eq!(healthy_record.submitted.load(Ordering::SeqCst), 1); assert!(journal - .failure(&serde_json::to_string(&stopped_route).unwrap()) + .head(&serde_json::to_string(&stopped_route).unwrap()) .await .unwrap() + .and_then(|head| head.failure) .is_none()); stopped.shutdown().await; healthy.shutdown().await; @@ -797,7 +810,7 @@ mod tests { #[tokio::test] async fn unauthorized_delivery_refreshes_credentials_at_the_same_head() { let tmp = tempfile::tempdir().unwrap(); - let journal = SpanJournal::open(&tmp.path().join("spans.sqlite")) + let journal = SessionStorage::at(&tmp.path().join("spans.sqlite")) .await .unwrap(); stored(&journal).await; @@ -808,7 +821,8 @@ mod tests { let refreshed = Arc::new(AtomicU64::new(0)); let mut opts = options(tmp.path(), &route, record.clone()); opts.auth_provider = Some(Arc::new(RefreshAuth(refreshed.clone()))); - let (consumer, progress, _error) = spawn(journal.subscribe(&route, 0).await.unwrap(), opts); + let (consumer, progress, _error) = + spawn(Cursor::open(&journal, &route).await.unwrap(), opts); wait_for(|| progress.completed() == 1).await; assert_eq!(refreshed.load(Ordering::SeqCst), 1); assert_eq!(consumer.config.borrow().auth.token, "fresh"); @@ -834,7 +848,7 @@ mod tests { .mount_as_scoped(&server) .await; let tmp = tempfile::tempdir().unwrap(); - let journal = SpanJournal::open(&tmp.path().join("spans.sqlite")) + let journal = SessionStorage::at(&tmp.path().join("spans.sqlite")) .await .unwrap(); stored(&journal).await; @@ -854,7 +868,8 @@ mod tests { crate::BraintrustSinkConfig::default(), )); let mut config = opts.config.borrow().clone(); - let (consumer, progress, error) = spawn(journal.subscribe(&route, 0).await.unwrap(), opts); + let (consumer, progress, error) = + spawn(Cursor::open(&journal, &route).await.unwrap(), opts); wait_for(|| error.lock().is_some()).await; assert_eq!(progress.completed(), 0); drop(rejection); @@ -884,7 +899,7 @@ mod tests { std::fs::write(&first, "export default span => ({...span,name:'bad'})").unwrap(); std::fs::write(&last,"export default span => {if(span.name==='bad') throw new Error('bad input'); return span}").unwrap(); let last_digest = crate::span_processor::file_digest(&last); - let journal = SpanJournal::open(&tmp.path().join("spans.sqlite")) + let journal = SessionStorage::at(&tmp.path().join("spans.sqlite")) .await .unwrap(); stored(&journal).await; @@ -894,15 +909,16 @@ mod tests { }; let record = Arc::new(Recording::default()); let (consumer, progress, error) = spawn( - journal.subscribe(&route, 0).await.unwrap(), + Cursor::open(&journal, &route).await.unwrap(), options(tmp.path(), &route, record.clone()), ); wait_for(|| error.lock().is_some()).await; let failure: Failure = serde_json::from_str( &journal - .failure(&serde_json::to_string(&route).unwrap()) + .head(&serde_json::to_string(&route).unwrap()) .await .unwrap() + .and_then(|head| head.failure) .unwrap(), ) .unwrap(); diff --git a/bt-daemon/src/pipeline/cursor.rs b/bt-daemon/src/pipeline/cursor.rs new file mode 100644 index 00000000..4eeb83e2 --- /dev/null +++ b/bt-daemon/src/pipeline/cursor.rs @@ -0,0 +1,1153 @@ +//! Route delivery from the durable SpanOp collection: each route receives +//! committed ops live or, after a gap, from storage, and removes them from its +//! view once its destination accepts them. + +use super::delivery::InputPort; +use super::live::{Receiver, Record, SharedOp, BYTE_BUDGET, WINDOW}; +use super::recovery::{Boundary, Failure, Recovery, RecoveryOutcome}; +use super::{Completion, Delivery, Stage}; +use crate::collections::{BindingChanged, HeldRoute, SessionStorage, DETACHED}; +#[cfg(test)] +use crate::translate::SpanOp; +use crate::wire::{RecoveryInfo, SessionConfig, SessionRoute}; +use parking_lot::Mutex; +use std::sync::{ + atomic::{AtomicBool, Ordering}, + Arc, +}; +use tokio::sync::watch; + +/// Keep the original subscription and backend binding while correcting +/// settings that can unblock an explicitly configuration-held delivery. +pub(crate) async fn reconfigure_held( + session: &SessionStorage, + route: &SessionRoute, + through: u64, +) -> anyhow::Result> { + let route = route.clone(); + session + .reconfigure_held(through, move |held: &HeldRoute| { + let failure = serde_json::from_str::(&held.failure).ok()?; + if !matches!( + failure.condition, + super::recovery::Condition::Configuration { .. } + | super::recovery::Condition::Plugin { .. } + ) || !held.route.same_destination(&route) + { + return None; + } + let previous = held.settings.as_ref().unwrap_or(&held.route); + if previous.same_route(&route) { + return None; + } + let mut corrected = route.clone(); + // Preserve the subscription's pinned credential selection. + corrected.auth = held.route.auth.clone(); + Some(corrected) + }) + .await +} + +pub(crate) struct Cursor { + session: SessionStorage, + pub route: String, + read: u64, + completed: u64, + changes: watch::Receiver, + progress: watch::Sender, + drain: watch::Sender, + abandoned: Arc, + settings: Option>, + version: String, + restored: bool, + live: Receiver, + queued: Option, + error: Arc>>, + recovery: Arc>>, +} + +/// The composition layer keeps this status handle; downstream stages only get +/// the InputPort and managed deliveries. +#[derive(Clone)] +pub(crate) struct Progress { + completed: watch::Receiver, + published: watch::Receiver, + drain: watch::Sender, +} +#[cfg(test)] +impl Default for Progress { + fn default() -> Self { + Self { + completed: watch::channel(0).1, + published: watch::channel(0).1, + drain: watch::channel(0).0, + } + } +} +impl Progress { + pub fn completed(&self) -> u64 { + *self.completed.borrow() + } + pub fn pending(&self) -> u64 { + self.published.borrow().saturating_sub(self.completed()) + } + + pub async fn through(&self, target: u64, error: &Mutex>) -> Result<(), String> { + // Flush callers already know the publication boundary they need. Wake + // collection and keep draining promptly until that boundary is reported. + self.drain.send_if_modified(|requested| { + if target > *requested { + *requested = target; + true + } else { + false + } + }); + let mut completed = self.completed.clone(); + loop { + if *completed.borrow_and_update() >= target { + return Ok(()); + } + if let Some(error) = error.lock().clone() { + return Err(error); + } + tokio::select! { + changed = completed.changed() => changed.map_err(|_| "journal input is gone".to_owned())?, + _ = tokio::time::sleep(std::time::Duration::from_millis(250)) => {}, + } + } + } +} + +pub(crate) struct Subscription { + pub input: Box>>, + pub progress: Progress, +} + +impl Cursor { + pub async fn open(session: &SessionStorage, route: &SessionRoute) -> anyhow::Result { + let subscriber = session.subscribe(route).await?; + let position = subscriber.position; + Ok(Self { + session: session.clone(), + route: serde_json::to_string(route)?, + read: position, + completed: position, + changes: subscriber.published, + progress: watch::channel(position).0, + drain: watch::channel(position).0, + abandoned: Arc::new(AtomicBool::new(false)), + settings: None, + version: String::new(), + restored: false, + live: subscriber.live, + queued: None, + error: Arc::new(Mutex::new(None)), + recovery: Arc::new(Mutex::new(None)), + }) + } + + pub fn into_input( + mut self, + settings: watch::Receiver, + version: String, + error: Arc>>, + recovery: Arc>>, + ) -> Subscription { + let progress = Progress { + completed: self.progress.subscribe(), + published: self.changes.clone(), + drain: self.drain.clone(), + }; + self.settings = Some(settings); + self.version = version; + self.error = error; + self.recovery = recovery; + Subscription { + input: Box::new(SharedCursor(self)), + progress, + } + } + + #[cfg(test)] + pub async fn next_batch( + &mut self, + limit: usize, + ) -> anyhow::Result>>> { + anyhow::ensure!(limit > 0, "cursor batch limit must be nonzero"); + let after = self.read; + let mut rows = self + .session + .read_after(after, usize::MAX, std::time::Duration::MAX) + .await?; + rows.truncate(limit); + let Some(through) = rows.last().map(|row| row.position) else { + return Ok(None); + }; + let ops = rows + .into_iter() + .map(|row| row.op.as_ref().clone()) + .collect::>(); + self.read = through; + Ok(Some(Delivery::new(ops, self.completion(after, through)))) + } + + pub(crate) async fn next_shared(&mut self) -> anyhow::Result>>> { + let published = *self.changes.borrow(); + if self.read >= published { + self.live.resume(); + return Ok(None); + } + let after = self.read; + let first = self.queued.take().or_else(|| self.live.try_recv()); + let mut records = Vec::new(); + if let Some(first) = first { + if first.position == after + 1 { + records.push(first); + } + } + if records.is_empty() { + // Restart, abandoned delivery, a late subscription, or a bounded + // live-queue overrun. Healthy live delivery never enters this path. + records = self.session.recover_after(after).await?; + self.live.clear(); + } else { + let deadline = tokio::time::Instant::now() + WINDOW; + let mut drain = self.drain.subscribe(); + let mut bytes = records[0].bytes; + while bytes < BYTE_BUDGET { + let next = if *drain.borrow_and_update() > after { + match self.live.try_recv() { + Some(record) => record, + None => break, + } + } else { + tokio::select! { + next = tokio::time::timeout_at(deadline, self.live.recv()) => match next { + Ok(Some(record)) => record, + _ => break, + }, + _ = drain.changed() => continue, + } + }; + if next.position != records.last().map_or(after, |record| record.position) + 1 + || bytes + next.bytes > BYTE_BUDGET + { + self.queued = Some(next); + break; + } + bytes += next.bytes; + records.push(next); + } + } + let Some(last) = records.last() else { + return Ok(None); + }; + let through = last.position; + self.read = through; + Ok(Some(Delivery::new( + records.into_iter().map(|record| record.op).collect(), + self.completion(after, through), + ))) + } + + /// Settles the delivery of ops in `(after, through]`. + fn completion(&self, after: u64, through: u64) -> HeadCompletion { + HeadCompletion { + session: self.session.clone(), + live: self.live.control(), + route: self.route.clone(), + expected: after, + through, + progress: self.progress.clone(), + abandoned: self.abandoned.clone(), + acknowledged: false, + error: self.error.clone(), + recovery: self.recovery.clone(), + } + } + + #[cfg(test)] + pub fn completed_position(&self) -> u64 { + self.completed + } + + pub async fn rewind(&mut self) -> anyhow::Result<()> { + self.completed = self + .session + .head(&self.route) + .await? + .ok_or_else(|| anyhow::anyhow!("route head is missing"))? + .position; + self.read = self.completed; + self.queued = None; + self.live.clear(); + self.progress.send_replace(self.completed); + Ok(()) + } + + #[cfg(test)] + pub async fn changed(&mut self) { + let _ = self.changes.changed().await; + } +} + +struct SharedCursor(Cursor); + +#[async_trait::async_trait] +impl InputPort for SharedCursor { + type Item = Vec; + async fn detach(&mut self) -> anyhow::Result<()> { + self.0.session.detach(&self.0.route).await?; + self.0.live.control().pause(); + self.0.live.clear(); + self.0.progress.send_replace(DETACHED); + Ok(()) + } + async fn receive(&mut self) -> anyhow::Result>> { + if *self.0.progress.borrow() == DETACHED { + self.0.live.control().pause(); + return Ok(None); + } + let result = self.0.receive_managed().await; + match result { + Ok(delivery) => Ok(Some(delivery)), + Err(error) => { + self.0.live.control().pause(); + let error = match error.downcast::() { + Ok(failure) => return Err(anyhow::Error::new(failure)), + Err(error) => error, + }; + let failure = Failure::storage(&error, &self.0.version, 0).at(self.0.completed + 1); + // An input failure has no delivery receipt to report through. + // Its source still owns persistence of the recovery evidence. + if let Err(error) = self + .0 + .session + .set_failure(&self.0.route, Some(serde_json::to_string(&failure)?)) + .await + { + tracing::warn!(%error, "input recovery evidence could not be persisted"); + } + Err(anyhow::Error::new(failure)) + } + } + } +} + +impl Cursor { + async fn receive_managed(&mut self) -> anyhow::Result>> { + let mut acknowledgements = self.progress.subscribe(); + loop { + if self.abandoned.load(Ordering::Acquire) { + self.rewind().await?; + self.abandoned.store(false, Ordering::Release); + } + self.completed = *self.progress.borrow(); + self.read = self.read.max(self.completed); + let config = self + .settings + .as_ref() + .map(|settings| settings.borrow().clone()); + if !self.restored { + let head = self.session.head(&self.route).await?; + if let Some(raw) = head.and_then(|head| head.failure) { + let failure = match serde_json::from_str::(&raw) { + Ok(failure) => failure, + Err(error) => match &config { + Some(config) => Failure::legacy(raw, self.completed + 1, config), + None => return Err(error.into()), + }, + }; + if matches!(failure.boundary, Boundary::Completion) + && self.completed >= failure.through.unwrap_or(failure.position) + { + self.session.set_failure(&self.route, None).await?; + } else { + *self.error.lock() = Some(failure.message()); + *self.recovery.lock() = Some(failure.info(false)); + if matches!( + (Recovery { + config: config.as_ref(), + version: &self.version + }) + .process(&failure) + .await, + RecoveryOutcome::Waiting + ) { + tokio::time::sleep(std::time::Duration::from_millis(250)).await; + continue; + } + *self.recovery.lock() = Some(failure.info(true)); + } + } + } + if let Some(config) = &config { + if let Err(error) = self.session.bind(&self.route, config).await { + if error.downcast_ref::().is_some() { + let failure = + Failure::legacy(error.to_string(), self.completed + 1, config); + self.session + .set_failure(&self.route, Some(serde_json::to_string(&failure)?)) + .await?; + return Err(anyhow::Error::new(failure)); + } + return Err(error); + } + } + if let Some(delivery) = self.next_shared().await? { + if self.abandoned.load(Ordering::Acquire) { + drop(delivery); + continue; + } + self.restored = true; + return Ok(delivery); + } + tokio::select! { + _ = self.changes.changed() => {}, + _ = acknowledgements.changed() => {}, + } + } + } +} + +#[cfg(test)] +#[async_trait::async_trait] +impl InputPort for Cursor { + type Item = Vec; + async fn receive(&mut self) -> anyhow::Result>> { + Ok(Some(self.receive_managed().await?.map(|ops| { + ops.into_iter().map(|op| op.as_ref().clone()).collect() + }))) + } +} + +struct HeadCompletion { + session: SessionStorage, + live: super::live::Control, + route: String, + expected: u64, + through: u64, + progress: watch::Sender, + abandoned: Arc, + acknowledged: bool, + error: Arc>>, + recovery: Arc>>, +} +impl Drop for HeadCompletion { + fn drop(&mut self) { + if !self.acknowledged { + self.live.pause(); + self.abandoned.store(true, Ordering::Release); + self.progress.send_modify(|_| {}); + } + } +} +#[async_trait::async_trait] +impl Completion for HeadCompletion { + async fn complete(&mut self) -> anyhow::Result<()> { + self.session + .remove_through(&self.route, self.expected, self.through) + .await + .map(|head| { + self.acknowledged = true; + self.progress.send_replace(head); + *self.error.lock() = None; + *self.recovery.lock() = None; + }) + } + + async fn failed(&mut self, failure: &mut Failure) -> anyhow::Result<()> { + self.live.pause(); + failure.position = self.expected + 1; + failure.through = Some(self.through); + *self.error.lock() = Some(failure.message()); + *self.recovery.lock() = Some(failure.info(false)); + self.session + .set_failure(&self.route, Some(serde_json::to_string(failure)?)) + .await + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::collections::inspect::{Fault, Inspector}; + use crate::translate::{OriginSnapshot, SpanRow}; + + fn op(name: &str) -> SpanOp { + SpanOp::Insert(SpanRow { + span_id: name.into(), + name: name.into(), + late_merge_key: Some("late".into()), + turn_span_id: Some("turn".into()), + is_turn: true, + origin: Some( + OriginSnapshot { + plugin_version: Some("capture".into()), + source_version: None, + bt_version: "test".into(), + } + .into(), + ), + ..SpanRow::default() + }) + } + fn route(name: &str) -> SessionRoute { + SessionRoute { + tags: [name.into()].into_iter().collect(), + ..SessionRoute::default() + } + } + + #[tokio::test] + async fn resolved_profile_completes_the_pre_authentication_placeholder() { + let tmp = tempfile::tempdir().unwrap(); + let journal = SessionStorage::at(&tmp.path().join("auth.sqlite")) + .await + .unwrap(); + let mut named = route("profile"); + named.auth.profile = Some("work".into()); + journal.register(&named).await.unwrap(); + journal.translated(10, vec![op("one")]).await.unwrap(); + journal.translated(10, Vec::new()).await.unwrap(); + let mut resolved = named.clone(); + resolved.auth.profile_id = Some("stable-id".into()); + let mut cursor = Cursor::open(&journal, &resolved).await.unwrap(); + assert_eq!(journal.routes().await.unwrap().len(), 1); + cursor + .next_shared() + .await + .unwrap() + .unwrap() + .into_completed() + .await + .ok() + .unwrap(); + assert_eq!(journal.stored().await.len(), 0); + } + + #[tokio::test] + async fn recovery_routes_at_different_heads_share_the_same_decode_window() { + let tmp = tempfile::tempdir().unwrap(); + let journal = SessionStorage::at(&tmp.path().join("shared-recovery.sqlite")) + .await + .unwrap(); + journal + .translated(10, vec![op("one"), op("two"), op("three")]) + .await + .unwrap(); + let mut a = Cursor::open(&journal, &route("a")).await.unwrap(); + let mut b = Cursor::open(&journal, &route("b")).await.unwrap(); + b.read = 1; + let first = a.next_shared().await.unwrap().unwrap(); + let second = b.next_shared().await.unwrap().unwrap(); + assert_eq!(first.value().len(), 3); + assert_eq!(second.value().len(), 2); + assert!(std::ptr::eq( + first.value()[1].as_ref(), + second.value()[0].as_ref() + )); + assert_eq!(journal.payload_reads(), 3); + } + + #[tokio::test] + async fn detached_route_stays_detached_and_does_not_pin_other_routes() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("spans.sqlite"); + let journal = SessionStorage::at(&path).await.unwrap(); + let route = route("a"); + let mut input = SharedCursor(Cursor::open(&journal, &route).await.unwrap()); + input.detach().await.unwrap(); + assert!(input.receive().await.unwrap().is_none()); + journal.translated(1, vec![op("later")]).await.unwrap(); + assert!(journal.route_complete(&route, 1).await.unwrap()); + assert_eq!(journal.stored().await.len(), 0); + drop((input, journal)); + let restored = SessionStorage::at(&path).await.unwrap(); + let mut input = SharedCursor(Cursor::open(&restored, &route).await.unwrap()); + assert!(input.receive().await.unwrap().is_none()); + } + + #[tokio::test] + async fn attachments_are_stored_once_and_released_after_every_route() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("attachments.sqlite"); + let storage = SessionStorage::at(&path).await.unwrap(); + let mut a = Cursor::open(&storage, &route("a")).await.unwrap(); + let mut b = Cursor::open(&storage, &route("b")).await.unwrap(); + let ops: Vec<_> = ["one", "two"] + .into_iter() + .map(|name| { + let mut op = op(name); + op.row_mut().input = Some( + serde_json::json!({"type":"file", "mime":"application/pdf", "data":"YWJj"}), + ); + op + }) + .collect(); + storage.translated(10, ops.clone()).await.unwrap(); + // A retried handoff of the same input acquires no other reference. + storage.translated(10, ops).await.unwrap(); + let db = Inspector::open(&path).unwrap(); + assert_eq!(db.attachment_refs(), [2], "both ops share one stored copy"); + assert_eq!(storage.stored().await[0].row().attachments[0].data, b"abc"); + let acknowledge = async |cursor: &mut Cursor| { + cursor + .next_batch(1) + .await + .unwrap() + .unwrap() + .into_completed() + .await + .ok() + .unwrap(); + }; + acknowledge(&mut a).await; + assert_eq!(db.attachment_refs(), [2], "route b still owes the first op"); + acknowledge(&mut b).await; + assert_eq!(db.attachment_refs(), [1]); + acknowledge(&mut a).await; + acknowledge(&mut b).await; + assert!(db.attachment_refs().is_empty()); + } + + #[tokio::test] + async fn all_route_acknowledgements_reclaim_payloads_and_preserve_watermarks() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("cleanup.sqlite"); + let journal = SessionStorage::at(&path).await.unwrap(); + let mut a = Cursor::open(&journal, &route("a")).await.unwrap(); + let mut b = Cursor::open(&journal, &route("b")).await.unwrap(); + journal.translated(10, vec![op("one")]).await.unwrap(); + journal.translated(10, Vec::new()).await.unwrap(); + let first = a.next_shared().await.unwrap().unwrap(); + let second = b.next_shared().await.unwrap().unwrap(); + first.into_completed().await.ok().unwrap(); + assert_eq!(journal.stored().await.len(), 1); + second.into_completed().await.ok().unwrap(); + assert_eq!(journal.stored().await.len(), 0); + assert_eq!(journal.status().await.unwrap().op_tail, 1); + assert_eq!( + journal.origins_for(vec!["one".into()]).await.unwrap()["one"].bt_version, + "test" + ); + drop(journal); + let restored = SessionStorage::at(&path).await.unwrap(); + assert_eq!(restored.status().await.unwrap().op_tail, 1); + assert_eq!(restored.status().await.unwrap().translated_through, 10); + let mut late = Cursor::open(&restored, &route("new")).await.unwrap(); + assert!(late.next_shared().await.unwrap().is_none()); + restored.translated(20, vec![op("two")]).await.unwrap(); + assert_eq!(restored.status().await.unwrap().op_tail, 2); + assert!(late.next_shared().await.unwrap().is_some()); + } + + #[tokio::test] + async fn explicit_flush_interrupts_live_batch_collection() { + let tmp = tempfile::tempdir().unwrap(); + let journal = SessionStorage::at(&tmp.path().join("flush.sqlite")) + .await + .unwrap(); + let mut cursor = Cursor::open(&journal, &route("a")).await.unwrap(); + let progress = Progress { + completed: cursor.progress.subscribe(), + published: cursor.changes.clone(), + drain: cursor.drain.clone(), + }; + journal.translated(10, vec![op("one")]).await.unwrap(); + let mut receiving = Box::pin(cursor.next_shared()); + assert!( + tokio::time::timeout(std::time::Duration::from_millis(20), &mut receiving) + .await + .is_err(), + "a sparse batch should wait for more operations" + ); + let error = Mutex::new(None); + tokio::time::timeout(std::time::Duration::from_secs(1), async { + let ((), result) = tokio::join!( + async { + receiving + .await + .unwrap() + .unwrap() + .into_completed() + .await + .ok() + .unwrap(); + }, + progress.through(1, &error) + ); + result.unwrap(); + }) + .await + .expect("explicit flush must bypass the 30-second window"); + assert_eq!(journal.payload_reads(), 0); + } + + #[tokio::test] + async fn newly_registered_route_starts_after_an_existing_routes_pending_output() { + let tmp = tempfile::tempdir().unwrap(); + let journal = SessionStorage::at(&tmp.path().join("routes.sqlite")) + .await + .unwrap(); + journal.register(&route("first")).await.unwrap(); + journal.translated(10, vec![op("old")]).await.unwrap(); + journal.register(&route("new")).await.unwrap(); + journal.translated(20, vec![op("new")]).await.unwrap(); + let mut new = Cursor::open(&journal, &route("new")).await.unwrap(); + let batch = new.next_batch(8).await.unwrap().unwrap(); + assert_eq!(batch.value().len(), 1); + let (SpanOp::Insert(row) | SpanOp::Merge(row)) = &batch.value()[0]; + assert_eq!(row.span_id, "new"); + batch.into_completed().await.ok().unwrap(); + let mut first = Cursor::open(&journal, &route("first")).await.unwrap(); + let batch = first.next_batch(8).await.unwrap().unwrap(); + assert_eq!( + batch.value().len(), + 2, + "the original destination still owns its backlog" + ); + } + + #[tokio::test] + async fn live_routes_share_original_payload_without_sqlite_reads() { + let tmp = tempfile::tempdir().unwrap(); + let journal = SessionStorage::at(&tmp.path().join("live.sqlite")) + .await + .unwrap(); + let mut first = Cursor::open(&journal, &route("first")).await.unwrap(); + let mut second = Cursor::open(&journal, &route("second")).await.unwrap(); + let payload = "x".repeat(BYTE_BUDGET * 2); + let pointer = payload.as_ptr(); + let mut ops = vec![SpanOp::Insert(SpanRow { + input: Some(serde_json::Value::String(payload)), + ..Default::default() + })]; + journal + .translated(10, std::mem::take(&mut ops)) + .await + .unwrap(); + assert!(ops.is_empty()); + // Live delivery is possible before the native event has finished. + let a = first.next_shared().await.unwrap().unwrap(); + let b = second.next_shared().await.unwrap().unwrap(); + assert!(std::ptr::eq(a.value()[0].as_ref(), b.value()[0].as_ref())); + let (SpanOp::Insert(row) | SpanOp::Merge(row)) = a.value()[0].as_ref(); + assert_eq!( + row.input.as_ref().unwrap().as_str().unwrap().as_ptr(), + pointer + ); + assert_eq!(journal.payload_reads(), 0); + let weak = a.value()[0].downgrade(); + drop(a.into_completed().await.ok().unwrap()); + drop(b.into_completed().await.ok().unwrap()); + assert!(weak.upgrade().is_none()); + } + + #[tokio::test] + async fn recovery_decodes_once_for_concurrent_routes_and_keeps_only_weak_references() { + let tmp = tempfile::tempdir().unwrap(); + let journal = SessionStorage::at(&tmp.path().join("recovery.sqlite")) + .await + .unwrap(); + journal.translated(10, vec![op("recover")]).await.unwrap(); + let mut first = Cursor::open(&journal, &route("first")).await.unwrap(); + let mut second = Cursor::open(&journal, &route("second")).await.unwrap(); + let a = first.next_shared().await.unwrap().unwrap(); + let b = second.next_shared().await.unwrap().unwrap(); + assert!(std::ptr::eq(a.value()[0].as_ref(), b.value()[0].as_ref())); + assert_eq!(journal.payload_reads(), 1); + let weak = a.value()[0].downgrade(); + drop(a); + drop(b); + assert!(weak.upgrade().is_none()); + } + + #[tokio::test] + async fn paused_route_recovers_without_blocking_a_healthy_live_route() { + let tmp = tempfile::tempdir().unwrap(); + let journal = SessionStorage::at(&tmp.path().join("lag.sqlite")) + .await + .unwrap(); + let mut fast = Cursor::open(&journal, &route("fast")).await.unwrap(); + let mut slow = Cursor::open(&journal, &route("slow")).await.unwrap(); + slow.live.control().pause(); + for index in 0..3 { + journal + .translated( + 10 + index, + vec![SpanOp::Insert(SpanRow { + name: index.to_string(), + input: Some(serde_json::json!("x".repeat(BYTE_BUDGET))), + ..Default::default() + })], + ) + .await + .unwrap(); + fast.next_shared() + .await + .unwrap() + .unwrap() + .into_completed() + .await + .ok() + .unwrap(); + } + assert_eq!(journal.payload_reads(), 0); + for _ in 0..3 { + let delivery = slow.next_shared().await.unwrap().unwrap(); + assert_eq!( + delivery.value().len(), + 1, + "an oversized operation travels alone" + ); + delivery.into_completed().await.ok().unwrap(); + } + slow.rewind().await.unwrap(); + assert_eq!(slow.completed_position(), 3); + assert_eq!(journal.payload_reads(), 3); + } + + #[tokio::test] + async fn root_candidates_commit_and_release_atomically() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("roots.sqlite"); + let journal = SessionStorage::at(&path).await.unwrap(); + let mut roots = crate::pipeline::roots::Roots::default(); + let mut root = op("root"); + let (SpanOp::Insert(row) | SpanOp::Merge(row)) = &mut root; + row.metadata = Some(serde_json::json!({"_bt_defer_root": true})); + assert!(roots.process(&vec![root]).await.is_empty()); + let db = Inspector::open(&path).unwrap(); + db.inject(Fault::Handoff).unwrap(); + assert!(journal + .commit_translation(crate::collections::Translated { + input: 10, + observation: true, + ops: Vec::new(), + roots: roots.pending().clone(), + state: None, + }) + .await + .is_err()); + assert_eq!(journal.status().await.unwrap().translated_through, 0); + assert!(journal.root_candidates().await.unwrap().is_empty()); + db.clear(Fault::Handoff).unwrap(); + journal + .commit_translation(crate::collections::Translated { + input: 10, + observation: true, + ops: Vec::new(), + roots: roots.pending().clone(), + state: None, + }) + .await + .unwrap(); + drop(journal); + + let journal = SessionStorage::at(&path).await.unwrap(); + let candidates = journal.root_candidates().await.unwrap(); + let (SpanOp::Insert(row) | SpanOp::Merge(row)) = &candidates["root"][0]; + assert_eq!(row.late_merge_key.as_deref(), Some("late")); + assert_eq!( + row.origin.as_ref().unwrap().plugin_version.as_deref(), + Some("capture") + ); + let mut roots = crate::pipeline::roots::Roots::restore(candidates); + let child = SpanOp::Insert(SpanRow { + span_id: "turn".into(), + parent_span_ids: vec!["root".into()], + ..Default::default() + }); + let ready = roots.process(&vec![child]).await; + assert_eq!(ready.len(), 2); + db.inject(Fault::Handoff).unwrap(); + assert!(journal + .commit_translation(crate::collections::Translated { + input: 20, + observation: true, + ops: ready.clone(), + roots: roots.pending().clone(), + state: None, + }) + .await + .is_err()); + assert_eq!(journal.status().await.unwrap().translated_through, 10); + assert_eq!(journal.status().await.unwrap().op_tail, 0); + assert_eq!(journal.root_candidates().await.unwrap().len(), 1); + db.clear(Fault::Handoff).unwrap(); + journal + .commit_translation(crate::collections::Translated { + input: 20, + observation: true, + ops: ready.clone(), + roots: roots.pending().clone(), + state: None, + }) + .await + .unwrap(); + assert_eq!(journal.status().await.unwrap().op_tail, 2); + assert!(journal.root_candidates().await.unwrap().is_empty()); + } + + #[tokio::test] + async fn input_port_replays_abandoned_delivery_without_cursor_control() { + use crate::pipeline::delivery::InputPort; + let tmp = tempfile::tempdir().unwrap(); + let journal = SessionStorage::at(&tmp.path().join("spans.sqlite")) + .await + .unwrap(); + journal.translated(1, vec![op("one")]).await.unwrap(); + let mut input: Box>> = + Box::new(Cursor::open(&journal, &route("a")).await.unwrap()); + let delivery = input.receive().await.unwrap().unwrap(); + drop(delivery); + // Cancel a receive while its storage read is pending, as a concurrent + // configuration update does. The replay obligation must survive it. + let storage = journal.lock_storage(); + let mut cancelled = Box::pin(input.receive()); + let mut context = std::task::Context::from_waker(std::task::Waker::noop()); + assert!(std::future::Future::poll(cancelled.as_mut(), &mut context).is_pending()); + drop(cancelled); + drop(storage); + let replay = tokio::time::timeout(std::time::Duration::from_millis(250), input.receive()) + .await + .expect("unacknowledged input must be replayed") + .unwrap() + .unwrap(); + let (SpanOp::Insert(row) | SpanOp::Merge(row)) = &replay.value()[0]; + assert_eq!(row.name, "one"); + replay.into_completed().await.ok().unwrap(); + assert!(journal.route_complete(&route("a"), 1).await.unwrap()); + assert!(!journal.route_complete(&route("b"), 1).await.unwrap()); + } + + #[tokio::test] + async fn a_committed_input_is_final_and_empty_commits_keep_the_boundary() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("spans.sqlite"); + let journal = SessionStorage::at(&path).await.unwrap(); + journal.translated(10, vec![op("retained")]).await.unwrap(); + let tail = journal.status().await.unwrap().op_tail; + journal.translated(10, vec![op("again")]).await.unwrap(); + assert_eq!( + journal.status().await.unwrap().op_tail, + tail, + "a committed input is final" + ); + journal.translated(20, Vec::new()).await.unwrap(); + assert_eq!(journal.status().await.unwrap().translated_through, 20); + let mut reader = Cursor::open(&journal, &route("a")).await.unwrap(); + let message = reader.next_batch(8).await.unwrap().unwrap(); + let (SpanOp::Insert(row) | SpanOp::Merge(row)) = &message.value()[0]; + assert_eq!(row.name, "retained"); + assert_eq!(row.late_merge_key.as_deref(), Some("late")); + assert!(row.is_turn); + assert_eq!( + row.origin.as_ref().unwrap().plugin_version.as_deref(), + Some("capture") + ); + } + + #[tokio::test] + async fn independent_heads_and_dropped_deliveries_resume_without_skipping() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("spans.sqlite"); + let journal = SessionStorage::at(&path).await.unwrap(); + journal + .translated(10, vec![op("one"), op("two")]) + .await + .unwrap(); + let mut a = Cursor::open(&journal, &route("a")).await.unwrap(); + let mut b = Cursor::open(&journal, &route("b")).await.unwrap(); + a.next_batch(2) + .await + .unwrap() + .unwrap() + .into_completed() + .await + .ok() + .unwrap(); + drop(b.next_batch(2).await.unwrap().unwrap()); + a.rewind().await.unwrap(); + b.rewind().await.unwrap(); + assert!(a.next_batch(2).await.unwrap().is_none()); + assert_eq!(b.next_batch(2).await.unwrap().unwrap().value().len(), 2); + let mut c = Cursor::open(&journal, &route("c")).await.unwrap(); + let first = c.next_batch(1).await.unwrap().unwrap(); + let second = c.next_batch(1).await.unwrap().unwrap(); + assert!( + second.into_completed().await.is_err(), + "later work cannot release an earlier obligation" + ); + first.into_completed().await.ok().unwrap(); + c.rewind().await.unwrap(); + assert_eq!(c.next_batch(2).await.unwrap().unwrap().value().len(), 1); + } + #[tokio::test] + async fn head_write_failure_retains_work_and_commit_wakes_readers() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("spans.sqlite"); + let journal = SessionStorage::at(&path).await.unwrap(); + let mut reader = Cursor::open(&journal, &route("a")).await.unwrap(); + journal.translated(10, vec![op("one")]).await.unwrap(); + tokio::time::timeout(std::time::Duration::from_secs(1), reader.changed()) + .await + .unwrap(); + assert_eq!(journal.status().await.unwrap().op_tail, 1); + journal + .set_failure(&reader.route, Some("held".into())) + .await + .unwrap(); + let inspector = Inspector::open(&path).unwrap(); + inspector.inject(Fault::AdvanceHead).unwrap(); + let pending = reader.next_batch(8).await.unwrap().unwrap(); + let failed = pending.into_completed().await.err().unwrap(); + assert!(failed.error.to_string().contains("injected fault_head")); + assert_eq!( + journal + .head(&reader.route) + .await + .unwrap() + .and_then(|head| head.failure) + .as_deref(), + Some("held") + ); + reader.rewind().await.unwrap(); + assert!(reader.next_batch(8).await.unwrap().is_some()); + inspector.clear(Fault::AdvanceHead).unwrap(); + failed.delivery.into_completed().await.ok().unwrap(); + assert!(journal + .head(&reader.route) + .await + .unwrap() + .and_then(|head| head.failure) + .is_none()); + reader.rewind().await.unwrap(); + assert!(reader.next_batch(8).await.unwrap().is_none()); + } + #[tokio::test] + async fn a_completed_canonical_head_also_covers_its_legacy_named_route() { + let tmp = tempfile::tempdir().unwrap(); + let journal = SessionStorage::at(&tmp.path().join("spans.sqlite")) + .await + .unwrap(); + journal.translated(10, vec![op("one")]).await.unwrap(); + let mut legacy = route("work"); + legacy.auth.profile = Some("work".into()); + let mut canonical = legacy.clone(); + canonical.auth.profile_id = Some("profile-id".into()); + let mut head = Cursor::open(&journal, &canonical).await.unwrap(); + head.next_batch(8) + .await + .unwrap() + .unwrap() + .into_completed() + .await + .ok() + .unwrap(); + assert!(journal.route_complete(&legacy, 10).await.unwrap()); + let mut other_profile = canonical.clone(); + other_profile.auth.profile_id = Some("different-id".into()); + assert!(!journal.route_complete(&other_profile, 10).await.unwrap()); + legacy.tags.insert("different route".into()); + assert!(!journal.route_complete(&legacy, 10).await.unwrap()); + } + + #[tokio::test] + async fn corrected_settings_survive_restart_without_advancing_or_retargeting_heads() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("spans.sqlite"); + let journal = SessionStorage::at(&path).await.unwrap(); + let original = SessionRoute { + destination: Some(crate::wire::TraceDestination::ProjectLogs { + project_id: Some("test-project".into()), + project_name: None, + }), + ..route("a") + }; + let cursor = Cursor::open(&journal, &original).await.unwrap(); + let failure = Failure { + boundary: Boundary::Sink, + position: 1, + through: None, + reason: "rejected row".into(), + attempt: 0, + condition: super::super::recovery::Condition::Configuration { + signature: "original".into(), + recheck_ms: None, + }, + }; + let raw = serde_json::to_string(&failure).unwrap(); + journal + .set_failure(&cursor.route, Some(raw.clone())) + .await + .unwrap(); + let mut corrected = original.clone(); + corrected.tags.insert("corrected".into()); + for unrelated in [ + SessionRoute { + destination: Some(crate::wire::TraceDestination::ProjectLogs { + project_id: Some("other-project".into()), + project_name: None, + }), + ..corrected.clone() + }, + SessionRoute { + auth: crate::wire::AuthSelection { + org_name: Some("other-org".into()), + ..Default::default() + }, + ..corrected.clone() + }, + ] { + assert!(reconfigure_held(&journal, &unrelated, 20) + .await + .unwrap() + .is_empty()); + } + assert_eq!( + reconfigure_held(&journal, &corrected, 20) + .await + .unwrap() + .len(), + 1 + ); + assert_eq!(cursor.completed, 0); + assert_eq!( + journal + .head(&cursor.route) + .await + .unwrap() + .and_then(|head| head.failure), + Some(raw) + ); + // A captured prefix must not revert a newer correction during startup replay. + assert!(reconfigure_held(&journal, &original, 10) + .await + .unwrap() + .is_empty()); + drop(journal); + let restored = SessionStorage::at(&path).await.unwrap(); + assert_eq!( + restored.route_settings(&original).await.unwrap().tags, + corrected.tags + ); + assert_eq!(restored.routes().await.unwrap().len(), 1); + assert_eq!( + Cursor::open(&restored, &original).await.unwrap().completed, + 0 + ); + restored.set_failure(&cursor.route, None).await.unwrap(); + let mut newer = corrected.clone(); + newer.tags.insert("independent".into()); + assert!( + reconfigure_held(&restored, &newer, 30) + .await + .unwrap() + .is_empty(), + "healthy independent subscriptions retain their settings" + ); + } +} diff --git a/bt-daemon/src/pipeline/input.rs b/bt-daemon/src/pipeline/input.rs index 6cd57de2..47a9f064 100644 --- a/bt-daemon/src/pipeline/input.rs +++ b/bt-daemon/src/pipeline/input.rs @@ -1,15 +1,32 @@ //! Stage input shared by direct capture and recovery. Storage supplies only -//! byte positions; original live payloads arrive from capture. -pub use crate::journal::PipelineControl; +//! record IDs; original live payloads arrive from capture. use crate::wire::Envelope; use parking_lot::Mutex; +use serde::{Deserialize, Serialize}; use std::{collections::VecDeque, sync::Arc}; const RECORD_BUDGET: usize = 64; const BYTE_BUDGET: u64 = 8 * 1024 * 1024; -/// Durable byte range returned by the journal append. -#[derive(Clone)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ControlKind { + Checkpoint, + Finalize, + Retire, + /// Discard translator state: the native source was rewritten. + Reset, +} + +/// An ordered lifecycle instruction stored among a session's events. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct PipelineControl { + pub kind: ControlKind, + pub bounds: std::collections::HashMap, +} + +/// The ID range a stored event record occupies. +#[derive(Clone, Copy, Debug)] pub(crate) struct SourcePosition { pub before: u64, pub through: u64, @@ -18,11 +35,6 @@ pub(crate) struct SourcePosition { pub(crate) enum SourceEvent { Event(Box), Control(PipelineControl), - /// An earlier daemon delivered this route's output through `through`. - LegacyDeliveryCheckpoint { - route: Box, - through: u64, - }, } pub(crate) struct SourceRecord { diff --git a/bt-daemon/src/pipeline/journal.rs b/bt-daemon/src/pipeline/journal.rs deleted file mode 100644 index debf2f05..00000000 --- a/bt-daemon/src/pipeline/journal.rs +++ /dev/null @@ -1,2506 +0,0 @@ -//! Concrete durable channel: one ordered SpanOp log and a head per route. -//! -//! Tracking mutations acquire SQLite write access before reading. Deferred -//! read-to-write upgrades can fail without waiting when another connection -//! writes concurrently, even with a busy timeout. -use super::live::{Multiplexer, Receiver, Record, SharedOp, BYTE_BUDGET, WINDOW}; -use super::{ - delivery::InputPort, - recovery::{Boundary, Failure, Recovery, RecoveryOutcome}, - Completion, Delivery, Stage, -}; -use crate::{ - translate::{OriginSnapshot, SpanOp, SpanRow, SpanType}, - wire::{RecoveryInfo, SessionConfig, SessionRoute}, -}; -use parking_lot::Mutex; -use rusqlite::{params, Connection, OptionalExtension}; -use serde::{Deserialize, Serialize}; -use std::{ - collections::BTreeMap, - path::Path, - sync::{ - atomic::{AtomicBool, Ordering}, - Arc, Mutex as StorageMutex, - }, -}; -use tokio::sync::watch; - -#[derive(Debug)] -pub(crate) struct BindingChanged; -impl std::fmt::Display for BindingChanged { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str( - "credential resolution changed the durable head's pinned backend or organization", - ) - } -} -impl std::error::Error for BindingChanged {} - -// SQLite positions are signed integers. The maximum value is a durable terminal -// subscription marker; it never pins payload retention or resumes on replay. -const DETACHED: u64 = i64::MAX as u64; - -type ReplayWindow = Vec<(u64, std::sync::Weak, usize)>; - -#[derive(Clone)] -pub(crate) struct SpanJournal { - connection: Arc>>, - changed: watch::Sender, - live: Arc, - replay: Arc>, - #[cfg(test)] - payload_reads: Arc, -} - -/// Explicit codec preserves fields intentionally omitted from wire/plugin JSON. -#[derive(Serialize, Deserialize)] -struct StoredOp { - version: u32, - op: Op, - #[serde(flatten)] - fields: crate::translate::SinkFields, -} - -impl StoredOp<&SpanOp> { - fn encode(op: &SpanOp) -> anyhow::Result> { - let (SpanOp::Insert(row) | SpanOp::Merge(row)) = op; - Ok(serde_json::to_vec(&StoredOp { - version: 1, - op, - fields: crate::translate::SinkFields::of(row), - })?) - } -} - -impl StoredOp { - fn decode(bytes: &[u8]) -> anyhow::Result { - let mut stored: Self = serde_json::from_slice(bytes)?; - anyhow::ensure!( - stored.version == 1, - "unsupported SpanOp codec {}", - stored.version - ); - let (SpanOp::Insert(row) | SpanOp::Merge(row)) = &mut stored.op; - stored.fields.restore(row); - Ok(stored.op) - } -} - -fn store_attachments(db: &Connection, position: i64, value: &[u8]) -> anyhow::Result<()> { - let mut op = StoredOp::decode(value)?; - let (SpanOp::Insert(row) | SpanOp::Merge(row)) = &mut op; - for attachment in &mut row.attachments { - use sha2::Digest; - anyhow::ensure!( - format!("{:x}", sha2::Sha256::digest(&attachment.data)) == attachment.digest, - "attachment digest does not match captured bytes" - ); - db.execute( - "INSERT OR IGNORE INTO attachment_blobs(digest,data,refs) VALUES (?,?,0)", - params![attachment.digest, attachment.data], - )?; - db.execute( - "INSERT OR IGNORE INTO operation_attachments(position,digest) VALUES (?,?)", - params![position, attachment.digest], - )?; - attachment.data.clear(); - } - db.execute( - "UPDATE ops SET value=? WHERE position=?", - params![StoredOp::encode(&op)?, position], - )?; - Ok(()) -} - -fn load_attachments(db: &Connection, value: &[u8]) -> anyhow::Result { - let mut op = StoredOp::decode(value)?; - let (SpanOp::Insert(row) | SpanOp::Merge(row)) = &mut op; - for attachment in &mut row.attachments { - attachment.data = db.query_row( - "SELECT data FROM attachment_blobs WHERE digest=?", - [&attachment.digest], - |r| r.get(0), - )?; - } - Ok(op) -} - -/// Metadata needed to restore correlation and provenance without retaining -/// conversation input/output after all delivery obligations are complete. -pub(super) fn metadata_only(op: &SpanOp) -> SpanOp { - let (SpanOp::Insert(row) | SpanOp::Merge(row)) = op; - let row = SpanRow { - span_id: row.span_id.clone(), - root_span_id: row.root_span_id.clone(), - parent_span_ids: row.parent_span_ids.clone(), - name: row.name.clone(), - span_type: row.span_type, - start_ms: row.start_ms, - end_ms: row.end_ms, - metadata: row.metadata.clone(), - origin: row.origin.clone(), - is_turn: row.is_turn, - ..Default::default() - }; - match op { - SpanOp::Insert(_) => SpanOp::Insert(row), - SpanOp::Merge(_) => SpanOp::Merge(row), - } -} -fn save_metadata(db: &Connection, op: &SpanOp, observation: bool) -> anyhow::Result<()> { - let (SpanOp::Insert(row) | SpanOp::Merge(row)) = op; - if let Some(origin) = &row.origin { - db.execute( - "INSERT OR IGNORE INTO origins(span_id,value) VALUES (?,?)", - params![row.span_id, serde_json::to_string(origin)?], - )?; - } - if !observation { - return Ok(()); - } - if matches!(op, SpanOp::Insert(_)) - && (row.span_type == SpanType::Tool - || (row.span_type == SpanType::Task && row.span_id == row.root_span_id)) - { - let mut birth = metadata_only(op); - let (SpanOp::Insert(birth_row) | SpanOp::Merge(birth_row)) = &mut birth; - birth_row.end_ms = None; - db.execute( - "INSERT OR REPLACE INTO span_state(span_id,kind,value,end_ms) VALUES (?,?,?,?)", - params![ - row.span_id, - if row.span_type == SpanType::Tool { - "tool" - } else { - "root" - }, - StoredOp::encode(&birth)?, - row.end_ms - ], - )?; - } else { - db.execute( - "UPDATE span_state SET end_ms=? WHERE span_id=?", - params![row.end_ms, row.span_id], - )?; - } - db.execute( - "DELETE FROM span_state WHERE span_id=? AND kind='tool' AND end_ms IS NOT NULL", - [&row.span_id], - )?; - Ok(()) -} -fn prune(db: &Connection) -> anyhow::Result<()> { - let through: Option = db.query_row( - "SELECT min(CASE WHEN position=9223372036854775807 THEN (SELECT tail FROM publication WHERE id=1) ELSE position END) FROM heads", - [], - |r| r.get(0), - )?; - if let Some(through) = through { - db.execute("DELETE FROM ops WHERE position<=?", [through])?; - db.execute( - "UPDATE publication SET floor=max(floor,?) WHERE id=1", - [through], - )?; - db.execute("DELETE FROM receipts WHERE EXISTS(SELECT 1 FROM batches WHERE batches.input=receipts.input AND committed=1) AND NOT EXISTS(SELECT 1 FROM ops WHERE ops.input=receipts.input)", [])?; - } - Ok(()) -} - -impl SpanJournal { - pub async fn open(path: &Path) -> anyhow::Result { - let path = path.to_owned(); - let connection = tokio::task::spawn_blocking(move || -> anyhow::Result<(Connection, u64)> { - let parent = path.parent().ok_or_else(|| anyhow::anyhow!("SpanOp journal path has no parent"))?; - std::fs::create_dir_all(parent)?; - let db = Connection::open(path)?; - db.busy_timeout(std::time::Duration::from_secs(5))?; - // Concurrent WAL transitions can return BUSY without invoking - // SQLite's busy handler. Retry initialization within the same - // bound, before any schema transaction has started. - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); - loop { - match db.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; BEGIN IMMEDIATE;") { - Ok(()) => break, - Err(error) if error.sqlite_error_code() == Some(rusqlite::ErrorCode::DatabaseBusy) - && std::time::Instant::now() < deadline => { - std::thread::sleep(std::time::Duration::from_millis(10)); - } - Err(error) => return Err(error.into()), - } - } - // Read the version under the same write transaction as every - // upgrade, so another opener cannot run a stale migration plan. - let version: u32 = db.query_row("PRAGMA user_version", [], |row| row.get(0))?; - anyhow::ensure!(version <= 7, "unsupported SpanOp journal schema {version}"); - if version < 3 { - db.execute_batch( - "CREATE TABLE IF NOT EXISTS batches ( - input INTEGER PRIMARY KEY, committed INTEGER NOT NULL DEFAULT 0, - observation INTEGER NOT NULL DEFAULT 1); - CREATE TABLE IF NOT EXISTS ops ( - position INTEGER PRIMARY KEY AUTOINCREMENT, - input INTEGER NOT NULL, value BLOB NOT NULL); - CREATE INDEX IF NOT EXISTS ops_input ON ops(input); - CREATE TABLE IF NOT EXISTS heads ( - route TEXT PRIMARY KEY, position INTEGER NOT NULL DEFAULT 0, - failure TEXT); - CREATE TABLE IF NOT EXISTS recovery (id INTEGER PRIMARY KEY CHECK(id=1),failure TEXT); - ", - )?; - if version == 1 { - db.execute_batch( - "ALTER TABLE batches ADD COLUMN observation INTEGER NOT NULL DEFAULT 1", - )?; - } - db.execute_batch("ALTER TABLE heads ADD COLUMN binding TEXT")?; - db.execute_batch("PRAGMA user_version=3")?; - } - if version < 4 { - db.execute_batch("CREATE TABLE root_candidates (span_id TEXT PRIMARY KEY, value BLOB NOT NULL); PRAGMA user_version=4")?; - } - if version < 5 { - db.execute_batch("ALTER TABLE heads ADD COLUMN settings TEXT; ALTER TABLE heads ADD COLUMN settings_through INTEGER NOT NULL DEFAULT 0; PRAGMA user_version=5")?; - } - if version < 6 { - db.execute_batch(" - DELETE FROM ops WHERE input IN (SELECT input FROM batches WHERE committed=0); - CREATE TABLE receipts (input INTEGER NOT NULL, ordinal INTEGER NOT NULL, PRIMARY KEY(input,ordinal)); - CREATE TABLE publication (id INTEGER PRIMARY KEY CHECK(id=1), tail INTEGER NOT NULL, floor INTEGER NOT NULL); - INSERT INTO publication VALUES(1,(SELECT coalesce(max(position),0) FROM ops),0); - CREATE TABLE origins (span_id TEXT PRIMARY KEY, value TEXT NOT NULL); - CREATE TABLE span_state (span_id TEXT PRIMARY KEY, kind TEXT NOT NULL, value BLOB NOT NULL, end_ms INTEGER); - ")?; - // One bounded upgrade pass extracts small recovery metadata. - let mut after = 0; - loop { - let record: Option<(u64,Vec,bool)> = db.query_row("SELECT position,value,observation FROM ops JOIN batches USING(input) WHERE position>? ORDER BY position LIMIT 1", [after], |r| Ok((r.get(0)?,r.get(1)?,r.get(2)?))).optional()?; - let Some((position,value,observation)) = record else { break; }; - save_metadata(&db, &StoredOp::decode(&value)?, observation)?; - after = position; - } - prune(&db)?; - db.execute_batch("PRAGMA user_version=6")?; - } - if version < 7 { - db.execute_batch("CREATE TABLE attachment_blobs(digest TEXT PRIMARY KEY, data BLOB NOT NULL, refs INTEGER NOT NULL CHECK(refs>=0)); - CREATE TABLE operation_attachments(position INTEGER NOT NULL, digest TEXT NOT NULL, PRIMARY KEY(position,digest)); - CREATE TRIGGER attachment_acquire AFTER INSERT ON operation_attachments BEGIN UPDATE attachment_blobs SET refs=refs+1 WHERE digest=NEW.digest; END; - CREATE TRIGGER attachment_release AFTER DELETE ON operation_attachments BEGIN UPDATE attachment_blobs SET refs=refs-1 WHERE digest=OLD.digest; DELETE FROM attachment_blobs WHERE digest=OLD.digest AND refs=0; END; - CREATE TRIGGER operation_release AFTER DELETE ON ops BEGIN DELETE FROM operation_attachments WHERE position=OLD.position; END; - PRAGMA user_version=7;")?; - } - let tail = db.query_row("SELECT tail FROM publication WHERE id=1", [], |row| row.get(0))?; - db.execute_batch("COMMIT")?; - Ok((db, tail)) - }) - .await??; - let (connection, tail) = connection; - let (changed, _) = watch::channel(tail); - Ok(Self { - connection: Arc::new(StorageMutex::new(Some(connection))), - changed, - live: Arc::new(Multiplexer::default()), - replay: Arc::new(tokio::sync::Mutex::new(Vec::new())), - #[cfg(test)] - payload_reads: Arc::default(), - }) - } - - async fn with_db( - &self, - operation: impl FnOnce(&mut Connection) -> anyhow::Result + Send + 'static, - ) -> anyhow::Result { - let db = self.connection.clone(); - tokio::task::spawn_blocking(move || { - let mut db = db - .lock() - .map_err(|_| anyhow::anyhow!("SpanOp storage lock poisoned"))?; - operation( - db.as_mut() - .ok_or_else(|| anyhow::anyhow!("SpanOp journal is closed"))?, - ) - }) - .await? - } - - /// Closing the shared cell also covers cancelled reads whose blocking - /// jobs can outlive their actor. Queued jobs cannot reopen the connection. - pub async fn close(&self) -> anyhow::Result<()> { - let connection = self.connection.clone(); - tokio::task::spawn_blocking(move || -> anyhow::Result<()> { - let database = connection - .lock() - .map_err(|_| anyhow::anyhow!("SpanOp storage lock poisoned"))? - .take(); - if let Some(database) = database { - database.close().map_err(|(_, error)| error)?; - } - Ok(()) - }) - .await? - } - - pub async fn translated_through(&self) -> anyhow::Result { - self.with_db(|db| { - Ok(db.query_row( - "SELECT coalesce(max(input),0) FROM batches WHERE committed=1", - [], - |row| row.get(0), - )?) - }) - .await - } - - pub async fn begin(&self, input: u64, observation: bool) -> anyhow::Result { - self.with_db(move |db| { - let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; - let done: Option = tx - .query_row( - "SELECT committed FROM batches WHERE input=?", - [input], - |row| row.get(0), - ) - .optional()?; - if done == Some(true) { - return Ok(false); - } - let published: bool = tx.query_row( - "SELECT EXISTS(SELECT 1 FROM receipts WHERE input=?)", - [input], - |r| r.get(0), - )?; - if !published { - tx.execute("DELETE FROM ops WHERE input=?", [input])?; - } - tx.execute( - "INSERT OR REPLACE INTO batches(input,committed,observation) VALUES (?,0,?)", - params![input, observation], - )?; - tx.commit()?; - Ok(true) - }) - .await - } - - /// Journal available operations and hand the original instances to routes. - /// Per-input operation ordinals survive a crash halfway through translation, - /// so rebuilding translator state does not publish an accepted prefix twice. - pub async fn append_live( - &self, - input: u64, - ordinal: &mut u64, - ops: &mut Vec, - ) -> anyhow::Result<()> { - for op in ops.iter_mut() { - let (SpanOp::Insert(row) | SpanOp::Merge(row)) = op; - for value in [&mut row.input, &mut row.output].into_iter().flatten() { - crate::attachments::capture(value, &mut row.attachments); - } - } - while !ops.is_empty() { - let started = std::time::Instant::now(); - let mut encoded = Vec::new(); - let mut bytes: usize = 0; - for op in ops.iter() { - let value = StoredOp::encode(op)?; - if !encoded.is_empty() && bytes + value.len() > BYTE_BUDGET { - break; - } - bytes += value.len(); - encoded.push(value); - if bytes >= BYTE_BUDGET || started.elapsed() >= WINDOW { - break; - } - } - let sizes = encoded.iter().map(Vec::len).collect::>(); - let metadata = ops - .iter() - .take(encoded.len()) - .map(metadata_only) - .collect::>(); - let first = *ordinal; - let positions = self - .with_db(move |db| { - let tx = - db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; - let mut positions = Vec::new(); - let (committed, observation): (bool, bool) = tx.query_row( - "SELECT committed,observation FROM batches WHERE input=?", - [input], - |r| Ok((r.get(0)?, r.get(1)?)), - )?; - for (index, value) in encoded.into_iter().enumerate() { - let ordinal = first + index as u64; - let exists = tx.query_row( - "SELECT EXISTS(SELECT 1 FROM receipts WHERE input=? AND ordinal=?)", - params![input, ordinal], - |r| r.get::<_, bool>(0), - )?; - if exists { - positions.push(None); - continue; - } - anyhow::ensure!(!committed, "cannot change a completed translation input"); - save_metadata(&tx, &metadata[index], observation)?; - tx.execute( - "INSERT INTO ops(input,value) VALUES (?,?)", - params![input, value], - )?; - let position = tx.last_insert_rowid() as u64; - store_attachments(&tx, position as i64, &value)?; - positions.push(Some(position)); - tx.execute("UPDATE publication SET tail=? WHERE id=1", [position])?; - tx.execute( - "INSERT INTO receipts(input,ordinal) VALUES (?,?)", - params![input, ordinal], - )?; - } - tx.commit()?; - Ok(positions) - }) - .await?; - let count = positions.len(); - *ordinal += count as u64; - for ((position, bytes), op) in positions.into_iter().zip(sizes).zip(ops.drain(..count)) - { - if let Some(position) = position { - self.live - .publish(Record { - position, - bytes, - op: SharedOp::new(op), - }) - .await; - self.changed.send_replace(position); - } - } - } - Ok(()) - } - - /// One serialized, weakly held recovery window is shared by all routes. - /// No decoded payload remains alive solely because of the replay cache. - async fn recover_after(&self, after: u64) -> anyhow::Result> { - let mut cache = self.replay.lock().await; - if cache - .first() - .is_some_and(|(position, _, _)| *position <= after + 1) - && cache - .last() - .is_some_and(|(position, _, _)| *position > after) - { - let shared = cache - .iter() - .filter(|(position, _, _)| *position > after) - .map(|(position, op, bytes)| { - Some(Record { - position: *position, - op: SharedOp::from_arc(op.upgrade()?), - bytes: *bytes, - }) - }) - .collect::>>(); - if let Some(shared) = shared { - return Ok(shared); - } - } - let records = self.with_db(move |db| { - let mut statement = db.prepare("SELECT position,value FROM ops JOIN batches USING(input) WHERE (committed=1 OR EXISTS(SELECT 1 FROM receipts WHERE receipts.input=ops.input)) AND position>? ORDER BY position")?; - let mut rows = statement.query([after])?; - let started = std::time::Instant::now(); - let mut records = Vec::new(); - let mut bytes: usize = 0; - while let Some(row) = rows.next()? { - let value = row.get_ref(1)?.as_blob()?; - let op = load_attachments(db, value)?; - let (SpanOp::Insert(span) | SpanOp::Merge(span)) = &op; - let size = value.len().saturating_add(span.attachments.iter().map(|attachment| attachment.data.len()).sum::()); - if !records.is_empty() && bytes.saturating_add(size) > BYTE_BUDGET { break; } - bytes = bytes.saturating_add(size); - records.push(Record { position:row.get(0)?, op:SharedOp::new(op), bytes:size }); - if bytes >= BYTE_BUDGET || started.elapsed() >= WINDOW { break; } - } - Ok(records) - }).await?; - #[cfg(test)] - self.payload_reads - .fetch_add(records.len() as u64, Ordering::Relaxed); - *cache = records - .iter() - .map(|record| (record.position, record.op.downgrade(), record.bytes)) - .collect(); - Ok(records) - } - - #[cfg(test)] - pub async fn append(&self, input: u64, ops: &[SpanOp]) -> anyhow::Result<()> { - let encoded = ops - .iter() - .map(StoredOp::encode) - .collect::>>()?; - self.with_db(move |db| { - let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; - let done: bool = tx.query_row( - "SELECT committed FROM batches WHERE input=?", - [input], - |r| r.get(0), - )?; - anyhow::ensure!(!done, "cannot change a committed translation input"); - for value in encoded { - save_metadata(&tx, &StoredOp::decode(&value)?, true)?; - tx.execute( - "INSERT INTO ops(input,value) VALUES (?,?)", - params![input, value], - )?; - store_attachments(&tx, tx.last_insert_rowid(), &value)?; - } - tx.commit()?; - Ok(()) - }) - .await - } - - pub async fn commit(&self, input: u64) -> anyhow::Result { - self.commit_output(input, None).await - } - - /// Root candidates and translated output share the consumed-input boundary. - pub async fn commit_with_roots( - &self, - input: u64, - roots: &BTreeMap>, - ) -> anyhow::Result { - let roots = roots - .iter() - .map(|(id, ops)| { - let ops = ops - .iter() - .map(StoredOp::encode) - .collect::>>()?; - Ok((id.clone(), serde_json::to_vec(&ops)?)) - }) - .collect::>>()?; - self.commit_output(input, Some(roots)).await - } - - pub async fn root_candidates(&self) -> anyhow::Result>> { - self.with_db(|db| { - let mut query = db.prepare("SELECT span_id,value FROM root_candidates")?; - let roots = query - .query_map([], |row| { - Ok((row.get::<_, String>(0)?, row.get::<_, Vec>(1)?)) - })? - .map(|row| { - let (id, bytes) = row?; - let ops: Vec> = serde_json::from_slice(&bytes)?; - Ok(( - id, - ops.iter() - .map(|bytes| StoredOp::decode(bytes)) - .collect::>>()?, - )) - }) - .collect(); - roots - }) - .await - } - - async fn commit_output( - &self, - input: u64, - roots: Option)>>, - ) -> anyhow::Result { - let tail = self - .with_db(move |db| { - let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; - let previous: u64 = tx.query_row( - "SELECT coalesce(max(input),0) FROM batches WHERE committed=1", - [], - |r| r.get(0), - )?; - anyhow::ensure!(input >= previous, "translation commits must be ordered"); - let earlier: u64 = tx.query_row( - "SELECT count(*) FROM batches WHERE committed=0 AND input anyhow::Result { - let live = self.live.subscribe(); - let route = serde_json::to_string(route)?; - let key = route.clone(); - let position = self - .with_db(move |db| { - let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; - // Auth can register a named-profile obligation before learning - // its stable ID. Move that unresolved placeholder to the resolved - // identity instead of leaving a second head that can never run. - let candidate: SessionRoute = serde_json::from_str(&key)?; - if candidate.auth.profile_id.is_some() { - let aliases = { - let mut query = tx.prepare("SELECT route FROM heads WHERE binding IS NULL AND route<>?")?; - let rows = query.query_map([&key], |r|r.get::<_,String>(0))?; - rows.collect::,_>>()? - }; - for alias in aliases { - let previous: SessionRoute = serde_json::from_str(&alias)?; - if previous.auth.profile_id.is_none() && previous.same_route(&candidate) { - tx.execute("UPDATE OR IGNORE heads SET route=? WHERE route=?", params![key,alias])?; - tx.execute("DELETE FROM heads WHERE route=?",[alias])?; - } - } - } - // Seed only a new head, using released event checkpoints where provable. - let legacy: u64 = tx.query_row( - "SELECT coalesce(max(position),0) FROM ops JOIN batches USING(input) - WHERE input<=? AND committed=1", - [legacy_through], - |r| r.get(0), - )?; - tx.execute( - "INSERT OR IGNORE INTO heads(route,position) VALUES (?,max(?,(SELECT floor FROM publication WHERE id=1)))", - params![key, legacy], - )?; - let position = - tx.query_row("SELECT position FROM heads WHERE route=?", [key], |r| { - r.get(0) - })?; - tx.commit()?; - Ok(position) - }) - .await?; - let (progress, _) = watch::channel(position); - Ok(Cursor { - journal: self.clone(), - route, - read: position, - completed: position, - changes: self.changed.subscribe(), - progress, - drain: watch::channel(position).0, - abandoned: Arc::new(AtomicBool::new(false)), - settings: None, - version: String::new(), - restored: false, - live, - queued: None, - error: Arc::new(Mutex::new(None)), - recovery: Arc::new(Mutex::new(None)), - }) - } - - #[cfg(test)] - pub async fn read_after(&self, after: u64, limit: usize) -> anyhow::Result> { - self.with_db(move |db| { - let mut statement = db.prepare("SELECT position,value FROM ops JOIN batches USING(input) WHERE (committed=1 OR EXISTS(SELECT 1 FROM receipts WHERE receipts.input=ops.input)) AND observation=1 AND position>? ORDER BY position LIMIT ?")?; - let rows = statement.query_map(params![after,limit as u64], |r| Ok((r.get::<_,u64>(0)?,r.get::<_,Vec>(1)?)))?; - rows.map(|row| { let (position,bytes)=row?; Ok((position,load_attachments(db, &bytes)?)) }).collect() - }).await - } - - pub async fn tail(&self) -> anyhow::Result { - self.with_db(|db| { - Ok(db.query_row("SELECT tail FROM publication WHERE id=1", [], |r| r.get(0))?) - }) - .await - } - - /// Apply a legacy delivery checkpoint to the route's head: an earlier - /// daemon delivered the output of every input through `input`. It did so - /// without recording provenance, so origins rebuilt for those spans are - /// discarded rather than attributed to this daemon. - pub async fn acknowledge_legacy(&self, route: &SessionRoute, input: u64) -> anyhow::Result<()> { - let route = serde_json::to_string(route)?; - self.with_db(move |db| { - let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; - let position: u64 = tx.query_row( - "SELECT coalesce(max(position),0) FROM ops WHERE input<=?", - [input], - |r| r.get(0), - )?; - let spans = { - let mut query = tx.prepare("SELECT value FROM ops WHERE input<=?")?; - let rows = query.query_map([input], |r| r.get::<_, Vec>(0))?; - let mut spans = Vec::new(); - for row in rows { - let (SpanOp::Insert(op) | SpanOp::Merge(op)) = StoredOp::decode(&row?)?; - spans.push(op.span_id); - } - spans - }; - for span in spans { - tx.execute("DELETE FROM origins WHERE span_id=?", [span])?; - } - tx.execute( - "INSERT INTO heads(route,position) VALUES(?,?) ON CONFLICT(route) DO UPDATE SET position=max(position,excluded.position)", - params![route, position], - )?; - prune(&tx)?; - tx.commit()?; - Ok(()) - }) - .await - } - - pub async fn origins_for( - &self, - spans: Vec, - ) -> anyhow::Result>> { - if spans.is_empty() { - return Ok(BTreeMap::new()); - } - self.with_db(move |db| { - let mut query = db.prepare_cached("SELECT value FROM origins WHERE span_id=?")?; - let mut origins = BTreeMap::new(); - for span in spans { - if let Some(value) = query - .query_row([&span], |r| r.get::<_, String>(0)) - .optional()? - { - origins.insert(span, serde_json::from_str(&value)?); - } - } - Ok(origins) - }) - .await - } - - #[cfg(test)] - pub async fn origins(&self) -> anyhow::Result> { - self.with_db(|db| { - let mut query = db.prepare("SELECT span_id,value FROM origins")?; - let rows = - query.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?; - rows.map(|row| { - let (id, value) = row?; - Ok((id, serde_json::from_str(&value)?)) - }) - .collect() - }) - .await - } - - pub async fn observations(&self) -> anyhow::Result> { - self.with_db(|db| { - let mut query = db.prepare("SELECT value,end_ms FROM span_state ORDER BY rowid")?; - let rows = query.query_map([], |r| { - Ok((r.get::<_, Vec>(0)?, r.get::<_, Option>(1)?)) - })?; - let mut result = Vec::new(); - for row in rows { - let (bytes, end) = row?; - let op = StoredOp::decode(&bytes)?; - let (SpanOp::Insert(birth) | SpanOp::Merge(birth)) = &op; - if let Some(end_ms) = end { - let mut terminal = birth.clone(); - terminal.end_ms = Some(end_ms); - result.push(op); - result.push(SpanOp::Merge(terminal)); - } else { - result.push(op); - } - } - Ok(result) - }) - .await - } - - pub async fn register(&self, route: &SessionRoute) -> anyhow::Result<()> { - let route = serde_json::to_string(route)?; - self.with_db(move |db| { - let candidate: SessionRoute = serde_json::from_str(&route)?; - let existing = { - let mut query = db.prepare("SELECT route FROM heads")?; - let rows = query.query_map([], |r|r.get::<_,String>(0))?; - let mut existing = false; - for row in rows { if serde_json::from_str::(&row?)?.same_route(&candidate) { existing = true; break; } } - existing - }; - if !existing { db.execute("INSERT OR IGNORE INTO heads(route,position) VALUES (?,(SELECT floor FROM publication WHERE id=1))",[route])?; } - Ok(()) - }).await - } - - /// A completed subscription can remain dormant until its source has new work. - pub async fn route_complete(&self, route: &SessionRoute, input: u64) -> anyhow::Result { - let route = route.clone(); - self.with_db(move |db| { - let committed: u64 = db.query_row( - "SELECT coalesce(max(input),0) FROM batches WHERE committed=1", - [], - |r| r.get(0), - )?; - if committed < input { - return Ok(false); - } - let tail: u64 = - db.query_row("SELECT tail FROM publication WHERE id=1", [], |r| r.get(0))?; - let mut query = - db.prepare("SELECT route FROM heads WHERE failure IS NULL AND position>=?")?; - for stored in query.query_map([tail], |r| r.get::<_, String>(0))? { - let stored: SessionRoute = serde_json::from_str(&stored?)?; - if stored.same_route(&route) { - return Ok(true); - } - } - Ok(false) - }) - .await - } - - /// Tokens can change; a durable head's backend and organization cannot. - pub async fn bind(&self, route: &str, config: &SessionConfig) -> anyhow::Result<()> { - let route = route.to_owned(); - let binding = serde_json::to_string(&serde_json::json!({ - "api_url": config.auth.api_url.as_deref().unwrap_or("https://api.braintrust.dev"), - "org_id":config.auth.org_id,"org_name":config.auth.org_name, - }))?; - self.with_db(move |db| { - let previous: Option = - db.query_row("SELECT binding FROM heads WHERE route=?", [&route], |r| { - r.get(0) - })?; - anyhow::ensure!( - previous - .as_ref() - .is_none_or(|previous| previous == &binding), - BindingChanged - ); - if previous.is_none() { - db.execute( - "UPDATE heads SET binding=? WHERE route=?", - params![binding, route], - )?; - } - Ok(()) - }) - .await - } - /// Keep the original subscription and backend binding while correcting settings - /// that can unblock an explicitly configuration-held delivery. - pub async fn reconfigure_held( - &self, - route: &SessionRoute, - through: u64, - ) -> anyhow::Result> { - let route = route.clone(); - self.with_db(move |db| { - let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; - let updates = { - let mut query = tx.prepare( - "SELECT route,failure,settings FROM heads WHERE failure IS NOT NULL AND settings_through(0)?, - row.get::<_, String>(1)?, - row.get::<_, Option>(2)?, - )) - })?; - let mut updates = Vec::new(); - for row in rows { - let (key, raw, settings) = row?; - let stored: SessionRoute = serde_json::from_str(&key)?; - let Ok(failure) = serde_json::from_str::(&raw) else { - continue; - }; - if !matches!( - failure.condition, - super::recovery::Condition::Configuration { .. } | super::recovery::Condition::Plugin { .. } - ) || !stored.same_destination(&route) - { - continue; - } - let previous: SessionRoute = settings - .as_deref() - .map(serde_json::from_str) - .transpose()? - .unwrap_or_else(|| stored.clone()); - if previous.same_route(&route) { - continue; - } - let mut corrected = route.clone(); - // Preserve the subscription's pinned credential selection. - corrected.auth = stored.auth.clone(); - updates.push((key, stored, corrected)); - } - updates - }; - for (key, _, corrected) in &updates { - tx.execute( - "UPDATE heads SET settings=?, settings_through=? WHERE route=?", - params![serde_json::to_string(corrected)?, through, key], - )?; - } - tx.commit()?; - Ok(updates - .into_iter() - .map(|(_, stored, corrected)| (stored, corrected)) - .collect()) - }) - .await - } - - pub async fn route_settings(&self, route: &SessionRoute) -> anyhow::Result { - let fallback = route.clone(); - let key = serde_json::to_string(route)?; - self.with_db(move |db| { - let settings: Option = db - .query_row("SELECT settings FROM heads WHERE route=?", [key], |row| { - row.get(0) - }) - .optional()? - .flatten(); - Ok(settings - .as_deref() - .map(serde_json::from_str) - .transpose()? - .unwrap_or(fallback)) - }) - .await - } - - pub async fn routes(&self) -> anyhow::Result> { - self.with_db(|db| { - let mut query = db.prepare("SELECT route FROM heads ORDER BY route")?; - let rows = query - .query_map([], |r| r.get::<_, String>(0))? - .map(|route| Ok(serde_json::from_str(&route?)?)) - .collect(); - rows - }) - .await - } - /// Remaining metadata can expire once input and every route are complete. - /// An empty subscriber set is not completion. - pub async fn collectible(&self, input: u64) -> anyhow::Result { - self.with_db(move |db| Ok(db.query_row("SELECT EXISTS(SELECT 1 FROM heads) - AND NOT EXISTS(SELECT 1 FROM heads WHERE failure IS NOT NULL OR position < (SELECT tail FROM publication WHERE id=1)) - AND NOT EXISTS(SELECT 1 FROM recovery WHERE failure IS NOT NULL) - AND NOT EXISTS(SELECT 1 FROM batches WHERE committed=0) - AND (SELECT coalesce(max(input),0) FROM batches WHERE committed=1)>=?",[input],|r|r.get(0))?)).await - } - pub async fn close_storage(&self) -> anyhow::Result<()> { - self.with_db(|db| { - db.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")?; - Ok(()) - }) - .await - } - - pub async fn source_failure(&self) -> anyhow::Result> { - self.with_db(|db| { - Ok(db - .query_row("SELECT failure FROM recovery WHERE id=1", [], |row| { - row.get(0) - }) - .optional()? - .flatten()) - }) - .await - } - pub async fn set_source_failure(&self, failure: Option) -> anyhow::Result<()> { - self.with_db(move |db| { - db.execute( - "INSERT OR REPLACE INTO recovery(id,failure) VALUES(1,?)", - [failure], - )?; - Ok(()) - }) - .await - } - - pub async fn failure(&self, route: &str) -> anyhow::Result> { - let route = route.to_owned(); - self.with_db(move |db| { - Ok( - db.query_row("SELECT failure FROM heads WHERE route=?", [route], |r| { - r.get(0) - })?, - ) - }) - .await - } - - pub async fn set_failure(&self, route: &str, failure: Option) -> anyhow::Result<()> { - let route = route.to_owned(); - self.with_db(move |db| { - db.execute( - "UPDATE heads SET failure=? WHERE route=?", - params![failure, route], - )?; - Ok(()) - }) - .await - } -} - -pub(crate) struct Cursor { - journal: SpanJournal, - pub route: String, - read: u64, - completed: u64, - changes: watch::Receiver, - progress: watch::Sender, - drain: watch::Sender, - abandoned: Arc, - settings: Option>, - version: String, - restored: bool, - live: Receiver, - queued: Option, - error: Arc>>, - recovery: Arc>>, -} - -/// The composition layer keeps this status handle; downstream stages only get -/// the InputPort and managed deliveries. -#[derive(Clone)] -pub(crate) struct Progress { - completed: watch::Receiver, - published: watch::Receiver, - drain: watch::Sender, -} -#[cfg(test)] -impl Default for Progress { - fn default() -> Self { - Self { - completed: watch::channel(0).1, - published: watch::channel(0).1, - drain: watch::channel(0).0, - } - } -} -impl Progress { - pub fn completed(&self) -> u64 { - *self.completed.borrow() - } - pub fn pending(&self) -> u64 { - self.published.borrow().saturating_sub(self.completed()) - } - - pub async fn through(&self, target: u64, error: &Mutex>) -> Result<(), String> { - // Flush callers already know the publication boundary they need. Wake - // collection and keep draining promptly until that boundary is reported. - self.drain.send_if_modified(|requested| { - if target > *requested { - *requested = target; - true - } else { - false - } - }); - let mut completed = self.completed.clone(); - loop { - if *completed.borrow_and_update() >= target { - return Ok(()); - } - if let Some(error) = error.lock().clone() { - return Err(error); - } - tokio::select! { - changed = completed.changed() => changed.map_err(|_| "journal input is gone".to_owned())?, - _ = tokio::time::sleep(std::time::Duration::from_millis(250)) => {}, - } - } - } -} - -pub(crate) struct Subscription { - pub input: Box>>, - pub progress: Progress, -} - -impl Cursor { - pub fn into_input( - mut self, - settings: watch::Receiver, - version: String, - error: Arc>>, - recovery: Arc>>, - ) -> Subscription { - let progress = Progress { - completed: self.progress.subscribe(), - published: self.changes.clone(), - drain: self.drain.clone(), - }; - self.settings = Some(settings); - self.version = version; - self.error = error; - self.recovery = recovery; - Subscription { - input: Box::new(SharedCursor(self)), - progress, - } - } - - #[cfg(test)] - pub async fn next_batch( - &mut self, - limit: usize, - ) -> anyhow::Result>>> { - anyhow::ensure!(limit > 0, "cursor batch limit must be nonzero"); - let after = self.read; - let rows = self - .journal - .with_db(move |db| { - let mut statement = db.prepare( - "SELECT position,value FROM ops JOIN batches USING(input) - WHERE (committed=1 OR EXISTS(SELECT 1 FROM receipts WHERE receipts.input=ops.input)) AND position>? ORDER BY position LIMIT ?", - )?; - let rows = statement.query_map(params![after, limit as u64], |r| { - Ok((r.get::<_, u64>(0)?, r.get::<_, Vec>(1)?)) - })?; - rows.map(|row| { let (position, bytes) = row?; Ok((position, load_attachments(db, &bytes)?)) }).collect::>>() - }) - .await?; - let Some(&(through, _)) = rows.last() else { - return Ok(None); - }; - let ops = rows.into_iter().map(|(_, op)| op).collect::>(); - self.read = through; - Ok(Some(Delivery::new( - ops, - HeadCompletion { - journal: self.journal.clone(), - live: self.live.control(), - route: self.route.clone(), - expected: after, - through, - progress: self.progress.clone(), - abandoned: self.abandoned.clone(), - acknowledged: false, - error: self.error.clone(), - recovery: self.recovery.clone(), - }, - ))) - } - - async fn next_shared(&mut self) -> anyhow::Result>>> { - let published = *self.changes.borrow(); - if self.read >= published { - self.live.resume(); - return Ok(None); - } - let after = self.read; - let first = self.queued.take().or_else(|| self.live.try_recv()); - let mut records = Vec::new(); - if let Some(first) = first { - if first.position == after + 1 { - records.push(first); - } - } - if records.is_empty() { - // Restart, abandoned delivery, a late subscription, or a bounded - // live-queue overrun. Healthy live delivery never enters this path. - records = self.journal.recover_after(after).await?; - self.live.clear(); - } else { - let deadline = tokio::time::Instant::now() + WINDOW; - let mut drain = self.drain.subscribe(); - let mut bytes = records[0].bytes; - while bytes < BYTE_BUDGET { - let next = if *drain.borrow_and_update() > after { - match self.live.try_recv() { - Some(record) => record, - None => break, - } - } else { - tokio::select! { - next = tokio::time::timeout_at(deadline, self.live.recv()) => match next { - Ok(Some(record)) => record, - _ => break, - }, - _ = drain.changed() => continue, - } - }; - if next.position != records.last().map_or(after, |record| record.position) + 1 - || bytes + next.bytes > BYTE_BUDGET - { - self.queued = Some(next); - break; - } - bytes += next.bytes; - records.push(next); - } - } - let Some(last) = records.last() else { - return Ok(None); - }; - let through = last.position; - self.read = through; - Ok(Some(Delivery::new( - records.into_iter().map(|record| record.op).collect(), - HeadCompletion { - journal: self.journal.clone(), - live: self.live.control(), - route: self.route.clone(), - expected: after, - through, - progress: self.progress.clone(), - abandoned: self.abandoned.clone(), - acknowledged: false, - error: self.error.clone(), - recovery: self.recovery.clone(), - }, - ))) - } - - #[cfg(test)] - pub fn completed_position(&self) -> u64 { - self.completed - } - - pub async fn rewind(&mut self) -> anyhow::Result<()> { - let key = self.route.clone(); - self.completed = self - .journal - .with_db(move |db| { - Ok( - db.query_row("SELECT position FROM heads WHERE route=?", [key], |r| { - r.get(0) - })?, - ) - }) - .await?; - self.read = self.completed; - self.queued = None; - self.live.clear(); - self.progress.send_replace(self.completed); - Ok(()) - } - - #[cfg(test)] - pub async fn changed(&mut self) { - let _ = self.changes.changed().await; - } -} - -struct SharedCursor(Cursor); - -#[async_trait::async_trait] -impl InputPort for SharedCursor { - type Item = Vec; - async fn detach(&mut self) -> anyhow::Result<()> { - let route = self.0.route.clone(); - self.0 - .journal - .with_db(move |db| { - let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; - tx.execute( - "UPDATE heads SET position=9223372036854775807, failure=NULL WHERE route=?", - [route], - )?; - prune(&tx)?; - tx.commit()?; - Ok(()) - }) - .await?; - self.0.live.control().pause(); - self.0.live.clear(); - self.0.progress.send_replace(DETACHED); - Ok(()) - } - async fn receive(&mut self) -> anyhow::Result>> { - if *self.0.progress.borrow() == DETACHED { - self.0.live.control().pause(); - return Ok(None); - } - let result = self.0.receive_managed().await; - match result { - Ok(delivery) => Ok(Some(delivery)), - Err(error) => { - self.0.live.control().pause(); - let error = match error.downcast::() { - Ok(failure) => return Err(anyhow::Error::new(failure)), - Err(error) => error, - }; - let failure = Failure::storage(&error, &self.0.version, 0).at(self.0.completed + 1); - // An input failure has no delivery receipt to report through. - // Its source still owns persistence of the recovery evidence. - if let Err(error) = self - .0 - .journal - .set_failure(&self.0.route, Some(serde_json::to_string(&failure)?)) - .await - { - tracing::warn!(%error, "input recovery evidence could not be persisted"); - } - Err(anyhow::Error::new(failure)) - } - } - } -} - -impl Cursor { - async fn receive_managed(&mut self) -> anyhow::Result>> { - let mut acknowledgements = self.progress.subscribe(); - loop { - if self.abandoned.load(Ordering::Acquire) { - self.rewind().await?; - self.abandoned.store(false, Ordering::Release); - } - self.completed = *self.progress.borrow(); - self.read = self.read.max(self.completed); - let config = self - .settings - .as_ref() - .map(|settings| settings.borrow().clone()); - if !self.restored { - if let Some(raw) = self.journal.failure(&self.route).await? { - let failure = match serde_json::from_str::(&raw) { - Ok(failure) => failure, - Err(error) => match &config { - Some(config) => Failure::legacy(raw, self.completed + 1, config), - None => return Err(error.into()), - }, - }; - if matches!(failure.boundary, Boundary::Completion) - && self.completed >= failure.through.unwrap_or(failure.position) - { - self.journal.set_failure(&self.route, None).await?; - } else { - *self.error.lock() = Some(failure.message()); - *self.recovery.lock() = Some(failure.info(false)); - if matches!( - (Recovery { - config: config.as_ref(), - version: &self.version - }) - .process(&failure) - .await, - RecoveryOutcome::Waiting - ) { - tokio::time::sleep(std::time::Duration::from_millis(250)).await; - continue; - } - *self.recovery.lock() = Some(failure.info(true)); - } - } - } - if let Some(config) = &config { - if let Err(error) = self.journal.bind(&self.route, config).await { - if error.downcast_ref::().is_some() { - let failure = - Failure::legacy(error.to_string(), self.completed + 1, config); - self.journal - .set_failure(&self.route, Some(serde_json::to_string(&failure)?)) - .await?; - return Err(anyhow::Error::new(failure)); - } - return Err(error); - } - } - if let Some(delivery) = self.next_shared().await? { - if self.abandoned.load(Ordering::Acquire) { - drop(delivery); - continue; - } - self.restored = true; - return Ok(delivery); - } - tokio::select! { - _ = self.changes.changed() => {}, - _ = acknowledgements.changed() => {}, - } - } - } -} - -#[cfg(test)] -#[async_trait::async_trait] -impl InputPort for Cursor { - type Item = Vec; - async fn receive(&mut self) -> anyhow::Result>> { - Ok(Some(self.receive_managed().await?.map(|ops| { - ops.into_iter().map(|op| op.as_ref().clone()).collect() - }))) - } -} - -struct HeadCompletion { - journal: SpanJournal, - live: super::live::Control, - route: String, - expected: u64, - through: u64, - progress: watch::Sender, - abandoned: Arc, - acknowledged: bool, - error: Arc>>, - recovery: Arc>>, -} -impl Drop for HeadCompletion { - fn drop(&mut self) { - if !self.acknowledged { - self.live.pause(); - self.abandoned.store(true, Ordering::Release); - self.progress.send_modify(|_| {}); - } - } -} -#[async_trait::async_trait] -impl Completion for HeadCompletion { - async fn complete(&mut self) -> anyhow::Result<()> { - let (route, expected, through) = (self.route.clone(), self.expected, self.through); - self.journal - .with_db(move |db| { - let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; - let head: u64 = - tx.query_row("SELECT position FROM heads WHERE route=?", [&route], |r| { - r.get(0) - })?; - if head >= through { - return Ok(head); - } - anyhow::ensure!(head >= expected, "completion cannot skip unresolved input"); - tx.execute( - "UPDATE heads SET position=?, failure=NULL WHERE route=?", - params![through, route], - )?; - prune(&tx)?; - tx.commit()?; - Ok(through) - }) - .await - .map(|head| { - self.acknowledged = true; - self.progress.send_replace(head); - *self.error.lock() = None; - *self.recovery.lock() = None; - }) - } - - async fn failed(&mut self, failure: &mut Failure) -> anyhow::Result<()> { - self.live.pause(); - failure.position = self.expected + 1; - failure.through = Some(self.through); - *self.error.lock() = Some(failure.message()); - *self.recovery.lock() = Some(failure.info(false)); - self.journal - .set_failure(&self.route, Some(serde_json::to_string(failure)?)) - .await - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::translate::{OriginSnapshot, SpanRow}; - - fn op(name: &str) -> SpanOp { - SpanOp::Insert(SpanRow { - span_id: name.into(), - name: name.into(), - late_merge_key: Some("late".into()), - turn_span_id: Some("turn".into()), - is_turn: true, - origin: Some( - OriginSnapshot { - plugin_version: Some("capture".into()), - source_version: None, - bt_version: "test".into(), - } - .into(), - ), - ..SpanRow::default() - }) - } - #[tokio::test] - async fn detached_route_stays_detached_and_does_not_pin_other_routes() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("spans.sqlite"); - let journal = SpanJournal::open(&path).await.unwrap(); - let route = SessionRoute::default(); - let cursor = journal.subscribe(&route, 0).await.unwrap(); - let mut input = SharedCursor(cursor); - input.detach().await.unwrap(); - assert!(input.receive().await.unwrap().is_none()); - journal.begin(1, true).await.unwrap(); - journal.append(1, &[op("later")]).await.unwrap(); - journal.commit(1).await.unwrap(); - assert!(journal.route_complete(&route, 1).await.unwrap()); - assert!(journal.read_after(0, 10).await.unwrap().is_empty()); - let restored = SpanJournal::open(&path).await.unwrap(); - let mut input = SharedCursor(restored.subscribe(&route, 0).await.unwrap()); - assert!(input.receive().await.unwrap().is_none()); - } - - #[test] - fn codec_preserves_aggregate_watermarks_and_reads_older_records() { - let mut op = op("root"); - let (SpanOp::Insert(row) | SpanOp::Merge(row)) = &mut op; - let version = crate::translate::LateMergeVersion { - ts_ms: 123, - native_id: Some("turn".into()), - }; - row.late_merge_version = Some(version.clone()); - let encoded = StoredOp::encode(&op).unwrap(); - let decoded = StoredOp::decode(&encoded).unwrap(); - let (SpanOp::Insert(row) | SpanOp::Merge(row)) = decoded; - assert_eq!(row.late_merge_version, Some(version)); - let mut legacy: serde_json::Value = serde_json::from_slice(&encoded).unwrap(); - legacy.as_object_mut().unwrap().remove("late_merge_version"); - let decoded = StoredOp::decode(&serde_json::to_vec(&legacy).unwrap()).unwrap(); - let (SpanOp::Insert(row) | SpanOp::Merge(row)) = decoded; - assert!(row.late_merge_version.is_none()); - assert!(serde_json::to_value(&op).unwrap()["Insert"] - .get("late_merge_version") - .is_none()); - } - - fn route(name: &str) -> SessionRoute { - SessionRoute { - tags: [name.into()].into_iter().collect(), - ..SessionRoute::default() - } - } - - #[tokio::test] - async fn schema_five_upgrade_reclaims_acknowledged_payloads_without_losing_provenance() { - let tmp = tempfile::tempdir().unwrap(); - let path = tmp.path().join("upgrade.sqlite"); - let journal = SpanJournal::open(&path).await.unwrap(); - journal.register(&route("old")).await.unwrap(); - journal.begin(10, true).await.unwrap(); - journal.append(10, &[op("old")]).await.unwrap(); - journal.commit(10).await.unwrap(); - journal.close().await.unwrap(); - let db = Connection::open(&path).unwrap(); - db.execute_batch("UPDATE heads SET position=1; DROP TABLE receipts; DROP TABLE publication; DROP TABLE origins; DROP TABLE span_state; DROP TRIGGER operation_release; DROP TRIGGER attachment_release; DROP TRIGGER attachment_acquire; DROP TABLE operation_attachments; DROP TABLE attachment_blobs; PRAGMA user_version=5").unwrap(); - drop(db); - let upgraded = SpanJournal::open(&path).await.unwrap(); - assert_eq!(upgraded.tail().await.unwrap(), 1); - assert_eq!(upgraded.origins().await.unwrap()["old"].bt_version, "test"); - assert_eq!( - upgraded - .with_db(|db| Ok( - db.query_row("SELECT count(*) FROM ops", [], |r| r.get::<_, u64>(0))? - )) - .await - .unwrap(), - 0 - ); - assert!(upgraded.collectible(10).await.unwrap()); - } - - #[tokio::test] - async fn resolved_profile_completes_the_pre_authentication_placeholder() { - let tmp = tempfile::tempdir().unwrap(); - let journal = SpanJournal::open(&tmp.path().join("auth.sqlite")) - .await - .unwrap(); - let mut named = route("profile"); - named.auth.profile = Some("work".into()); - journal.register(&named).await.unwrap(); - journal.begin(10, true).await.unwrap(); - journal - .append_live(10, &mut 0, &mut vec![op("one")]) - .await - .unwrap(); - journal.commit(10).await.unwrap(); - let mut resolved = named.clone(); - resolved.auth.profile_id = Some("stable-id".into()); - let mut cursor = journal.subscribe(&resolved, 0).await.unwrap(); - assert_eq!(journal.routes().await.unwrap().len(), 1); - cursor - .next_shared() - .await - .unwrap() - .unwrap() - .into_completed() - .await - .ok() - .unwrap(); - assert_eq!( - journal - .with_db(|db| Ok( - db.query_row("SELECT count(*) FROM ops", [], |r| r.get::<_, u64>(0))? - )) - .await - .unwrap(), - 0 - ); - } - - #[tokio::test] - async fn recovery_routes_at_different_heads_share_the_same_decode_window() { - let tmp = tempfile::tempdir().unwrap(); - let journal = SpanJournal::open(&tmp.path().join("shared-recovery.sqlite")) - .await - .unwrap(); - journal.begin(10, true).await.unwrap(); - journal - .append_live(10, &mut 0, &mut vec![op("one"), op("two"), op("three")]) - .await - .unwrap(); - let mut a = journal.subscribe(&route("a"), 0).await.unwrap(); - let mut b = journal.subscribe(&route("b"), 0).await.unwrap(); - b.read = 1; - let first = a.next_shared().await.unwrap().unwrap(); - let second = b.next_shared().await.unwrap().unwrap(); - assert_eq!(first.value().len(), 3); - assert_eq!(second.value().len(), 2); - assert!(std::ptr::eq( - first.value()[1].as_ref(), - second.value()[0].as_ref() - )); - assert_eq!(journal.payload_reads.load(Ordering::Relaxed), 3); - } - - #[tokio::test] - async fn concurrent_opens_upgrade_one_schema_atomically() { - let tmp = tempfile::tempdir().unwrap(); - let path = tmp.path().join("concurrent-upgrade.sqlite"); - let db = Connection::open(&path).unwrap(); - db.execute_batch("CREATE TABLE batches(input INTEGER PRIMARY KEY,committed INTEGER NOT NULL DEFAULT 0); PRAGMA user_version=1;").unwrap(); - drop(db); - let ready = Arc::new(tokio::sync::Barrier::new(8)); - let mut tasks = Vec::new(); - for _ in 0..8 { - let path = path.clone(); - let ready = ready.clone(); - tasks.push(tokio::spawn(async move { - ready.wait().await; - SpanJournal::open(&path).await - })); - } - let mut opened = Vec::new(); - for task in tasks { - opened.push(task.await.unwrap().unwrap()); - } - for journal in opened { - assert_eq!(journal.tail().await.unwrap(), 0); - } - } - - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn translation_begin_waits_for_a_concurrent_writer_before_reading() { - let tmp = tempfile::tempdir().unwrap(); - let path = tmp.path().join("concurrent.sqlite"); - let journal = SpanJournal::open(&path).await.unwrap(); - let mut peer = Connection::open(&path).unwrap(); - let transaction = peer - .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate) - .unwrap(); - transaction - .execute("INSERT INTO batches(input,committed) VALUES(10,1)", []) - .unwrap(); - let begin = tokio::spawn(async move { journal.begin(10, true).await }); - tokio::time::sleep(std::time::Duration::from_millis(50)).await; - let failed_early = begin.is_finished(); - transaction.commit().unwrap(); - assert!( - !begin.await.unwrap().unwrap(), - "a committed input must remain committed after waiting for its writer" - ); - assert!( - !failed_early, - "a read-before-write transaction must wait rather than fail to upgrade its snapshot" - ); - } - - #[tokio::test] - async fn attachments_deduplicate_replay_and_release_after_all_routes() { - let tmp = tempfile::tempdir().unwrap(); - let path = tmp.path().join("attachments.sqlite"); - let journal = SpanJournal::open(&path).await.unwrap(); - journal.register(&route("a")).await.unwrap(); - journal.register(&route("b")).await.unwrap(); - journal.begin(10, true).await.unwrap(); - let mut ops = vec![op("one"), op("two")]; - for op in &mut ops { - let (SpanOp::Insert(row) | SpanOp::Merge(row)) = op; - row.input = - Some(serde_json::json!({"type":"file", "mime":"application/pdf", "data":"YWJj"})); - } - journal.append_live(10, &mut 0, &mut ops).await.unwrap(); - // Rebuilding a partially published input must not acquire another reference. - let mut repeated = vec![op("one"), op("two")]; - journal - .append_live(10, &mut 0, &mut repeated) - .await - .unwrap(); - journal.commit(10).await.unwrap(); - journal.close().await.unwrap(); - let journal = SpanJournal::open(&path).await.unwrap(); - let mut a = journal.subscribe(&route("a"), 0).await.unwrap(); - let mut b = journal.subscribe(&route("b"), 0).await.unwrap(); - assert_eq!( - journal - .with_db(|db| Ok(db - .query_row("SELECT refs FROM attachment_blobs", [], |r| r - .get::<_, u64>(0))?)) - .await - .unwrap(), - 2 - ); - let rows = journal.read_after(0, 10).await.unwrap(); - let (SpanOp::Insert(row) | SpanOp::Merge(row)) = &rows[0].1; - assert_eq!(row.attachments[0].data, b"abc"); - a.next_batch(1) - .await - .unwrap() - .unwrap() - .into_completed() - .await - .ok() - .unwrap(); - assert_eq!( - journal - .with_db(|db| Ok(db.query_row( - "SELECT count(*) FROM attachment_blobs", - [], - |r| r.get::<_, u64>(0) - )?)) - .await - .unwrap(), - 1 - ); - b.next_batch(1) - .await - .unwrap() - .unwrap() - .into_completed() - .await - .ok() - .unwrap(); - assert_eq!( - journal - .with_db(|db| Ok(db - .query_row("SELECT refs FROM attachment_blobs", [], |r| r - .get::<_, u64>(0))?)) - .await - .unwrap(), - 1 - ); - a.next_batch(1) - .await - .unwrap() - .unwrap() - .into_completed() - .await - .ok() - .unwrap(); - b.next_batch(1) - .await - .unwrap() - .unwrap() - .into_completed() - .await - .ok() - .unwrap(); - assert_eq!( - journal - .with_db(|db| Ok(db.query_row( - "SELECT count(*) FROM attachment_blobs", - [], - |r| r.get::<_, u64>(0) - )?)) - .await - .unwrap(), - 0 - ); - } - - #[tokio::test] - async fn all_route_acknowledgements_reclaim_payloads_and_preserve_watermarks() { - let tmp = tempfile::tempdir().unwrap(); - let path = tmp.path().join("cleanup.sqlite"); - let journal = SpanJournal::open(&path).await.unwrap(); - let mut a = journal.subscribe(&route("a"), 0).await.unwrap(); - let mut b = journal.subscribe(&route("b"), 0).await.unwrap(); - journal.begin(10, true).await.unwrap(); - journal - .append_live(10, &mut 0, &mut vec![op("one")]) - .await - .unwrap(); - journal.commit(10).await.unwrap(); - let first = a.next_shared().await.unwrap().unwrap(); - let second = b.next_shared().await.unwrap().unwrap(); - first.into_completed().await.ok().unwrap(); - assert_eq!( - journal - .with_db(|db| Ok( - db.query_row("SELECT count(*) FROM ops", [], |r| r.get::<_, u64>(0))? - )) - .await - .unwrap(), - 1 - ); - second.into_completed().await.ok().unwrap(); - assert_eq!( - journal - .with_db(|db| Ok( - db.query_row("SELECT count(*) FROM ops", [], |r| r.get::<_, u64>(0))? - )) - .await - .unwrap(), - 0 - ); - assert_eq!(journal.tail().await.unwrap(), 1); - assert_eq!(journal.origins().await.unwrap()["one"].bt_version, "test"); - journal.close().await.unwrap(); - let restored = SpanJournal::open(&path).await.unwrap(); - assert_eq!(restored.tail().await.unwrap(), 1); - assert_eq!(restored.translated_through().await.unwrap(), 10); - let mut late = restored.subscribe(&route("new"), 0).await.unwrap(); - assert!(late.next_shared().await.unwrap().is_none()); - restored.begin(20, true).await.unwrap(); - restored - .append_live(20, &mut 0, &mut vec![op("two")]) - .await - .unwrap(); - assert_eq!(restored.tail().await.unwrap(), 2); - assert!(late.next_shared().await.unwrap().is_some()); - } - - #[tokio::test] - async fn explicit_flush_interrupts_live_batch_collection() { - let tmp = tempfile::tempdir().unwrap(); - let journal = SpanJournal::open(&tmp.path().join("flush.sqlite")) - .await - .unwrap(); - let mut cursor = journal.subscribe(&route("a"), 0).await.unwrap(); - let progress = Progress { - completed: cursor.progress.subscribe(), - published: cursor.changes.clone(), - drain: cursor.drain.clone(), - }; - journal.begin(10, true).await.unwrap(); - journal - .append_live(10, &mut 0, &mut vec![op("one")]) - .await - .unwrap(); - let mut receiving = Box::pin(cursor.next_shared()); - assert!( - tokio::time::timeout(std::time::Duration::from_millis(20), &mut receiving) - .await - .is_err(), - "a sparse batch should wait for more operations" - ); - let error = Mutex::new(None); - tokio::time::timeout(std::time::Duration::from_secs(1), async { - let ((), result) = tokio::join!( - async { - receiving - .await - .unwrap() - .unwrap() - .into_completed() - .await - .ok() - .unwrap(); - }, - progress.through(1, &error) - ); - result.unwrap(); - }) - .await - .expect("explicit flush must bypass the 30-second window"); - assert_eq!(journal.payload_reads.load(Ordering::Relaxed), 0); - } - - #[tokio::test] - async fn live_routes_share_original_payload_without_sqlite_reads() { - let tmp = tempfile::tempdir().unwrap(); - let journal = SpanJournal::open(&tmp.path().join("live.sqlite")) - .await - .unwrap(); - let mut first = journal.subscribe(&route("first"), 0).await.unwrap(); - let mut second = journal.subscribe(&route("second"), 0).await.unwrap(); - let payload = "x".repeat(BYTE_BUDGET * 2); - let pointer = payload.as_ptr(); - let mut ops = vec![SpanOp::Insert(SpanRow { - input: Some(serde_json::Value::String(payload)), - ..Default::default() - })]; - journal.begin(10, true).await.unwrap(); - journal.append_live(10, &mut 0, &mut ops).await.unwrap(); - assert!(ops.is_empty()); - // Live delivery is possible before the native event has finished. - let a = first.next_shared().await.unwrap().unwrap(); - let b = second.next_shared().await.unwrap().unwrap(); - assert!(std::ptr::eq(a.value()[0].as_ref(), b.value()[0].as_ref())); - let (SpanOp::Insert(row) | SpanOp::Merge(row)) = a.value()[0].as_ref(); - assert_eq!( - row.input.as_ref().unwrap().as_str().unwrap().as_ptr(), - pointer - ); - assert_eq!(journal.payload_reads.load(Ordering::Relaxed), 0); - let weak = a.value()[0].downgrade(); - drop(a.into_completed().await.ok().unwrap()); - drop(b.into_completed().await.ok().unwrap()); - assert!(weak.upgrade().is_none()); - } - - #[tokio::test] - async fn recovery_decodes_once_for_concurrent_routes_and_keeps_only_weak_references() { - let tmp = tempfile::tempdir().unwrap(); - let journal = SpanJournal::open(&tmp.path().join("recovery.sqlite")) - .await - .unwrap(); - journal.begin(10, true).await.unwrap(); - journal - .append_live(10, &mut 0, &mut vec![op("recover")]) - .await - .unwrap(); - let mut first = journal.subscribe(&route("first"), 0).await.unwrap(); - let mut second = journal.subscribe(&route("second"), 0).await.unwrap(); - let a = first.next_shared().await.unwrap().unwrap(); - let b = second.next_shared().await.unwrap().unwrap(); - assert!(std::ptr::eq(a.value()[0].as_ref(), b.value()[0].as_ref())); - assert_eq!(journal.payload_reads.load(Ordering::Relaxed), 1); - let weak = a.value()[0].downgrade(); - drop(a); - drop(b); - assert!(weak.upgrade().is_none()); - } - - #[tokio::test] - async fn partial_event_restart_preserves_published_operations_and_route_heads() { - let tmp = tempfile::tempdir().unwrap(); - let path = tmp.path().join("partial.sqlite"); - let journal = SpanJournal::open(&path).await.unwrap(); - let mut first = journal.subscribe(&route("first"), 0).await.unwrap(); - journal.begin(10, true).await.unwrap(); - journal - .append_live(10, &mut 0, &mut vec![op("one")]) - .await - .unwrap(); - first - .next_shared() - .await - .unwrap() - .unwrap() - .into_completed() - .await - .ok() - .unwrap(); - assert_eq!(journal.translated_through().await.unwrap(), 0); - journal.close().await.unwrap(); - let journal = SpanJournal::open(&path).await.unwrap(); - journal.begin(10, true).await.unwrap(); - let mut ordinal = 0; - journal - .append_live(10, &mut ordinal, &mut vec![op("one"), op("two")]) - .await - .unwrap(); - journal.commit(10).await.unwrap(); - let mut restored = journal.subscribe(&route("first"), 0).await.unwrap(); - let delivery = restored.next_shared().await.unwrap().unwrap(); - assert_eq!(delivery.value().len(), 1); - let (SpanOp::Insert(row) | SpanOp::Merge(row)) = delivery.value()[0].as_ref(); - assert_eq!(row.name, "two"); - assert_eq!(journal.tail().await.unwrap(), 2); - } - - #[tokio::test] - async fn paused_route_recovers_without_blocking_a_healthy_live_route() { - let tmp = tempfile::tempdir().unwrap(); - let journal = SpanJournal::open(&tmp.path().join("lag.sqlite")) - .await - .unwrap(); - let mut fast = journal.subscribe(&route("fast"), 0).await.unwrap(); - let mut slow = journal.subscribe(&route("slow"), 0).await.unwrap(); - slow.live.control().pause(); - journal.begin(10, true).await.unwrap(); - let mut ordinal = 0; - for index in 0..3 { - journal - .append_live( - 10, - &mut ordinal, - &mut vec![SpanOp::Insert(SpanRow { - name: index.to_string(), - input: Some(serde_json::json!("x".repeat(BYTE_BUDGET))), - ..Default::default() - })], - ) - .await - .unwrap(); - fast.next_shared() - .await - .unwrap() - .unwrap() - .into_completed() - .await - .ok() - .unwrap(); - } - assert_eq!(journal.payload_reads.load(Ordering::Relaxed), 0); - journal.commit(10).await.unwrap(); - for _ in 0..3 { - let delivery = slow.next_shared().await.unwrap().unwrap(); - assert_eq!( - delivery.value().len(), - 1, - "an oversized operation travels alone" - ); - delivery.into_completed().await.ok().unwrap(); - } - slow.rewind().await.unwrap(); - assert_eq!(slow.completed_position(), 3); - assert_eq!(journal.payload_reads.load(Ordering::Relaxed), 3); - } - - #[tokio::test] - async fn root_candidates_commit_and_release_atomically() { - let tmp = tempfile::tempdir().unwrap(); - let path = tmp.path().join("roots.sqlite"); - let journal = SpanJournal::open(&path).await.unwrap(); - let mut roots = crate::pipeline::roots::Roots::default(); - let mut root = op("root"); - let (SpanOp::Insert(row) | SpanOp::Merge(row)) = &mut root; - row.metadata = Some(serde_json::json!({"_bt_defer_root": true})); - assert!(roots.process(&vec![root]).await.is_empty()); - journal.begin(10, true).await.unwrap(); - let db = Connection::open(&path).unwrap(); - db.execute_batch("CREATE TRIGGER fail_roots BEFORE INSERT ON root_candidates BEGIN SELECT RAISE(FAIL,'root write'); END;").unwrap(); - assert!(journal - .commit_with_roots(10, roots.pending()) - .await - .is_err()); - assert_eq!(journal.translated_through().await.unwrap(), 0); - assert!(journal.root_candidates().await.unwrap().is_empty()); - db.execute_batch("DROP TRIGGER fail_roots").unwrap(); - journal - .commit_with_roots(10, roots.pending()) - .await - .unwrap(); - journal.close().await.unwrap(); - - let journal = SpanJournal::open(&path).await.unwrap(); - let candidates = journal.root_candidates().await.unwrap(); - let (SpanOp::Insert(row) | SpanOp::Merge(row)) = &candidates["root"][0]; - assert_eq!(row.late_merge_key.as_deref(), Some("late")); - assert_eq!( - row.origin.as_ref().unwrap().plugin_version.as_deref(), - Some("capture") - ); - let mut roots = crate::pipeline::roots::Roots::restore(candidates); - let child = SpanOp::Insert(SpanRow { - span_id: "turn".into(), - parent_span_ids: vec!["root".into()], - ..Default::default() - }); - let ready = roots.process(&vec![child]).await; - assert_eq!(ready.len(), 2); - journal.begin(20, true).await.unwrap(); - journal.append(20, &ready).await.unwrap(); - db.execute_batch("CREATE TRIGGER fail_release BEFORE DELETE ON root_candidates BEGIN SELECT RAISE(FAIL,'release'); END;").unwrap(); - assert!(journal - .commit_with_roots(20, roots.pending()) - .await - .is_err()); - assert_eq!(journal.translated_through().await.unwrap(), 10); - assert_eq!(journal.tail().await.unwrap(), 0); - assert_eq!(journal.root_candidates().await.unwrap().len(), 1); - db.execute_batch("DROP TRIGGER fail_release").unwrap(); - journal - .commit_with_roots(20, roots.pending()) - .await - .unwrap(); - assert_eq!(journal.tail().await.unwrap(), 2); - assert!(journal.root_candidates().await.unwrap().is_empty()); - } - - #[tokio::test] - async fn input_port_replays_abandoned_delivery_without_cursor_control() { - use crate::pipeline::delivery::InputPort; - let tmp = tempfile::tempdir().unwrap(); - let journal = SpanJournal::open(&tmp.path().join("spans.sqlite")) - .await - .unwrap(); - journal.begin(1, true).await.unwrap(); - journal.append(1, &[op("one")]).await.unwrap(); - journal.commit(1).await.unwrap(); - let mut input: Box>> = - Box::new(journal.subscribe(&route("a"), 0).await.unwrap()); - let delivery = input.receive().await.unwrap().unwrap(); - drop(delivery); - // Cancel a receive while its storage read is pending, as a concurrent - // configuration update does. The replay obligation must survive it. - let storage = journal.connection.lock(); - let mut cancelled = Box::pin(input.receive()); - let mut context = std::task::Context::from_waker(std::task::Waker::noop()); - assert!(std::future::Future::poll(cancelled.as_mut(), &mut context).is_pending()); - drop(cancelled); - drop(storage); - let replay = tokio::time::timeout(std::time::Duration::from_millis(250), input.receive()) - .await - .expect("unacknowledged input must be replayed") - .unwrap() - .unwrap(); - let (SpanOp::Insert(row) | SpanOp::Merge(row)) = &replay.value()[0]; - assert_eq!(row.name, "one"); - replay.into_completed().await.ok().unwrap(); - assert!(journal.route_complete(&route("a"), 1).await.unwrap()); - assert!(!journal.route_complete(&route("b"), 1).await.unwrap()); - } - - #[tokio::test] - async fn preparatory_schema_upgrades_without_changing_committed_positions() { - let tmp = tempfile::tempdir().unwrap(); - let path = tmp.path().join("old.sqlite"); - let db = Connection::open(&path).unwrap(); - db.execute_batch("CREATE TABLE batches(input INTEGER PRIMARY KEY,committed INTEGER NOT NULL DEFAULT 0); INSERT INTO batches VALUES(10,1); PRAGMA user_version=1;").unwrap(); - drop(db); - let journal = SpanJournal::open(&path).await.unwrap(); - assert_eq!(journal.translated_through().await.unwrap(), 10); - journal.begin(20, false).await.unwrap(); - journal.append(20, &[op("retirement")]).await.unwrap(); - journal.commit(20).await.unwrap(); - assert!( - journal.read_after(0, 8).await.unwrap().is_empty(), - "retirement output is not a native correlation observation" - ); - let mut route = journal.subscribe(&route("a"), 0).await.unwrap(); - assert_eq!( - route.next_batch(8).await.unwrap().unwrap().value().len(), - 1, - "all published output still reaches durable delivery subscribers" - ); - } - - #[tokio::test] - async fn legacy_uncommitted_output_empty_commit_and_restart_preserve_the_boundary() { - let tmp = tempfile::tempdir().unwrap(); - let path = tmp.path().join("spans.sqlite"); - let journal = SpanJournal::open(&path).await.unwrap(); - journal.begin(10, true).await.unwrap(); - journal.append(10, &[op("abandoned")]).await.unwrap(); - let mut reader = journal.subscribe(&route("a"), 0).await.unwrap(); - assert!(reader.next_batch(8).await.unwrap().is_none()); - drop(reader); - drop(journal); - let journal = SpanJournal::open(&path).await.unwrap(); - assert_eq!(journal.translated_through().await.unwrap(), 0); - journal.begin(10, true).await.unwrap(); - journal.append(10, &[op("retained")]).await.unwrap(); - journal.commit(10).await.unwrap(); - assert!(!journal.begin(10, true).await.unwrap()); - journal.begin(20, true).await.unwrap(); - journal.commit(20).await.unwrap(); - assert_eq!(journal.translated_through().await.unwrap(), 20); - let mut reader = journal.subscribe(&route("a"), 0).await.unwrap(); - let message = reader.next_batch(8).await.unwrap().unwrap(); - let (SpanOp::Insert(row) | SpanOp::Merge(row)) = &message.value()[0]; - assert_eq!(row.name, "retained"); - assert_eq!(row.late_merge_key.as_deref(), Some("late")); - assert!(row.is_turn); - assert_eq!( - row.origin.as_ref().unwrap().plugin_version.as_deref(), - Some("capture") - ); - } - - #[tokio::test] - async fn independent_heads_and_dropped_deliveries_resume_without_skipping() { - let tmp = tempfile::tempdir().unwrap(); - let path = tmp.path().join("spans.sqlite"); - let journal = SpanJournal::open(&path).await.unwrap(); - journal.begin(10, true).await.unwrap(); - journal.append(10, &[op("one"), op("two")]).await.unwrap(); - journal.commit(10).await.unwrap(); - let mut a = journal.subscribe(&route("a"), 0).await.unwrap(); - let mut b = journal.subscribe(&route("b"), 0).await.unwrap(); - a.next_batch(2) - .await - .unwrap() - .unwrap() - .into_completed() - .await - .ok() - .unwrap(); - drop(b.next_batch(2).await.unwrap().unwrap()); - a.rewind().await.unwrap(); - b.rewind().await.unwrap(); - assert!(a.next_batch(2).await.unwrap().is_none()); - assert_eq!(b.next_batch(2).await.unwrap().unwrap().value().len(), 2); - let mut c = journal.subscribe(&route("c"), 0).await.unwrap(); - let first = c.next_batch(1).await.unwrap().unwrap(); - let second = c.next_batch(1).await.unwrap().unwrap(); - assert!( - second.into_completed().await.is_err(), - "later work cannot release an earlier obligation" - ); - first.into_completed().await.ok().unwrap(); - c.rewind().await.unwrap(); - assert_eq!(c.next_batch(2).await.unwrap().unwrap().value().len(), 1); - } - #[tokio::test] - async fn head_write_failure_retains_work_and_commit_wakes_readers() { - let tmp = tempfile::tempdir().unwrap(); - let journal = SpanJournal::open(&tmp.path().join("spans.sqlite")) - .await - .unwrap(); - let mut reader = journal.subscribe(&route("a"), 0).await.unwrap(); - journal.begin(10, true).await.unwrap(); - journal.append(10, &[op("one")]).await.unwrap(); - journal.commit(10).await.unwrap(); - tokio::time::timeout(std::time::Duration::from_secs(1), reader.changed()) - .await - .unwrap(); - assert_eq!(journal.tail().await.unwrap(), 1); - journal - .set_failure(&reader.route, Some("held".into())) - .await - .unwrap(); - journal.with_db(|db| { - db.execute_batch("CREATE TRIGGER fail_head BEFORE UPDATE OF position ON heads BEGIN SELECT RAISE(FAIL,'injected head failure'); END;")?; - Ok(()) - }).await.unwrap(); - let pending = reader.next_batch(8).await.unwrap().unwrap(); - let failed = pending.into_completed().await.err().unwrap(); - assert!(failed.error.to_string().contains("injected head failure")); - assert_eq!( - journal.failure(&reader.route).await.unwrap().as_deref(), - Some("held") - ); - reader.rewind().await.unwrap(); - assert!(reader.next_batch(8).await.unwrap().is_some()); - journal - .with_db(|db| { - db.execute_batch("DROP TRIGGER fail_head;")?; - Ok(()) - }) - .await - .unwrap(); - failed.delivery.into_completed().await.ok().unwrap(); - assert!(journal.failure(&reader.route).await.unwrap().is_none()); - reader.rewind().await.unwrap(); - assert!(reader.next_batch(8).await.unwrap().is_none()); - } - #[tokio::test] - async fn a_completed_canonical_head_also_covers_its_legacy_named_route() { - let tmp = tempfile::tempdir().unwrap(); - let journal = SpanJournal::open(&tmp.path().join("spans.sqlite")) - .await - .unwrap(); - journal.begin(10, true).await.unwrap(); - journal.append(10, &[op("one")]).await.unwrap(); - journal.commit(10).await.unwrap(); - let mut legacy = route("work"); - legacy.auth.profile = Some("work".into()); - let mut canonical = legacy.clone(); - canonical.auth.profile_id = Some("profile-id".into()); - let mut head = journal.subscribe(&canonical, 0).await.unwrap(); - head.next_batch(8) - .await - .unwrap() - .unwrap() - .into_completed() - .await - .ok() - .unwrap(); - assert!(journal.route_complete(&legacy, 10).await.unwrap()); - let mut other_profile = canonical.clone(); - other_profile.auth.profile_id = Some("different-id".into()); - assert!(!journal.route_complete(&other_profile, 10).await.unwrap()); - legacy.tags.insert("different route".into()); - assert!(!journal.route_complete(&legacy, 10).await.unwrap()); - } - - #[tokio::test] - async fn schema_two_heads_upgrade_and_keep_a_nonsecret_backend_binding() { - let tmp = tempfile::tempdir().unwrap(); - let path = tmp.path().join("old.sqlite"); - let db = Connection::open(&path).unwrap(); - db.execute_batch("CREATE TABLE heads(route TEXT PRIMARY KEY,position INTEGER NOT NULL DEFAULT 0,failure TEXT); PRAGMA user_version=2;").unwrap(); - let route = route("canonical"); - let key = serde_json::to_string(&route).unwrap(); - db.execute("INSERT INTO heads(route,position) VALUES(?,7)", [&key]) - .unwrap(); - drop(db); - let journal = SpanJournal::open(&path).await.unwrap(); - let mut config = route.with_auth(crate::wire::BackendAuth { - token: "secret-a".into(), - api_url: Some("https://one.test".into()), - app_url: None, - org_id: Some("org".into()), - org_name: None, - }); - journal.bind(&key, &config).await.unwrap(); - config.auth.token = "secret-b".into(); - journal.bind(&key, &config).await.unwrap(); - config.auth.api_url = Some("https://other.test".into()); - assert!(journal - .bind(&key, &config) - .await - .unwrap_err() - .downcast_ref::() - .is_some()); - let restored = journal.subscribe(&route, 0).await.unwrap(); - assert_eq!(restored.completed_position(), 7); - journal - .with_db(|db| { - let binding: String = - db.query_row("SELECT binding FROM heads", [], |r| r.get(0))?; - assert!(!binding.contains("secret-")); - Ok(()) - }) - .await - .unwrap(); - } - #[tokio::test] - async fn corrected_settings_survive_restart_without_advancing_or_retargeting_heads() { - let tmp = tempfile::tempdir().unwrap(); - let path = tmp.path().join("spans.sqlite"); - let journal = SpanJournal::open(&path).await.unwrap(); - let original = SessionRoute { - destination: Some(crate::wire::TraceDestination::ProjectLogs { - project_id: Some("test-project".into()), - project_name: None, - }), - ..route("a") - }; - let cursor = journal.subscribe(&original, 0).await.unwrap(); - let failure = Failure { - boundary: Boundary::Sink, - position: 1, - through: None, - reason: "rejected row".into(), - attempt: 0, - condition: super::super::recovery::Condition::Configuration { - signature: "original".into(), - recheck_ms: None, - }, - }; - let raw = serde_json::to_string(&failure).unwrap(); - journal - .set_failure(&cursor.route, Some(raw.clone())) - .await - .unwrap(); - let mut corrected = original.clone(); - corrected.tags.insert("corrected".into()); - for unrelated in [ - SessionRoute { - destination: Some(crate::wire::TraceDestination::ProjectLogs { - project_id: Some("other-project".into()), - project_name: None, - }), - ..corrected.clone() - }, - SessionRoute { - auth: crate::wire::AuthSelection { - org_name: Some("other-org".into()), - ..Default::default() - }, - ..corrected.clone() - }, - ] { - assert!(journal - .reconfigure_held(&unrelated, 20) - .await - .unwrap() - .is_empty()); - } - assert_eq!( - journal - .reconfigure_held(&corrected, 20) - .await - .unwrap() - .len(), - 1 - ); - assert_eq!(cursor.completed, 0); - assert_eq!(journal.failure(&cursor.route).await.unwrap(), Some(raw)); - // A captured prefix must not revert a newer correction during startup replay. - assert!(journal - .reconfigure_held(&original, 10) - .await - .unwrap() - .is_empty()); - journal.close().await.unwrap(); - let restored = SpanJournal::open(&path).await.unwrap(); - assert_eq!( - restored.route_settings(&original).await.unwrap().tags, - corrected.tags - ); - assert_eq!(restored.routes().await.unwrap().len(), 1); - assert_eq!(restored.subscribe(&original, 0).await.unwrap().completed, 0); - restored.set_failure(&cursor.route, None).await.unwrap(); - let mut newer = corrected.clone(); - newer.tags.insert("independent".into()); - assert!( - restored - .reconfigure_held(&newer, 30) - .await - .unwrap() - .is_empty(), - "healthy independent subscriptions retain their settings" - ); - } - - #[tokio::test] - async fn close_releases_storage_even_when_a_blocking_read_was_cancelled() { - let tmp = tempfile::tempdir().unwrap(); - let path = tmp.path().join("spans.sqlite"); - let journal = SpanJournal::open(&path).await.unwrap(); - let reader = journal.clone(); - let (entered, started) = tokio::sync::oneshot::channel(); - let (release, blocked) = std::sync::mpsc::channel(); - let read = tokio::spawn(async move { - reader - .with_db(move |_| { - let _ = entered.send(()); - blocked.recv().unwrap(); - Ok(()) - }) - .await - }); - started.await.unwrap(); - read.abort(); - assert!(read.await.unwrap_err().is_cancelled()); - let closing = journal.clone(); - let close = tokio::spawn(async move { closing.close().await }); - tokio::time::sleep(std::time::Duration::from_millis(20)).await; - assert!(!close.is_finished()); - release.send(()).unwrap(); - close.await.unwrap().unwrap(); - assert!(journal.tail().await.is_err()); - std::fs::remove_file(path).unwrap(); - } -} diff --git a/bt-daemon/src/pipeline/mod.rs b/bt-daemon/src/pipeline/mod.rs index 5e318aeb..7724a825 100644 --- a/bt-daemon/src/pipeline/mod.rs +++ b/bt-daemon/src/pipeline/mod.rs @@ -21,7 +21,7 @@ pub(crate) trait Stage: Send { async fn process(&mut self, input: &Self::Input) -> Self::Outcome; } -pub(crate) mod journal; +pub(crate) mod cursor; pub(crate) mod translation; pub(crate) mod consumer; diff --git a/bt-daemon/src/pipeline/recovery.rs b/bt-daemon/src/pipeline/recovery.rs index b7111574..c1a6f1f8 100644 --- a/bt-daemon/src/pipeline/recovery.rs +++ b/bt-daemon/src/pipeline/recovery.rs @@ -253,11 +253,13 @@ impl Failure { } } pub fn storage(error: &anyhow::Error, version: &str, attempt: u32) -> Self { - if error.downcast_ref::().is_some() || error.downcast_ref::().is_some_and(|error| { - matches!(error,rusqlite::Error::SqliteFailure(code,_) if matches!(code.code,rusqlite::ErrorCode::DatabaseCorrupt|rusqlite::ErrorCode::NotADatabase)) - }) { - Self::revision(Boundary::Journal,0,error.to_string(),version) - } else { Self::delay(Boundary::Journal,0,error.to_string(),attempt) } + if error.downcast_ref::().is_some() + || crate::collections::is_corruption(error) + { + Self::revision(Boundary::Journal, 0, error.to_string(), version) + } else { + Self::delay(Boundary::Journal, 0, error.to_string(), attempt) + } } pub fn info(&self, eligible: bool) -> RecoveryInfo { let retry = match &self.condition { diff --git a/bt-daemon/src/pipeline/translation.rs b/bt-daemon/src/pipeline/translation.rs index 1a0a0abd..8a12f03a 100644 --- a/bt-daemon/src/pipeline/translation.rs +++ b/bt-daemon/src/pipeline/translation.rs @@ -1,6 +1,8 @@ //! One ordered source consumer. Output publication is independent of route delivery. -use super::input::{SourceEvent, SourceInput, SourcePosition, SourceRecord}; -use super::journal::SpanJournal; +use super::cursor::Cursor; +use super::input::{ + ControlKind, PipelineControl, SourceEvent, SourceInput, SourcePosition, SourceRecord, +}; use super::prepare::Prepare; use super::roots::Roots; use super::{ @@ -8,11 +10,13 @@ use super::{ Stage, }; use crate::{ - journal::{ControlKind, JournalReader, JournalRecord, JournalWriter, PipelineControl}, + collections::{EventReader, EventRecord, SessionStorage, Translated}, translate::{AgentTranslator, OriginSnapshot, Registry, SessionCtx, SpanOp, WeakOrigins}, wire::{SessionConfig, SessionRoute}, }; +use futures::TryStreamExt; use parking_lot::Mutex; +use serde::{Deserialize, Serialize}; use std::{ collections::{HashMap, HashSet}, path::PathBuf, @@ -59,7 +63,7 @@ struct RouteLifetimes { pub(crate) struct Translation { tx: mpsc::Sender, task: tokio::sync::Mutex>>, - journal: SpanJournal, + storage: SessionStorage, pub error: Arc>>, pub recovery: Arc>>, routes: Mutex, @@ -73,8 +77,7 @@ pub(crate) struct TranslationOptions { pub namespace: String, pub version: String, pub data_dir: PathBuf, - pub events: Arc>, - pub event_path: PathBuf, + pub storage: SessionStorage, pub input: SourceInput, pub registry: Arc, pub correlation: Arc, @@ -84,7 +87,7 @@ pub(crate) struct TranslationOptions { impl Translation { pub async fn spawn(options: TranslationOptions) -> anyhow::Result> { let actor = Producer::open(options).await?; - let journal = actor.journal.clone(); + let storage = actor.options.storage.clone(); let progress = actor.progress.clone(); let error = actor.error.clone(); let recovery = actor.recovery.clone(); @@ -93,7 +96,7 @@ impl Translation { Ok(Arc::new(Self { tx, task: tokio::sync::Mutex::new(Some(task)), - journal, + storage, error, recovery, routes: Mutex::new(RouteLifetimes::default()), @@ -106,9 +109,6 @@ impl Translation { if let Some(task) = task.take() { let _ = task.await; } - if let Err(error) = self.journal.close().await { - tracing::warn!(%error, "SpanOp journal could not be closed during source shutdown"); - } } pub async fn observe(&self, observer: Observation) -> anyhow::Result<()> { self.routes.lock().active += 1; @@ -171,21 +171,17 @@ impl Translation { route: &SessionRoute, through: u64, ) -> anyhow::Result> { - self.journal.reconfigure_held(route, through).await + super::cursor::reconfigure_held(&self.storage, route, through).await } pub async fn route_settings(&self, route: &SessionRoute) -> anyhow::Result { - self.journal.route_settings(route).await + self.storage.route_settings(route).await } /// Connect a route to the committed SpanOp stream without exposing its /// storage adapter to the route actor. - pub async fn subscribe( - &self, - route: &SessionRoute, - legacy_through: u64, - ) -> anyhow::Result { - self.journal.subscribe(route, legacy_through).await + pub async fn subscribe(&self, route: &SessionRoute) -> anyhow::Result { + Cursor::open(&self.storage, route).await } } @@ -193,31 +189,44 @@ enum State { Processing, Recovering(Failure), } +#[derive(Serialize, Deserialize)] +struct Continuation { + source: String, + native: Box, + #[serde(default)] + last_control: Option, + bounds: HashMap, + capture: Option, +} + +/// One input's translation in progress. Chunks are prepared into `built` and +/// handed off together once the translator has drained, so a storage failure +/// retries only the handoff and never translates the input again. struct Publication { input: u64, - ordinal: u64, observation: bool, capture: Option, + /// The next chunk the translator produced, not yet prepared. ops: Option>, - begun: bool, - prepared: bool, + built: Vec, complete: bool, + continuation: Option>, } struct Producer { options: TranslationOptions, progress: Arc, - journal: SpanJournal, error: Arc>>, recovery: Arc>>, translator: Option>, - reader: Option, + reader: Option, observers: Vec, origins: WeakOrigins, roots: Roots, capture: Option, pending_snapshots: HashSet, bounds: HashMap, + last_control: Option, position: u64, committed: u64, state: State, @@ -227,19 +236,15 @@ struct Producer { impl Producer { async fn open(options: TranslationOptions) -> anyhow::Result { - let path = options.data_dir.join("pipeline").join(format!( - "{}.sqlite", - crate::ids::session_storage_id(&options.source, &options.session_id) - )); - let journal = SpanJournal::open(&path).await?; - let committed = journal.translated_through().await?; + let status = options.storage.status().await?; + let committed = status.translated_through; let progress = Arc::new(Progress { requested: AtomicU64::new(committed), committed: AtomicU64::new(committed), }); let recovery = Arc::new(Mutex::new(None)); let error = Arc::new(Mutex::new(None)); - let state = match journal.source_failure().await? { + let state = match status.source_failure { Some(raw) => State::Recovering(serde_json::from_str(&raw).unwrap_or_else(|_| { Failure::revision(Boundary::Journal, committed + 1, raw, &options.version) })), @@ -248,7 +253,6 @@ impl Producer { Ok(Self { options, progress, - journal, error, recovery, translator: None, @@ -259,6 +263,7 @@ impl Producer { capture: None, pending_snapshots: HashSet::new(), bounds: HashMap::new(), + last_control: None, position: 0, committed, state, @@ -317,7 +322,12 @@ impl Producer { }; if recorded.as_ref() != Some(&encoded) && super::recovery::now_ms() >= record_retry { - match self.journal.set_source_failure(Some(encoded.clone())).await { + match self + .options + .storage + .set_source_failure(Some(encoded.clone())) + .await + { Ok(()) => recorded = Some(encoded.clone()), Err(error) => { record_retry = super::recovery::now_ms().saturating_add(1_000); @@ -391,7 +401,7 @@ impl Producer { self.state = State::Recovering(failure); continue; } - if let Err(error) = self.journal.set_source_failure(None).await { + if let Err(error) = self.options.storage.set_source_failure(None).await { self.phase = Boundary::Journal; self.state = State::Recovering(self.failure(error, attempts)); continue; @@ -457,7 +467,12 @@ impl Producer { if let State::Recovering(failure) = &self.state { return Err(failure.message()); } - self.journal.tail().await.map_err(|error| error.to_string()) + self.options + .storage + .status() + .await + .map(|status| status.op_tail) + .map_err(|error| error.to_string()) } async fn control(&mut self, kind: ControlKind) -> anyhow::Result { @@ -471,7 +486,7 @@ impl Producer { if let Some(through) = self.append_control(kind).await? { self.advance(through).await?; } - self.journal.tail().await + Ok(self.options.storage.status().await?.op_tail) } async fn append_control(&mut self, kind: ControlKind) -> anyhow::Result> { self.phase = Boundary::Journal; @@ -484,65 +499,67 @@ impl Producer { bounds.insert(path.clone(), through); } let control = PipelineControl { kind, bounds }; - let through = { - let mut writer = self.options.events.lock().await; - // A checkpoint observes dispatched work. If capture is ahead, - // flush the published tail and let queued events arrive normally; - // chasing the file here can reorder parent/child processing. - if writer.position() > self.position { - return Ok(None); - } - let before = writer.position(); - let through = writer.append_control(&control).await?; - let position = SourcePosition { before, through }; - self.options.input.push(SourceRecord { - event: SourceEvent::Control(control), - position, - }); - through + if matches!(kind, ControlKind::Retire) && self.last_control.as_ref() == Some(&control) { + return Ok(None); + } + // A checkpoint observes dispatched work. If capture is ahead, flush the + // published tail and let queued events arrive normally; chasing capture + // here can reorder parent/child processing. + let Some(appended) = self + .options + .storage + .append(control.clone(), Some(self.position)) + .await? + else { + return Ok(None); }; + let through = appended.through; + self.options.input.push(SourceRecord { + event: SourceEvent::Control(control), + position: appended, + }); self.progress .requested .fetch_max(through, Ordering::Relaxed); Ok(Some(through)) } - fn new_translator( - &self, - ) -> impl std::future::Future>> + Send + 'static - { - let registry = self.options.registry.clone(); - let source = self.options.source.clone(); - let namespace = self.options.namespace.clone(); - async move { - tokio::task::spawn_blocking(move || { - registry.create_checked_with_session_namespace(&source, &namespace) - }) - .await? - } - } - async fn initialize(&mut self) -> anyhow::Result<()> { if self.translator.is_some() { return Ok(()); } - self.committed = self.journal.translated_through().await?; - self.roots = Roots::restore(self.journal.root_candidates().await?); + let continuation = self.options.storage.continuation().await?; + self.committed = self.options.storage.status().await?.translated_through; + self.roots = Roots::restore(self.options.storage.root_candidates().await?); for ops in self.roots.pending().values() { - for op in ops { - let (SpanOp::Insert(row) | SpanOp::Merge(row)) = op; + for row in ops.iter().map(SpanOp::row) { if let Some(origin) = &row.origin { self.origins.insert(row.span_id.clone(), origin); } } } self.translator = Some(self.new_translator().await?); + if let Some(bytes) = continuation { + let source = self.options.source.clone(); + let saved = self + .translate(move |translator, _| { + let saved: Continuation = serde_json::from_slice(&bytes)?; + anyhow::ensure!(saved.source == source, "checkpoint source mismatch"); + translator.restore_state(&saved.native)?; + Ok(saved) + }) + .await?; + self.bounds = saved.bounds; + self.last_control = saved.last_control; + self.capture = saved.capture; + self.position = self.committed; + self.reader = None; + return Ok(()); + } self.position = 0; - self.reader = if self.committed > 0 { - JournalReader::open(&self.options.event_path, self.committed).await? - } else { - None - }; + // Storage without a continuation predates checkpoints: rebuild + // translator state from the retained input it already translated. + self.reader = (self.committed > 0).then(|| self.options.storage.read(0, self.committed)); Ok(()) } @@ -557,35 +574,27 @@ impl Producer { return Ok(None); } if self.reader.is_none() { - self.reader = Some( - JournalReader::resume(&self.options.event_path, self.position, through).await?, - ); + self.reader = Some(self.options.storage.read(self.position, through)); } let reader = self .reader .as_mut() .ok_or_else(|| anyhow::anyhow!("recovery reader is missing"))?; reader.extend(through); - let Some(entry) = reader.next_record().await? else { + let Some(entry) = reader.try_next().await? else { return Ok(None); }; let event = match entry.record { - JournalRecord::Event(event) => { + EventRecord::Event(event) => { SourceEvent::Event(Box::new(crate::journal::envelope_from_redacted(event))) } - JournalRecord::Control(control) => SourceEvent::Control(control), - JournalRecord::DeliveryCheckpoint { route, through } => { - SourceEvent::LegacyDeliveryCheckpoint { - route: Box::new(route), - through, - } - } + EventRecord::Control(control) => SourceEvent::Control(control), }; Ok(Some(SourceRecord { event, position: SourcePosition { before: self.position, - through: entry.through, + through: entry.id, }, })) } @@ -608,10 +617,12 @@ impl Producer { while let Some(entry) = self.next_input(through).await? { let input = entry.position.through; let observation = !matches!(&entry.event,SourceEvent::Control(control) if matches!(control.kind,ControlKind::Retire)); + let mut continuation = None; let (first, capture) = match entry.event { SourceEvent::Event(mut env) => { + self.last_control = None; if let Some(route) = &env.route { - self.journal.register(route).await?; + self.options.storage.register(route).await?; } if crate::translate::canonical_source_name(&env.source) != self.options.source { self.position = input; @@ -649,6 +660,7 @@ impl Producer { ) } SourceEvent::Control(control) => { + self.last_control = Some(control.clone()); // Retirement exports defensive terminal updates but does not // close native state when rebuilding for later captured work. if input <= self.committed && matches!(control.kind, ControlKind::Retire) { @@ -656,6 +668,9 @@ impl Producer { continue; } self.phase = Boundary::Translation; + if matches!(control.kind, ControlKind::Retire) { + continuation = Some(self.continuation().await?); + } let ops = if matches!(control.kind, ControlKind::Reset) { self.translator = Some(self.new_translator().await?); Vec::new() @@ -671,37 +686,79 @@ impl Producer { }; (ops, self.capture.clone()) } - SourceEvent::LegacyDeliveryCheckpoint { route, through } => { - self.journal.acknowledge_legacy(&route, through).await?; - if input > self.committed { - self.journal.begin(input, observation).await?; - self.journal.commit(input).await?; - self.committed = input; - self.progress.committed.store(input, Ordering::Relaxed); - } - self.position = input; - continue; - } }; self.publication = Some(Publication { input, - ordinal: 0, observation, capture, ops: Some(first), - begun: false, - prepared: false, + built: Vec::new(), complete: false, + continuation, }); self.publish().await?; self.phase = Boundary::Journal; self.position = input; } + if self.position < through { + // Every stored record through `through` is consumed. The rest of + // the range is what a legacy journal reserved without importing a + // record (such as a delivery checkpoint): input with no output. + if through > self.committed { + let state = self.continuation().await?; + self.options + .storage + .commit_translation(Translated { + input: through, + observation: true, + ops: Vec::new(), + roots: self.roots.pending().clone(), + state: Some(state), + }) + .await?; + self.committed = through; + self.progress.committed.store(through, Ordering::Relaxed); + } + self.position = through; + } Ok(()) } - /// Each chunk stays owned until its local write succeeds. A commit retry - /// cannot call translation or advance to the following event. + fn new_translator( + &self, + ) -> impl std::future::Future>> + Send + 'static + { + let registry = self.options.registry.clone(); + let source = self.options.source.clone(); + let namespace = self.options.namespace.clone(); + async move { + tokio::task::spawn_blocking(move || { + registry.create_checked_with_session_namespace(&source, &namespace) + }) + .await? + } + } + + async fn continuation(&mut self) -> anyhow::Result> { + let source = self.options.source.clone(); + let last_control = self.last_control.clone(); + let bounds = self.bounds.clone(); + let capture = self.capture.clone(); + self.translate(move |translator, _| { + Ok(serde_json::to_vec(&Continuation { + source, + native: translator.save_state()?, + last_control, + bounds, + capture, + })?) + }) + .await + } + + /// Each chunk stays owned until it is prepared; the input's complete + /// output is handed to delivery in one transaction with its removal. A + /// commit retry cannot call translation or advance to the following event. async fn publish(&mut self) -> anyhow::Result<()> { let mut pending = self .publication @@ -709,85 +766,38 @@ impl Producer { .ok_or_else(|| anyhow::anyhow!("pending publication is missing"))?; let result = async { let publish = pending.input > self.committed; - if publish && !pending.begun { - self.phase = Boundary::Journal; - self.journal - .begin(pending.input, pending.observation) - .await?; - pending.begun = true; - } while !pending.complete { - if let Some(ops) = pending.ops.as_mut() { - if !pending.prepared { - let missing = ops - .iter() - .filter_map(|op| { - let (SpanOp::Insert(row) | SpanOp::Merge(row)) = op; - self.origins - .get(&row.span_id) - .is_none() - .then(|| row.span_id.clone()) - }) - .collect(); - let mut saved = self.journal.origins_for(missing).await?; - for op in ops.iter_mut() { - let insert = matches!(op, SpanOp::Insert(_)); - let (SpanOp::Insert(row) | SpanOp::Merge(row)) = op; - let origin = self - .origins - .get(&row.span_id) - .or_else(|| saved.remove(&row.span_id)) - .or_else(|| { - insert.then(|| { - Arc::new(pending.capture.clone().unwrap_or_else(|| { - OriginSnapshot { - plugin_version: None, - source_version: None, - bt_version: self.options.version.clone(), - } - })) - }) - }); - if let Some(origin) = &origin { - self.origins.insert(row.span_id.clone(), origin); - } - row.origin = origin; - } - self.phase = Boundary::Journal; - if pending.observation { - for observer in &self.observers { - Self::observe( - &self.options, - &mut self.pending_snapshots, - ops, - observer, - ) - .await?; - } - } - if publish { - *ops = self.roots.process_owned(std::mem::take(ops)); - } - pending.prepared = true; + if let Some(mut ops) = pending.ops.take() { + if let Err(error) = self.prepare(&pending, &mut ops).await { + pending.ops = Some(ops); + return Err(error); } if publish { - self.journal - .append_live(pending.input, &mut pending.ordinal, ops) - .await?; + pending.built.extend(self.roots.process_owned(ops)); } - pending.ops = None; } self.phase = Boundary::Translation; pending.ops = self .translate(|translator, ctx| translator.drain_pending(ctx)) .await?; pending.complete = pending.ops.is_none(); - pending.prepared = false; } if publish { self.phase = Boundary::Journal; - self.journal - .commit_with_roots(pending.input, self.roots.pending()) + let state = match &pending.continuation { + Some(state) => state.clone(), + None => self.continuation().await?, + }; + pending.continuation = Some(state.clone()); + self.options + .storage + .commit_translation(Translated { + input: pending.input, + observation: pending.observation, + ops: pending.built.clone(), + roots: self.roots.pending().clone(), + state: Some(state), + }) .await?; self.committed = pending.input; self.progress @@ -804,11 +814,52 @@ impl Producer { result } + /// Stamp provenance and let correlation observe one translated chunk. + async fn prepare(&mut self, pending: &Publication, ops: &mut [SpanOp]) -> anyhow::Result<()> { + let missing = ops + .iter() + .map(|op| &op.row().span_id) + .filter(|span| self.origins.get(span).is_none()) + .cloned() + .collect(); + let mut saved = self.options.storage.origins_for(missing).await?; + for op in ops.iter_mut() { + let insert = matches!(op, SpanOp::Insert(_)); + let row = op.row_mut(); + let origin = self + .origins + .get(&row.span_id) + .or_else(|| saved.remove(&row.span_id)) + .or_else(|| { + // Output rebuilt from input an earlier daemon already + // delivered keeps only the provenance it recorded. + (insert && pending.input > self.committed).then(|| { + Arc::new(pending.capture.clone().unwrap_or_else(|| OriginSnapshot { + plugin_version: None, + source_version: None, + bt_version: self.options.version.clone(), + })) + }) + }); + if let Some(origin) = &origin { + self.origins.insert(row.span_id.clone(), origin); + } + row.origin = origin; + } + self.phase = Boundary::Journal; + if pending.observation { + for observer in &self.observers { + Self::observe(&self.options, &mut self.pending_snapshots, ops, observer).await?; + } + } + Ok(()) + } + async fn observe_history(&mut self, observer: &Observation) -> anyhow::Result<()> { // Candidates have no delivery position yet, but their birth records // identify the session for correlation. Defensive retirement updates // are not native observations and must not close a recreated observer. - for ops in self.journal.root_candidates().await?.into_values() { + for ops in self.options.storage.root_candidates().await?.into_values() { let births = ops .into_iter() .filter(|op| matches!(op, SpanOp::Insert(_))) @@ -821,7 +872,7 @@ impl Producer { ) .await?; } - let ops = self.journal.observations().await?; + let ops = self.options.storage.observations().await?; Self::observe(&self.options, &mut self.pending_snapshots, &ops, observer).await?; Ok(()) } @@ -833,7 +884,7 @@ impl Producer { ) -> anyhow::Result<()> { let mut ops = ops .iter() - .map(super::journal::metadata_only) + .map(crate::collections::metadata_only) .collect::>(); Prepare::new(&options.source).apply(&mut ops, &observer.config); if options @@ -860,6 +911,7 @@ impl Producer { #[cfg(test)] pub(crate) mod tests { use super::*; + use crate::collections::inspect::{Fault, Inspector, Table}; use crate::{pipeline::delivery::InputPort, translate::SpanRow}; mod streams { use crate as bt_daemon; @@ -877,17 +929,15 @@ pub(crate) mod tests { impl SourceFixture { pub(crate) async fn new(agent: &str) -> Self { let dir = tempfile::tempdir().unwrap(); - let path = crate::journal::source_journal_path(dir.path(), agent, "checkpoint"); let options = TranslationOptions { source: agent.into(), session_id: "checkpoint".into(), namespace: crate::ids::session_namespace(agent, "checkpoint"), version: "test".into(), data_dir: dir.path().into(), - events: Arc::new(tokio::sync::Mutex::new( - JournalWriter::open_path(&path).await.unwrap(), - )), - event_path: path, + storage: SessionStorage::open(dir.path(), agent, "checkpoint") + .await + .unwrap(), input: SourceInput::default(), registry: Arc::new(Registry::default_agents()), correlation: Arc::default(), @@ -901,48 +951,46 @@ pub(crate) mod tests { } } pub(crate) async fn write(&self, event: &crate::wire::Envelope, live: bool) -> u64 { - let mut writer = self.options.events.lock().await; - let before = writer.position(); - let through = writer.append(event).await.unwrap(); - let position = SourcePosition { before, through }; + let appended = self + .options + .storage + .append(event, None) + .await + .unwrap() + .unwrap(); if live { - self.options.input.push_event(event.clone(), position); + self.options.input.push_event(event.clone(), appended); } - through + appended.through } pub(crate) async fn process(&self, through: u64) { self.source.advance(through).await.unwrap(); self.source.barrier().await.unwrap(); assert_eq!( - self.source.journal.translated_through().await.unwrap(), + self.source + .storage + .status() + .await + .unwrap() + .translated_through, through ); } async fn reopen(&mut self) { self.source.shutdown().await; - *self.options.events.lock().await = JournalWriter::open_path(&self.options.event_path) - .await - .unwrap(); self.options.input = SourceInput::default(); self.source = Translation::spawn(self.options.clone()).await.unwrap(); } - fn db(&self) -> rusqlite::Connection { - rusqlite::Connection::open(self.options.data_dir.join("pipeline").join(format!( - "{}.sqlite", - crate::ids::session_storage_id(&self.options.source, &self.options.session_id) - ))) + fn db(&self) -> Inspector { + Inspector::session( + &self.options.data_dir, + &self.options.source, + &self.options.session_id, + ) .unwrap() } pub(crate) async fn poison(&self, range: std::ops::Range) { - let mut bytes = tokio::fs::read(&self.options.event_path).await.unwrap(); - for byte in &mut bytes[range.start as usize..range.end as usize] { - if *byte != b'\n' { - *byte = b'x'; - } - } - tokio::fs::write(&self.options.event_path, bytes) - .await - .unwrap(); + self.db().corrupt_events(range.start, range.end).unwrap(); } } @@ -988,7 +1036,10 @@ pub(crate) mod tests { let mut covered = Vec::new(); for (agent, mut events, _files) in streams::native_streams() { covered.push(agent.clone()); - events.insert(0, events[0].clone()); + // A repeated native event, captured separately. + let mut repeated = events[0].clone(); + repeated.ts_ms += 1; + events.insert(0, repeated); for event in &mut events { event.payload["padding"] = serde_json::json!("é📚history".repeat(1024)); } @@ -1010,10 +1061,10 @@ pub(crate) mod tests { f.process(positions[1]).await; f.source.control(ControlKind::Checkpoint).await.unwrap(); assert_eq!( - f.source.journal.translated_through().await.unwrap(), + f.source.storage.status().await.unwrap().translated_through, positions[1] ); - assert_eq!(f.options.events.lock().await.position(), tail); + assert_eq!(f.options.storage.status().await.unwrap().event_tail, tail); f.poison(0..tail).await; } "overflow" => { @@ -1034,18 +1085,10 @@ pub(crate) mod tests { } f.process(tail).await; f.source.control(ControlKind::Finalize).await.unwrap(); - assert!(f.source.journal.translated_through().await.unwrap() > tail); + assert!(f.source.storage.status().await.unwrap().translated_through > tail); // StoredOp already includes the private correlation fields; // compare its complete encoding rather than duplicate its codec. - let db = f.db(); - let mut query = db - .prepare("SELECT value FROM ops ORDER BY position") - .unwrap(); - let rows: Vec> = query - .query_map([], |row| row.get(0)) - .unwrap() - .map(Result::unwrap) - .collect(); + let rows: Vec> = f.db().op_records(); assert!(!rows.is_empty(), "{agent} {mode} produced no observations"); if let Some(expected) = &expected { assert_eq!(&rows, expected, "{agent} {mode} split {split}"); @@ -1060,6 +1103,163 @@ pub(crate) mod tests { assert_eq!(covered, Registry::default_agents().sources()); } + #[tokio::test] + async fn a_failed_checkpoint_publishes_nothing_and_retries_the_whole_handoff() { + let mut f = SourceFixture::new("debug").await; + let db = f.db(); + db.inject(Fault::Handoff).unwrap(); + let event: crate::wire::Envelope = serde_json::from_value(serde_json::json!({ + "source":"debug", "session_id":"checkpoint", "event":"tool", "ts_ms":1, + "payload":{"value":1}, "route":{} + })) + .unwrap(); + let through = f.write(&event, true).await; + f.source.advance(through).await.unwrap(); + assert!(f.source.barrier().await.is_err()); + // The input is kept and none of its output reached delivery. + assert_eq!(db.count(Table::Events), 1); + assert_eq!(db.count(Table::Ops), 0); + let mut route = f + .source + .subscribe(event.route.as_ref().unwrap()) + .await + .unwrap(); + assert!(route.next_batch(8).await.unwrap().is_none()); + drop(route); + f.source.shutdown().await; + db.clear(Fault::Handoff).unwrap(); + f.reopen().await; + f.source.advance(through).await.unwrap(); + tokio::time::timeout(std::time::Duration::from_secs(5), async { + while f.source.barrier().await.is_err() { + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + assert_eq!(f.source.storage.status().await.unwrap().op_tail, 2); + assert_eq!(f.source.storage.stored().await.len(), 2); + let bytes = f.source.storage.continuation().await.unwrap().unwrap(); + let state: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(state["native"]["event_seq"], 1); + assert_eq!(db.count(Table::Events), 0); + f.source.shutdown().await; + } + + #[tokio::test] + async fn unchanged_restarts_do_not_append_retirement_records() { + let mut f = SourceFixture::new("debug").await; + let event: crate::wire::Envelope = serde_json::from_value(serde_json::json!({ + "source":"debug", "session_id":"checkpoint", "event":"tool", "ts_ms":1, + "payload":{}, "route":{} + })) + .unwrap(); + let through = f.write(&event, true).await; + f.process(through).await; + f.source.control(ControlKind::Retire).await.unwrap(); + let through = f.options.storage.status().await.unwrap().event_tail; + let tail = f.source.storage.status().await.unwrap().op_tail; + for _ in 0..3 { + f.reopen().await; + f.source.control(ControlKind::Retire).await.unwrap(); + assert_eq!( + f.options.storage.status().await.unwrap().event_tail, + through + ); + assert_eq!(f.source.storage.status().await.unwrap().op_tail, tail); + assert_eq!(f.db().count(Table::Events), 0); + } + f.source.shutdown().await; + } + + fn legacy_line(value: &serde_json::Value) -> Vec { + let mut line = serde_json::to_vec(value).unwrap(); + line.push(b'\n'); + line + } + + fn legacy_options(dir: &std::path::Path, storage: SessionStorage) -> TranslationOptions { + TranslationOptions { + source: "debug".into(), + session_id: "s".into(), + namespace: crate::ids::session_namespace("debug", "s"), + version: "test".into(), + data_dir: dir.into(), + storage, + input: SourceInput::default(), + registry: Arc::new(Registry::default_agents()), + correlation: Arc::default(), + correlation_changed: Arc::default(), + } + } + + #[tokio::test] + async fn bytes_a_legacy_journal_reserved_without_records_are_translated() { + let tmp = tempfile::tempdir().unwrap(); + let path = crate::journal::source_journal_path(tmp.path(), "debug", "s"); + let route = serde_json::json!({}); + let event = serde_json::json!({"source":"debug","session_id":"s","event":"tool", + "ts_ms":1,"payload":{},"route":route}); + let mut bytes = legacy_line(&event); + let first = bytes.len() as u64; + bytes.extend(legacy_line(&event)); + // A trailing checkpoint is reserved but not imported as a record. + bytes.extend(legacy_line(&serde_json::json!({ + "_bt_record_type":"delivery_checkpoint","route":route,"through":first}))); + tokio::fs::create_dir_all(path.parent().unwrap()) + .await + .unwrap(); + tokio::fs::write(&path, &bytes).await.unwrap(); + let events = SessionStorage::open(tmp.path(), "debug", "s") + .await + .unwrap(); + let tail = events.status().await.unwrap().event_tail; + assert_eq!(tail, bytes.len() as u64); + let translation = Translation::spawn(legacy_options(tmp.path(), events.clone())) + .await + .unwrap(); + translation.advance(tail).await.unwrap(); + translation.barrier().await.unwrap(); + assert_eq!(events.status().await.unwrap().translated_through, tail); + // Lifecycle controls can be ordered after the reserved range again. + translation.control(ControlKind::Retire).await.unwrap(); + assert!(events.status().await.unwrap().event_tail > tail); + let mut route = translation + .subscribe(&serde_json::from_value(route).unwrap()) + .await + .unwrap(); + while let Some(delivery) = route.next_batch(100).await.unwrap() { + delivery.into_completed().await.ok().unwrap(); + } + assert!(events.complete().await.unwrap()); + translation.shutdown().await; + } + + #[tokio::test] + async fn a_delivered_session_migrated_from_main_is_complete() { + let tmp = tempfile::tempdir().unwrap(); + let path = crate::journal::source_journal_path(tmp.path(), "debug", "s"); + let event = serde_json::json!({"source":"debug","session_id":"s","event":"tool", + "ts_ms":1,"payload":{},"route":{}}); + let bytes = legacy_line(&event); + tokio::fs::create_dir_all(path.parent().unwrap()) + .await + .unwrap(); + tokio::fs::write(&path, &bytes).await.unwrap(); + // Main translated and delivered the journal's only event. + let db = crate::collections::inspect::Inspector::session(tmp.path(), "debug", "s").unwrap(); + db.add_head(&SessionRoute::default()).unwrap(); + db.set_translated(bytes.len() as u64).unwrap(); + drop(db); + let sessions = crate::collections::SessionStorage::all(tmp.path()) + .await + .unwrap(); + let session = SessionStorage::at(&sessions[0]).await.unwrap(); + // The imported input only rebuilds translator state if the session + // resumes; it does not keep a delivered session from collection. + assert!(session.complete().await.unwrap()); + } + struct BlockedTranslator { entered: Arc, release: std::sync::mpsc::Receiver<()>, @@ -1096,6 +1296,8 @@ pub(crate) mod tests { let f = SourceFixture::new("debug").await; let event = streams::native_streams().pop().unwrap().1.remove(0); let through = f.write(&event, false).await; + let mut later = event.clone(); + later.ts_ms += 1; let mut producer = Producer::open(f.options.clone()).await.unwrap(); let entered = Arc::new(Notify::new()); let (release, receiver) = std::sync::mpsc::channel(); @@ -1111,7 +1313,7 @@ pub(crate) mod tests { entered.notified().await; assert!(started.elapsed() < std::time::Duration::from_secs(1)); assert!( - tokio::time::timeout(std::time::Duration::from_secs(1), f.write(&event, true)) + tokio::time::timeout(std::time::Duration::from_secs(1), f.write(&later, true)) .await .unwrap() > through @@ -1124,23 +1326,29 @@ pub(crate) mod tests { let (producer, result) = work.await.unwrap(); result.unwrap(); assert_eq!( - producer.journal.translated_through().await.unwrap(), + producer + .options + .storage + .status() + .await + .unwrap() + .translated_through, through ); f.source.shutdown().await; } #[tokio::test] - async fn shared_storage_stays_open_until_the_last_route_finishes_draining() { + async fn translation_stays_running_until_the_last_route_finishes_draining() { let f = SourceFixture::new("debug").await; let translation = &f.source; translation.routes.lock().active = 2; assert!(!translation.begin_route_shutdown()); assert!(translation.begin_route_shutdown()); translation.finish_route_shutdown().await; - assert_eq!(translation.journal.tail().await.unwrap(), 0); + assert_eq!(translation.barrier().await.unwrap(), 0); translation.finish_route_shutdown().await; - assert!(translation.journal.tail().await.is_err()); + assert!(translation.barrier().await.is_err()); } #[tokio::test] @@ -1164,10 +1372,15 @@ pub(crate) mod tests { }), ]) .await; - translation.journal.begin(10, false).await.unwrap(); translation - .journal - .commit_with_roots(10, roots.pending()) + .storage + .commit_translation(Translated { + input: 10, + observation: false, + ops: Vec::new(), + roots: roots.pending().clone(), + state: None, + }) .await .unwrap(); let route = SessionRoute::default(); @@ -1202,22 +1415,31 @@ pub(crate) mod tests { let tmp = tempfile::tempdir().unwrap(); let source = "debug"; let session = "stored"; - let event_path = crate::journal::source_journal_path(tmp.path(), source, session); - std::fs::create_dir_all(event_path.parent().unwrap()).unwrap(); - // Any translation replay of this file would fail immediately. - std::fs::write(&event_path, b"not JSON\n").unwrap(); - let input = std::fs::metadata(&event_path).unwrap().len(); - let journal = SpanJournal::open(&tmp.path().join("pipeline").join(format!( - "{}.sqlite", - crate::ids::session_storage_id(source, session) - ))) - .await - .unwrap(); - journal.begin(input, true).await.unwrap(); - journal + let events = SessionStorage::open(tmp.path(), source, session) + .await + .unwrap(); + let input = events .append( + &serde_json::from_value::(serde_json::json!({ + "source": source, "session_id": session, "event": "native", + "ts_ms": 1, "payload": {} + })) + .unwrap(), + None, + ) + .await + .unwrap() + .unwrap() + .through; + // Any translation replay of this record would fail immediately. + Inspector::session(tmp.path(), source, session) + .unwrap() + .corrupt_events(0, input) + .unwrap(); + let tail = events + .translated( input, - &[SpanOp::Insert(SpanRow { + vec![SpanOp::Insert(SpanRow { span_id: "durable".into(), root_span_id: "durable".into(), name: "already translated".into(), @@ -1226,17 +1448,13 @@ pub(crate) mod tests { ) .await .unwrap(); - let tail = journal.commit(input).await.unwrap(); let translation = Translation::spawn(TranslationOptions { source: source.into(), session_id: session.into(), namespace: crate::ids::session_namespace(source, session), version: "test".into(), data_dir: tmp.path().into(), - events: Arc::new(tokio::sync::Mutex::new( - JournalWriter::open_path(&event_path).await.unwrap(), - )), - event_path, + storage: events, input: SourceInput::default(), registry: Arc::new(Registry::default_agents()), correlation: Arc::new(crate::correlation::CorrelationRegistry::default()), @@ -1249,8 +1467,7 @@ pub(crate) mod tests { assert_eq!(translation.progress.pending(), 0); assert!(translation.error.lock().is_none()); let mut route = translation - .journal - .subscribe(&SessionRoute::default(), 0) + .subscribe(&SessionRoute::default()) .await .unwrap(); let delivery = InputPort::receive(&mut route).await.unwrap().unwrap(); @@ -1287,17 +1504,12 @@ pub(crate) mod tests { let f = SourceFixture::new("debug").await; f.source.shutdown().await; let mut producer = Producer::open(f.options.clone()).await.unwrap(); - let journal = producer.journal.clone(); - let path = f.options.data_dir.as_path().join("pipeline").join(format!( - "{}.sqlite", - crate::ids::session_storage_id("debug", "checkpoint") - )); - let db = rusqlite::Connection::open(path).unwrap(); + let journal = producer.options.storage.clone(); + let db = f.db(); let drains = Arc::new(AtomicU64::new(0)); producer.translator = Some(Box::new(CountedTranslation(drains.clone()))); producer.publication = Some(Publication { input: 10, - ordinal: 0, observation: true, capture: None, ops: Some(vec![ @@ -1311,23 +1523,25 @@ pub(crate) mod tests { ..Default::default() }), ]), - begun: false, - prepared: false, + built: Vec::new(), complete: false, + continuation: None, }); - db.execute_batch("CREATE TRIGGER fail_append BEFORE INSERT ON ops BEGIN SELECT RAISE(FAIL,'append'); END;").unwrap(); - assert!(producer.publish().await.is_err()); - assert_eq!(drains.load(Ordering::Relaxed), 0); - assert_eq!(journal.translated_through().await.unwrap(), 0); - db.execute_batch("DROP TRIGGER fail_append; CREATE TRIGGER fail_commit BEFORE UPDATE OF committed ON batches BEGIN SELECT RAISE(FAIL,'commit'); END;").unwrap(); + // A failed handoff publishes nothing and keeps the built output. + db.inject(Fault::InsertOps).unwrap(); assert!(producer.publish().await.is_err()); assert_eq!(drains.load(Ordering::Relaxed), 1); - assert_eq!(journal.tail().await.unwrap(), 1); - db.execute_batch("DROP TRIGGER fail_commit").unwrap(); + assert_eq!(journal.status().await.unwrap().translated_through, 0); + assert_eq!(journal.status().await.unwrap().op_tail, 0); + db.clear(Fault::InsertOps).unwrap(); + db.inject(Fault::Handoff).unwrap(); + assert!(producer.publish().await.is_err()); + assert_eq!(journal.status().await.unwrap().op_tail, 0); + db.clear(Fault::Handoff).unwrap(); producer.publish().await.unwrap(); assert_eq!(drains.load(Ordering::Relaxed), 1); - assert_eq!(journal.translated_through().await.unwrap(), 10); - assert_eq!(journal.tail().await.unwrap(), 1); + assert_eq!(journal.status().await.unwrap().translated_through, 10); + assert_eq!(journal.status().await.unwrap().op_tail, 1); let roots = journal.root_candidates().await.unwrap(); assert_eq!( roots["unused-root"].len(), diff --git a/bt-daemon/src/server/ingress.rs b/bt-daemon/src/server/ingress.rs index e9a4be37..6aa6a6b6 100644 --- a/bt-daemon/src/server/ingress.rs +++ b/bt-daemon/src/server/ingress.rs @@ -3,13 +3,14 @@ //! the journals as overflow when the queue is full. use super::*; +use futures::TryStreamExt; use std::collections::VecDeque; /// Captures remain ordered and bounded. Evicted entries are /// already durable; their source journal's high-water mark is replayed first. #[derive(Default)] pub(super) struct CaptureBuffer { pub(super) events: VecDeque, - pub(super) evicted: HashMap, + pub(super) evicted: HashMap<(String, String), EvictedRange>, } #[derive(Clone, Copy, Debug)] @@ -19,16 +20,11 @@ pub(super) struct EvictedRange { } impl CaptureBuffer { - fn push(&mut self, data_dir: &std::path::Path, event: PendingEvent) { + fn push(&mut self, event: PendingEvent) { if self.events.len() == INGRESS_QUEUE_CAPACITY { if let Some(oldest) = self.events.pop_front() { - let path = journal::source_journal_path( - data_dir, - &oldest.env.source, - &oldest.env.session_id, - ); self.evicted - .entry(path) + .entry((oldest.env.source.clone(), oldest.env.session_id.clone())) .and_modify(|range| range.through = range.through.max(oldest.journal_through)) .or_insert(EvictedRange { from: oldest.replay_through, @@ -41,7 +37,7 @@ impl CaptureBuffer { } pub(super) enum CaptureWork { - Evicted(HashMap), + Evicted(HashMap<(String, String), EvictedRange>), Event(Box), Finished, } @@ -84,11 +80,14 @@ pub(super) async fn drain_capture_buffer(daemon: &Arc) -> anyhow::Result /// startup recovery does. Rebuild decoder context before each range. pub(super) async fn replay_evicted( daemon: &Arc, - bounds: &HashMap, + bounds: &HashMap<(String, String), EvictedRange>, ) -> anyhow::Result<()> { let mut ready = Vec::new(); - for (path, range) in bounds { - let mut reader = journal::JournalReader::resume(path, range.from, range.through).await?; + for ((source, session_id), range) in bounds { + let mut reader = daemon + .storage_for(source, session_id) + .await? + .read(range.from, range.through); if let Some((timestamp, event)) = next_evicted_event(daemon, &mut reader, range.through).await? { @@ -112,17 +111,17 @@ pub(super) async fn replay_evicted( async fn next_evicted_event( daemon: &Daemon, - reader: &mut journal::JournalReader, + reader: &mut crate::collections::EventReader, through: u64, ) -> anyhow::Result> { while reader.position() < through { let before = reader.position(); let entry = reader - .next_record() + .try_next() .await? .ok_or_else(|| anyhow::anyhow!("replay range ends inside a record"))?; - anyhow::ensure!(entry.through <= through, "invalid replay end boundary"); - if let journal::JournalRecord::Event(redacted) = entry.record { + anyhow::ensure!(entry.id <= through, "invalid replay end boundary"); + if let EventRecord::Event(redacted) = entry.record { let mut env = journal::envelope_from_redacted(redacted); let Some(source) = daemon.translators.canonical_source(&env.source) else { continue; @@ -133,7 +132,7 @@ async fn next_evicted_event( PendingEvent { env, replay_through: before, - journal_through: entry.through, + journal_through: entry.id, settings_through: None, }, ))); @@ -356,25 +355,26 @@ impl Daemon { /// Caller holds the source-session capture lock; frozen observations enter /// the same durable queue as hooks without reacquiring that lock. pub(super) async fn journal_and_enqueue(&self, env: Envelope) -> Result { - let writer = self - .journal_writer_for(&env.source, &env.session_id) + let events = self + .storage_for(&env.source, &env.session_id) + .await + .map_err(|error| format!("capture storage failed: {error}"))?; + let Some(appended) = self + .append_event(&env, &events) .await - .map_err(|error| format!("journal failed: {error}"))?; - let (replay_through, journal_through) = { - let mut writer = writer.lock().await; - let position = self - .append_to_journal(&env, &mut writer) - .await - .map_err(|error| format!("journal failed: {error}"))?; - (position.before, position.through) + .map_err(|error| format!("capture storage failed: {error}"))? + else { + // Already captured: acknowledge without delivering it twice. + return Ok(true); }; + let (replay_through, journal_through) = (appended.before, appended.through); let event = PendingEvent { env, replay_through, journal_through, settings_through: None, }; - self.capture_buffer.lock().push(&self.data_dir, event); + self.capture_buffer.lock().push(event); match self.ingress_tx.try_send(IngressMsg::Wake) { Ok(()) | Err(mpsc::error::TrySendError::Full(_)) => {} Err(mpsc::error::TrySendError::Closed(_)) => { diff --git a/bt-daemon/src/server/maintenance.rs b/bt-daemon/src/server/maintenance.rs index 5738c84a..00c1119b 100644 --- a/bt-daemon/src/server/maintenance.rs +++ b/bt-daemon/src/server/maintenance.rs @@ -2,6 +2,7 @@ //! watchdog, and draining on shutdown. use super::*; +use futures::TryStreamExt; /// How long recovery state is kept on disk. pub(super) const RETENTION: Duration = Duration::from_secs(7 * 24 * 60 * 60); @@ -10,18 +11,17 @@ pub(super) const RETENTION: Duration = Duration::from_secs(7 * 24 * 60 * 60); pub(super) const GC_INTERVAL: Duration = Duration::from_secs(60 * 60); pub(super) async fn collect_garbage(daemon: &Daemon) { - collect_partitions(daemon, RETENTION).await; - // Imports deliver through the daemon, so ledgers written by earlier - // in-process imports hold nothing a current pipeline reads. + collect_sessions(daemon).await; + // Delivery is acknowledged by SpanOp heads; ledgers from earlier daemons + // hold nothing a current pipeline reads. match tokio::fs::remove_dir_all(daemon.data_dir.join("delivery-ledger")).await { Ok(()) => {} Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(error) => tracing::warn!(%error, "legacy delivery ledger cleanup failed"), } - journal::gc_old_journals(&daemon.data_dir, RETENTION).await; journal::gc_old_managed_runs(&daemon.data_dir, RETENTION).await; - // Protect references from every retained input log, including completed - // partitions still inside retention and sessions with no registered heads. + // Protect references held by every retained session, including sessions + // still inside retention and sessions with no registered heads. let Ok(protected) = retained_references(&daemon.data_dir).await else { return; }; @@ -44,142 +44,83 @@ async fn old(path: &std::path::Path, age: Duration) -> bool { .is_some_and(|elapsed| elapsed > age) } -async fn collect_partitions(daemon: &Daemon, age: Duration) { - let Ok(mut entries) = tokio::fs::read_dir(journal::journal_dir(&daemon.data_dir)).await else { +async fn collect_sessions(daemon: &Daemon) { + let Ok(sessions) = crate::collections::SessionStorage::all(&daemon.data_dir).await else { return; }; - while let Ok(Some(entry)) = entries.next_entry().await { - let path = entry.path(); - if path.extension().and_then(|v| v.to_str()) != Some("ndjson") || !old(&path, age).await { - continue; - } - let recorded = journal::JournalReader::recorded_len(&path).await; - let Ok(Some(mut reader)) = journal::JournalReader::open(&path, recorded).await else { - continue; - }; - let Ok(Some(first)) = reader.next_entry().await else { - continue; - }; - let id = crate::ids::session_storage_id(&first.source, &first.session_id); - // Legacy mixed-source logs are handled by their own conservative reader. - if path != journal::source_journal_path(&daemon.data_dir, &first.source, &first.session_id) - { - continue; - } - let storage = daemon - .data_dir - .join("pipeline") - .join(format!("{id}.sqlite")); - if !old(&storage, age).await { - continue; - } - let wal = storage.with_extension("sqlite-wal"); - if tokio::fs::try_exists(&wal).await.unwrap_or(true) && !old(&wal, age).await { - continue; - } - // Scanning a large journal must not hold the capture lock. The length - // and route set are revalidated under that lock before deletion. - let Ok(partition) = crate::pipeline::journal::SpanJournal::open(&storage).await else { - continue; - }; - let Ok(routes) = partition.routes().await else { - continue; - }; - if !captured_routes_registered(&daemon.data_dir, &path, recorded, &routes).await { - continue; - } - let lock = daemon.session_lock(&first.source, &first.session_id); - let _guard = lock.lock().await; - let namespace = crate::ids::session_namespace(&first.source, &first.session_id); - if daemon.journals.lock().contains_key(&path) - || daemon.translations.lock().contains_key(&namespace) - { - continue; - } - if journal::JournalReader::recorded_len(&path).await != recorded { - continue; - } - let Ok(current_routes) = partition.routes().await else { - continue; - }; - let (Ok(current_routes), Ok(scanned_routes)) = ( - serde_json::to_value(¤t_routes), - serde_json::to_value(&routes), - ) else { - continue; - }; - if current_routes != scanned_routes { - continue; - } - let pending = daemon.pending_sessions.lock().values().any(|state| { - state.events.iter().any(|event| { - event.env.source == first.source && event.env.session_id == first.session_id - }) - }); - if pending { - continue; - } - - if routes.iter().any(|route| { - DeliveryKey::new(&first.source, &first.session_id, route) - .is_ok_and(|key| daemon.correlation.has_active_tools(&key.correlation_key())) - }) { - continue; - } - if !partition.collectible(recorded).await.unwrap_or(false) - || partition.close_storage().await.is_err() - { - continue; - } - drop(partition); - drop(reader); - // Delete the output partition first. A failed input removal can only - // cause idempotent replay; it cannot hide new captures behind an old receipt. - if tokio::fs::remove_file(&storage).await.is_err() { - continue; - } - for sidecar in [wal, storage.with_extension("sqlite-shm"), path] { - if let Err(error) = tokio::fs::remove_file(&sidecar).await { - if error.kind() != std::io::ErrorKind::NotFound { - tracing::warn!(%error,path=%sidecar.display(),"expired partition cleanup failed"); - } - } + for path in sessions { + if let Err(error) = collect_session(daemon, &path).await { + tracing::warn!(%error, path = %path.display(), "session storage cleanup failed"); } } } -// Authentication/discovery may have prevented subscription registration. Such -// captured routes are obligations too, even if all existing heads are complete. -async fn captured_routes_registered( - data_dir: &std::path::Path, - path: &std::path::Path, - recorded: u64, - heads: &[SessionRoute], -) -> bool { - let Ok(Some(mut reader)) = journal::JournalReader::open(path, recorded).await else { - return false; +/// Remove the storage of a cold source session that owes nothing: every +/// captured event is translated and every route has delivered every SpanOp. +/// A session with live actors, queued captures or active tools is retained. +pub(super) async fn collect_session(daemon: &Daemon, path: &std::path::Path) -> anyhow::Result<()> { + // Inspection must never create storage for a session that has none. + if !tokio::fs::try_exists(path).await? { + return Ok(()); + } + let session = crate::collections::SessionStorage::at(path).await?; + let Some((source, session_id)) = session.status().await?.owner() else { + // Output storage that no captured input ever claimed has no owner to + // complete it. Keep it only while it may still be in use. + drop(session); + if old(path, RETENTION).await { + crate::collections::SessionStorage::remove(path).await?; + } + return Ok(()); }; - loop { - match reader.next_record().await { - Ok(Some(record)) => { - if let journal::JournalRecord::Event(event) = record.record { - let env = journal::envelope_from_redacted(event); - let route = read_correlation_state(data_dir, &automatic_link_key(&env)) - .await - .and_then(|state| state.linked_route) - .or(env.route); - if route - .as_ref() - .is_none_or(|route| !heads.iter().any(|head| head.same_route(route))) - { - return false; - } - } - } - Ok(None) => return true, - Err(_) => return false, - } + let namespace = crate::ids::session_namespace(&source, &session_id); + let lock = daemon.session_lock(&source, &session_id); + let _guard = lock.lock().await; + let queued = daemon.pending_sessions.lock().values().any(|state| { + state + .events + .iter() + .any(|event| event.env.source == source && event.env.session_id == session_id) + }); + if queued { + return Ok(()); } + // A session that never ends keeps only what it still uses: expire stale + // capture identities, finished span metadata and stuck routes, even + // while the session is live. + let live: Vec = daemon + .sessions + .lock() + .keys() + .filter(|key| key.source == source && key.session_id == session_id) + .map(|key| key.route.clone()) + .collect(); + session.expire(RETENTION, live).await?; + if daemon.open_storage.lock().contains_key(&namespace) + || daemon.translations.lock().contains_key(&namespace) + { + return Ok(()); + } + let routes = session.routes().await?; + if routes.iter().any(|route| { + DeliveryKey::new(&source, &session_id, route) + .is_ok_and(|key| daemon.correlation.has_active_tools(&key.correlation_key())) + }) { + return Ok(()); + } + // Delivered payloads are already gone. What remains is the translator + // continuation and span metadata a resumed session needs to extend its + // trace instead of re-creating it, so keep it until the session goes cold. + // Output that no destination ever subscribed to can never be delivered. + let complete = routes.is_empty() || session.complete().await?; + if !complete || session.status().await?.idle_for <= RETENTION { + return Ok(()); + } + drop(session); + if crate::collections::SessionStorage::remove(path).await? { + tracing::debug!(session_id = %session_id, "completed session storage removed"); + } + Ok(()) } async fn retained_references(data_dir: &std::path::Path) -> anyhow::Result> { @@ -203,48 +144,56 @@ async fn retained_references(data_dir: &std::path::Path) -> anyhow::Result {} } } - let mut protected = HashSet::new(); - let mut sources = HashSet::new(); - let mut entries = match tokio::fs::read_dir(journal::journal_dir(data_dir)).await { - Ok(entries) => entries, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(protected), - Err(error) => return Err(error.into()), - }; - while let Some(entry) = entries.next_entry().await? { - if entry.path().extension().and_then(|v| v.to_str()) != Some("ndjson") { - continue; - } - let mut reader = journal::JournalReader::open( - &entry.path(), - journal::JournalReader::recorded_len(&entry.path()).await, - ) - .await?; - while let Some(record) = match reader.as_mut() { - Some(reader) => reader.next_record().await?, - None => None, - } { - if let journal::JournalRecord::Event(event) = record.record { - mirrors(&event.payload, &mut protected); - let env = journal::envelope_from_redacted(event); - let key = automatic_link_key(&env); - protected.insert(correlation_state_path(data_dir, &key)); - protected.insert(active_parent_snapshot_path(data_dir, &key)); - let storage = data_dir.join("pipeline").join(format!( - "{}.sqlite", - crate::ids::session_storage_id(&env.source, &env.session_id) - )); - if sources.insert((env.source.clone(), env.session_id.clone())) - && tokio::fs::try_exists(&storage).await? - { - let partition = crate::pipeline::journal::SpanJournal::open(&storage).await?; - for route in partition.routes().await? { - let key = DeliveryKey::new(&env.source, &env.session_id, &route)? - .correlation_key(); - protected.insert(correlation_state_path(data_dir, &key)); - protected.insert(active_parent_snapshot_path(data_dir, &key)); + // Consumed event records no longer own transcript or correlation references. + // Their durable continuation and source identity take over that ownership. + fn checkpoint_paths(value: &Value, root: &std::path::Path, protected: &mut HashSet) { + match value { + Value::String(value) if std::path::Path::new(value).starts_with(root) => { + protected.insert(value.into()); + } + Value::Object(fields) => { + for (key, value) in fields { + if std::path::Path::new(key).starts_with(root) { + protected.insert(key.into()); } + checkpoint_paths(value, root, protected); + } + } + Value::Array(values) => { + for value in values { + checkpoint_paths(value, root, protected); } } + _ => {} + } + } + let mut protected = HashSet::new(); + for path in crate::collections::SessionStorage::all(data_dir).await? { + let session = crate::collections::SessionStorage::at(&path).await?; + let Some(identity) = session.identity().await? else { + continue; + }; + mirrors(&identity.payload, &mut protected); + let tail = session.status().await?.event_tail; + let mut events = std::pin::pin!(session.read(0, tail).events()); + while let Some(event) = events.try_next().await? { + mirrors(&event.payload, &mut protected); + } + let env = journal::envelope_from_redacted(identity); + let key = automatic_link_key(&env); + protected.insert(correlation_state_path(data_dir, &key)); + protected.insert(active_parent_snapshot_path(data_dir, &key)); + if let Some(bytes) = session.continuation().await? { + checkpoint_paths( + &serde_json::from_slice(&bytes)?, + &data_dir.join("transcripts"), + &mut protected, + ); + } + for route in session.routes().await? { + let key = DeliveryKey::new(&env.source, &env.session_id, &route)?.correlation_key(); + protected.insert(correlation_state_path(data_dir, &key)); + protected.insert(active_parent_snapshot_path(data_dir, &key)); } } Ok(protected) @@ -357,7 +306,10 @@ pub(super) async fn drain_all(daemon: &Arc) { .collect(); let mut targets = HashMap::new(); for (key, source) in sources { - if let Ok(tail) = source.control(crate::journal::ControlKind::Retire).await { + if let Ok(tail) = source + .control(crate::pipeline::input::ControlKind::Retire) + .await + { targets.insert(key, tail); } } @@ -385,7 +337,7 @@ pub(super) async fn drain_all(daemon: &Arc) { } daemon.sessions.lock().clear(); daemon.translations.lock().clear(); - daemon.journals.lock().clear(); + daemon.open_storage.lock().clear(); daemon.source_inputs.lock().clear(); let (reply, done) = oneshot::channel(); if daemon @@ -431,6 +383,7 @@ pub(super) async fn probe_alive(endpoint: &std::path::Path) -> bool { #[cfg(test)] mod tests { use super::*; + use crate::pipeline::cursor::Cursor; use crate::{ translate::{SpanOp, SpanRow}, wire::Envelope, @@ -508,13 +461,11 @@ mod tests { async fn capture_is_durable_during_startup_and_recovery_stops_before_it() { let tmp = tempfile::tempdir().unwrap(); let mut env = event("resuming", SessionRoute::default()); - let path = journal::source_journal_path(tmp.path(), &env.source, &env.session_id); - let old_end = JournalWriter::open_path(&path) - .await - .unwrap() - .append(&env) - .await - .unwrap(); + let events = + crate::collections::SessionStorage::open(tmp.path(), &env.source, &env.session_id) + .await + .unwrap(); + let old_end = events.append(&env, None).await.unwrap().unwrap().through; let (daemon, ready) = paused_ingress(tmp.path()); env.ts_ms = 2; env.event = "next".into(); @@ -524,10 +475,15 @@ mod tests { .unwrap() .unwrap() ); - assert!(tokio::fs::read_to_string(&path) + let tail = events.status().await.unwrap().event_tail; + let captured: Vec<_> = events + .read(0, tail) + .events() + .map_ok(|event| event.event) + .try_collect() .await - .unwrap() - .contains("next")); + .unwrap(); + assert!(captured.iter().any(|event| event == "next")); assert!(daemon.translations.lock().is_empty()); assert!( daemon.source_inputs.lock().is_empty(), @@ -544,16 +500,9 @@ mod tests { daemon.settle_ingress().await; let source = daemon.translations.lock().values().next().unwrap().clone(); assert!(source.barrier().await.unwrap() > 0); - let storage = tmp.path().join("pipeline").join(format!( - "{}.sqlite", - crate::ids::session_storage_id("debug", "resuming") - )); - let partition = crate::pipeline::journal::SpanJournal::open(&storage) - .await - .unwrap(); assert_eq!( - partition.translated_through().await.unwrap(), - journal::JournalReader::recorded_len(&path).await + events.status().await.unwrap().translated_through, + events.status().await.unwrap().event_tail ); drain_all(&daemon).await; } @@ -613,35 +562,24 @@ mod tests { .barrier() .await .unwrap(); - let path = journal::source_journal_path(tmp.path(), &env.source, &env.session_id); - let storage = tmp.path().join("pipeline").join(format!( - "{}.sqlite", - crate::ids::session_storage_id(&env.source, &env.session_id) - )); - let partition = crate::pipeline::journal::SpanJournal::open(&storage) + let events = daemon + .storage_for(&env.source, &env.session_id) .await .unwrap(); assert_eq!( - partition.translated_through().await.unwrap(), - journal::JournalReader::recorded_len(&path).await + events.status().await.unwrap().translated_through, + events.status().await.unwrap().event_tail ); - let db = rusqlite::Connection::open(storage).unwrap(); - let count: usize = db - .query_row( - "SELECT count(*) FROM batches WHERE committed=1", - [], - |row| row.get(0), - ) - .unwrap(); let expected: Vec<_> = (slot..total).step_by(envs.len()).collect(); - assert_eq!(count, expected.len()); + let state = events.continuation().await.unwrap().unwrap(); + let state: Value = serde_json::from_slice(&state).unwrap(); if env.source == "debug" { - let actual: Vec<_> = partition - .read_after(0, total) + assert_eq!(state["native"]["event_seq"], expected.len() as u64); + let actual: Vec<_> = events + .stored() .await - .unwrap() .into_iter() - .filter_map(|(_, op)| { + .filter_map(|op| { let (SpanOp::Insert(row) | SpanOp::Merge(row)) = op; row.input?.get("index")?.as_u64() }) @@ -680,10 +618,16 @@ mod tests { .await .unwrap() .unwrap(); - let path = journal::source_journal_path(tmp.path(), &env.source, &env.session_id); - let content = tokio::fs::read_to_string(path).await.unwrap(); + let identity = daemon + .storage_for(&env.source, &env.session_id) + .await + .unwrap() + .identity() + .await + .unwrap() + .unwrap(); assert!( - content.contains("TranscriptUpdate"), + identity.event == "TranscriptUpdate", "late transcript must be journaled before shutdown" ); } @@ -752,64 +696,52 @@ mod tests { } #[tokio::test] - async fn retention_requires_complete_inactive_partitions_and_nonempty_heads() { + async fn completed_inactive_sessions_are_removed_and_every_obligation_retains_one() { for scenario in [ "no_heads", "unresolved", - "unregistered", + "second_unresolved", "held", "source_held", "untranslated", - "invisible", "active", "within_retention", "complete", ] { let tmp = tempfile::tempdir().unwrap(); let env = event(scenario, SessionRoute::default()); - let raw = journal::source_journal_path(tmp.path(), &env.source, &env.session_id); - let mut writer = JournalWriter::open_path(&raw).await.unwrap(); - let mut through = writer.append(&env).await.unwrap(); - if scenario == "unregistered" { - let mut other = env.clone(); - other - .route - .as_mut() - .unwrap() - .tags - .insert("not registered".into()); - through = writer.append(&other).await.unwrap(); - } - drop(writer); - let storage = tmp.path().join("pipeline").join(format!( - "{}.sqlite", - crate::ids::session_storage_id(&env.source, &env.session_id) - )); - let partition = crate::pipeline::journal::SpanJournal::open(&storage) - .await - .unwrap(); - let input = if scenario == "untranslated" { - through - 1 - } else { - through - }; - partition.begin(input, true).await.unwrap(); - partition - .append( - input, - &[SpanOp::Insert(SpanRow { + let events = + crate::collections::SessionStorage::open(tmp.path(), &env.source, &env.session_id) + .await + .unwrap(); + let through = events.append(&env, None).await.unwrap().unwrap().through; + events + .commit_translation(crate::collections::Translated { + input: through, + observation: true, + ops: vec![SpanOp::Insert(SpanRow { span_id: "stored".into(), ..Default::default() })], - ) + roots: Default::default(), + state: Some(b"null".to_vec()), + }) .await .unwrap(); - partition.commit(input).await.unwrap(); + if scenario == "untranslated" { + let mut later = env.clone(); + later.ts_ms += 1; + events.append(&later, None).await.unwrap().unwrap(); + } if scenario != "no_heads" { - let mut head = partition - .subscribe(env.route.as_ref().unwrap(), 0) + let mut head = Cursor::open(&events, env.route.as_ref().unwrap()) .await .unwrap(); + if scenario == "second_unresolved" { + let mut second = env.route.clone().unwrap(); + second.tags.insert("second".into()); + Cursor::open(&events, &second).await.unwrap(); + } if scenario != "unresolved" { head.next_batch(8) .await @@ -821,43 +753,51 @@ mod tests { .unwrap(); } if scenario == "held" { - partition + events .set_failure(&head.route, Some("held".into())) .await .unwrap(); } } if scenario == "source_held" { - partition + events .set_source_failure(Some("held".into())) .await .unwrap(); } - if scenario == "invisible" { - partition.begin(through + 1, true).await.unwrap(); - } - drop(partition); + drop(events); let daemon = Daemon::new( super::super::debug_serve_options("test", tmp.path()), tmp.path().into(), ); if scenario == "active" { daemon - .journal_writer_for(&env.source, &env.session_id) + .storage_for(&env.source, &env.session_id) .await .unwrap(); } - let age = if scenario == "within_retention" { - RETENTION - } else { - Duration::ZERO - }; - collect_partitions(&daemon, age).await; - assert_eq!(storage.exists(), scenario != "complete", "{scenario}"); - assert_eq!(raw.exists(), scenario != "complete", "{scenario}"); + let storage = + crate::collections::inspect::session_path(tmp.path(), &env.source, &env.session_id); + if scenario != "within_retention" { + crate::collections::inspect::Inspector::open(&storage) + .unwrap() + .age(RETENTION + Duration::from_secs(3600)) + .unwrap(); + } + collect_sessions(&daemon).await; + // Output no destination subscribed to can never be delivered. + let complete = matches!(scenario, "complete" | "no_heads"); + assert_eq!(storage.exists(), !complete, "{scenario}"); + for sidecar in ["sqlite-wal", "sqlite-shm"] { + assert!( + !complete || !storage.with_extension(sidecar).exists(), + "{scenario}: {sidecar}" + ); + } drain_all(&daemon).await; } } + #[tokio::test] async fn retained_inputs_protect_only_their_reconstruction_references() { for routed in [true, false] { @@ -874,10 +814,13 @@ mod tests { } env.payload = serde_json::json!({"_bt_transcript_mirror":{"mirror": retained,"through":8}}); - let raw = journal::source_journal_path(tmp.path(), "debug", "test"); - let mut writer = JournalWriter::open_path(&raw).await.unwrap(); - writer.append(&env).await.unwrap(); - drop(writer); + crate::collections::SessionStorage::open(tmp.path(), "debug", "test") + .await + .unwrap() + .append(&env, None) + .await + .unwrap() + .unwrap(); let key = automatic_link_key(&env); let state = PendingSession { events: vec![PendingEvent { diff --git a/bt-daemon/src/server/mod.rs b/bt-daemon/src/server/mod.rs index 2b25a34f..1a541088 100644 --- a/bt-daemon/src/server/mod.rs +++ b/bt-daemon/src/server/mod.rs @@ -22,8 +22,9 @@ use recovery::*; use rpc::*; use sessions::*; +use crate::collections::{EventRecord, SessionStorage}; use crate::dispatch::{hydrate_transcript_reference, Session, SessionOptions}; -use crate::journal::{self, JournalWriter}; +use crate::journal; use crate::sink::{BraintrustSinkConfig, BraintrustSinkFactory, DebugSinkFactory, SinkFactory}; use crate::translate::Registry; use crate::transport::{self, Listener, ServerStream}; @@ -102,7 +103,7 @@ struct SessionAuthState { lease: AuthLease, } -type JournalSlot = Arc>>>; +type StorageSlot = Arc>; pub struct Daemon { version: String, @@ -117,7 +118,8 @@ pub struct Daemon { /// Serializes daemon-side routing and actor creation independently of /// capture, which must never inherit actor or sink backpressure. dispatch_locks: Mutex>>>, - journals: Mutex>, + /// Open session storage by source-session namespace. + open_storage: Mutex>, source_inputs: Mutex>, claude_transcripts: Mutex>, managed_run_sessions: Mutex>>, @@ -135,7 +137,7 @@ pub struct Daemon { ingress_tx: mpsc::Sender, /// Earliest live append during startup, keyed by source journal path. /// Recovery must not absorb queued live events into its historical head. - startup_cutoffs: Mutex>>, + startup_cutoffs: Mutex>>, capture_buffer: Mutex, started: Instant, last_activity: Mutex, @@ -171,7 +173,7 @@ impl Daemon { route_aliases: Mutex::new(HashMap::new()), session_locks: Mutex::new(HashMap::new()), dispatch_locks: Mutex::new(HashMap::new()), - journals: Mutex::new(HashMap::new()), + open_storage: Mutex::new(HashMap::new()), source_inputs: Mutex::new(HashMap::new()), claude_transcripts: Mutex::new(HashMap::new()), managed_run_sessions: Mutex::new(HashMap::new()), diff --git a/bt-daemon/src/server/recovery.rs b/bt-daemon/src/server/recovery.rs index 2d525c2c..00bc4987 100644 --- a/bt-daemon/src/server/recovery.rs +++ b/bt-daemon/src/server/recovery.rs @@ -1,6 +1,7 @@ //! Startup recovery of journaled events the previous daemon did not finish. use super::*; +use futures::TryStreamExt; pub(super) async fn discover_unprocessed_journals(daemon: &Arc) -> Vec { let pending: Vec = daemon @@ -9,35 +10,60 @@ pub(super) async fn discover_unprocessed_journals(daemon: &Arc) -> Vec

storage.status().await.map(|status| status.owner()), + Err(error) => { + tracing::warn!(%error, path = %path.display(), "session storage cannot be recovered"); + continue; + } + }; + let Ok(Some((source, session_id))) = owner else { continue; - } - let recorded_len = daemon.journal_snapshot(&path).await; + }; + let Ok(events) = daemon.storage_for(&source, &session_id).await else { + continue; + }; + let Ok(status) = events.status().await else { + continue; + }; + let tail = status.event_tail; + let namespace = crate::ids::session_namespace(&source, &session_id); let recorded_len = daemon .startup_cutoffs .lock() .as_ref() - .and_then(|cutoffs| cutoffs.get(&path).copied()) - .map_or(recorded_len, |cutoff| recorded_len.min(cutoff)); + .and_then(|cutoffs| cutoffs.get(&namespace).copied()) + .map_or(tail, |cutoff| tail.min(cutoff)); if let Some(cutoffs) = daemon.startup_cutoffs.lock().as_mut() { - cutoffs.entry(path.clone()).or_insert(recorded_len); + cutoffs.entry(namespace).or_insert(recorded_len); } - let Ok(Some(mut reader)) = journal::JournalReader::open(&path, recorded_len).await else { - continue; - }; + let mut reader = events.read(0, recorded_len); let mut before = 0u64; - let mut acknowledged_by_route: HashMap = HashMap::new(); let mut latest_by_route: HashMap = HashMap::new(); - while let Ok(Some(entry)) = reader.next_record().await { - let through = entry.through; + if let Ok(Some(template)) = events.identity().await { + let env = journal::envelope_from_redacted(template); + daemon.remember_claude_transcripts(&env); + if let Some(route) = &env.route { + latest_by_route.insert( + serde_json::to_string(route).unwrap_or_default(), + PendingEvent { + env, + replay_through: recorded_len, + journal_through: recorded_len, + settings_through: Some(0), + }, + ); + } + } + while let Ok(Some(entry)) = reader.try_next().await { + let through = entry.id; match entry.record { - journal::JournalRecord::Event(redacted) => { + EventRecord::Event(redacted) => { let mut env = journal::envelope_from_redacted(redacted); let Some(source) = daemon.translators.canonical_source(&env.source) else { before = through; @@ -66,37 +92,15 @@ pub(super) async fn discover_unprocessed_journals(daemon: &Arc) -> Vec

{} - journal::JournalRecord::DeliveryCheckpoint { route, through } => { - let key = serde_json::to_string(&route).unwrap_or_default(); - let acknowledged = acknowledged_by_route.entry(key).or_default(); - *acknowledged = (*acknowledged).max(through); - } + EventRecord::Control(_) => {} } before = through; } // Heads are the authoritative subscriptions, including dormant routes // and canonical profile IDs absent from older captured envelopes. - let templates: Vec<_> = latest_by_route.values().cloned().collect(); - let mut sources = HashSet::new(); - for template in templates { - if !sources.insert((template.env.source.clone(), template.env.session_id.clone())) { - continue; - } - let span_path = daemon.data_dir.join("pipeline").join(format!( - "{}.sqlite", - crate::ids::session_storage_id(&template.env.source, &template.env.session_id) - )); - if !tokio::fs::try_exists(&span_path).await.unwrap_or(false) { - continue; - } - let Ok(journal) = crate::pipeline::journal::SpanJournal::open(&span_path).await else { - continue; - }; - let Ok(routes) = journal.routes().await else { - continue; - }; - for route in routes { + // Every record in one session's storage belongs to that session. + if let Some(template) = latest_by_route.values().next().cloned() { + for route in events.routes().await.unwrap_or_default() { let route_key = match serde_json::to_string(&route) { Ok(key) => key, Err(error) => { @@ -107,13 +111,11 @@ pub(super) async fn discover_unprocessed_journals(daemon: &Arc) -> Vec

) -> Vec

) -> Vec

journal - .route_complete(route, recorded_len) - .await - .unwrap_or(false), - _ => false, + let completed = match recovered_route.as_ref() { + Some(route) => { + let routes = events.routes().await.unwrap_or_default(); + if routes.iter().any(|head| head.same_route(route)) { + events + .route_complete(route, recorded_len) + .await + .unwrap_or(false) + } else { + // Only migrated input an earlier daemon delivered + // is translated before any route subscribes. + routes.is_empty() + && events.status().await.is_ok_and(|status| { + status.translated_through >= event.journal_through + }) + } } - } else { - acknowledged_by_route.get(&route).copied().unwrap_or(0) >= event.journal_through + None => false, }; if !completed { // Ordered controls after the final native event also belong to recovery. @@ -221,6 +220,7 @@ pub(super) async fn recover_unprocessed_journals(daemon: &Arc) { #[cfg(test)] pub(super) mod tests { use super::*; + use crate::pipeline::cursor::Cursor; use crate::translate::{SpanOp, SpanRow}; pub(crate) struct TestAuth; @@ -260,22 +260,14 @@ pub(super) mod tests { "payload":{}, "route":route, })) .unwrap(); - let raw = journal::source_journal_path(tmp.path(), "debug", "test"); - let mut writer = JournalWriter::open_path(&raw).await.unwrap(); - let through = writer.append(&env).await.unwrap(); - drop(writer); - let path = tmp.path().join("pipeline").join(format!( - "{}.sqlite", - crate::ids::session_storage_id("debug", "test"), - )); - let spans = crate::pipeline::journal::SpanJournal::open(&path) + let writer = crate::collections::SessionStorage::open(tmp.path(), "debug", "test") .await .unwrap(); - spans.begin(through, true).await.unwrap(); - spans - .append( + let through = writer.append(&env, None).await.unwrap().unwrap().through; + writer + .translated( through, - &[SpanOp::Insert(SpanRow { + vec![SpanOp::Insert(SpanRow { span_id: "stored".into(), name: "stored".into(), root_span_id: "stored".into(), @@ -285,11 +277,10 @@ pub(super) mod tests { ) .await .unwrap(); - spans.commit(through).await.unwrap(); - spans.subscribe(&route, 0).await.unwrap(); + Cursor::open(&writer, &route).await.unwrap(); let mut dormant = route.clone(); dormant.tags.insert("dormant".into()); - spans.subscribe(&dormant, 0).await.unwrap(); + Cursor::open(&writer, &dormant).await.unwrap(); let mut options = debug_serve_options("test", tmp.path()); options.auth_provider = Some(Arc::new(TestAuth)); @@ -311,13 +302,13 @@ pub(super) mod tests { recover_unprocessed_journals(&daemon).await; daemon.ingress_barrier().await; tokio::time::timeout(Duration::from_secs(5), async { - while !spans.route_complete(&dormant, through).await.unwrap() { + while !writer.route_complete(&dormant, through).await.unwrap() { tokio::time::sleep(Duration::from_millis(10)).await; } }) .await .unwrap(); - assert!(!spans.route_complete(&route, through).await.unwrap()); + assert!(!writer.route_complete(&route, through).await.unwrap()); assert_eq!(daemon.pending_sessions.lock()[&pending_key].events.len(), 1); assert!(daemon .sessions @@ -327,7 +318,8 @@ pub(super) mod tests { } #[tokio::test] async fn startup_preserves_corrected_settings_before_a_held_head_completes() { - use crate::pipeline::{journal::SpanJournal, recovery::Failure}; + use crate::collections::SessionStorage; + use crate::pipeline::{cursor::Cursor, recovery::Failure}; let tmp = tempfile::tempdir().unwrap(); let original = SessionRoute { destination: Some(crate::wire::TraceDestination::ProjectLogs { @@ -343,31 +335,31 @@ pub(super) mod tests { "payload":{}, "route":original })) .unwrap(); - let raw = journal::source_journal_path(tmp.path(), "debug", &env.session_id); - let mut writer = JournalWriter::open_path(&raw).await.unwrap(); - let first = writer.append(&env).await.unwrap(); + let writer = crate::collections::SessionStorage::open(tmp.path(), "debug", &env.session_id) + .await + .unwrap(); + let first = writer.append(&env, None).await.unwrap().unwrap().through; env.route = Some(corrected.clone()); env.event = "Stop".into(); env.ts_ms = 2; - let settings_through = writer.append(&env).await.unwrap(); + let settings_through = writer.append(&env, None).await.unwrap().unwrap().through; let tail = writer - .append_control(&journal::PipelineControl { - kind: journal::ControlKind::Checkpoint, - bounds: HashMap::new(), - }) - .await - .unwrap(); - drop(writer); - let path = tmp.path().join("pipeline").join(format!( - "{}.sqlite", - crate::ids::session_storage_id("debug", &env.session_id) - )); - let spans = SpanJournal::open(&path).await.unwrap(); - spans.begin(first, true).await.unwrap(); - spans .append( + crate::pipeline::input::PipelineControl { + kind: crate::pipeline::input::ControlKind::Checkpoint, + bounds: HashMap::new(), + }, + Some(settings_through), + ) + .await + .unwrap() + .unwrap() + .through; + let path = crate::collections::inspect::session_path(tmp.path(), "debug", &env.session_id); + writer + .translated( first, - &[SpanOp::Insert(SpanRow { + vec![SpanOp::Insert(SpanRow { span_id: "stored".into(), name: "stored".into(), root_span_id: "stored".into(), @@ -377,32 +369,30 @@ pub(super) mod tests { ) .await .unwrap(); - spans.commit(first).await.unwrap(); - spans.subscribe(&original, 0).await.unwrap(); + Cursor::open(&writer, &original).await.unwrap(); let lease = TestAuth .resolve(&original.auth, AuthResolveReason::Initial) .await .unwrap(); let failure = Failure::legacy("rejected row".into(), 1, &original.with_auth(lease.auth)); - spans + writer .set_failure( &serde_json::to_string(&original).unwrap(), Some(serde_json::to_string(&failure).unwrap()), ) .await .unwrap(); - spans - .reconfigure_held(&corrected, settings_through) + crate::pipeline::cursor::reconfigure_held(&writer, &corrected, settings_through) .await .unwrap(); // Crash window: the correction is durable, but no consumer has retried it. - spans.close().await.unwrap(); + drop(writer); let mut options = debug_serve_options("test", tmp.path()); options.auth_provider = Some(Arc::new(TestAuth)); let daemon = Daemon::new(options, tmp.path().into()); recover_unprocessed_journals(&daemon).await; daemon.ingress_barrier().await; - let restored = SpanJournal::open(&path).await.unwrap(); + let restored = SessionStorage::at(&path).await.unwrap(); assert_eq!( restored.route_settings(&original).await.unwrap().tags, corrected.tags @@ -438,9 +428,10 @@ pub(super) mod tests { "payload":{}, "route":original })) .unwrap(); - let raw = journal::source_journal_path(tmp.path(), "debug", &env.session_id); - let mut writer = JournalWriter::open_path(&raw).await.unwrap(); - let through = writer.append(&env).await.unwrap(); + let writer = crate::collections::SessionStorage::open(tmp.path(), "debug", &env.session_id) + .await + .unwrap(); + let through = writer.append(&env, None).await.unwrap().unwrap().through; drop(writer); let mut options = debug_serve_options("test", tmp.path()); options.auth_provider = Some(Arc::new(TestAuth)); @@ -450,8 +441,10 @@ pub(super) mod tests { .automatic_links .lock() .insert(key.clone(), linked.clone()); - let storage = tmp.path().join("pipeline"); - std::fs::write(&storage, "blocked storage path").unwrap(); + let storage = + crate::collections::inspect::Inspector::session(tmp.path(), "debug", &env.session_id) + .unwrap(); + storage.set_schema_version(999).unwrap(); assert!(accept_event( &daemon, PendingEvent { @@ -467,7 +460,7 @@ pub(super) mod tests { assert!(saved.linked_route.as_ref().unwrap().same_route(&linked)); assert_eq!(saved.recovery.unwrap().info(false).stage, "journal"); assert_eq!(daemon.pending_sessions.lock()[&key].events.len(), 1); - std::fs::remove_file(storage).unwrap(); + storage.restore_schema_version().unwrap(); tokio::time::timeout(Duration::from_secs(5), async { loop { let _ = retry_pending_sessions(&daemon).await; diff --git a/bt-daemon/src/server/rpc.rs b/bt-daemon/src/server/rpc.rs index eed7659f..bc87080f 100644 --- a/bt-daemon/src/server/rpc.rs +++ b/bt-daemon/src/server/rpc.rs @@ -467,6 +467,8 @@ impl Daemon { } } + /// Imports are captured like hooks. Finishing one waits for its captured + /// events to reach every matching delivery route and reports what they sent. async fn finish_import( self: &Arc, params: &crate::wire::ImportFinishParams, @@ -560,7 +562,7 @@ impl Daemon { .cloned(); if let Some(translation) = translation { translation - .control(crate::journal::ControlKind::Reset) + .control(crate::pipeline::input::ControlKind::Reset) .await .map_err(|error| anyhow::anyhow!(error))?; } diff --git a/bt-daemon/src/server/sessions.rs b/bt-daemon/src/server/sessions.rs index 63231e8b..38321b35 100644 --- a/bt-daemon/src/server/sessions.rs +++ b/bt-daemon/src/server/sessions.rs @@ -1,4 +1,4 @@ -//! Delivery keys and the per-session actors, journal writers and locks. +//! Delivery keys and the per-session actors, event collections and locks. use super::*; @@ -47,20 +47,13 @@ impl Daemon { if let Some(source) = self.translations.lock().get(&storage_key).cloned() { return Ok(source); } - let event_path = - journal::ensure_source_journal(&self.data_dir, &env.source, &env.session_id).await?; + let events = self.storage_for(&env.source, &env.session_id).await?; let native = crate::ids::native_session_id(&env.session_id); - let namespace = - if journal::legacy_journal_has_session(&self.data_dir, &env.source, &env.session_id) - .await - { - env.session_id.clone() - } else { - crate::ids::session_namespace(&env.source, native) - }; - let events = self - .journal_writer_for(&env.source, &env.session_id) - .await?; + let namespace = if events.status().await?.legacy_namespace { + env.session_id.clone() + } else { + crate::ids::session_namespace(&env.source, native) + }; let source = crate::pipeline::translation::Translation::spawn( crate::pipeline::translation::TranslationOptions { source: env.source.clone(), @@ -68,8 +61,7 @@ impl Daemon { namespace, version: self.version.clone(), data_dir: self.data_dir.clone(), - events, - event_path, + storage: events, input: self.source_input_for(&env.source, &env.session_id), registry: self.translators.clone(), correlation: self.correlation.clone(), @@ -106,11 +98,6 @@ impl Daemon { // appended, so replay covers prior source observations only. Every // destination consumes that shared observation stream, with its own // delivery checkpoint controlling which rows reach its sink. - let journal_path = - journal::ensure_source_journal(&self.data_dir, &env.source, &env.session_id).await?; - let legacy_through = - journal::JournalReader::acknowledged_through(&journal_path, replay_through, &route) - .await; let translation = self.translation_for(env).await?; let settings = translation.route_settings(&route).await?; let config = settings.with_auth(config.auth); @@ -128,7 +115,7 @@ impl Daemon { // Materialize historical output before seeding a released completion boundary. translation.advance(replay_through).await?; let _ = translation.barrier().await; - let input = translation.subscribe(&route, legacy_through).await?; + let input = translation.subscribe(&route).await?; let mut map = self.sessions.lock(); if let Some(s) = map.get(key) { return Ok(s.clone()); @@ -224,11 +211,7 @@ impl Daemon { self.claude_transcripts.lock().retain(|candidate, _| { candidate.source != key.source || candidate.session_id != key.session_id }); - self.journals.lock().remove(&journal::source_journal_path( - &self.data_dir, - &key.source, - &key.session_id, - )); + self.open_storage.lock().remove(&storage_key); let mut inputs = self.source_inputs.lock(); if inputs .get(&storage_key) @@ -263,45 +246,22 @@ impl Daemon { .collect() } - pub(super) async fn journal_writer_for( + /// The shared storage for a source session. Opening it imports any + /// legacy journal once, before capture or recovery can use it. + pub(super) async fn storage_for( &self, source: &str, session_id: &str, - ) -> anyhow::Result>> { - let path = journal::source_journal_path(&self.data_dir, source, session_id); + ) -> anyhow::Result { let slot = self - .journals + .open_storage .lock() - .entry(path.clone()) + .entry(crate::ids::session_namespace(source, session_id)) .or_default() .clone(); - // A recovery actor and capture may open the same source concurrently. - // Tail repair must finish exactly once before either can append. - let writer = slot - .get_or_try_init(|| async { - let path = - journal::ensure_source_journal(&self.data_dir, source, session_id).await?; - let writer = JournalWriter::open_path(&path).await?; - Ok::<_, anyhow::Error>(Arc::new(tokio::sync::Mutex::new(writer))) - }) - .await?; - Ok(writer.clone()) - } - - /// Take only the durable append position, never hold the writer while - /// reading/replaying records. Recheck after metadata I/O if it opened meanwhile. - pub(super) async fn journal_snapshot(&self, path: &std::path::Path) -> u64 { - let slot = self.journals.lock().get(path).cloned(); - if let Some(writer) = slot.and_then(|slot| slot.get().cloned()) { - return writer.lock().await.position(); - } - let recorded = journal::JournalReader::recorded_len(path).await; - let slot = self.journals.lock().get(path).cloned(); - if let Some(writer) = slot.and_then(|slot| slot.get().cloned()) { - recorded.min(writer.lock().await.position()) - } else { - recorded - } + slot.get_or_try_init(|| SessionStorage::open(&self.data_dir, source, session_id)) + .await + .cloned() } pub(super) fn source_input_for( @@ -316,18 +276,20 @@ impl Daemon { .clone() } - pub(super) async fn append_to_journal( + pub(super) async fn append_event( &self, env: &Envelope, - writer: &mut JournalWriter, - ) -> anyhow::Result { - let before = writer.position(); + events: &SessionStorage, + ) -> anyhow::Result> { + let Some(appended) = events.append(env, None).await? else { + return Ok(None); + }; if let Some(cutoffs) = self.startup_cutoffs.lock().as_mut() { - let path = journal::source_journal_path(&self.data_dir, &env.source, &env.session_id); - cutoffs.entry(path).or_insert(before); + cutoffs + .entry(crate::ids::session_namespace(&env.source, &env.session_id)) + .or_insert(appended.before); } - let through = writer.append(env).await?; - Ok(crate::pipeline::input::SourcePosition { before, through }) + Ok(Some(appended)) } pub(super) fn session_lock( diff --git a/bt-daemon/src/trace_runtime.rs b/bt-daemon/src/trace_runtime.rs index 45938ba5..75676bf8 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -1497,19 +1497,14 @@ mod tests { for corrupt in [false, true] { let daemon = TestDaemon::start(Arc::new(OtherProfileDaemonAuth)).await; let data = daemon._dir.path().join("data"); - let storage = data.join("pipeline"); + let db = + crate::collections::inspect::Inspector::session(&data, "codex", "storage-failure") + .unwrap(); if corrupt { - std::fs::create_dir_all(&storage).unwrap(); - std::fs::write( - storage.join(format!( - "{}.sqlite", - crate::ids::session_storage_id("codex", "storage-failure") - )), - "not a database", - ) - .unwrap(); + db.corrupt_checkpoint().unwrap(); } else { - std::fs::write(&storage, "blocked storage directory").unwrap(); + db.inject(crate::collections::inspect::Fault::Handoff) + .unwrap(); } daemon .forward_event("codex", "storage-failure", SessionRoute::default()) diff --git a/bt-daemon/src/translate/mod.rs b/bt-daemon/src/translate/mod.rs index 50f25391..87e8d6c9 100644 --- a/bt-daemon/src/translate/mod.rs +++ b/bt-daemon/src/translate/mod.rs @@ -142,6 +142,19 @@ pub enum SpanOp { Merge(SpanRow), } +impl SpanOp { + /// The row this op inserts or merges. + pub fn row(&self) -> &SpanRow { + let (Self::Insert(row) | Self::Merge(row)) = self; + row + } + + pub fn row_mut(&mut self) -> &mut SpanRow { + let (Self::Insert(row) | Self::Merge(row)) = self; + row + } +} + /// Cross-cutting per-session context handed to the translator on each call. /// The translator's own state lives in the translator instance; this carries /// only what the dispatcher owns. diff --git a/bt-daemon/tests/agent_integration.rs b/bt-daemon/tests/agent_integration.rs index f4a4c9d9..df5a5787 100644 --- a/bt-daemon/tests/agent_integration.rs +++ b/bt-daemon/tests/agent_integration.rs @@ -4,6 +4,8 @@ reason = "Integration test assertions and fixtures fail immediately on unexpected values." )] +#[path = "support/journal_store.rs"] +mod journal_store; mod support; use axum::http::StatusCode; @@ -1191,7 +1193,15 @@ async fn opencode_v2_subagent_is_nested() { "{}", String::from_utf8_lossy(&output.stderr) ); - let rows = world.wait_for_trace_delivery().await; + let rows = world + .wait_for_trace_rows_matching(|rows| { + rows.iter() + .any(|row| row["span_attributes"]["name"] == "OpenCode") + && rows + .iter() + .any(|row| row["metadata"]["is_subagent"] == true) + }) + .await; let root = rows .iter() .find(|r| r["span_attributes"]["name"] == "OpenCode") @@ -1524,20 +1534,19 @@ async fn opencode_v2_standalone_delivers_events_when_daemon_acknowledgements_are run.env("BRAINTRUST_DAEMON_SOCKET", &proxy_path); // Verify the journal boundary directly while acknowledgements are held. // The timeout bounds the test; it is not part of hook dispatch. - let journal_dir = world.temp_path("daemon/journal"); + let data_dir = world.temp_path("daemon"); let journaled = async { loop { - if let Ok(entries) = std::fs::read_dir(&journal_dir) { - if entries.flatten().any(|entry| { - std::fs::read_to_string(entry.path()).is_ok_and(|contents| { - contents.contains("session.execution.succeeded") - && contents.contains("opencode") - }) - }) { - break; - } + let data_dir = data_dir.clone(); + let captured = tokio::task::spawn_blocking(move || { + journal_store::has_completed_opencode_capture(&data_dir) + }) + .await + .unwrap(); + if captured { + break; } - tokio::task::yield_now().await; + tokio::time::sleep(std::time::Duration::from_millis(10)).await; } }; let (output, ()) = tokio::join!(world.output(&mut run), async { diff --git a/bt-daemon/tests/cursor_pipeline.rs b/bt-daemon/tests/cursor_pipeline.rs index 5e3ccb88..2f84551d 100644 --- a/bt-daemon/tests/cursor_pipeline.rs +++ b/bt-daemon/tests/cursor_pipeline.rs @@ -7,14 +7,17 @@ //! Cursor hooks freeze native transcript observations before journal ingress. //! Recovery must use those mirrors even after native files change or disappear. +#[path = "support/journal_store.rs"] +mod journal_store; + use async_trait::async_trait; use bt_daemon::wire::{ AuthSelection, BackendAuth, Envelope, FlushMode, SessionRoute, TraceDestination, }; use bt_daemon::{ debug_serve_options, flush_session, forward_envelope, run_serve, run_status, shutdown_daemon, - source_journal_path, AuthLease, AuthProvider, AuthResolveReason, HostInfo, ServeArgs, Sink, - SinkFactory, SpanOp, StatusArgs, + AuthLease, AuthProvider, AuthResolveReason, HostInfo, ServeArgs, Sink, SinkFactory, SpanOp, + StatusArgs, }; use serde_json::{json, Value}; use std::collections::BTreeSet; @@ -25,19 +28,10 @@ use std::time::Duration; /// Register a dormant route before any output exists, so completed peers cannot /// reclaim the recovery payloads this fixture deliberately leaves unresolved. fn seed_dormant_route(data: &Path, source: &str, session: &str, route: &SessionRoute) { - let journal = bt_daemon::source_journal_path(data, source, session); - let stem = journal.file_stem().unwrap().to_str().unwrap(); - let id = stem.rsplit("--").next().unwrap(); - std::fs::create_dir_all(data.join("pipeline")).unwrap(); - let db = - rusqlite::Connection::open(data.join("pipeline").join(format!("{id}.sqlite"))).unwrap(); - // The daemon upgrades this preparatory schema on first use. - db.execute_batch("CREATE TABLE heads(route TEXT PRIMARY KEY,position INTEGER NOT NULL DEFAULT 0,failure TEXT)").unwrap(); - db.execute( - "INSERT INTO heads(route,position) VALUES (?,0)", - [serde_json::to_string(route).unwrap()], - ) - .unwrap(); + bt_daemon::storage_inspect::Inspector::session(data, source, session) + .unwrap() + .add_head(route) + .unwrap(); } /// Smoke-test Cursor's portable direct command through the native Windows @@ -366,13 +360,13 @@ fn transcript(prompt: &str, response: &str) -> String { ) } -fn span_journal(data: &Path) -> rusqlite::Connection { +fn span_journal(data: &Path) -> bt_daemon::storage_inspect::Inspector { let path = std::fs::read_dir(data.join("pipeline")) .unwrap() .map(|entry| entry.unwrap().path()) .find(|path| path.extension().and_then(|ext| ext.to_str()) == Some("sqlite")) .unwrap(); - rusqlite::Connection::open(path).unwrap() + bt_daemon::storage_inspect::Inspector::open(&path).unwrap() } fn rows(path: &Path) -> Vec { @@ -454,7 +448,6 @@ async fn late_response_is_delivered_and_checkpointed_without_another_hook() { ] { send_with_flush_mode(&socket, event, ts_ms, payload, FlushMode::FlushOnTurnEnd).await; } - let journal = source_journal_path(&data, "cursor", "cursor-recovery"); // Ingress acknowledges capture before the out-of-band sink flush finishes. // Wait for delivery and its checkpoint without requesting an explicit flush. let completed = tokio::time::timeout(Duration::from_secs(5), async { @@ -462,22 +455,7 @@ async fn late_response_is_delivered_and_checkpointed_without_another_hook() { let delivered = buffered.lock().unwrap().delivered.iter().any(|op| { matches!(op, SpanOp::Merge(row) if row.output == Some(json!("late final answer"))) }); - let text = std::fs::read_to_string(&journal).unwrap_or_default(); - let mut position = 0; - let mut response_through = None; - - for line in text.split_inclusive('\n') { - position += line.len() as u64; - let Ok(row) = serde_json::from_str::(line) else { - continue; - }; - if row["event"] == "afterAgentResponse" { - response_through = Some(position); - } - } - let completed = delivered && response_through.is_some_and(|offset| { - span_journal(&data).query_row("SELECT min(position)>=(SELECT coalesce(max(position),0) FROM ops JOIN batches USING(input) WHERE committed=1) AND (SELECT coalesce(max(input),0) FROM batches WHERE committed=1)>=? FROM heads", [offset], |row|row.get::<_,bool>(0)).unwrap_or(false) - }); + let completed = delivered && span_journal(&data).delivered(); if delivered && completed { break; } @@ -694,28 +672,26 @@ async fn cursor_mirror_generations_and_capture_bounds_survive_deleted_native_rec assert!(llms .iter() .all(|row| row["parent_span_ids"].as_array().unwrap().len() == 1)); - let journal = source_journal_path(&data, "cursor", "cursor-recovery"); - let persisted = rows(&journal); - let observations = persisted - .iter() - .filter(|row| row["event"] == "stop") - .map(|row| &row["payload"]["_bt_transcript_mirror"]) - .collect::>(); - assert_eq!(observations.len(), 2); - assert_ne!(observations[0]["mirror"], observations[1]["mirror"]); - for observation in &observations { - assert_eq!(observation["through"], first.len()); - assert!(Path::new(observation["mirror"].as_str().unwrap()) - .starts_with(data.join("transcripts"))); + let checkpoint = journal_store::checkpoint(&data, "cursor", "cursor-recovery").unwrap(); + let bounds = checkpoint["bounds"].as_object().unwrap(); + assert_eq!( + bounds.len(), + 2, + "continuation owns both captured mirror generations" + ); + for (path, through) in bounds { + assert!(through.as_u64().unwrap() <= first.len() as u64); + assert!(Path::new(path).starts_with(data.join("transcripts"))); } - assert!(!std::fs::read_to_string(&journal) - .unwrap() - .contains("cursor-test-secret")); + assert_eq!( + checkpoint["native"]["transcript"]["offset"], + first.len() as u64 + ); + assert!(journal_store::pending(&data, "cursor", "cursor-recovery").is_empty()); + assert!(!checkpoint.to_string().contains("cursor-test-secret")); // Recover the dormant route as well as the primary route from the retained payloads. - span_journal(&data) - .execute("UPDATE heads SET position=0,failure=NULL", []) - .unwrap(); + span_journal(&data).rewind_heads().unwrap(); std::fs::remove_file(&native).unwrap(); std::fs::remove_file(&output).unwrap(); let recovered_daemon = start(&data, &socket).await; diff --git a/bt-daemon/tests/distributed_tracing.rs b/bt-daemon/tests/distributed_tracing.rs index ea02b8ec..02e65314 100644 --- a/bt-daemon/tests/distributed_tracing.rs +++ b/bt-daemon/tests/distributed_tracing.rs @@ -11,14 +11,16 @@ //! matrix in the ordinary test suite while still exercising IPC, journaling, //! translation, automatic routing, and sink configuration. +#[path = "support/journal_store.rs"] +mod journal_store; mod support; use async_trait::async_trait; use braintrust_sdk_rust::{SpanComponents, SpanObjectType}; use bt_daemon::wire::{AuthSelection, BackendAuth, Envelope, SessionConfig, TraceDestination}; use bt_daemon::{ - flush_session, forward_envelope, run_serve, run_status, shutdown_daemon, source_journal_path, - AuthLease, AuthProvider, AuthResolveReason, HostInfo, Registry, ServeArgs, ServeOptions, Sink, + flush_session, forward_envelope, run_serve, run_status, shutdown_daemon, AuthLease, + AuthProvider, AuthResolveReason, HostInfo, Registry, ServeArgs, ServeOptions, Sink, SinkFactory, SpanOp, SpanRow, SpanType, StatusArgs, }; use std::collections::HashMap; @@ -1332,14 +1334,11 @@ async fn ipc_initialize_pid_is_captured_without_hook_metadata() { shutdown_daemon(&socket).await.unwrap(); daemon.await.unwrap(); - let journal = tokio::fs::read_to_string(source_journal_path( + let row = journal_store::identity( &tmp.path().join("data"), "claude-code", "automatic-process-capture", - )) - .await - .unwrap(); - let row: serde_json::Value = serde_json::from_str(journal.lines().next().unwrap()).unwrap(); + ); let chain = row .pointer("/capture/process_chain") .and_then(serde_json::Value::as_array) @@ -2927,6 +2926,7 @@ async fn pending_restart_preserves_current_candidates_and_decided_legacy_links() let host = test_host(); let mut fixtures = DistributedFixtures::new(); let mut events = pending_child(&mut fixtures, &socket, &host).await; + flush("bounded-parent", &socket).await; let original_route = events[0].route.clone().unwrap(); let mut prompt = events[1].clone(); prompt.capture = events[0].capture.clone(); @@ -2941,11 +2941,28 @@ async fn pending_restart_preserves_current_candidates_and_decided_legacy_links() let (path, saved) = stored_pending_child(&data_dir, "bounded-child").await; let journal_path = bt_daemon::source_journal_path(&data_dir, "claude-code", "bounded-child"); - let journal = tokio::fs::read(&journal_path).await.unwrap(); + let journal = journal_store::pending(&data_dir, "claude-code", "bounded-child") + .iter() + .map(|value| format!("{value}\n")) + .collect::(); + assert!(!journal.is_empty()); + let backup = data_dir.parent().unwrap().join("pending-backup.sqlite"); + bt_daemon::storage_inspect::Inspector::open(&journal_store::path( + &data_dir, + "claude-code", + "bounded-child", + )) + .unwrap() + .backup(&backup) + .unwrap(); + let saved_database = std::fs::read(&backup).unwrap(); shutdown_daemon(&socket).await.unwrap(); daemon.await.unwrap(); // Restore the accepted-but-undelivered checkpoint, as after an abrupt // process exit. Shutdown itself is covered separately above. + tokio::fs::create_dir_all(journal_path.parent().unwrap()) + .await + .unwrap(); tokio::fs::write(&journal_path, journal).await.unwrap(); // This crash fixture rolls back source persistence as well as delivery. let id = journal_path @@ -2962,6 +2979,17 @@ async fn pending_restart_preserves_current_candidates_and_decided_legacy_links() tokio::fs::remove_file(path).await.unwrap(); } } + if format == "current" { + // A current-version crash preserves the SQLite collection and its + // exact IDs, rather than manufacturing a legacy NDJSON replacement. + tokio::fs::remove_file(&journal_path).await.unwrap(); + tokio::fs::write( + journal_store::path(&data_dir, "claude-code", "bounded-child"), + saved_database, + ) + .await + .unwrap(); + } let mut legacy_route = original_route.clone(); legacy_route.destination = Some(external_parent()); // A decided legacy link already put earlier rows in that parent's @@ -2972,7 +3000,7 @@ async fn pending_restart_preserves_current_candidates_and_decided_legacy_links() } else { original_route.destination.clone() }; - let state = if format == "current" { + let mut state = if format == "current" { saved } else { serde_json::json!({ @@ -2987,6 +3015,14 @@ async fn pending_restart_preserves_current_candidates_and_decided_legacy_links() } else { saved["events"].clone() }, }) }; + // Model an immediate crash/restart rather than spending the pending + // ancestry window on this fixture's graceful-shutdown rollback. + if format == "current" { + state["first_seen_ms"] = serde_json::json!(std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis() as i64); + } tokio::fs::write(path, serde_json::to_vec(&state).unwrap()) .await .unwrap(); diff --git a/bt-daemon/tests/pipeline.rs b/bt-daemon/tests/pipeline.rs index b3ac8737..a114434b 100644 --- a/bt-daemon/tests/pipeline.rs +++ b/bt-daemon/tests/pipeline.rs @@ -13,7 +13,11 @@ reason = "Test fixtures intentionally launch raw children." )] +#[path = "support/journal_store.rs"] +mod journal_store; + use async_trait::async_trait; +use bt_daemon::storage_inspect::{Inspector, Table}; use bt_daemon::wire::{ AuthSelection, AuthSource, BackendAuth, Envelope, SessionConfig, SessionRoute, }; @@ -187,19 +191,10 @@ impl Sink for RouteRecordingSink { /// Register a dormant route before any output exists, so completed peers cannot /// reclaim the recovery payloads this fixture deliberately leaves unresolved. fn seed_dormant_route(data: &Path, source: &str, session: &str, route: &SessionRoute) { - let journal = bt_daemon::source_journal_path(data, source, session); - let stem = journal.file_stem().unwrap().to_str().unwrap(); - let id = stem.rsplit("--").next().unwrap(); - std::fs::create_dir_all(data.join("pipeline")).unwrap(); - let db = - rusqlite::Connection::open(data.join("pipeline").join(format!("{id}.sqlite"))).unwrap(); - // The daemon upgrades this preparatory schema on first use. - db.execute_batch("CREATE TABLE heads(route TEXT PRIMARY KEY,position INTEGER NOT NULL DEFAULT 0,failure TEXT)").unwrap(); - db.execute( - "INSERT INTO heads(route,position) VALUES (?,0)", - [serde_json::to_string(route).unwrap()], - ) - .unwrap(); + Inspector::session(data, source, session) + .unwrap() + .add_head(route) + .unwrap(); } fn dummy_host() -> HostInfo { @@ -394,22 +389,17 @@ async fn start_daemon_at_with( } /// These fixtures contain one source partition. Read its durable progress directly. -fn pipeline_database(data_dir: &Path) -> rusqlite::Connection { +fn pipeline_database(data_dir: &Path) -> Inspector { let path = std::fs::read_dir(data_dir.join("pipeline")) .unwrap() .map(|entry| entry.unwrap().path()) .find(|path| path.extension().and_then(|ext| ext.to_str()) == Some("sqlite")) .unwrap(); - rusqlite::Connection::open(path).unwrap() + Inspector::open(&path).unwrap() } fn head_and_tail(data_dir: &Path) -> (u64, u64) { - pipeline_database(data_dir) - .query_row( - "SELECT position,(SELECT tail FROM publication WHERE id=1) FROM heads", - [], - |row| Ok((row.get(0)?, row.get(1)?)), - ) - .unwrap() + let db = pipeline_database(data_dir); + (db.heads()[0].position, db.published_tail()) } async fn wait_for(endpoint: &Path) { @@ -696,9 +686,8 @@ async fn rejected_flush_retries_the_span_journal_before_checkpointing() { shutdown(&socket).await; handle.await.unwrap(); - let journal_path = source_journal_path(&data_dir, "debug", session); - let journal = std::fs::read_to_string(&journal_path).unwrap(); - assert!(!journal.contains("delivery_checkpoint"), "{journal}"); + assert!(journal_store::pending(&data_dir, "debug", session).is_empty()); + assert!(journal_store::checkpoint(&data_dir, "debug", session).is_some()); assert!(sink.flushes.load(Ordering::SeqCst) > 1); let emitted_before_restart = sink.emitted.load(Ordering::SeqCst); @@ -751,8 +740,7 @@ async fn routed_sessions_resolve_multiple_profiles_without_journaling_credential assert_eq!(calls[1].1, AuthResolveReason::Initial); for session in ["work-session", "personal-session"] { - let journal = - std::fs::read_to_string(source_journal_path(&data_dir, "debug", session)).unwrap(); + let journal = journal_store::identity(&data_dir, "debug", session).to_string(); assert!(journal.contains("\"route\"")); assert!(!journal.contains("secret-")); assert!(!journal.contains("token_sha256_prefix")); @@ -791,12 +779,7 @@ async fn environment_routes_remain_environment_auth_without_journaling_credentia assert_eq!(calls[0].0.profile, None); assert_eq!(calls[0].0.org_name.as_deref(), Some("env-org")); - let journal = std::fs::read_to_string(source_journal_path( - &data_dir, - "debug", - "environment-session", - )) - .unwrap(); + let journal = journal_store::identity(&data_dir, "debug", "environment-session").to_string(); assert!(journal.contains(r#""source":"environment""#)); assert!(!journal.contains("secret-environment")); @@ -932,7 +915,7 @@ async fn one_session_reports_to_multiple_routes_and_orgs_concurrently() { } #[tokio::test] -async fn recovery_checkpoints_are_scoped_to_their_delivery_route() { +async fn legacy_checkpoints_skip_only_input_every_route_delivered() { let tmp = tempfile::tempdir().unwrap(); let data_dir = tmp.path().join("data"); let socket = test_endpoint(tmp.path()); @@ -969,15 +952,16 @@ async fn recovery_checkpoints_are_scoped_to_their_delivery_route() { .unwrap(); assert!(flushed.flushed, "flush did not complete: {flushed:?}"); + // Migration keeps one translation boundary for the session: work's later + // checkpoint must not suppress personal recovery, so work may see its + // delivered spans again (idempotent upserts of the same span IDs). let sinks = recording.sinks.lock().unwrap().clone(); - assert_eq!(sinks.len(), 1, "only the unacknowledged route is recovered"); - assert_eq!( - sinks[0].org.lock().unwrap().as_deref(), - Some("personal-org"), - "a later checkpoint for work must not suppress personal recovery" - ); + let personal = sinks + .iter() + .find(|sink| sink.org.lock().unwrap().as_deref() == Some("personal-org")) + .expect("the unacknowledged route is recovered"); assert!( - sinks[0].emitted.load(std::sync::atomic::Ordering::Relaxed) > 0, + personal.emitted.load(std::sync::atomic::Ordering::Relaxed) > 0, "the unacknowledged route must reach its sink" ); @@ -1206,7 +1190,7 @@ async fn auth_resolution_failure_is_reported_without_exposing_credentials() { assert!(status_error.contains("select a profile explicitly")); assert!(!status_error.contains("secret-")); assert!( - source_journal_path(&data_dir, "debug", "login-needed").exists(), + !journal_store::pending(&data_dir, "debug", "login-needed").is_empty(), "capture must remain durable even when background auth fails" ); { @@ -1238,34 +1222,13 @@ async fn events_are_ordered_journaled_and_emitted() { assert!(flushed.flushed, "flush did not complete: {flushed:?}"); assert_eq!(flushed.pending, 0); - // Journal: three events plus a durable delivery checkpoint, with only the - // non-secret route. Checkpoints are control records, not agent events. - let journal = source_journal_path(&data_dir, "debug", "sess-1"); - let jtext = std::fs::read_to_string(&journal).unwrap(); - let jlines: Vec<&str> = jtext.lines().filter(|l| !l.trim().is_empty()).collect(); - assert_eq!( - jlines.len(), - 4, - "expected 3 event lines plus one checkpoint, got {}", - jlines.len() - ); - assert!( - !jtext.contains("sk-TOP-SECRET-abc123"), - "token leaked into journal!" - ); - assert!(!jtext.contains("token_sha256_prefix")); - - let events: Vec = jlines - .iter() - .filter(|line| !line.contains("\"_bt_record_type\"")) - .map(|l| { - serde_json::from_str::(l).unwrap()["event"] - .as_str() - .unwrap() - .to_string() - }) - .collect(); - assert_eq!(events, vec!["SessionStart", "PostToolUse", "Stop"]); + // Translated events are gone; continuation replaces their replay history. + assert_eq!(journal_store::accepted(&data_dir, "debug", session), 3); + assert!(journal_store::pending(&data_dir, "debug", session).is_empty()); + assert!(!source_journal_path(&data_dir, "debug", session).exists()); + let identity = journal_store::identity(&data_dir, "debug", session).to_string(); + assert!(!identity.contains("sk-TOP-SECRET-abc123")); + assert!(!identity.contains("token_sha256_prefix")); // Spans: debug translator emits a root once + one span per event = 4. let spans = data_dir.join("spans").join("sess-1.ndjson"); @@ -1277,6 +1240,16 @@ async fn events_are_ordered_journaled_and_emitted() { "expected 4 span rows, got {}: {stext}", slines.len() ); + let events: Vec<_> = slines + .iter() + .map(|line| serde_json::from_str::(line).unwrap()) + .filter_map(|row| { + row["Insert"]["metadata"]["seq"] + .as_u64() + .map(|_| row["Insert"]["name"].as_str().unwrap().to_owned()) + }) + .collect(); + assert_eq!(events, vec!["SessionStart", "PostToolUse", "Stop"]); // The span rows carry the raw payload but never the auth token. assert!( !stext.contains("sk-TOP-SECRET-abc123"), @@ -1305,14 +1278,8 @@ async fn session_ids_longer_than_a_file_name_are_journaled_and_emitted() { let flushed = flush_session(&session, &socket, 5000).await.unwrap(); assert!(flushed.flushed, "flush did not complete: {flushed:?}"); - let jtext = std::fs::read_to_string(source_journal_path(&data_dir, "debug", &session)).unwrap(); - assert_eq!( - jtext - .lines() - .filter(|line| !line.contains("\"_bt_record_type\"")) - .count(), - 2 - ); + assert_eq!(journal_store::accepted(&data_dir, "debug", &session), 2); + assert!(journal_store::pending(&data_dir, "debug", &session).is_empty()); let spans: Vec<_> = std::fs::read_dir(data_dir.join("spans")) .unwrap() .map(|entry| std::fs::read_to_string(entry.unwrap().path()).unwrap()) @@ -1418,18 +1385,16 @@ async fn identical_native_ids_from_different_sources_are_isolated() { let claude_journal = source_journal_path(&data_dir, "claude-code", "shared-native-id"); assert_ne!(codex_journal, claude_journal); assert_eq!( - std::fs::read_to_string(codex_journal) - .unwrap() - .lines() - .count(), - 2 + journal_store::identity(&data_dir, "codex", "shared-native-id")["source"], + "codex" ); assert_eq!( - std::fs::read_to_string(claude_journal) - .unwrap() - .lines() - .count(), - 2 + journal_store::identity(&data_dir, "claude-code", "shared-native-id")["source"], + "claude-code" + ); + assert_ne!( + journal_store::path(&data_dir, "codex", "shared-native-id"), + journal_store::path(&data_dir, "claude-code", "shared-native-id") ); let rows = std::fs::read_to_string(data_dir.join("spans/shared-native-id.ndjson")).unwrap(); @@ -1463,10 +1428,10 @@ async fn distinct_sessions_are_isolated() { flush_session("a", &socket, 5000).await.unwrap(); flush_session("b", &socket, 5000).await.unwrap(); - let a = std::fs::read_to_string(source_journal_path(&data_dir, "debug", "a")).unwrap(); - let b = std::fs::read_to_string(source_journal_path(&data_dir, "debug", "b")).unwrap(); - assert_eq!(a.lines().filter(|l| !l.trim().is_empty()).count(), 3); - assert_eq!(b.lines().filter(|l| !l.trim().is_empty()).count(), 2); + assert_eq!(journal_store::accepted(&data_dir, "debug", "a"), 2); + assert_eq!(journal_store::accepted(&data_dir, "debug", "b"), 1); + assert!(journal_store::pending(&data_dir, "debug", "a").is_empty()); + assert!(journal_store::pending(&data_dir, "debug", "b").is_empty()); handle.abort(); } @@ -1698,16 +1663,10 @@ async fn hook_capture_stops_at_the_durable_journal_boundary() { matches!(accepted, Ok(Ok(()))), "turn-end capture waited for translation or flushing: {accepted:?}" ); - let journal = std::fs::read_to_string(source_journal_path( - &tmp.path().join("data"), - "debug", - "fast-capture", - )) - .unwrap(); assert_eq!( - journal.lines().count(), + journal_store::accepted(&tmp.path().join("data"), "debug", "fast-capture"), 2, - "hook returned before journaling" + "hook returned before durable admission" ); shutdown(&socket).await; handle.await.unwrap(); @@ -1740,13 +1699,10 @@ async fn saturated_ingress_uses_the_journal_as_its_bounded_overflow_queue() { .unwrap(); } - let journal = - std::fs::read_to_string(source_journal_path(&data_dir, "debug", "bounded-overflow")) - .unwrap(); assert_eq!( - journal.lines().count(), - EVENT_COUNT as usize, - "every hook returns only after its event reaches the journal" + journal_store::accepted(&data_dir, "debug", "bounded-overflow"), + EVENT_COUNT as u64, + "every accepted event is pending or represented by the continuation" ); gate.notify_one(); @@ -1899,15 +1855,11 @@ async fn shutdown_drains_then_retries_late_capture_on_replacement() { let shutdown_task = tokio::spawn(async move { shutdown_daemon(&shutdown_socket).await }); // Wait for proof that the server received shutdown and began draining. // A fixed sleep can expire before the client sends its request on busy CI. - let journal_path = source_journal_path(&data_dir, "debug", "drained-shutdown"); tokio::time::timeout(Duration::from_secs(5), async { loop { - let journal = tokio::fs::read_to_string(&journal_path).await.unwrap(); - if journal.lines().any(|line| { - serde_json::from_str::(line).is_ok_and(|record| { - record["_bt_record_type"] == "pipeline_control" && record["kind"] == "retire" - }) - }) { + if journal_store::checkpoint(&data_dir, "debug", "drained-shutdown") + .is_some_and(|state| state["last_control"]["kind"] == "retire") + { break; } tokio::time::sleep(Duration::from_millis(10)).await; @@ -1942,12 +1894,10 @@ async fn shutdown_drains_then_retries_late_capture_on_replacement() { late_event.await.unwrap().unwrap(); shutdown(&socket).await; replacement.await.unwrap(); - let journal = - std::fs::read_to_string(source_journal_path(&data_dir, "debug", "drained-shutdown")) - .unwrap(); - assert!( - journal.contains(r#""n":2"#), - "replacement daemon did not journal the retried event: {journal}" + assert_eq!( + journal_store::accepted(&data_dir, "debug", "drained-shutdown"), + 2, + "replacement did not durably process the retried event" ); } @@ -2003,15 +1953,12 @@ async fn cold_worker_rebuilds_acknowledged_journal_without_redelivery() { shutdown(&socket).await; first.await.unwrap(); - // A cold worker receives durable files only: event history plus SpanOps and heads. + // A cold worker receives only SQLite: continuation, pending output, and heads. let recovered_data_dir = tmp.path().join("recovered-data"); - let source = source_journal_path(&data_dir, "debug", "resume"); - let recovered_journal = source_journal_path(&recovered_data_dir, "debug", "resume"); - std::fs::create_dir_all(recovered_journal.parent().unwrap()).unwrap(); - std::fs::copy(source, &recovered_journal).unwrap(); + assert!(!source_journal_path(&data_dir, "debug", "resume").exists()); let db = pipeline_database(&data_dir); - db.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)").unwrap(); + db.checkpoint_wal().unwrap(); std::fs::create_dir_all(recovered_data_dir.join("pipeline")).unwrap(); for entry in std::fs::read_dir(data_dir.join("pipeline")).unwrap() { let path = entry.unwrap().path(); @@ -2032,15 +1979,11 @@ async fn cold_worker_rebuilds_acknowledged_journal_without_redelivery() { .unwrap(); flush_session("resume", &socket, 5000).await.unwrap(); - let journal = std::fs::read_to_string(recovered_journal).unwrap(); assert_eq!( - journal - .lines() - .filter(|line| !line.contains("\"_bt_record_type\"")) - .count(), - 2, - "the event history remains separate from ordered pipeline controls" + journal_store::accepted(&recovered_data_dir, "debug", "resume"), + 2 ); + assert!(journal_store::pending(&recovered_data_dir, "debug", "resume").is_empty()); let spans = std::fs::read_to_string(recovered_data_dir.join("spans/resume.ndjson")).unwrap(); let rows: Vec = spans .lines() @@ -2586,9 +2529,10 @@ async fn claude_journal_does_not_grow_with_the_transcript_on_every_turn() { flush_session("grow", &socket, 5000).await.unwrap(); let transcript_len = std::fs::metadata(&transcript).unwrap().len(); - let journal_len = std::fs::metadata(source_journal_path(&data_dir, "claude-code", "grow")) - .unwrap() - .len(); + let journal_len = journal_store::pending(&data_dir, "claude-code", "grow") + .iter() + .map(|value| value.to_string().len() as u64) + .sum::(); // Re-journaling the transcript every turn would put this near // TURNS * transcript_len / 2 (tens of megabytes). References are ~a few @@ -2725,15 +2669,10 @@ async fn managed_run_flush_is_scoped_to_its_accepted_sessions() { assert!(result.flushed, "managed run did not flush: {result:?}"); assert_eq!(result.pending, 0); let controls = |session| { - std::fs::read_to_string(source_journal_path( - &tmp.path().join("data"), - "debug", - session, - )) - .unwrap() - .lines() - .filter(|line| line.contains("pipeline_control")) - .count() + usize::from( + journal_store::checkpoint(&tmp.path().join("data"), "debug", session) + .is_some_and(|state| state["last_control"].is_object()), + ) }; assert_eq!(controls("run-a-main"), 1); assert_eq!(controls("run-a-child"), 1); @@ -3145,20 +3084,16 @@ async fn muse_managed_run_preserves_saved_settings_and_foreign_hooks() { assert!(!flushed.is_empty()); let mut main_session = false; for session in flushed.keys() { - let journal = source_journal_path(&daemon_dir.path().join("data"), "muse", session); - for line in std::fs::read_to_string(journal).unwrap().lines() { - let row: serde_json::Value = serde_json::from_str(line).unwrap(); - if row["source"] != "muse" { - continue; - } - assert_eq!( - row["route"]["destination"]["project_name"], - "muse-managed-test" - ); - assert!(row["managed_run_id"].as_str().is_some()); - assert_eq!(row["source_version"], native_version); - main_session |= row["event"] == "SessionStart"; - } + let data = daemon_dir.path().join("data"); + let row = journal_store::identity(&data, "muse", session); + assert_eq!( + row["route"]["destination"]["project_name"], + "muse-managed-test" + ); + assert!(row["managed_run_id"].as_str().is_some()); + assert_eq!(row["source_version"], native_version); + main_session |= journal_store::checkpoint(&data, "muse", session) + .is_some_and(|state| state["native"]["root_created"] == true); } assert!(main_session); assert!(flushed.values().copied().sum::() >= 1); @@ -3617,8 +3552,7 @@ async fn packaged_grok_hook_replays_bounded_transcripts_to_isolated_debug_routes 1, "the native session_end event must trigger one daemon-owned flush" ); - let decoy_journal_text = - std::fs::read_to_string(source_journal_path(&data_dir, "grok", "grok-decoy")).unwrap(); + let decoy_journal_text = journal_store::identity(&data_dir, "grok", "grok-decoy").to_string(); let decoy_spans_path = data_dir.join("spans/grok-decoy.ndjson"); let decoy_before_restart = std::fs::read(&decoy_spans_path).unwrap(); let decoy_text = String::from_utf8(decoy_before_restart.clone()).unwrap(); @@ -3661,96 +3595,26 @@ async fn packaged_grok_hook_replays_bounded_transcripts_to_isolated_debug_routes "replaying the primary route must not emit into the decoy debug sink" ); - let journal_text = - std::fs::read_to_string(source_journal_path(&data_dir, "grok", "grok-primary")).unwrap(); + let identity = journal_store::identity(&data_dir, "grok", "grok-primary"); + let journal_text = identity.to_string(); assert!(!journal_text.contains("secret-environment")); assert!(!journal_text.contains("token_sha256_prefix")); assert!(!journal_text.contains("decoy-route")); - let journal: Vec = journal_text - .lines() - .map(|line| serde_json::from_str(line).unwrap()) - .filter(|record: &serde_json::Value| record.get("_bt_record_type").is_none()) - .collect(); - assert_eq!(journal.len(), 2); - assert_eq!(journal[0]["source"], "grok"); - assert_eq!(journal[1]["source"], "grok"); - assert_eq!(journal[0]["source_version"], "1.0.13"); - assert_eq!(journal[1]["source_version"], "1.0.13"); - assert_eq!(journal[0]["plugin_version"], plugin_version); - assert_eq!(journal[1]["plugin_version"], plugin_version); - assert_eq!(journal[0]["event"], "stop"); - assert_eq!(journal[1]["event"], "session_end"); - assert_eq!( - journal[0]["route"]["additional_metadata"]["route_marker"], - "primary-route" - ); - - let first_mirrors = &journal[0]["payload"]["_bt_grok_transcript_mirrors"]; - let second_mirrors = &journal[1]["payload"]["_bt_grok_transcript_mirrors"]; + assert_eq!(identity["source"], "grok"); + assert_eq!(identity["source_version"], "1.0.13"); + assert_eq!(identity["plugin_version"], plugin_version); + assert_eq!(identity["event"], "session_end"); + assert!(journal_store::pending(&data_dir, "grok", "grok-primary").is_empty()); + let checkpoint = journal_store::checkpoint(&data_dir, "grok", "grok-primary").unwrap(); assert_eq!( - first_mirrors.as_object().unwrap().len(), - 2, - "the first hook must journal the available updates and system prompt mirrors" - ); - assert!(first_mirrors.get("events").is_none()); - assert_eq!( - first_mirrors["updates"]["through"], - first_updates_through as u64 - ); - assert_eq!(second_mirrors["updates"]["through"], updates.len() as u64); - assert!( - first_updates_through < updates.len(), - "updates must advance between lifecycle boundaries" - ); - assert_eq!( - first_mirrors["updates"]["path"], - primary_updates.to_str().unwrap() - ); - assert_eq!( - first_mirrors["updates"]["mirror"], second_mirrors["updates"]["mirror"], - "updates must append to one stable daemon-owned mirror" - ); - let updates_mirror = PathBuf::from(second_mirrors["updates"]["mirror"].as_str().unwrap()); - assert!(updates_mirror.starts_with(data_dir.join("transcripts"))); - assert_eq!( - std::fs::metadata(updates_mirror).unwrap().len(), + checkpoint["native"]["updates"]["offset"], updates.len() as u64 ); assert_eq!( - first_mirrors["system_prompt"]["through"], - system_prompt.len() as u64 - ); - assert_eq!( - second_mirrors["system_prompt"]["through"], - system_prompt.len() as u64 - ); - assert_eq!( - first_mirrors["system_prompt"]["path"], - primary_system_prompt.to_str().unwrap() - ); - assert_eq!( - first_mirrors["system_prompt"]["mirror"], second_mirrors["system_prompt"]["mirror"], - "the system prompt must retain one stable daemon-owned snapshot" - ); - let system_prompt_mirror = - PathBuf::from(second_mirrors["system_prompt"]["mirror"].as_str().unwrap()); - assert!(system_prompt_mirror.starts_with(data_dir.join("transcripts"))); - assert_eq!( - std::fs::read_to_string(system_prompt_mirror).unwrap(), - system_prompt - ); - - assert_eq!(second_mirrors["events"]["through"], events.len() as u64); - assert_eq!( - second_mirrors["events"]["path"], - primary_events.to_str().unwrap() - ); - let events_mirror = PathBuf::from(second_mirrors["events"]["mirror"].as_str().unwrap()); - assert!(events_mirror.starts_with(data_dir.join("transcripts"))); - assert_eq!( - std::fs::metadata(events_mirror).unwrap().len(), + checkpoint["native"]["events"]["offset"], events.len() as u64 ); + assert!(first_updates_through < updates.len()); wait_for_grok_enrichment(&primary_spans_path).await; let all_ops = read_span_ops(&primary_spans_path); @@ -4019,14 +3883,7 @@ async fn missing_credentials_recover_without_another_native_event() { .unwrap(); tokio::time::timeout(Duration::from_secs(5), async { loop { - let db = rusqlite::Connection::open(&db_path).unwrap(); - let count: u64 = db - .query_row( - "SELECT count(*) FROM ops JOIN batches USING(input) WHERE committed=1", - [], - |r| r.get(0), - ) - .unwrap(); + let count = Inspector::open(&db_path).unwrap().count(Table::Ops); if count >= 2 { break; } @@ -4228,12 +4085,10 @@ async fn clean_shutdown_delivers_the_shared_retirement_tail_to_every_route() { ); let (head, tail) = head_and_tail(&data_dir); let heads = pipeline_database(&data_dir) - .prepare("SELECT position FROM heads") - .unwrap() - .query_map([], |r| r.get::<_, u64>(0)) - .unwrap() - .collect::, _>>() - .unwrap(); + .heads() + .into_iter() + .map(|head| head.position) + .collect::>(); assert_eq!(heads.len(), 2); assert!( heads.iter().all(|position| *position == tail), @@ -4248,8 +4103,7 @@ async fn clean_shutdown_delivers_the_shared_retirement_tail_to_every_route() { #[tokio::test] async fn initial_span_storage_failure_reports_journal_and_recovers_without_native_input() { let (data, socket, handle, _tmp) = start_daemon().await; - let storage = data.join("pipeline"); - std::fs::write(&storage, "blocked storage path").unwrap(); + journal_store::block_translation(&data, "debug", "storage-open"); forward_envelope( &envelope("storage-open", "SessionStart", 1), &socket, @@ -4278,7 +4132,7 @@ async fn initial_span_storage_failure_reports_journal_and_recovers_without_nativ }) .await .unwrap(); - std::fs::remove_file(&storage).unwrap(); + journal_store::unblock_translation(&data, "debug", "storage-open"); tokio::time::timeout(Duration::from_secs(45), async { loop { if std::fs::read_to_string(data.join("spans/storage-open.ndjson")) @@ -4443,19 +4297,17 @@ async fn changed_settings_resume_the_original_rejected_route_through_ingress() { .await .unwrap(); let db = pipeline_database(&data); - let held: u64 = db.query_row("SELECT count(*) FROM heads WHERE failure IS NOT NULL OR position<(SELECT max(position) FROM ops JOIN batches USING(input) WHERE committed=1)", [], |r| r.get(0)).unwrap(); + let held = db.held_heads(); assert_eq!( held, 0, "both original and corrected subscriptions must complete" ); - let settings: String = db - .query_row( - "SELECT settings FROM heads WHERE settings IS NOT NULL", - [], - |r| r.get(0), - ) + let settings = db + .heads() + .into_iter() + .find_map(|head| head.settings) .unwrap(); - assert!(settings.contains("corrected")); + assert!(settings.to_string().contains("corrected")); drop(db); shutdown(&socket).await; handle.await.unwrap(); @@ -4540,13 +4392,11 @@ async fn changed_plugin_chain_resumes_the_original_held_route() { .await .unwrap(); let db = pipeline_database(&data); - let held: u64 = db - .query_row( - "SELECT count(*) FROM heads WHERE failure IS NOT NULL", - [], - |r| r.get(0), - ) - .unwrap(); + let held = db + .heads() + .iter() + .filter(|head| head.failure.is_some()) + .count(); assert_eq!(held, 0); shutdown(&socket).await; handle.await.unwrap(); @@ -4586,22 +4436,7 @@ async fn storage_failure_after_retirement_is_reported_and_recovers_without_nativ }) .await .unwrap(); - // Retirement removes the session from status before every storage handle - // closes. Windows may still deny renaming that directory briefly. - tokio::time::timeout(Duration::from_secs(5), async { - loop { - match std::fs::rename(data.join("pipeline"), data.join("saved-pipeline")) { - Ok(()) => break, - Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => { - tokio::time::sleep(Duration::from_millis(10)).await; - } - Err(error) => panic!("move retired storage: {error}"), - } - } - }) - .await - .unwrap(); - std::fs::write(data.join("pipeline"), "blocked storage path").unwrap(); + journal_store::block_translation(&data, "debug", "retired-failure"); forward_envelope( &envelope("retired-failure", "Stop", 2), &socket, @@ -4642,8 +4477,7 @@ async fn storage_failure_after_retirement_is_reported_and_recovers_without_nativ .sessions .iter() .any(|session| session.queued > 0 && session.last_error.is_some())); - std::fs::remove_file(data.join("pipeline")).unwrap(); - std::fs::rename(data.join("saved-pipeline"), data.join("pipeline")).unwrap(); + journal_store::unblock_translation(&data, "debug", "retired-failure"); tokio::time::timeout(Duration::from_secs(45), async { loop { if std::fs::read_to_string(data.join("spans/retired-failure.ndjson")) diff --git a/bt-daemon/tests/root_provenance.rs b/bt-daemon/tests/root_provenance.rs index 68ce06a5..a57e6fa1 100644 --- a/bt-daemon/tests/root_provenance.rs +++ b/bt-daemon/tests/root_provenance.rs @@ -456,12 +456,12 @@ async fn legacy_acknowledged_spans_receive_late_updates_without_inventing_origin let journal = source_journal_path(&data_dir, "claude-code", session); // Model a released pre-SpanOp-journal daemon: accepted native history and // a legacy delivery checkpoint, with no newer durable partition. - let raw = std::fs::read_to_string(&journal).unwrap(); - let mut history = raw - .lines() - .filter(|line| !line.contains("_bt_record_type")) - .map(|line| format!("{line}\n")) - .collect::(); + let mut history = format!( + "{}\n", + serde_json::to_string(&capture("UserPromptSubmit", "v1", "native1", 1_000).redacted()) + .unwrap() + ); + std::fs::create_dir_all(journal.parent().unwrap()).unwrap(); let through = history.len() as u64; history.push_str(&format!("{}\n",json!({"_bt_record_type":"delivery_checkpoint", "route":capture("UserPromptSubmit","v1","native1",1_000).route, "through":through}))); std::fs::write(&journal, &history).unwrap(); diff --git a/bt-daemon/tests/support/journal_store.rs b/bt-daemon/tests/support/journal_store.rs new file mode 100644 index 00000000..ce47986f --- /dev/null +++ b/bt-daemon/tests/support/journal_store.rs @@ -0,0 +1,90 @@ +#![allow( + dead_code, + reason = "Shared integration-test inspection helpers are used by different suites." +)] +//! Inspect recovery ownership in session storage from integration tests. +use bt_daemon::storage_inspect::{Fault, Inspector}; +use serde_json::Value; +use std::path::{Path, PathBuf}; + +pub fn path(data: &Path, source: &str, session: &str) -> PathBuf { + bt_daemon::storage_inspect::session_path(data, source, session) +} +fn existing(data: &Path, source: &str, session: &str) -> Option { + Inspector::existing(&path(data, source, session)) +} +/// The translator continuation for a session, if one has been saved. +pub fn checkpoint(data: &Path, source: &str, session: &str) -> Option { + existing(data, source, session)?.continuation() +} +pub fn identity(data: &Path, source: &str, session: &str) -> Value { + existing(data, source, session) + .and_then(|db| db.identity()) + .unwrap_or(Value::Null) +} +/// Captured events that translation has not yet consumed. +pub fn pending(data: &Path, source: &str, session: &str) -> Vec { + existing(data, source, session) + .map(|db| db.events()) + .unwrap_or_default() +} +/// Debug-source events accepted: consumed into the continuation, or pending. +pub fn accepted(data: &Path, source: &str, session: &str) -> u64 { + let Some(db) = existing(data, source, session) else { + return 0; + }; + let count = db + .continuation() + .and_then(|state| state["native"]["event_seq"].as_u64()) + .unwrap_or(0); + count + + db.events() + .iter() + .filter(|v| v.get("event").is_some()) + .count() as u64 +} +pub fn block_translation(data: &Path, source: &str, session: &str) { + Inspector::session(data, source, session) + .unwrap() + .inject(Fault::Handoff) + .unwrap(); +} +pub fn unblock_translation(data: &Path, source: &str, session: &str) { + Inspector::session(data, source, session) + .unwrap() + .clear(Fault::Handoff) + .unwrap(); +} + +// A native completion can still be queued, or already transferred into durable +// continuation state while its RPC acknowledgement is held by the test proxy. +pub fn has_completed_opencode_capture(data: &Path) -> bool { + let Ok(entries) = std::fs::read_dir(data.join("pipeline")) else { + return false; + }; + for entry in entries.flatten() { + if entry.path().extension().is_none_or(|ext| ext != "sqlite") { + continue; + } + let Some(db) = Inspector::existing(&entry.path()) else { + continue; + }; + let succeeded = |value: &Value| { + value["source"] == "opencode" && value["event"] == "session.execution.succeeded" + }; + if db.events().iter().any(succeeded) || db.identity().is_some_and(|v| succeeded(&v)) { + return true; + } + if db.continuation().is_some_and(|value| { + value["source"] == "opencode" + && value["native"]["v2"]["sessions"] + .as_object() + .is_some_and(|sessions| { + sessions.values().any(|session| session["idle"] == true) + }) + }) { + return true; + } + } + false +}