Repository navigation
feat(log): read-only SQL over the transcript index, single-user (v1 Phase 2) - #328
Conversation
…hase 2) `cairn log query SQL [--limit N] [--json]` runs ONE SELECT over two owner-scoped views (`log_sessions`, `log_units`) on a separate connection that logs in as a dedicated SELECT-only role. The route exists only on a single-user instance whose cairn-ui is given $CAIRN_UI_LOG_QUERY_DSN; the DSN on a multi-user instance refuses to start (Q2). - pgstore: ProvisionLogQueryRole (idempotent, needs a superuser main role: the role, the views as security barriers bound to one owner via current_user, role settings, REVOKE TEMP and EXECUTE on set_config / advisory locks / pg_notify / backend signals / query_to_xml from PUBLIC), VerifyLogQueryRole (startup check; a widened role disables the route), and the executor: subquery wrap, one Parse, BEGIN READ ONLY, SET LOCAL timeout, always ROLLBACK, a connection per request, row and byte caps cut by the statement. - the escape battery (Postgres tier): 31 escapes, each refused by the production executor, reached by a weakened one, and refused by every layer its row names alone (65 single-layer refusals). Mutation sweep: dropping set_config from the deny list, the barrier, the TEMP revoke, the view's owner filter, the idle-connection discard, a startup-check clause, the membership revoke, or the wrap each turns a test red; dropping read-only or rollback from production is caught only by the labelled invariant pin. - clientapi: the route with its own narrower gate (QueryEnabled); absent on multi-user, mutation-checked. - client: `log query` in its own file; table output, --json verbatim. Not deployed; the eval was not run (the l2/both arms do not offer `query`). Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…e verb (#328 final) Operator decisions on #328, folded into one commit (not re-audited): - Isolation (D1): $CAIRN_UI_LOG_QUERY_DSN points at a read-only physical standby. Provisioning is a one-shot operator mode, `cairn-ui -provision-log-query-role`, run against the PRIMARY with -db-dsn as a superuser; the role, views and grants replicate. At runtime cairn-ui only verifies (writes nothing), and a query connection on the main database's own server (same system_identifier and recovery state) is refused unless -log-query-allow-shared-primary. - Any SQL-verb failure disables only the verb: standby down, role not yet replicated, role not verifying, isolation refusal -> 503 {"error":"sql-unavailable","reason":...}, one log line per state change, re-verify on a 30 s -> 5 min backoff. Multi-user stays route-absent (404). Only an unparseable DSN refuses to start. - D2: the deny list stays revoked from PUBLIC (a role-level revoke cannot override PUBLIC), and every revoked function plus TEMP is granted back to the main role, so cairn-ui never needs superuser. Reversal recipe documented. - D3: the owner is a literal in the view definitions; transcript_query_roles is gone. Re-provisioning rewrites the views; startup verification reads the owner out of them. - Rollback recipe drops the views first; migration-list note on the view dependency; the mode drops and recreates the views every run. - Deny list: + ts_stat, ts_rewrite, the table_/schema_/database_to_xml families. Header corrected (DML CTE is 0A000, not a syntax error). - Memory: documented as unbounded by any layer; isolation confines the blast radius; the standby's limit is the operator's sizing decision. - The mode drops roles it created earlier under other names, scoped to its own database (a cluster-wide mark dropped a neighbour database's role, caught by the tier running two packages at once). Battery: 33 escapes refused on production (role as the mode provisions it), reached on a weakened role, 67 single-layer refusals. Real hot standby measured by hand; the tier simulates it. R9 (eval) and audit 🟢 7 stay open. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
|
Audit round 1 (adversarial, read-only) of |
…re-check while serving, no superuser migration 1. -log-query-main-role is REQUIRED with -provision-log-query-role (usage error, exit 78, naming the flag), and pgstore.ProvisionLogQueryRole refuses an empty MainRole. The old default (the admin connection's session_user, a superuser) granted the revoked functions to the superuser, so a non-superuser cairn-ui lost set_config and pg_advisory_lock (42501, exit 78 on restart). 2. Provisioning refuses (ErrLogQueryRoleTaken) to alter an existing role that does not carry its own mark for THIS database, and refuses a query role equal to the main role before any statement runs. 3. The serving gate re-runs VerifyLogQueryRole (one connection) and the isolation check every 60 s (logQueryRecheckEvery) and closes on the first failure; opening and re-checking share one predicate (logQueryCheck). The pgstore header now says a widening lasts up to one interval. 4. The provisioning mode opens with pgstore.OpenForProvisioning, which never migrates and refuses a schema not at this build's version (start cairn-ui first, as its own role). 5. -log-query-dsn / -log-query-main-role help, internal/transcript/README.md and the plan doc describe the current design. Tests (Postgres 18.6 tier, targeted): red at 7904a73, green here — TestProvisioningKeepsANonSuperuserMainRoleWorking, TestProvisioningRefusesToTakeOverARoleItDidNotCreate, TestProvisioningNeedsTheMainRole, TestTheProvisioningModeNeverMigrates, TestTheSQLRouteComesUpByItselfOnceItsRoleIsProvisioned (GRANT while serving -> 503 at the next re-check). New: TestOpenForProvisioningNeverMigrates, TestAServingGateReChecksOnItsIntervalAndClosesOnAFailure (plain tier, fake clock). 11 mutants, each killed by its own guard's assertion. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
|
Fix round 1 for the audit of legend: The script warned about an earlier block: the audit half's block records the self-range |
|
Round 2 delta audit (
|
…mpare-and-set; bounded label - ProvisionLogQueryRole refuses a main role that does not OWN schema_migrations (the role that applied the schema), naming the actual owner; with no schema_migrations it refuses as ErrSchemaNotMigrated. An existing but wrong -log-query-main-role (the admin) previously exited 0 and a non-superuser cairn-ui then died 78/42501. - logQueryGate.fail: a query that fails on a querier a re-check has already replaced no longer overwrites the gate's reason or leaves a stale wake (compare-and-set on the serving querier). - queryWhere (the AVAILABLE label) runs under logQueryLabelTimeout (dbConnectTimeout) instead of the loop's unbounded context. - -log-query-allow-shared-primary help: the verb degrades to 503, cairn-ui does not refuse to start. -log-query-main-role help and the transcript README name the ownership requirement. Tests: TestProvisioningRefusesAMainRoleThatDoesNotOwnTheSchema and the new wrong-main-role step of TestProvisioningKeepsANonSuperuserMainRoleWorking are red at a6c5c99, green here (PG 18.6). New plain-tier TestAQueryThatOutlivesItsQuerierDoesNotSpeakForTheGate and TestTheAvailableLabelIsBounded. 7 mutants, each killed by its own assertion. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…n place Operator decision on #329's round-0 Q1: `cwd_under` and `cwd` keep RECORDS, not sessions. The index kept one cwd per session (its first), so a session launched in repo A that then worked in client repo B answered B's records to A's search. - Each indexed unit now carries its own record's cwd (`IndexUnit.Cwd`): a Claude Code record naming none takes the last one its stream named (tracked over the whole stream, so a batch starting mid-stream carries it); an opencode unit takes its session's directory; a unit with none matches no directory filter. - Search filters `transcript_units.cwd`, and a hit's cwd is its unit's. - List reads a new `transcript_session_cwds` table, one row per (session, directory), merged across batches: a session is listed when ANY directory passes, answering the earliest-first passing directory, ITS first prompt and the span over every passing one. No unit is scanned. - `--cwd` is per record the same way (a prefix): a behaviour change, documented. - Migration 5 adds the column (no rewrite) and the table and zeroes every index cursor, so the indexer's startup backfill re-reads every stream and replaces rows by key. Until a root is re-read its units carry cwd '' and the scoped search answers less, never more; `--all-repos` is unaffected. - Round-0 D1: the `cwd_under` echo and its exit-3 branch are deleted. A 405 on the scoped POST stays exit 3, and the client's per-hit/per-row check stays exit 5 (exact now that the listener filters per record). - `log query` (#328) is left unscoped (a separate decision). Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…n place Operator decision on #329's round-0 Q1: `cwd_under` and `cwd` keep RECORDS, not sessions. The index kept one cwd per session (its first), so a session launched in repo A that then worked in client repo B answered B's records to A's search. - Each indexed unit now carries its own record's cwd (`IndexUnit.Cwd`): a Claude Code record naming none takes the last one its stream named (tracked over the whole stream, so a batch starting mid-stream carries it); an opencode unit takes its session's directory; a unit with none matches no directory filter. - Search filters `transcript_units.cwd`, and a hit's cwd is its unit's. - List reads a new `transcript_session_cwds` table, one row per (session, directory), merged across batches: a session is listed when ANY directory passes, answering the earliest-first passing directory, ITS first prompt and the span over every passing one. No unit is scanned. - `--cwd` is per record the same way (a prefix): a behaviour change, documented. - Migration 5 adds the column (no rewrite) and the table and zeroes every index cursor, so the indexer's startup backfill re-reads every stream and replaces rows by key. Until a root is re-read its units carry cwd '' and the scoped search answers less, never more; `--all-repos` is unaffected. - Round-0 D1: the `cwd_under` echo and its exit-3 branch are deleted. A 405 on the scoped POST stays exit 3, and the client's per-hit/per-row check stays exit 5 (exact now that the listener filters per record). - `log query` (#328) is left unscoped (a separate decision). Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…all-repos to widen) (#329) * feat(log): list and search cover the current repo's sessions by default `cairn log list|search` now print only sessions whose cwd is, or lies below, a worktree of the git repository --repo names (default: the working directory). `--cwd PREFIX` replaces that default, `--all-repos` removes it, the two together are exit 2, and outside a git repo with neither the verb refuses (exit 2) instead of searching everything. stderr names what was covered: `cairn: sessions=repo:<main worktree> worktrees=<N>`, `sessions=cwd:<PREFIX>` or `sessions=all-repos`. `log read` is unchanged. Why: `--repo` picked the instance and filtered nothing, so a search from one repo printed other repos' transcript content into the calling session's own (captured) transcript. Mechanism: the stored records carry `cwd` and `gitBranch` and nothing that identifies a repository, so the client resolves the set itself with `git worktree list --porcelain` and sends one `cwd_under` per outermost worktree. The listener keeps a session whose cwd IS one of them or lies below one (transcriptwire.CwdUnderAny, at a path-component boundary; the same rule in pgstore SQL, pinned by the Postgres tier) and echoes the set. A plain prefix cannot work: worktrees are sibling directories, and the prefix that names them also names unrelated `<repo>-*` repos. The scoped request is a POST with a form body (new rows in the client listener's route ledger): one path per worktree is tens of KiB on a repo with hundreds of worktrees, past a proxied GET request line. Fail closed against an older listener: a 405 on the POST, or an answer without the `cwd_under` echo, is exit 3 with nothing printed; an echoed answer naming a session outside the set is exit 5, nothing printed. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * docs(changelog): index the log repo-scope default (#329) Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * test(log): pin the scope-free ledger probe and the binary's POST routes The ledger-class probe ran `log search` with no scope flag, which outside a git checkout (the nix sandbox, the mutant copies) is now the exit-2 refusal; it passes --all-repos, since it measures the ledger class, not the scope. The binary's Postgres-tier test counts the listener's 11 routes and drives a POSTed cwd_under search through the real listener and SQL. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat(log): the repo scope is per RECORD; index migration 5 re-reads in place Operator decision on #329's round-0 Q1: `cwd_under` and `cwd` keep RECORDS, not sessions. The index kept one cwd per session (its first), so a session launched in repo A that then worked in client repo B answered B's records to A's search. - Each indexed unit now carries its own record's cwd (`IndexUnit.Cwd`): a Claude Code record naming none takes the last one its stream named (tracked over the whole stream, so a batch starting mid-stream carries it); an opencode unit takes its session's directory; a unit with none matches no directory filter. - Search filters `transcript_units.cwd`, and a hit's cwd is its unit's. - List reads a new `transcript_session_cwds` table, one row per (session, directory), merged across batches: a session is listed when ANY directory passes, answering the earliest-first passing directory, ITS first prompt and the span over every passing one. No unit is scanned. - `--cwd` is per record the same way (a prefix): a behaviour change, documented. - Migration 5 adds the column (no rewrite) and the table and zeroes every index cursor, so the indexer's startup backfill re-reads every stream and replaces rows by key. Until a root is re-read its units carry cwd '' and the scoped search answers less, never more; `--all-repos` is unaffected. - Round-0 D1: the `cwd_under` echo and its exit-3 branch are deleted. A 405 on the scoped POST stays exit 3, and the client's per-hit/per-row check stays exit 5 (exact now that the listener filters per record). - `log query` (#328) is left unscoped (a separate decision). Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(log): round-1 findings — resume cwd from the cursor, narrow scoped search to its sessions - 🟡1 The carried cwd is stored WITH each stream's cursor (`Cursor.Cwd`, `transcript_index_cursors.cwd`, added to the still-unreleased migration 5), so a pass decodes only the records after its cursor instead of map-decoding every earlier record to relearn the directory. - 🟡2 Opencode per-record cwd is tested (transcript + Postgres tier): the mutant that blanks it now dies. - 🟡3 A scoped search first names its sessions from transcript_session_cwds (`scopeRoots`) and both steps read only their units through the (root, at) index; a scope whose records all lie in the window (no untimed unit) is answered by the window step alone, never Partial. EXPLAIN ANALYZE on a 300k-unit fixture: the scoped all-time step went 19.7 ms (parallel seq scan, ~300k rows removed by filter) -> 1.25 ms (bitmap on (root, at)); no index on the per-unit cwd is needed. - 🟢4 The documented index DROP recipe includes transcript_session_cwds, and a Postgres-tier test runs it as written. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
e72afdf) #328 landed its own "6.2 Phase 2" section in claudedocs/plan-cairn-v1-event-log.md, so the Phase 5 retirement ledger this branch adds is renumbered 6.3 and every pointer to it (AGENTS.md, CHANGELOG.md, README.md, server/README.md, ci.yml's FLOOR comment, cli.go, three test docstrings) follows. The Phase 2 row's own "(§6.2)" is #328's and is left alone. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
v1 Phase 2: read-only SQL over the transcript index, single-user only
cairn log query "SELECT …" [--limit N] [--json]runs ONE statement over two views of the caller's own sessions:log_sessions: session, host, runtime, cwd, first_prompt, first_at, last_atlog_units: session, stream, seq, unit, at, class, tool_name, call_id, text, text_bytes, tsv_enIt runs on a separate connection that logs in as a dedicated SELECT-only role. The route exists only on a single-user instance that has a query-role DSN (
$CAIRN_UI_LOG_QUERY_DSN). Setting that DSN on a multi-user instance makes cairn-ui refuse to start, per Q2.Guarantee as implemented
How the role is provisioned. cairn-ui creates it at startup through its own connection, with
pgstore.ProvisionLogQueryRole. This is idempotent. It needs a superuser main role; the reference deployment's main role is one (checked live). It is not a numbered migration, for three reasons: roles are cluster-wide, the password is a secret, and the PUBLIC REVOKEs need a superuser. cairn-ui then logs in as the role and refuses to start unlessVerifyLogQueryRoleholds.What the role can do:
set_config, the advisory locks,pg_notify,pg_terminate_backend/pg_cancel_backendorquery_to_xml*. These are revoked from PUBLIC in that database.The views are security barriers, filtered by
current_userto the one owner the role is bound to (-worker-owner).How each statement runs: as a subquery, through one Parse, inside
BEGIN READ ONLYwithSET LOCAL statement_timeout/work_mem. The transaction is always rolled back, and each request gets its own connection, closed afterwards. The statement itself cuts the answer at 1,000 rows and 1 MiB.Why the owner-filtered view gives the same guarantee as search, on single-user only. An aggregate names no session, so there is nothing to re-check with
Store.View. Under the single-user policy,Viewadmits every credential of the uploader. That makes the owner filter its verdict, except for a session whose deletion is still in progress. On multi-user it would break in three ways:set_configcan widen.What it does not claim: the role can read the catalogs PUBLIC can read, and
pg_sleepis bounded only by the timeout. Text search through a view scans the table (@@is not leakproof), so uselog searchfor text.Escape battery (
internal/pgstore/logquery_pgtest_test.go)There are 31 escapes. Each one is refused by the production executor (
OpenLogQuery) and reached on a weakened role (a superuser twin, or service login plusSET ROLE). Each is also refused by every layer its row names, taken alone: 65 single-layer refusals. The escapes are:set_configon statement_timeout, search_path, role and a custom settingRESET ROLE,SET ROLEandSET SESSION AUTHORIZATIONCREATE TEMP TABLE,SELECT … INTOand a temp-table writepg_sleep(10)COPY … TO PROGRAMCREATE EXTENSION dblinklo_importandpg_read_filetranscript_units,transcript_sessions,sessions,invites,memos, the role binding andpg_authidLOCKNOTIFYandpg_notifypg_terminate_backendquery_to_xmlThe measured set includes two results worth noting:
LOCKis not refused by READ ONLY alone, andNOTIFYis not refused by the role.A weakened role fails the startup check in each of 12 ways, and re-provisioning repairs it.
Mutation sweep. Each of these made a test fail:
set_configlog_unitsQueryEnabledwithout single-usermainwithoutWithQuerierTurning off read-only or rollback in production is caught only by an invariant pin, labelled as one: the other layers overlap them.
Not done
l2/botharms don't offerqueryyet, so the "eval not lower than Phase 1" half of the exit criterion is still open.Local: scoped
go testpassed, leakscan passed with its self-test, andtests/pgtest/run.shpassed (354 tests, PG 18.6).🤖 Generated with Claude Code