Repository navigation
feat(runtime): hash-link the event journal and export/verify the audit chain (SK1) - #165
devin-ai-integration[bot] wants to merge 2 commits into
Conversation
…t chain (SK1) Schema 36 -> 37 adds events.previous_hash, events.record_hash and workspaces.audit_head (nullable; pre-37 rows stay NULL and verify as an unhashed prefix). Each append hashes the exact stored envelope bytes against the workspace head inside the same transaction, before publication. SessionRuntime::export_audit pages the stored bytes plus links (bounded by MAX_AUDIT_PAGE); verify_audit walks the chain from a per-workspace genesis and reports the first sequence whose bytes, link, or head no longer match. Refs ADR-0042. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
There was a problem hiding this comment.
Devin Review found 2 potential issues.
1 flag not posted on this PR by your GitHub settings — view it in Devin Review. (Configure)
| /// Most records one `export_audit` page returns. | ||
| pub const MAX_AUDIT_PAGE: u16 = 1_024; |
There was a problem hiding this comment.
🔴 Audit pages can exhaust process memory
When export_audit or verify_audit reads 1,024 near-limit events, one page holds roughly a gigabyte of JSON. MAX_PERSISTED_EVENT_BYTES permits nearly 1 MiB per event, so the process can run out of memory.
Learn more
Audit pages collect event JSON before returning. MAX_PERSISTED_EVENT_BYTES permits almost 1 MiB per event, and read_audit_page collects up to 1,024 rows. Both the worker and its caller can hold the returned vector at once, and serialization adds further copies.
Example: If a workspace has 1,024 events with 900 KiB envelopes, export_audit(workspace, 0, 1024) holds roughly 900 MiB of JSON alone.
Recommended fix: Bound the total bytes returned per page as well as its row count, preserving cursor-based continuation; stream verification or give it a smaller internal byte-bounded batch.
Was this helpful? React with 👍 or 👎 to provide feedback.
| let parse = |text: Option<String>| -> Result<Option<ContentHash>, SessionRuntimeError> { | ||
| text.map(|text| text.parse().map_err(|_| SessionRuntimeError::CODEC)) | ||
| .transpose() | ||
| }; | ||
| Ok(AuditChainRecord { | ||
| cursor: EventCursor { | ||
| store_id, | ||
| workspace_id, | ||
| sequence, | ||
| }, | ||
| previous_hash: parse(previous)?, | ||
| record_hash: parse(record)?, |
There was a problem hiding this comment.
🟡 Malformed hashes prevent broken-chain reports
When a stored link contains invalid hash text, read_audit_page returns CODEC before ChainWalk can report its sequence. A malformed audit_head also returns CODEC, so corruption produces an error instead of Broken.
Learn more
verify_audit reports AuditVerification::Broken for mismatched records and heads. The page reader converts stored hash text to ContentHash before the walk can inspect it, so a non-hex edit causes SessionRuntimeError::CODEC instead. audit_head has the same behavior for corrupt head text.
Example: Change events.record_hash at sequence 2 to bad. verify_audit(workspace) returns a codec error rather than Broken { sequence: 2, ... }.
Recommended fix: Preserve malformed stored link and head values through the read path, and let verification map them to a fault at the relevant row or head while retaining typed read errors for genuine database failures.
Was this helpful? React with 👍 or 👎 to provide feedback.
|
Thanks for this contribution — the tool-set pinning idea is one we want in QQ, and the reviewed design has now landed as a single integration PR: #194 ( #194 ports the MCP pinning delta from this stack and repairs the issues found in review (details and reproducing probes in the PR description and
This PR will be closed as superseded once #194 merges. |
… dispatch; add qq mcp inspect (#194) * feat(mcp)!: pin MCP tool sets in config and plan identity; enforce at dispatch; add qq mcp inspect An MCP server's tool descriptors are untrusted text the model reads as instructions, and the server may change them at any time. A server declaration may now carry `pin`: the SHA-256 tool-set digest (64 hex digits, validated at load) of the listing an operator reviewed. A pinned server whose listing digests differently is quarantined: it contributes no tools, the readiness message names both digests, and every call to it is refused (`McpCallFailure::Quarantined` -> `HostCallError::Refused`). This takes over the contributed stack #163 / #165 / #171 and ships only the MCP pinning delta, repaired against QQ's own contracts (ADR-0046): - Dispatch-time enforcement. A pinned call resolves the cached listing before waiting for a permit, re-checks the listing generation and the `list_changed` flag after it, requires the tool to be in that listing, and sends exactly one `tools/call` whose enqueue poll runs under a synchronous dispatch gate shared with `on_tool_list_changed`, `bump_generation`, and `shutdown`. Previously a queued call that passed the pin check executed after the server was quarantined. - Durable identity. `McpServerDescriptor.pin` is recorded and `DESCRIPTOR_VERSION` moves 9 -> 10; pinned and unpinned plans no longer share a digest. - Injective digest. Domain `qq-mcp-tool-set-v2` with length-prefixed fields replaces the `\0`-separated v1 encoding. - Whole listings only. Malformed or duplicate tool names fail the listing instead of being skipped before hashing; fetches are bounded to 32 pages, 512 tools, and 1 MiB; a `list_changed` during a fetch discards it. - Inspection. `McpManager::inspect` and `qq mcp inspect NAME` print the live digest and every descriptor as JSON without calling a tool, so the digest is reviewed before it is pinned rather than copied out of a quarantine error. The per-event audit hash chain from #165 is not ported: it has no consumer, checkpoint, or retention contract yet, and its verifier accepted a cursor rewrite. Approval/argument binding is deferred. Breaking: `DESCRIPTOR_VERSION` 9 -> 10 invalidates cached plan digests (recompiled on next load; no store migration). No protocol change. Verification: fmt, clippy (-D warnings), workspace build and tests, the minimal qq-provider profile, and `plan_compile` bench within noise of the baseline (ledger `docs/plans/progress/mcp-pinning.md`). Closes ENG-939. Supersedes #163, #165, #171. Co-Authored-By: romy <[email protected]> Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(mcp): count listing descriptor bytes without buffering an encoded copy Codex review on #194: `serde_json::to_vec(tool)` allocated the whole encoded descriptor before the 1 MiB check, doubling the resident bytes for a page `rmcp` had already decoded. Measure through a counting `ByteBudget` writer instead; the write that crosses the budget is rejected and nothing is allocated. The check now bounds only what it claims to bound; the transport read limit remains an `rmcp` concern (SSE events are capped at 16 MiB there, stdio lines are unbounded) and is noted in the ledger. Co-Authored-By: romy <[email protected]> Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: romy <[email protected]> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
What changes for users
None visible in the TUI/CLI. Embedders get two new
SessionRuntimemethods:A store edited behind the kernel's back (row rewritten, middle row deleted, tail rows deleted, row inserted without hashes) now verifies as
Brokenat the offending sequence instead of reading back as history.Why / design
Port of
axiom-events(A3 in the integration plan) as library code insideqq-core, per ADR-0042 (stacked on #163). Store stays the trust root; no service, no new dependency (sha2already inqq-core).events.previous_hash,events.record_hash,workspaces.audit_head(nullable TEXT). Pre-37 rows keep NULL and verify as anunhashed_prefix; a new NULL row after the chain began isUnhashed(written around the kernel).record_hash = sha256("qq-audit-v1\0" ‖ previous_hash_hex ‖ "\0" ‖ envelope_json), genesisprevious = sha256("qq-audit-genesis-v1\0" ‖ workspace_id)— domain-separated fromContentHashes of the same bytes, and two workspaces never share a chain.events.rs):UPDATE workspaces … RETURNING next_sequence, audit_head→ hash the exactencodedbytes →INSERTwith both links → advance head → thenfeed::stage. Persist-before-publish unchanged; a failed write moves neither sequence nor head.Store::audit_pagereturns the page and the head from the same store call, so a chain that grows whileverify_auditwalks it still verifies against its own head.Linear: ENG- (none assigned; workstream ticket per parent session)
Slice: docs/plans/security-kernel.md#sk1
How verified
cargo fmt --all -- --checkcargo clippy --workspace --all-targets --all-features -- -D warningscargo test --workspace(qq-core: 727 passed, 3 ignored)cargo test -p qq-provider --no-default-features --features test-support—qq-providerunchangedcargo test -p qq-core --lib sessions::tests::audit— 7 new tests:every_commit_is_chained_from_genesis_and_exports_the_stored_bytes(also paging by cursor + raw-JSON export),the_chain_continues_across_restart_and_a_fresh_workspace_is_intact_and_empty,an_edited_row_is_a_hash_mismatch_at_its_sequence,a_removed_middle_row_breaks_the_link_at_the_next_sequence,a_removed_tail_row_is_a_head_mismatch,a_row_written_around_the_kernel_is_unhashed_not_history,pre_37_rows_are_an_unhashed_prefix_and_the_chain_starts_after_migration. Existinga_current_store_reopens_without_rerunning_migrationscaught a missing"37"in the earlier "already migrated" guards during development.Impact
UPDATE workspacesper event, inside the existing transaction.cargo bench -p qq-core --bench store_output_batch: 18–20 ms/batch on this branch vs 18–19 ms onmain(3 runs × 5 iterations each) — within noise.pre_37_rows_are_an_unhashed_prefix_and_the_chain_starts_after_migrationplus the historical fixtures intests/migrations.rsnow assert the final version37.docs/design/architecture.md§ Persistence (audit chain paragraph);docs/plans/progress/security-kernel.mdSK1 receipt.Link to Devin session: https://app.devin.ai/sessions/4a83e789a14d4b4190950fb8678d668e
Open in Devin Desktop: https://app.devin.ai/desktop/session/4a83e789a14d4b4190950fb8678d668e?variant=devin
Requested by: @integrate-your-mind