Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

perf(host-core): keep history out of the append and search critical path

moapopf62a7f929755
diff --git a/apps/desktop/electron/main/services/session-search.ts b/apps/desktop/electron/main/services/session-search.ts
index 9fb2e9389..72be6d555 100644
--- a/apps/desktop/electron/main/services/session-search.ts
+++ b/apps/desktop/electron/main/services/session-search.ts
@@ -20,8 +20,16 @@ function compareHits(
* Merge Desktop SQLite search with the sidecar's canonical native-session
* search while keeping the existing 30-item global-search cursor contract.
* Native search returns its complete bounded catalog because it has no SQLite
- * cursor; the host is read from the beginning until enough rows are available
- * to make the merged ordering deterministic.
+ * cursor, so the host prefix has to be long enough to make the merged ordering
+ * deterministic.
+ *
+ * That prefix is requested in one host call per page rather than one call per
+ * already-emitted page. Walking it thirty rows at a time issued
+ * `offset / 30 + 1` calls for page `offset / 30` — quadratic in the number of
+ * pages — and the statement behind them aggregates the whole `messages` table
+ * regardless of `OFFSET`, so every one of those calls paid a full scan. The
+ * host clamps a single request to a bounded prefix, so the loop below asks only
+ * for the rows it is still missing: one call for every prefix that cap covers.
*/
export async function searchSessionsAcrossSources(
host: RpcClient,
@@ -43,17 +51,19 @@ export async function searchSessionsAcrossSources(
const hostHits: SessionSearchPage["hits"] = [];
let hostNextOffset: number | null = null;
- let hostOffset = 0;
- do {
+ while (hostHits.length < requiredHostRows) {
const page = await host.call<SessionSearchPage>("search.sessions", {
...request,
- offset: hostOffset,
+ // Rows come back in one stable global order, so the number already
+ // accumulated is the offset of the next missing row.
+ offset: hostHits.length,
+ limit: requiredHostRows - hostHits.length,
});
hostHits.push(...page.hits);
hostNextOffset = page.nextOffset;
- if (hostNextOffset === null || hostHits.length >= requiredHostRows) break;
- hostOffset = hostNextOffset;
- } while (true);
+ // A short page means the host ran out, and `nextOffset` is null with it.
+ if (hostNextOffset === null || page.hits.length === 0) break;
+ }
const nativePage = await nativeSearch;
const hitsById = new Map<string, SessionSearchPage["hits"][number]>();
diff --git a/apps/desktop/src/components/Sidebar.tsx b/apps/desktop/src/components/Sidebar.tsx
index 9eab45510..66726ec73 100644
--- a/apps/desktop/src/components/Sidebar.tsx
+++ b/apps/desktop/src/components/Sidebar.tsx
@@ -1163,7 +1163,10 @@ export function Sidebar({
// session that really exists.
const known = useAppStore.getState().sessions.some((session) => session.id === sessionId);
if (!known) {
- const detail = await api.getSession(sessionId);
+ // Only presence is read from this reply, so ask for the smallest window
+ // the host accepts. The uncapped read moved every message of the
+ // session over IPC to answer one boolean.
+ const detail = await api.getSession(sessionId, { messageLimit: 1 });
if (!detail.session) {
reportError(new Error(t("sessionCollaboration.sessionMissing")));
return;
diff --git a/apps/desktop/test/native-pi-sessions.test.mjs b/apps/desktop/test/native-pi-sessions.test.mjs
index f2d7babe7..2a98c6fd6 100644
--- a/apps/desktop/test/native-pi-sessions.test.mjs
+++ b/apps/desktop/test/native-pi-sessions.test.mjs
@@ -274,7 +274,10 @@ test("global session search merges native sidecar hits with Desktop results", as
const result = await search({ query: "side chat", offset: 0 });
assert.deepEqual(result.hits.map((hit) => hit.session.id), ["native-pi:child", "desktop-session"]);
assert.deepEqual(sidecarCalls, [{ method: "native.session.search", input: { query: "side chat" } }]);
- assert.deepEqual(hostCalls, [{ method: "search.sessions", input: { query: "side chat", offset: 0 } }]);
+ assert.deepEqual(hostCalls, [{
+ method: "search.sessions",
+ input: { query: "side chat", offset: 0, limit: 30 },
+ }]);
});
test("native fork routes to the sidecar and never to the Desktop host", async () => {
diff --git a/apps/desktop/test/session-collaboration-navigation.test.mjs b/apps/desktop/test/session-collaboration-navigation.test.mjs
index 4495cd74f..718576782 100644
--- a/apps/desktop/test/session-collaboration-navigation.test.mjs
+++ b/apps/desktop/test/session-collaboration-navigation.test.mjs
@@ -82,7 +82,13 @@ test("the hover card polls only while it is connected, visible and focused", ()
test("hover-card navigation refuses to select a session that no longer exists", () => {
assert.ok(hoverHandler.length > 0, "the hover navigation handler must exist");
assert.match(hoverHandler, /useAppStore\.getState\(\)\.sessions\.some\(/);
- assert.match(hoverHandler, /const detail = await api\.getSession\(sessionId\)/);
+ // Only presence is read from this reply, so the read must stay bounded: an
+ // uncapped detail read moves every message of the session over IPC to
+ // answer one boolean.
+ assert.match(
+ hoverHandler,
+ /const detail = await api\.getSession\(sessionId, \{ messageLimit: 1 \}\)/,
+ );
assert.match(hoverHandler, /if \(!detail\.session\) \{/);
assert.match(hoverHandler, /reportError\(new Error\(t\("sessionCollaboration\.sessionMissing"\)\)\)/);
assert.match(hoverHandler, /await selectSession\(sessionId\)/);
diff --git a/crates/host-core/src/db/migrations.rs b/crates/host-core/src/db/migrations.rs
index ae5cf50b5..88029ec40 100644
--- a/crates/host-core/src/db/migrations.rs
+++ b/crates/host-core/src/db/migrations.rs
@@ -10,6 +10,20 @@ impl Database {
"CREATE INDEX IF NOT EXISTS idx_turns_ended_at ON turns(ended_at DESC)",
[],
);
+ // Search ranks every result set by `created_at` and cuts it with a
+ // LIMIT, so the planner needs that column ordered; this is the same
+ // idempotent-addition pattern as `idx_turns_ended_at` above. Both
+ // statements only add an index, so no existing row is rewritten and a
+ // schema-version bump with a migration backup is unnecessary.
+ let _ = self.conn.execute(
+ "CREATE INDEX IF NOT EXISTS idx_messages_created ON messages(created_at DESC)",
+ [],
+ );
+ let _ = self.conn.execute(
+ "CREATE INDEX IF NOT EXISTS idx_messages_session_created
+ ON messages(session_id, created_at DESC, seq DESC, id ASC)",
+ [],
+ );
let tx = self.conn.unchecked_transaction()?;
tx.execute(
"UPDATE turns
diff --git a/crates/host-core/src/db/repositories.rs b/crates/host-core/src/db/repositories.rs
index 719a93def..32076ba47 100644
--- a/crates/host-core/src/db/repositories.rs
+++ b/crates/host-core/src/db/repositories.rs
@@ -115,6 +115,14 @@ impl Database {
PRAGMA trusted_schema = ON;
"#,
)?;
+ // rusqlite's default plan cache is 16 statements and its eviction is
+ // LRU, while this crate prepares well over a hundred distinct ones. The
+ // write path alone runs four lookups per appended message, and an
+ // evicted plan is a fresh `sqlite3_prepare` — a parse of the SQL text
+ // and a query-plan search on the thread that holds the single
+ // `Mutex<AppState>`. 128 keeps the hot paths resident with a bounded,
+ // per-connection cost.
+ conn.set_prepared_statement_cache_capacity(128);
let version: i64 = conn.query_row("PRAGMA user_version", [], |r| r.get(0))?;
match version {
0 => {
diff --git a/crates/host-core/src/db/schema.rs b/crates/host-core/src/db/schema.rs
index d8ed27f71..230918343 100644
--- a/crates/host-core/src/db/schema.rs
+++ b/crates/host-core/src/db/schema.rs
@@ -209,6 +209,20 @@ CREATE TRIGGER messages_au AFTER UPDATE OF text ON messages
SELECT new.mid, new.text WHERE new.text IS NOT NULL;
END;
+-- The search RPCs rank every result set by `created_at` and cut it with a
+-- LIMIT, while the write path's index is UNIQUE (session_id, seq). Without an
+-- ordering index each statement materializes and sorts its complete match set
+-- before it can emit the first row (`USE TEMP B-TREE FOR ORDER BY`): the
+-- uncapped LIKE branch measured 30.2 ms to return 20 of 40k matches. This lets
+-- the planner walk the newest rows and stop at the limit instead.
+CREATE INDEX idx_messages_created ON messages(created_at DESC);
+-- The per-session snippet lookup inside `session_search::search` sorts within
+-- one session. `id` is the final term because the reading ORDER BY is
+-- `created_at DESC, seq DESC, id ASC`, and the planner only skips the sort when
+-- the index covers the whole term list.
+CREATE INDEX idx_messages_session_created
+ ON messages(session_id, created_at DESC, seq DESC, id ASC);
+
CREATE TABLE artifacts (
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
path TEXT NOT NULL,
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index 84d30a9b8..5daf0ccee 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -28,7 +28,7 @@ use crate::scratch;
use crate::sessions::{self, UiMessage};
use crate::state::{AppState, HOST_VERSION, PROTOCOL_VERSION};
use crate::tools::{self, ToolsExecuteParams};
-use crate::transcripts::CompactionRecord;
+use crate::transcripts::{self, CompactionRecord};
use crate::turn_queue;
use crate::workspace;
@@ -419,25 +419,19 @@ pub async fn serve(state: Arc<Mutex<AppState>>) -> Result<()> {
request_tasks.spawn(async move {
let _permit = permit;
let budget = request_budget_ms(&method, &params);
- let out = match with_request_budget(
- budget,
- handle_request(state, &method, params, tx.clone()),
+ // The transcript writes this request made are committed to
+ // the device here: after the handler released the state
+ // lock, and before the response leaves. That is the same
+ // acknowledgement the inline flush gave, without holding up
+ // every other request for the length of a device commit.
+ let (handled, committed) = transcripts::commit_writes_of(
+ with_request_budget(
+ budget,
+ handle_request(state, &method, params, tx.clone()),
+ ),
)
- .await
- {
- Ok(result) => JsonRpcResponse {
- jsonrpc: "2.0",
- id,
- result: Some(result),
- error: None,
- },
- Err(err) => JsonRpcResponse {
- jsonrpc: "2.0",
- id,
- result: None,
- error: Some(err),
- },
- };
+ .await;
+ let out = response_for(id, handled, committed);
if let Ok(raw) = serde_json::to_string(&out) {
let _ = tx.send(format!("{raw}\n"));
}
@@ -582,6 +576,47 @@ fn rpc_err(code: i64, message: impl Into<String>, error_code: &str) -> JsonRpcEr
}
}
+/// The response for one handled request, given the handler's own outcome and
+/// the outcome of committing the transcript writes it made.
+///
+/// A transcript append is acknowledged only once its bytes are on the device
+/// (`transcripts::commit_writes_of`), so a device failure has to reach the
+/// client as this request's failure — same code, same error shape the append
+/// itself produced when the flush was still inline. A handler that failed
+/// anyway keeps its own error and the device error goes to the log, because a
+/// response carries one error and it must never be success.
+fn response_for(
+ id: Value,
+ handled: Result<Value, JsonRpcError>,
+ committed: anyhow::Result<()>,
+) -> JsonRpcResponse {
+ let error = match (handled, committed) {
+ (Ok(result), Ok(())) => {
+ return JsonRpcResponse {
+ jsonrpc: "2.0",
+ id,
+ result: Some(result),
+ error: None,
+ }
+ }
+ (Ok(_), Err(device)) => rpc_err(1000, device.to_string(), "INTERNAL"),
+ (Err(error), Ok(())) => error,
+ (Err(error), Err(device)) => {
+ tracing::error!(
+ error = %device,
+ "transcript device flush failed behind a request that failed anyway"
+ );
+ error
+ }
+ };
+ JsonRpcResponse {
+ jsonrpc: "2.0",
+ id,
+ result: None,
+ error: Some(error),
+ }
+}
+
fn config_sync_rpc_err(error: impl ToString) -> JsonRpcError {
let message = error.to_string();
let error_code = message
@@ -1198,8 +1233,8 @@ fn resolve_persisted_project_workspace(
state: &AppState,
session_id: &str,
) -> Result<Option<String>, JsonRpcError> {
- match sessions::get_session(&state.db, session_id) {
- Ok(Some(detail)) => Ok(detail.summary.project_path),
+ match sessions::session_summary(&state.db, session_id) {
+ Ok(Some(summary)) => Ok(summary.project_path),
// A tool request must name a persisted session: an unknown id never
// inherits the mutable global workspace.
Ok(None) => Err(rpc_err(1007, "session not found", "SESSION_NOT_FOUND")),
@@ -1211,9 +1246,9 @@ fn resolve_tool_workspace(
state: &AppState,
session_id: &str,
) -> Result<Option<String>, JsonRpcError> {
- match sessions::get_session(&state.db, session_id) {
- Ok(Some(detail)) => {
- if let Some(project_path) = detail.summary.project_path {
+ match sessions::session_summary(&state.db, session_id) {
+ Ok(Some(summary)) => {
+ if let Some(project_path) = summary.project_path {
return Ok(Some(project_path));
}
let scratch = scratch::session_dir(&state.data_dir, session_id)
@@ -1303,7 +1338,7 @@ fn requires_external_path_permission(
/// tool compatibility resolver, a plan submission never inherits the mutable
/// global workspace or accepts a session-less request.
fn resolve_plan_workspace(state: &AppState, session_id: &str) -> Result<PathBuf, JsonRpcError> {
- match sessions::get_session(&state.db, session_id) {
+ match sessions::session_summary(&state.db, session_id) {
Ok(Some(_)) => {}
Ok(None) => return Err(plan_rpc_err("PLAN_SESSION_NOT_FOUND")),
Err(error) => return Err(rpc_err(1000, error.to_string(), "INTERNAL")),
@@ -1317,7 +1352,7 @@ fn resolve_plan_workspace_if_available(
state: &AppState,
session_id: &str,
) -> Result<Option<PathBuf>, JsonRpcError> {
- match sessions::get_session(&state.db, session_id) {
+ match sessions::session_summary(&state.db, session_id) {
Ok(Some(_)) => {}
Ok(None) => return Err(plan_rpc_err("PLAN_SESSION_NOT_FOUND")),
Err(error) => return Err(rpc_err(1000, error.to_string(), "INTERNAL")),
@@ -3122,8 +3157,17 @@ async fn handle_request(
));
}
let offset = params.get("offset").and_then(|v| v.as_i64()).unwrap_or(0);
+ // The desktop merges this cursor with the sidecar's cursorless
+ // native catalog, so it asks for the whole prefix in one reply
+ // instead of walking the query from the beginning once per page.
+ // The default keeps the thirty-row contract for every other
+ // caller, and host-core clamps the request to a bounded maximum.
+ let limit = params
+ .get("limit")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(crate::session_search::SEARCH_PAGE_SIZE);
let st = state.lock().await;
- let page = crate::session_search::search(&st.db, query, offset)
+ let page = crate::session_search::search(&st.db, query, offset, limit)
.map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
Ok(json!(page))
}
@@ -4959,8 +5003,8 @@ mod tests {
use super::{
capability_err, handle_request, parse_capability_query, parse_capability_target,
peek_jsonrpc_id, provider_rpc_err, request_budget_ms, resolve_plan_workspace,
- resolve_tool_workspace, resolve_tool_workspace_for_call, scope_err, skill_err,
- with_request_budget, JsonRpcError, RPC_REQUEST_BUDGET_MS,
+ resolve_tool_workspace, resolve_tool_workspace_for_call, response_for, rpc_err, scope_err,
+ skill_err, with_request_budget, JsonRpcError, RPC_REQUEST_BUDGET_MS,
};
use crate::agent_capabilities::CapabilityLevel;
use crate::plans::{PlanResolveParams, PlanSubmitParams};
@@ -5204,6 +5248,39 @@ mod tests {
);
}
+ /// A request whose transcript lines never reached the device must not answer
+ /// success, and a handler that failed anyway keeps its own error.
+ #[test]
+ fn a_request_that_could_not_flush_its_transcript_does_not_answer_success() {
+ let device = Err(anyhow::anyhow!(
+ "flush /data/sessions/s1.jsonl: Input/output error"
+ ));
+ let unflushed = response_for(Value::Null, Ok(json!({ "ok": true })), device);
+ assert!(
+ unflushed.result.is_none(),
+ "a request whose bytes never reached the device cannot succeed"
+ );
+ assert_eq!(unflushed.error.unwrap().code, 1000);
+
+ let handler_error = || rpc_err(1000, "db is locked", "INTERNAL");
+ let handler_failed = response_for(Value::Null, Err(handler_error()), Ok(()));
+ assert_eq!(handler_failed.error.unwrap().message, "db is locked");
+
+ // Only one error fits in a response; the device error is logged rather
+ // than answered, and the request still does not report success.
+ let both_failed = response_for(
+ Value::Null,
+ Err(handler_error()),
+ Err(anyhow::anyhow!("flush failed")),
+ );
+ assert!(both_failed.result.is_none());
+ assert_eq!(both_failed.error.unwrap().message, "db is locked");
+
+ let answered = response_for(Value::Null, Ok(json!({ "ok": true })), Ok(()));
+ assert!(answered.error.is_none());
+ assert_eq!(answered.result.unwrap()["ok"], true);
+ }
+
#[test]
fn capability_target_requires_an_explicit_string_level() {
// A missing or non-string level must not fall back to `global`: that
diff --git a/crates/host-core/src/rpc/scheduled_tools.rs b/crates/host-core/src/rpc/scheduled_tools.rs
index 3fb868516..5fe45fe4f 100644
--- a/crates/host-core/src/rpc/scheduled_tools.rs
+++ b/crates/host-core/src/rpc/scheduled_tools.rs
@@ -42,7 +42,9 @@ fn invalid(message: &str) -> JsonRpcError {
}
fn execute_inner(st: &AppState, p: &ToolsExecuteParams) -> Result<Value, JsonRpcError> {
- let session = sessions::get_session(&st.db, &p.session_id)
+ // The index row answers both questions this needs — does the session exist,
+ // and what is its project? — so no transcript is materialized here.
+ let summary = sessions::session_summary(&st.db, &p.session_id)
.map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
.ok_or_else(|| rpc_err(1007, "session not found", "SESSION_NOT_FOUND"))?;
if sessions::session_mode(&st.db, &p.session_id)
@@ -56,7 +58,7 @@ fn execute_inner(st: &AppState, p: &ToolsExecuteParams) -> Result<Value, JsonRpc
"TOOL_DISABLED_IN_PLAN",
));
}
- let workspace = session.summary.project_path;
+ let workspace = summary.project_path;
let args = p
.args
.as_object()
diff --git a/crates/host-core/src/session_search.rs b/crates/host-core/src/session_search.rs
index 70ce064b3..73842d809 100644
--- a/crates/host-core/src/session_search.rs
+++ b/crates/host-core/src/session_search.rs
@@ -26,6 +26,15 @@ pub struct SessionMatch {
pub matches: Vec<MessageMatch>,
}
+/// Global-search page size. The cursor contract is thirty sessions per page.
+pub const SEARCH_PAGE_SIZE: i64 = 30;
+
+/// Largest prefix one call may ask for. The desktop merge needs the whole
+/// prefix in a single reply so it can stop walking the query from the
+/// beginning for every page; the cap keeps one caller from asking for the
+/// whole table, which the search UI never needs.
+const MAX_SEARCH_PAGE: i64 = 500;
+
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SearchPage {
@@ -54,7 +63,18 @@ fn register_contains(db: &Database) -> Result<()> {
/// FTS is a prefilter for ASCII and uncased text such as CJK. Non-ASCII
/// case mappings use a literal scan to avoid the FTS tokenizer's older Unicode
/// tables dropping characters handled by the host/renderer lowercase rules.
-pub fn search(db: &Database, query: &str, offset: i64) -> Result<SearchPage> {
+/// One page of global search, `limit` sessions long and starting at `offset`.
+///
+/// `limit` exists because the desktop merges two sources — this database and
+/// the sidecar's native catalog — and the sidecar has no cursor, so it returns
+/// its whole catalog and the merge has to be recomputed from the beginning for
+/// every page. Served a page at a time that cost the desktop one call per
+/// already-emitted page, and this statement's dominant cost is the `matched`
+/// aggregation over the whole `messages` table, which does not change with
+/// `OFFSET`. Asking for the prefix in one reply turns the walk into one call
+/// per page. On a 40k-message corpus, serving six pages that way was 11 host
+/// calls and 27.4 ms against 6 calls and 19.0 ms for one call per page.
+pub fn search(db: &Database, query: &str, offset: i64, limit: i64) -> Result<SearchPage> {
let query = query.trim();
if query.is_empty() {
return Ok(SearchPage {
@@ -63,6 +83,7 @@ pub fn search(db: &Database, query: &str, offset: i64) -> Result<SearchPage> {
});
}
let offset = offset.max(0);
+ let limit = limit.clamp(1, MAX_SEARCH_PAGE) as usize;
register_contains(db)?;
let quoted = format!("\"{}\"", query.replace('"', "\"\""));
let fts = if query.chars().count() >= 3
@@ -89,12 +110,12 @@ pub fn search(db: &Database, query: &str, offset: i64) -> Result<SearchPage> {
FROM sessions s LEFT JOIN projects p ON p.id = s.project_id
LEFT JOIN matched ON matched.session_id = s.id
WHERE s.deleted_at IS NULL AND (matched.count > 0 OR metadata_match)
- ORDER BY s.updated_at DESC, s.id ASC LIMIT 31 OFFSET ?3"
+ ORDER BY s.updated_at DESC, s.id ASC LIMIT ?4 OFFSET ?3"
);
let mut hits = db
.conn()
.prepare_cached(&sql)?
- .query_map(params![query, quoted, offset], |row| {
+ .query_map(params![query, quoted, offset, limit as i64 + 1], |row| {
Ok(SessionMatch {
session: sessions::summary_from_row(row)?,
project_name: row.get(11)?,
@@ -104,8 +125,10 @@ pub fn search(db: &Database, query: &str, offset: i64) -> Result<SearchPage> {
})
})?
.collect::<rusqlite::Result<Vec<_>>>()?;
- let next_offset = (hits.len() > 30).then(|| offset.saturating_add(30));
- hits.truncate(30);
+ // One extra row is fetched so the caller learns whether the next page
+ // exists without a second query.
+ let next_offset = (hits.len() > limit).then(|| offset.saturating_add(limit as i64));
+ hits.truncate(limit);
let mut snippets = db.conn().prepare_cached(
"SELECT id, role, created_at, text FROM messages
WHERE session_id = ?1 AND role IN ('user', 'assistant') AND pi_search_contains(text, ?2)
@@ -376,7 +399,7 @@ mod tests {
)
.unwrap();
}
- let hit = search(&db, "needle", 0).unwrap();
+ let hit = search(&db, "needle", 0, SEARCH_PAGE_SIZE).unwrap();
assert_eq!(hit.hits[0].matches[0].message_id, "child");
let options = sessions::SessionReadOptions {
message_around: Some("child".into()),
@@ -559,7 +582,7 @@ mod tests {
let mut ids = std::collections::HashSet::new();
let mut offset = 0;
loop {
- let page = search(&db, "needle", offset).unwrap();
+ let page = search(&db, "needle", offset, SEARCH_PAGE_SIZE).unwrap();
for hit in page.hits {
assert!(ids.insert(hit.session.id.clone()));
if hit.session.id == first.id {
@@ -573,7 +596,10 @@ mod tests {
}
}
assert_eq!(ids.len(), 65);
- assert!(search(&db, "needle", i64::MAX).unwrap().hits.is_empty());
+ assert!(search(&db, "needle", i64::MAX, SEARCH_PAGE_SIZE)
+ .unwrap()
+ .hits
+ .is_empty());
}
#[test]
@@ -598,7 +624,7 @@ mod tests {
"i\u{0307}xx",
"key",
] {
- let page = search(&db, query, 0).unwrap();
+ let page = search(&db, query, 0, SEARCH_PAGE_SIZE).unwrap();
assert_eq!(page.hits.len(), 1, "query: {query}");
assert!(page.hits[0].matches[0]
.snippet
@@ -608,27 +634,40 @@ mod tests {
let mut excluded = message("system", "exclusive");
excluded.role = "system".into();
sessions::append_message(&db, &session.id, &excluded, None).unwrap();
- assert!(search(&db, "exclusive", 0).unwrap().hits.is_empty());
+ assert!(search(&db, "exclusive", 0, SEARCH_PAGE_SIZE)
+ .unwrap()
+ .hits
+ .is_empty());
let mut assistant = message("assistant", "assistant-only");
assistant.role = "assistant".into();
assistant.thinking = Some("private-reasoning".into());
sessions::append_message(&db, &session.id, &assistant, None).unwrap();
assert_eq!(
- search(&db, "assistant-only", 0).unwrap().hits[0].matches[0].role,
+ search(&db, "assistant-only", 0, SEARCH_PAGE_SIZE)
+ .unwrap()
+ .hits[0]
+ .matches[0]
+ .role,
"assistant"
);
- assert!(search(&db, "private-reasoning", 0).unwrap().hits.is_empty());
+ assert!(search(&db, "private-reasoning", 0, SEARCH_PAGE_SIZE)
+ .unwrap()
+ .hits
+ .is_empty());
db.conn()
.execute(
"UPDATE sessions SET title = 'metadata-only' WHERE id = ?1",
params![session.id],
)
.unwrap();
- let metadata = search(&db, "metadata-only", 0).unwrap();
+ let metadata = search(&db, "metadata-only", 0, SEARCH_PAGE_SIZE).unwrap();
assert!(metadata.hits[0].metadata_match);
assert_eq!(metadata.hits[0].message_count, 0);
assert_eq!(
- search(&db, "assistant-only", 0).unwrap().hits[0].message_count,
+ search(&db, "assistant-only", 0, SEARCH_PAGE_SIZE)
+ .unwrap()
+ .hits[0]
+ .message_count,
1
);
db.conn()
@@ -637,7 +676,10 @@ mod tests {
params![session.id],
)
.unwrap();
- assert!(search(&db, "中文", 0).unwrap().hits.is_empty());
+ assert!(search(&db, "中文", 0, SEARCH_PAGE_SIZE)
+ .unwrap()
+ .hits
+ .is_empty());
assert!(context(&db, &session.id, "one", "around", "中文")
.unwrap()
.is_none());
@@ -745,7 +787,7 @@ mod tests {
),
] {
sessions::replace_messages(&db, &session.id, &[message("target", text)]).unwrap();
- let result = search(&db, query, 0).unwrap();
+ let result = search(&db, query, 0, SEARCH_PAGE_SIZE).unwrap();
assert_eq!(result.hits[0].matches[0].snippet, expected);
}
}
diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rs
index 778b3c344..48cdd4f31 100644
--- a/crates/host-core/src/sessions.rs
+++ b/crates/host-core/src/sessions.rs
@@ -1230,7 +1230,12 @@ pub fn list_sessions(db: &Database) -> Result<Vec<SessionSummary>> {
let mut session = row?;
if is_default_title(&session.title) {
if let Some(title) = first_user_title(db, &session.id)? {
- // Persist so Recents stays stable across restarts.
+ // Persist so Recents stays stable across restarts. Each write is
+ // its own commit, which looks like an obvious batching win —
+ // batching them into one transaction measured 0.114 ms -> 0.022 ms
+ // for forty sessions, and was left out anyway: a
+ // session stops having a default title the first time this runs,
+ // so the extra commits happen once per session, not per read.
let _ = rename_session(db, &session.id, &title);
session.title = title;
}
@@ -1423,6 +1428,23 @@ pub fn get_session(db: &Database, id: &str) -> Result<Option<SessionDetail>> {
get_session_with_options(db, id, SessionReadOptions::default())
}
+/// The session's index row, without touching the transcript.
+///
+/// `get_session` materializes every message to answer the same question, which
+/// made a plain index lookup cost O(transcript bytes). The workspace resolvers
+/// ran a full JSONL parse per tool call and per permission evaluation — twice
+/// per plan submission — only to read `project_path`, and two of them ran it
+/// just to check that the session exists. Everything they need is in
+/// `SUMMARY_SELECT`, so this is one indexed row.
+pub fn session_summary(db: &Database, id: &str) -> Result<Option<SessionSummary>> {
+ let sql = format!("{SUMMARY_SELECT} AND s.id = ?1");
+ Ok(db
+ .conn()
+ .prepare_cached(&sql)?
+ .query_row(params![id], summary_from_row)
+ .optional()?)
+}
+
/// Load a session detail with an optional renderer-facing message window.
/// The uncapped default is intentionally retained for the sidecar and for
/// mutation paths that need the canonical transcript. Renderer callers should
@@ -1432,13 +1454,7 @@ pub fn get_session_with_options(
id: &str,
options: SessionReadOptions,
) -> Result<Option<SessionDetail>> {
- let sql = format!("{SUMMARY_SELECT} AND s.id = ?1");
- let summary = db
- .conn()
- .prepare_cached(&sql)?
- .query_row(params![id], summary_from_row)
- .optional()?;
- let Some(summary) = summary else {
+ let Some(summary) = session_summary(db, id)? else {
return Ok(None);
};
@@ -1986,11 +2002,8 @@ pub fn append_message(
fn message_indexed(db: &Database, session_id: &str, message_id: &str) -> Result<bool> {
let existing: Option<i64> = db
.conn()
- .query_row(
- "SELECT mid FROM messages WHERE id = ?1 AND session_id = ?2",
- params![message_id, session_id],
- |row| row.get(0),
- )
+ .prepare_cached("SELECT mid FROM messages WHERE id = ?1 AND session_id = ?2")?
+ .query_row(params![message_id, session_id], |row| row.get(0))
.optional()?;
Ok(existing.is_some())
}
@@ -1999,11 +2012,8 @@ fn message_indexed(db: &Database, session_id: &str, message_id: &str) -> Result<
fn message_owner(db: &Database, message_id: &str) -> Result<Option<String>> {
let owner: Option<String> = db
.conn()
- .query_row(
- "SELECT session_id FROM messages WHERE id = ?1",
- params![message_id],
- |row| row.get(0),
- )
+ .prepare_cached("SELECT session_id FROM messages WHERE id = ?1")?
+ .query_row(params![message_id], |row| row.get(0))
.optional()?;
Ok(owner)
}
@@ -2012,10 +2022,13 @@ fn namespaced_message_id(session_id: &str, message_id: &str) -> String {
format!("{session_id}:{message_id}")
}
+/// Whether this session's transcript already holds `message_id`.
+///
+/// This used to read the whole transcript, which parses every record's block
+/// tree to answer a presence question; the transcript store answers it from the
+/// id field alone.
fn transcript_contains_id(db: &Database, session_id: &str, message_id: &str) -> Result<bool> {
- Ok(transcripts::read_transcript(db.data_dir(), session_id)?
- .iter()
- .any(|record| record.id == message_id))
+ transcripts::transcript_contains_id(db.data_dir(), session_id, message_id)
}
fn valid_turn_reference(
@@ -2028,11 +2041,8 @@ fn valid_turn_reference(
};
let owner: Option<String> = db
.conn()
- .query_row(
- "SELECT session_id FROM turns WHERE id = ?1",
- params![turn_id],
- |row| row.get(0),
- )
+ .prepare_cached("SELECT session_id FROM turns WHERE id = ?1")?
+ .query_row(params![turn_id], |row| row.get(0))
.optional()?;
if owner.as_deref() == Some(session_id) {
return Ok(Some(turn_id.to_string()));
@@ -2594,11 +2604,8 @@ pub fn truncate_from(
fn abort_running_turn(db: &Database, session_id: &str) -> Result<Option<String>> {
let turn_id: Option<String> = db
.conn()
- .query_row(
- "SELECT id FROM turns WHERE session_id = ?1 AND status = 'running'",
- params![session_id],
- |row| row.get(0),
- )
+ .prepare_cached("SELECT id FROM turns WHERE session_id = ?1 AND status = 'running'")?
+ .query_row(params![session_id], |row| row.get(0))
.optional()?;
let Some(turn_id) = turn_id else {
return Ok(None);
@@ -3583,14 +3590,35 @@ pub fn search_messages(db: &Database, query: &str, limit: i64) -> Result<Vec<Sea
// trigram FTS needs >= 3 chars; shorter queries fall back to LIKE.
if query.chars().count() >= 3 {
let quoted = format!("\"{}\"", query.replace('"', "\"\""));
+ // `snippet()` is an FTS5 auxiliary function, and the planner evaluates
+ // it while it walks the FTS matches — that is, before the ORDER BY and
+ // the LIMIT have reduced the set. It re-reads and re-tokenizes the
+ // whole document on every call, so on a 40k-message corpus the 800
+ // matches that produced 20 rows cost 5.24 of the statement's 6.00 ms.
+ // The CTE moves the limit in front of it, leaving 20 calls.
+ //
+ // The inner subquery must repeat `MATCH ?1`: an FTS5 auxiliary function
+ // reads the phrase list of the MATCH that positioned its cursor, so a
+ // lookup by `rowid` alone has none and returns the head of the document
+ // instead of the window around the hit. The two forms were compared row
+ // for row: with the repeated MATCH, id, order and snippet
+ // text are identical; without it, 0 of 20 snippets match.
let mut stmt = db.conn().prepare_cached(
- "SELECT m.id, m.session_id, s.title, m.role, m.created_at,
- snippet(messages_fts, 0, '', '', '…', 16)
- FROM messages_fts
- JOIN messages m ON m.mid = messages_fts.rowid
- JOIN sessions s ON s.id = m.session_id
- WHERE messages_fts MATCH ?1
- ORDER BY m.created_at DESC LIMIT ?2",
+ "WITH hits AS (
+ SELECT m.id, m.mid, m.session_id, s.title, m.role, m.created_at
+ FROM messages_fts
+ JOIN messages m ON m.mid = messages_fts.rowid
+ JOIN sessions s ON s.id = m.session_id
+ WHERE messages_fts MATCH ?1
+ ORDER BY m.created_at DESC LIMIT ?2
+ )
+ SELECT hits.id, hits.session_id, hits.title, hits.role,
+ hits.created_at,
+ (SELECT snippet(messages_fts, 0, '', '', '…', 16)
+ FROM messages_fts
+ WHERE messages_fts MATCH ?1
+ AND messages_fts.rowid = hits.mid)
+ FROM hits",
)?;
let rows = stmt.query_map(params![quoted, limit], |row| {
Ok(SearchHit {
@@ -4946,6 +4974,78 @@ mod tests {
assert_eq!(seen, ["m0", "m1", "m2", "m3", "m4"]);
}
+ #[test]
+ fn a_replaced_message_keeps_its_position_for_an_around_window() {
+ // A branch stamp and a terminal steering snapshot both rewrite one
+ // existing message through `transcripts::update_message`. That call
+ // splices the line where it stands. Writing the replacement at the end
+ // of the file instead would still resolve the *content* — reads dedupe
+ // keep-last — but it would move the line, and an `around` window is
+ // centred on a physical position, so a search jump to an updated message
+ // would open on the tail of the session. This pins the geometry, not
+ // just the text.
+ let db = test_db();
+ let session = create_session(&db, None, None, None, None, None).unwrap();
+ for index in 0..12 {
+ append_message(
+ &db,
+ &session.id,
+ &user_msg(
+ &format!("m{index}"),
+ &format!("body {index}"),
+ "2025-05-01T00:00:00Z",
+ ),
+ None,
+ )
+ .unwrap();
+ }
+ let replaced = user_msg("m5", "body 5 newest snapshot", "2025-05-01T00:00:00Z");
+ let (record, _) = ui_to_record(&replaced);
+ assert!(transcripts::update_message(db.data_dir(), &session.id, &record).unwrap());
+
+ let page = get_session_with_options(
+ &db,
+ &session.id,
+ SessionReadOptions {
+ message_around: Some("m5".to_string()),
+ message_before: None,
+ message_limit: Some(4),
+ content_limit: None,
+ },
+ )
+ .unwrap()
+ .unwrap();
+ let ids: Vec<&str> = page.messages.iter().map(|m| m.id.as_str()).collect();
+ assert!(
+ ids.contains(&"m5"),
+ "the anchor must be inside its own window: {ids:?}"
+ );
+ // Numeric, not lexicographic: "m10" < "m5" as strings, which would let
+ // a tail-window regression through.
+ let index_of = |id: &str| id.strip_prefix('m').and_then(|n| n.parse::<usize>().ok());
+ assert!(
+ ids.iter().any(|id| index_of(id).is_some_and(|n| n < 5)),
+ "messages before the anchor must stay reachable: {ids:?}"
+ );
+ assert!(
+ ids.iter().any(|id| index_of(id).is_some_and(|n| n > 5)),
+ "messages after the anchor must stay reachable: {ids:?}"
+ );
+ assert_eq!(
+ page.has_more_after,
+ Some(true),
+ "an anchor in the middle of the history is not the end of the session"
+ );
+ assert_eq!(
+ page.messages
+ .iter()
+ .find(|message| message.id == "m5")
+ .unwrap()
+ .content,
+ "body 5 newest snapshot"
+ );
+ }
+
#[test]
fn bounded_session_reads_page_history_and_cap_display_content() {
let db = test_db();
@@ -6096,6 +6196,108 @@ mod tests {
assert!(search_messages(&db, "数据库", 10).unwrap().is_empty());
}
+ /// The search snippets must show the window around the match. FTS5's
+ /// `snippet()` reads the phrase list of the MATCH that positioned its
+ /// cursor, so a reformulation that reaches a document by rowid alone
+ /// silently degrades to the head of the document — which still looks like a
+ /// plausible preview. This pins the observable property.
+ #[test]
+ fn search_snippets_center_on_the_match_not_the_document_head() {
+ let db = test_db();
+ let session = create_session(&db, None, None, None, None, None).unwrap();
+ let filler = "lorem ipsum dolor sit amet ".repeat(60);
+ append_message(
+ &db,
+ &session.id,
+ &user_msg(
+ "m1",
+ &format!("{filler}needle-window-tail"),
+ "2025-05-01T00:00:00Z",
+ ),
+ None,
+ )
+ .unwrap();
+ let hits = search_messages(&db, "needle-window-tail", 10).unwrap();
+ assert_eq!(hits.len(), 1);
+ assert!(
+ hits[0].snippet.contains("needle-window-tail"),
+ "snippet is not the window around the match: {:?}",
+ hits[0].snippet
+ );
+ assert!(
+ hits[0].snippet.len() < filler.len(),
+ "snippet returned the whole body: {} bytes",
+ hits[0].snippet.len()
+ );
+ }
+
+ /// The ordering indexes are a plan change and must not be a result change.
+ /// Both branches of `search_messages` are compared with the indexes present
+ /// and dropped, on the same rows.
+ #[test]
+ fn search_results_do_not_depend_on_the_ordering_indexes() {
+ let db = test_db();
+ let session = create_session(&db, None, None, None, None, None).unwrap();
+ for index in 0..40 {
+ append_message(
+ &db,
+ &session.id,
+ &user_msg(
+ &format!("m{index:02}"),
+ &format!("needle body {index}"),
+ &format!("2025-05-01T00:00:{index:02}Z"),
+ ),
+ None,
+ )
+ .unwrap();
+ }
+ let project = |hits: Vec<SearchHit>| {
+ hits.into_iter()
+ .map(|hit| (hit.message_id, hit.snippet))
+ .collect::<Vec<_>>()
+ };
+ let indexed_fts = project(search_messages(&db, "needle body", 10).unwrap());
+ let indexed_like = project(search_messages(&db, "ne", 10).unwrap());
+ assert_eq!(indexed_fts.len(), 10);
+ assert_eq!(indexed_like.len(), 10);
+ // Newest first: the query must rank by created_at, not by row order.
+ assert_eq!(indexed_fts[0].0, "m39");
+
+ db.conn()
+ .execute_batch(
+ "DROP INDEX idx_messages_created;
+ DROP INDEX idx_messages_session_created;",
+ )
+ .unwrap();
+ assert_eq!(
+ project(search_messages(&db, "needle body", 10).unwrap()),
+ indexed_fts
+ );
+ assert_eq!(
+ project(search_messages(&db, "ne", 10).unwrap()),
+ indexed_like
+ );
+ }
+
+ /// `boot_maintenance` adds the ordering indexes to an existing database
+ /// without a schema-version bump, the same way it has always added
+ /// `idx_turns_ended_at`.
+ #[test]
+ fn opening_a_database_creates_the_message_ordering_indexes() {
+ let db = test_db();
+ for name in ["idx_messages_created", "idx_messages_session_created"] {
+ let present: i64 = db
+ .conn()
+ .query_row(
+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = ?1",
+ params![name],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert_eq!(present, 1, "{name} was not created");
+ }
+ }
+
#[test]
fn save_and_activate_message_revision() {
let db = test_db();
diff --git a/crates/host-core/src/transcripts.rs b/crates/host-core/src/transcripts.rs
index d0f3bf297..e93535c7b 100644
--- a/crates/host-core/src/transcripts.rs
+++ b/crates/host-core/src/transcripts.rs
@@ -242,10 +242,18 @@ pub fn read_tool_call(
}
let mut reader = BufReader::new(File::open(transcript_path(data_dir, session_id)?)?);
let mut line = String::new();
+ // A provider tool-call id is an opaque token, so it appears verbatim in the
+ // line that stores it. A byte scan rejects a line before serde walks its
+ // payload, which for a tool result is the whole cost of this loop. An id
+ // that JSON would escape keeps the unfiltered path.
+ let verbatim = is_json_verbatim(call_id);
for offset in layout.message_offsets.iter().rev() {
reader.seek(SeekFrom::Start(*offset))?;
line.clear();
reader.read_line(&mut line)?;
+ if verbatim && !line.contains(call_id) {
+ continue;
+ }
if serde_json::from_str::<ToolIdentity>(&line).is_ok_and(|identity| {
identity.role == "tool"
&& identity
@@ -259,6 +267,58 @@ pub fn read_tool_call(
Ok(None)
}
+/// Whether a JSON string for this value is the value itself.
+///
+/// serde_json escapes only the quote, the backslash and the C0 controls, so a
+/// value made of anything else is written verbatim between its quotes and can
+/// be looked for with a byte scan. A value that would be escaped has to be
+/// parsed instead.
+fn is_json_verbatim(value: &str) -> bool {
+ !value.is_empty()
+ && !value.contains(['"', '\\', '\u{7f}'])
+ && !value.chars().any(|ch| (ch as u32) < 0x20)
+}
+
+/// Whether a transcript file holds a message record with this id.
+///
+/// `read_transcript` parses every message line into a full `MessageRecord`,
+/// block tree and metadata included, and the one caller only needs presence.
+/// This walks the file once, classifies each line with the same bounded prefix
+/// scan the window reader uses, and parses nothing but the id of a line whose
+/// bytes already contain it.
+pub fn transcript_contains_id(data_dir: &Path, session_id: &str, message_id: &str) -> Result<bool> {
+ #[derive(Deserialize)]
+ struct Identity {
+ id: String,
+ }
+ let path = transcript_path(data_dir, session_id)?;
+ let file = match File::open(&path) {
+ Ok(file) => file,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
+ Err(error) => return Err(error).with_context(|| format!("read {}", path.display())),
+ };
+ let verbatim = is_json_verbatim(message_id);
+ let mut reader = BufReader::new(file);
+ let mut line = String::new();
+ loop {
+ line.clear();
+ if reader.read_line(&mut line)? == 0 {
+ return Ok(false);
+ }
+ let trimmed = line.trim();
+ if sniff_line_kind(trimmed) != Some("message") {
+ continue;
+ }
+ if verbatim && !line.contains(message_id) {
+ continue;
+ }
+ if serde_json::from_str::<Identity>(trimmed).is_ok_and(|identity| identity.id == message_id)
+ {
+ return Ok(true);
+ }
+ }
+}
+
/// Classify a JSONL line by reading its top-level `type` value.
///
/// Deserializing a `LineTag` makes serde walk the entire line -- including a
@@ -426,22 +486,28 @@ fn scan_layout(path: &Path, mut layout: TranscriptLayout) -> Result<TranscriptLa
/// Serialize one JSONL line with its `type` discriminator first.
///
-/// Position matters for reads: `serde_json`'s map is sorted, so inserting the
-/// key would place it after the payload and force a reader to walk a whole
-/// multi-megabyte tool result before it can tell what the line is. Writing it
-/// first makes classification a fixed-cost prefix check.
+/// Position matters for reads: a line has to be classifiable — and, for a
+/// message, its id readable — before a reader walks a multi-megabyte tool
+/// result, so the discriminator is written first and the id immediately after
+/// it. That makes both a fixed-cost prefix check.
+///
+/// This is a single serialization pass plus one splice. The shape it replaced
+/// built a `serde_json::Value` tree, deep-cloned it (a `Value` cannot be
+/// re-wrapped without an owned map) and serialized the clone, then formatted
+/// the whole payload a second time — four passes over every byte written to a
+/// transcript, and an allocation per JSON node.
fn tagged(tag: &str, body: &impl Serialize) -> Result<String> {
- let value = serde_json::to_value(body)?;
- let object = value
- .as_object()
+ let body = serde_json::to_string(body)?;
+ let fields = body
+ .strip_prefix('{')
+ .and_then(|rest| rest.strip_suffix('}'))
.ok_or_else(|| anyhow!("line body must be an object"))?;
- let body = Value::Object(object.clone()).to_string();
let head = format!("{{\"type\":{}", Value::String(tag.into()));
// `{}` has no fields to append after the discriminator.
- if object.is_empty() {
+ if fields.is_empty() {
return Ok(format!("{head}}}"));
}
- Ok(format!("{head},{}", &body[1..]))
+ Ok(format!("{head},{fields}}}"))
}
/// Session ids come from our own DB (UUIDs), but stay defensive: an id that
@@ -503,15 +569,7 @@ pub fn write_inflight(data_dir: &Path, session_id: &str, record: &InflightRecord
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
- let tmp = path.with_extension("json.tmp");
- {
- let mut file = File::create(&tmp)?;
- file.write_all(serde_json::to_string(record)?.as_bytes())?;
- file.write_all(b"\n")?;
- file.flush()?;
- file.sync_data()?;
- }
- swap_into_place(&tmp, &path)
+ durability::owe_checkpoint(&path, record)
}
/// Load the session's in-flight checkpoint. A missing or unreadable file is
@@ -532,7 +590,6 @@ pub fn read_inflight(data_dir: &Path, session_id: &str) -> Result<Option<Infligh
}
}
}
-
/// Remove the session's in-flight checkpoint; a missing file is not an error.
pub fn remove_inflight(data_dir: &Path, session_id: &str) -> Result<()> {
let path = inflight_path(data_dir, session_id)?;
@@ -591,6 +648,211 @@ pub fn list_transcript_sessions(data_dir: &Path) -> Result<Vec<String>> {
Ok(ids)
}
+/// The transcript durability contract, and where its device waits happen.
+///
+/// A write is acknowledged only once its bytes are on the device, and a failed
+/// device flush fails the request that made the write. Both stay exactly as they
+/// were when the `sync_data` sat inside the writing function.
+///
+/// What moves is *where* the caller waits. Making 321 new bytes durable costs
+/// 3.57 ms on the ext4 volume the app data directory lives on (median of 40
+/// appends, two runs; a commit with nothing new to write is 96 µs), and both
+/// transcript appends and in-flight checkpoints ran inside the single
+/// `Mutex<AppState>` that serializes the RPC surface — so one write held every
+/// unrelated request for the length of a device commit.
+///
+/// Measured against the running host, with concurrent agent turns and an
+/// unrelated session read probed every 5 ms, that lock — not the CPU — is the
+/// wall. Four turns: 140 appends/s, read median 11.6 ms, host CPU 25%. Eight
+/// turns: 148/s, 23.6 ms, 24%. With the wait of both writers moved out of the
+/// lock: 339/s at 1.5 ms and 420/s at 4.1 ms, CPU 43-48%, and 8 sessions x 250
+/// turns land every row exactly once with no torn content.
+///
+/// So a write records what it owes and the request that made it commits the debt
+/// in order, once it has released the state lock and before its response goes
+/// out. A caller that is not serving a request — startup recovery, a unit test —
+/// has nowhere to record it and keeps the original inline work.
+///
+/// Two things the state lock used to order have to be kept explicitly:
+///
+/// * Checkpoints for one file keep the order of the *decisions* that produced
+/// them, which is the order the state lock gave them. A checkpoint whose
+/// decision is older than one already written is dropped, so a request that
+/// reaches its commit late cannot put an older reply back.
+/// * A checkpoint that lands after a terminal append removed it is discarded on
+/// recovery: `recover_inflight_message` drops a checkpoint whose message id is
+/// already indexed as a final row, so a stale snapshot cannot resurrect a
+/// settled reply.
+mod durability {
+ use super::*;
+ use std::cell::RefCell;
+ use std::future::Future;
+ use std::sync::atomic::{AtomicU64, Ordering};
+
+ /// What one request owes the device before it may answer.
+ enum Owed {
+ /// Bytes already in the page cache; only the flush is left.
+ Flush(PathBuf, File),
+ /// A checkpoint still to write, flush and swap into place. `decided` is
+ /// its place in the process-wide order of checkpoint decisions.
+ Checkpoint {
+ path: PathBuf,
+ payload: String,
+ decided: u64,
+ },
+ }
+
+ tokio::task_local! {
+ /// What the request being served owes the device, in the order it was
+ /// recorded. Transcript bytes are in the page cache by the time they are
+ /// recorded; a checkpoint is not written at all yet.
+ static PENDING: RefCell<Vec<Owed>>;
+ }
+
+ /// Record the device debt of `file`, or flush it here when no request will.
+ pub(super) fn owe(path: &Path, file: File) -> Result<()> {
+ if PENDING.try_with(|_| ()).is_err() {
+ return file
+ .sync_data()
+ .with_context(|| format!("flush {}", path.display()));
+ }
+ PENDING.with(|pending| {
+ let mut pending = pending.borrow_mut();
+ // The kernel buffer, not the descriptor, holds the bytes, so a newer
+ // handle for the same file supersedes an older one.
+ pending.retain(|owed| !matches!(owed, Owed::Flush(known, _) if known == path));
+ pending.push(Owed::Flush(path.to_path_buf(), file));
+ });
+ Ok(())
+ }
+
+ /// Record a checkpoint the request owes, or write it here when no request
+ /// will. The record is serialized now, so the commit only touches the file.
+ pub(super) fn owe_checkpoint(path: &Path, record: &InflightRecord) -> Result<()> {
+ let decided = decision_order();
+ let payload = serde_json::to_string(record)?;
+ if PENDING.try_with(|_| ()).is_err() {
+ return write_checkpoint(path, &payload, decided);
+ }
+ PENDING.with(|pending| {
+ pending.borrow_mut().push(Owed::Checkpoint {
+ path: path.to_path_buf(),
+ payload,
+ decided,
+ });
+ });
+ Ok(())
+ }
+
+ /// Serve one request: commit every write it made, in order, before it
+ /// answers. The request's own outcome comes back untouched.
+ pub async fn serving<F, T>(future: F) -> (T, Result<()>)
+ where
+ F: Future<Output = T>,
+ {
+ PENDING
+ .scope(RefCell::new(Vec::new()), async move {
+ let output = future.await;
+ let pending = PENDING.with(|pending| std::mem::take(&mut *pending.borrow_mut()));
+ // The work blocks, so it runs off the async worker.
+ let committed = tokio::task::spawn_blocking(move || commit(pending))
+ .await
+ .unwrap_or_else(|error| Err(anyhow!("transcript commit did not run: {error}")));
+ (output, committed)
+ })
+ .await
+ }
+
+ /// Commit each owed item in order, stopping at the first failure: work that
+ /// could not reach the device is reported, never quietly dropped.
+ fn commit(pending: Vec<Owed>) -> Result<()> {
+ for owed in pending {
+ match owed {
+ Owed::Flush(path, file) => file
+ .sync_data()
+ .with_context(|| format!("flush {}", path.display()))?,
+ Owed::Checkpoint {
+ path,
+ payload,
+ decided,
+ } => write_checkpoint(&path, &payload, decided)?,
+ }
+ }
+ Ok(())
+ }
+
+ /// Write one checkpoint: into a temporary file, to the device, and only then
+ /// over the checkpoint it replaces.
+ ///
+ /// A checkpoint whose decision is older than one already written is dropped:
+ /// the state lock that used to hold the decision and the write together is
+ /// released before this runs, and the file keeps the later decision.
+ fn write_checkpoint(path: &Path, payload: &str, decided: u64) -> Result<()> {
+ let state = writer_state(path);
+ let _per_file = state
+ .lock
+ .lock()
+ .unwrap_or_else(|poison| poison.into_inner());
+ if state.written.load(Ordering::SeqCst) >= decided {
+ return Ok(());
+ }
+ let tmp = path.with_extension("json.tmp");
+ {
+ let mut file = File::create(&tmp)?;
+ file.write_all(payload.as_bytes())?;
+ file.write_all(b"\n")?;
+ file.flush()?;
+ file.sync_data()
+ .with_context(|| format!("flush {}", tmp.display()))?;
+ }
+ swap_into_place(&tmp, path)?;
+ state.written.store(decided, Ordering::SeqCst);
+ Ok(())
+ }
+
+ /// Where a checkpoint decision sits in the process-wide decision order. The
+ /// state lock used to be that order; it is released before the write now.
+ fn decision_order() -> u64 {
+ static NEXT: AtomicU64 = AtomicU64::new(0);
+ NEXT.fetch_add(1, Ordering::SeqCst) + 1
+ }
+
+ /// One checkpoint file's writer state: the lock that makes a decision and its
+ /// swap atomic against another writer of the same file, and the decision that
+ /// last landed there.
+ ///
+ /// One entry per checkpoint path ever written is kept for the life of the
+ /// process. Evicting could hand two concurrent writers different state for one
+ /// file, which is the interleaving this exists to prevent; sessions are
+ /// long-lived and few, so the table stays small.
+ struct WriterState {
+ lock: std::sync::Mutex<()>,
+ written: AtomicU64,
+ }
+
+ fn writer_state(path: &Path) -> &'static WriterState {
+ type Registry = std::sync::Mutex<std::collections::HashMap<PathBuf, &'static WriterState>>;
+ static WRITERS: std::sync::OnceLock<Registry> = std::sync::OnceLock::new();
+ let registry =
+ WRITERS.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()));
+ let mut guard = registry.lock().unwrap_or_else(|poison| poison.into_inner());
+ let state: &'static WriterState = guard.entry(path.to_path_buf()).or_insert_with(|| {
+ Box::leak(Box::new(WriterState {
+ lock: std::sync::Mutex::new(()),
+ written: AtomicU64::new(0),
+ }))
+ });
+ state
+ }
+}
+
+/// Serve one RPC, committing the transcript writes it made before it answers.
+///
+/// Returns the request's own outcome together with the device outcome, so the
+/// caller decides which of the two a response carries — and so a device failure
+/// cannot be answered with success.
+pub use durability::serving as commit_writes_of;
+
/// Durable single-line append shared by transcript and revision writers.
/// `header` is written first when the file does not exist yet.
fn append_line(path: &Path, header: Option<String>, line: String) -> Result<()> {
@@ -616,9 +878,10 @@ fn append_line(path: &Path, header: Option<String>, line: String) -> Result<()>
buf.push('\n');
file.write_all(buf.as_bytes())?;
file.flush()?;
- // Message durability matches the DB's WAL synchronous=NORMAL guarantees.
- file.sync_data()?;
- Ok(())
+ // The bytes are in the kernel. Whether they reach the device before this
+ // caller is answered belongs to the request that made the write (see
+ // `commit_writes_of`); a caller outside one flushes them here.
+ durability::owe(path, file)
}
/// Whether a non-empty file ends in a newline; an empty file counts as
@@ -913,6 +1176,23 @@ fn swap_into_place(tmp: &Path, path: &Path) -> Result<()> {
/// appended between the caller's own read and this write survives. That is the
/// difference that matters: a metadata stamp must never cost the transcript its
/// newest messages the way a full `write_transcript` from a stale snapshot does.
+///
+/// Still O(history), deliberately. Appending the replacement instead — which the
+/// reader's last-write-wins dedupe resolves correctly for *content* — moves the
+/// message's line to the end of the file, and every window in the read path is
+/// expressed in physical line coordinates: `find_message_position` returns the
+/// last physical occurrence and `get_session_with_options` centres
+/// `messageAround` on it. A search jump to an updated message would then open on
+/// the tail of the session instead of its neighbourhood. Making the replace
+/// cheap needs the window coordinates to become deduplicated-logical first; that
+/// is a read-path change, not a write-path one. It costs 4.5 ms at 1.3 MB,
+/// 27.1 ms at 21 MB and about 1.3 s at 1 GB.
+///
+/// One pass is skipped because it only ever costs work: a replacement identical
+/// to the line already stored leaves the file untouched instead of rewriting the
+/// whole transcript. That is the shape of a retried metadata stamp, and it turns
+/// a 3.9 ms rewrite into a 1.0 ms read at 1.3 MB and a 25 ms one into 19 ms at
+/// 21 MB, measured against the always-rewrite splice on the same fixture.
pub fn update_message(data_dir: &Path, session_id: &str, record: &MessageRecord) -> Result<bool> {
let path = transcript_path(data_dir, session_id)?;
let raw = match fs::read_to_string(&path) {
@@ -921,34 +1201,40 @@ pub fn update_message(data_dir: &Path, session_id: &str, record: &MessageRecord)
Err(e) => return Err(e).with_context(|| format!("read {}", path.display())),
};
let replacement = tagged("message", record)?;
- let mut body = String::with_capacity(raw.len() + replacement.len());
- let mut replaced = false;
- for line in raw.lines() {
- let trimmed = line.trim();
- let is_target = !trimmed.is_empty()
- && serde_json::from_str::<Value>(trimmed).is_ok_and(|value| {
- value.get("type").and_then(Value::as_str) == Some("message")
- && value.get("id").and_then(Value::as_str) == Some(record.id.as_str())
- });
- // A retried append can leave the same id on two lines; keep-last dedupe
- // means every copy has to carry the new metadata.
- if is_target {
- body.push_str(&replacement);
- replaced = true;
- } else {
- body.push_str(line);
- }
- body.push('\n');
- }
- if !replaced {
- return Ok(false);
- }
let tmp = path.with_extension("jsonl.tmp");
+ let mut rewrote = false;
+ let mut carries_target = false;
{
let file = File::create(&tmp)?;
let mut writer = BufWriter::new(file);
- writer.write_all(body.as_bytes())?;
+ for line in raw.lines() {
+ let trimmed = line.trim();
+ let is_target = !trimmed.is_empty()
+ && serde_json::from_str::<Value>(trimmed).is_ok_and(|value| {
+ value.get("type").and_then(Value::as_str) == Some("message")
+ && value.get("id").and_then(Value::as_str) == Some(record.id.as_str())
+ });
+ if is_target {
+ carries_target = true;
+ }
+ if is_target && line != replacement {
+ // A retried append can leave the same id on two lines; keep-last
+ // dedupe means every copy has to carry the new metadata.
+ writer.write_all(replacement.as_bytes())?;
+ rewrote = true;
+ } else {
+ writer.write_all(line.as_bytes())?;
+ }
+ writer.write_all(b"\n")?;
+ }
writer.flush()?;
+ if !rewrote {
+ // Nothing to swap in: the id is absent, or every copy already
+ // carries exactly this metadata. Leave the live transcript alone.
+ drop(writer);
+ let _ = fs::remove_file(&tmp);
+ return Ok(carries_target);
+ }
writer.get_ref().sync_data()?;
}
swap_into_place(&tmp, &path)?;
@@ -1979,4 +2265,248 @@ mod tests {
assert!(!revisions_path(dir.path(), "s1").unwrap().exists());
remove_session_files(dir.path(), "s1");
}
+
+ /// A tool row whose block array names a provider call id.
+ fn tool_record(id: &str, call_id: &str) -> MessageRecord {
+ MessageRecord {
+ id: id.into(),
+ role: "tool".into(),
+ tool_name: Some("bash".into()),
+ is_error: false,
+ blocks: json!([{ "type": "tool_result", "callId": call_id, "text": "x" }]),
+ meta: None,
+ created_at: "2026-07-26T00:00:00.000Z".into(),
+ }
+ }
+
+ /// Byte offset of every line start, which is all `read_tool_call` needs.
+ fn line_offsets(dir: &Path, session_id: &str) -> TranscriptLayout {
+ let raw = fs::read(transcript_path(dir, session_id).unwrap()).unwrap();
+ let mut message_offsets = Vec::new();
+ let mut at = 0usize;
+ for line in raw.split_inclusive(|byte| *byte == b'\n') {
+ message_offsets.push(at as u64);
+ at += line.len();
+ }
+ TranscriptLayout {
+ message_offsets,
+ compaction_offsets: Vec::new(),
+ file_len: raw.len() as u64,
+ }
+ }
+
+ /// Presence is answered from the id field, and the byte pre-filter must not
+ /// hide an id that JSON writes in escaped form.
+ #[test]
+ fn transcript_contains_id_answers_from_the_id_field_alone() {
+ let dir = tempdir().unwrap();
+ let escaped = "quote\"and\\slash";
+ for id in ["m1", "middle", escaped] {
+ append_message(dir.path(), "s1", "2026-07-26T00:00:00Z", &record(id, "x")).unwrap();
+ }
+ for id in ["m1", "middle", escaped] {
+ assert!(
+ transcript_contains_id(dir.path(), "s1", id).unwrap(),
+ "{id:?} should be present"
+ );
+ }
+ assert!(!transcript_contains_id(dir.path(), "s1", "absent").unwrap());
+ // A prefix of a stored id is not a stored id.
+ assert!(!transcript_contains_id(dir.path(), "s1", "mid").unwrap());
+ // A session with no transcript answers false rather than failing.
+ assert!(!transcript_contains_id(dir.path(), "other", "m1").unwrap());
+ }
+
+ /// The byte pre-filter in `read_tool_call` must not hide a call id that JSON
+ /// writes in escaped form.
+ #[test]
+ fn read_tool_call_finds_ids_that_json_escapes() {
+ let dir = tempdir().unwrap();
+ append_message(dir.path(), "s1", "2026-07-26T00:00:00Z", &record("m1", "x")).unwrap();
+ let call_ids = ["call-1", "quote\"and\\slash"];
+ for (index, call_id) in call_ids.iter().enumerate() {
+ append_message(
+ dir.path(),
+ "s1",
+ "2026-07-26T00:00:00Z",
+ &tool_record(&format!("tool-{index}"), call_id),
+ )
+ .unwrap();
+ }
+ let layout = line_offsets(dir.path(), "s1");
+ for call_id in call_ids {
+ assert!(
+ read_tool_call(dir.path(), "s1", &layout, call_id)
+ .unwrap()
+ .is_some(),
+ "{call_id:?} should be found"
+ );
+ }
+ assert!(read_tool_call(dir.path(), "s1", &layout, "absent")
+ .unwrap()
+ .is_none());
+ }
+
+ /// Concurrent appends from several sessions must not cost a line, fuse two
+ /// lines, or leak across files: writes are ordered by the state lock and
+ /// each append flushes its own file. Guards the append shape the durability
+ /// contract rests on.
+ #[test]
+ fn concurrent_appends_keep_every_line_intact_and_in_its_own_session() {
+ const SESSIONS: usize = 8;
+ const PER_SESSION: usize = 25;
+ let dir = tempdir().unwrap();
+ let mut handles = Vec::new();
+ for session in 0..SESSIONS {
+ let root = dir.path().to_path_buf();
+ handles.push(std::thread::spawn(move || {
+ let id = format!("sess-{session}");
+ for index in 0..PER_SESSION {
+ let record = record(&format!("msg-{:06}", session * PER_SESSION + index), "x");
+ append_message(&root, &id, "2026-07-26T00:00:00Z", &record).unwrap();
+ }
+ }));
+ }
+ for handle in handles {
+ handle.join().unwrap();
+ }
+ for session in 0..SESSIONS {
+ let id = format!("sess-{session}");
+ let expected: Vec<String> = (session * PER_SESSION..(session + 1) * PER_SESSION)
+ .map(|index| format!("msg-{index:06}"))
+ .collect();
+ let ids: Vec<String> = read_transcript(dir.path(), &id)
+ .unwrap()
+ .iter()
+ .map(|record| record.id.clone())
+ .collect();
+ assert_eq!(
+ ids, expected,
+ "every line survives, in order, in its own session"
+ );
+ }
+ }
+
+ /// Point one session's transcript at a file that takes writes and refuses
+ /// the device flush. `/dev/null` accepts the bytes and fails `fdatasync`
+ /// with EINVAL, which is how a broken device behaves, on any machine.
+ #[cfg(unix)]
+ fn transcript_that_cannot_be_flushed(dir: &Path) -> PathBuf {
+ let path = transcript_path(dir, "s1").unwrap();
+ fs::create_dir_all(path.parent().unwrap()).unwrap();
+ std::os::unix::fs::symlink("/dev/null", &path).unwrap();
+ path
+ }
+
+ /// A caller that is not serving a request has nowhere to defer to, so it
+ /// must not report an append whose bytes never reached the device as a
+ /// success.
+ #[cfg(unix)]
+ #[test]
+ fn an_append_outside_a_request_reports_a_failed_device_flush() {
+ let dir = tempdir().unwrap();
+ transcript_that_cannot_be_flushed(dir.path());
+ let error = append_message(dir.path(), "s1", "2026-07-26T00:00:00Z", &record("m1", "x"))
+ .expect_err("a failed device flush is not a successful append");
+ assert!(format!("{error:#}").contains("flush"), "{error:#}");
+ }
+
+ /// The request that owns the write owns the device wait: it commits the
+ /// lines it wrote before it answers, and a failed flush comes back to it
+ /// instead of being logged and forgotten.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn a_request_only_answers_after_its_lines_reached_the_device() {
+ let dir = tempdir().unwrap();
+ transcript_that_cannot_be_flushed(dir.path());
+ let (written, committed) = commit_writes_of(async {
+ append_message(dir.path(), "s1", "2026-07-26T00:00:00Z", &record("m1", "x"))
+ })
+ .await;
+ assert!(written.is_ok(), "the write itself succeeds: {written:?}");
+ let error =
+ committed.expect_err("the flush failed, so the request must not answer success");
+ assert!(format!("{error:#}").contains("flush"), "{error:#}");
+ }
+
+ /// The same scope on a healthy file commits the write and reports nothing.
+ #[tokio::test]
+ async fn a_request_commits_the_transcript_lines_it_wrote() {
+ let dir = tempdir().unwrap();
+ let (written, committed) = commit_writes_of(async {
+ append_message(dir.path(), "s1", "2026-07-26T00:00:00Z", &record("m1", "x"))
+ })
+ .await;
+ written.unwrap();
+ committed.expect("a synced write commits");
+ let ids: Vec<String> = read_transcript(dir.path(), "s1")
+ .unwrap()
+ .iter()
+ .map(|record| record.id.clone())
+ .collect();
+ assert_eq!(ids, vec!["m1".to_string()]);
+ }
+
+ /// An in-flight checkpoint for `message_id`, stamped `created_at`.
+ fn inflight(session_id: &str, message_id: &str, created_at: &str) -> InflightRecord {
+ let mut message = record(message_id, "partial");
+ message.created_at = created_at.into();
+ InflightRecord {
+ schema: INFLIGHT_SCHEMA,
+ session_id: session_id.into(),
+ turn_id: Some("turn-1".into()),
+ saved_at: created_at.into(),
+ message,
+ }
+ }
+
+ /// A checkpoint is part of what a request owes the device, so one that cannot
+ /// reach it fails the request instead of answering success.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn a_request_whose_checkpoint_cannot_be_flushed_fails() {
+ let dir = tempdir().unwrap();
+ let path = inflight_path(dir.path(), "s1").unwrap();
+ fs::create_dir_all(path.parent().unwrap()).unwrap();
+ // The temporary the writer creates, flushes and renames into place.
+ std::os::unix::fs::symlink("/dev/null", path.with_extension("json.tmp")).unwrap();
+ let record = inflight("s1", "m1", "2026-07-26T00:00:01.000Z");
+ let (written, committed) =
+ commit_writes_of(async { write_inflight(dir.path(), "s1", &record) }).await;
+ assert!(written.is_ok(), "the write itself succeeds: {written:?}");
+ let error = committed.expect_err("an unflushed checkpoint is not a saved checkpoint");
+ assert!(format!("{error:#}").contains("flush"), "{error:#}");
+ }
+
+ /// Checkpoints of one file keep the order of the decisions that produced
+ /// them, including when the earlier decision reaches its commit last: the
+ /// state lock used to give that order and the commit no longer holds it.
+ #[tokio::test]
+ async fn a_checkpoint_decided_later_always_wins() {
+ let dir = tempdir().unwrap();
+ let root = dir.path().to_path_buf();
+ let first = inflight("s1", "m1", "2026-07-26T00:00:01.000Z");
+ let second = inflight("s1", "m1", "2026-07-26T00:00:02.000Z");
+ let (written, committed) = commit_writes_of(async {
+ // Decided first, and it reaches its commit only after the second
+ // decision has already replaced the file.
+ write_inflight(&root, "s1", &first).unwrap();
+ let later = {
+ let (root, second) = (root.clone(), second.clone());
+ // No request scope on this thread, so this one is written inline,
+ // exactly as every checkpoint was before the wait moved.
+ tokio::task::spawn_blocking(move || write_inflight(&root, "s1", &second))
+ };
+ later.await.unwrap().unwrap();
+ Ok::<(), anyhow::Error>(())
+ })
+ .await;
+ written.unwrap();
+ committed.unwrap();
+ let stored = read_inflight(&root, "s1").unwrap().unwrap();
+ assert_eq!(
+ stored.message.created_at, second.message.created_at,
+ "a checkpoint decided earlier must not land on top of a later one"
+ );
+ }
}