Skip to content

feat(runtime): hash-link the event journal and export/verify the audit chain (SK1) - #165

Closed
devin-ai-integration[bot] wants to merge 2 commits into
devin/1790291851-security-kernel-adrfrom
devin/1790292004-audit-chain
Closed

devin-ai-integration[bot] wants to merge 2 commits into
devin/1790291851-security-kernel-adrfrom
devin/1790292004-audit-chain

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

What changes for users

None visible in the TUI/CLI. Embedders get two new SessionRuntime methods:

// committed rows after `after`, oldest first, ≤ MAX_AUDIT_PAGE (1024); the
// stored envelope bytes plus both chain links, serialisable as raw JSON
pub async fn export_audit(&self, workspace: WorkspaceId, after: u64, limit: u16)
    -> Result<Vec<AuditChainRecord>, SessionRuntimeError>;

// walks the whole chain in bounded pages
pub async fn verify_audit(&self, workspace: WorkspaceId)
    -> Result<AuditVerification, SessionRuntimeError>;

enum AuditVerification { Intact { records, unhashed_prefix, head }, Broken { sequence, fault } }
enum AuditFault { Unhashed, HashMismatch, LinkBroken, HeadMismatch { expected, actual } }

A store edited behind the kernel's back (row rewritten, middle row deleted, tail rows deleted, row inserted without hashes) now verifies as Broken at the offending sequence instead of reading back as history.

Why / design

Port of axiom-events (A3 in the integration plan) as library code inside qq-core, per ADR-0042 (stacked on #163). Store stays the trust root; no service, no new dependency (sha2 already in qq-core).

  • Schema 36 → 37, additive: events.previous_hash, events.record_hash, workspaces.audit_head (nullable TEXT). Pre-37 rows keep NULL and verify as an unhashed_prefix; a new NULL row after the chain began is Unhashed (written around the kernel).
  • record_hash = sha256("qq-audit-v1\0" ‖ previous_hash_hex ‖ "\0" ‖ envelope_json), genesis previous = sha256("qq-audit-genesis-v1\0" ‖ workspace_id) — domain-separated from ContentHashes of the same bytes, and two workspaces never share a chain.
  • Append transaction (events.rs): UPDATE workspaces … RETURNING next_sequence, audit_head → hash the exact encoded bytes → INSERT with both links → advance head → then feed::stage. Persist-before-publish unchanged; a failed write moves neither sequence nor head.
  • Store::audit_page returns the page and the head from the same store call, so a chain that grows while verify_audit walks it still verifies against its own head.
  • Not ported: signatures/issuer keys over the head, external anchoring (supervisor's job per ADR-0009), CLI/HTTP export surface (follow-up once the control plane names its sink).

Linear: ENG- (none assigned; workstream ticket per parent session)
Slice: docs/plans/security-kernel.md#sk1

How verified

  • cargo fmt --all -- --check
  • cargo clippy --workspace --all-targets --all-features -- -D warnings
  • cargo test --workspace (qq-core: 727 passed, 3 ignored)
  • cargo test -p qq-provider --no-default-features --features test-support — qq-provider unchanged
  • Manual check: cargo 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. Existing a_current_store_reopens_without_rerunning_migrations caught a missing "37" in the earlier "already migrated" guards during development.

Impact

  • Performance: one SHA-256 over the envelope + one UPDATE workspaces per 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 on main (3 runs × 5 iterations each) — within noise.
  • Compatibility: PROTOCOL/DESCRIPTOR unchanged. Store schema 36→37; migration test pre_37_rows_are_an_unhashed_prefix_and_the_chain_starts_after_migration plus the historical fixtures in tests/migrations.rs now assert the final version 37.
  • Docs: docs/design/architecture.md § Persistence (audit chain paragraph); docs/plans/progress/security-kernel.md SK1 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


Devin Review

integrate-your-mind and others added 2 commits September 24, 2026 23:39
…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>
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Devin Review found 2 potential issues.

1 flag not posted on this PR by your GitHub settings — view it in Devin Review. (Configure)

Devin Review

Comment on lines +20 to +21
/// Most records one `export_audit` page returns.
pub const MAX_AUDIT_PAGE: u16 = 1_024;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

🔴 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.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +199 to +210
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)?,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

🟡 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.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

@lg2m

lg2m commented Sep 26, 2026

Copy link
Copy Markdown
Collaborator

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 (feat/eng-939-mcp-pinning-stack, tracking ENG-939). Your authorship is preserved via Co-Authored-By on the commit.

#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 docs/adr/0046-mcp-tool-set-pinning.md):

  • The audit hash chain from this PR is deferred, not rejected: the verifier returned Intact after a SQL cursor rewrite (UPDATE events SET sequence = 2 WHERE sequence = 1) and treated an unhashed row inserted into a fresh schema-37 store as a legacy unhashed_prefix; export_audit pages are bounded by record count (1,024) but not bytes (~1 GiB possible at the 1 MiB per-event cap); and there is no consuming checkpoint or retention contract yet, while a continuous per-workspace chain conflicts with the proposed ADR-0038 event deletion. Recorded as decisions-needed build(release): publish tagged releases and embed the source revision… #10 in docs/plans/progress/decisions-needed.md.
  • If you want to pursue it, a design note covering the threat model (who verifies, against what anchor), byte-bounded pages, cutover rules for pre-chain rows, and the retention interaction would be the right next step before code.

This PR will be closed as superseded once #194 merges.

lg2m added a commit that referenced this pull request Sep 26, 2026
… 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>
@lg2m lg2m closed this Sep 26, 2026
@lg2m
lg2m deleted the devin/1790292004-audit-chain branch September 28, 2026 05:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants