Skip to content

Serve content-addressed artifacts as their exact canonical bytes - #154

Merged
djh58 merged 2 commits into
2.x.xfrom
dan/artifact-hash-mismatch-fix
Aug 19, 2026
Merged

djh58 merged 2 commits into
2.x.xfrom
dan/artifact-hash-mismatch-fix

Conversation

@djh58

@djh58 djh58 commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

Problem

GET /public/v1/artifacts/{sha256} returns a document whose SHA-256 is not the requested hash, so no external verifier can confirm any artifact byte-for-byte. The hash side and the serve side use different serializers:

  • hash side: canonical_json_text() = json.dumps(payload, sort_keys=True, separators=(",", ":")) (share_ledger.py)
  • serve side: json.dumps(payload, sort_keys=True) + trailing \n — the generic write_json path

public_api.artifact() returned a parsed dict, so the exact hashed bytes were lost before the response was written.

Mainnet reproduction (2026-08-19), artifact b3db0a91406f4288da5985fb708fc1da3749f037275845ad920a346421a8c163 (qbit.prism.ctv-fanout-manifest.v1, 8,860 bytes served):

serialization sha256
served bytes 6c1df2a6ab0eb220…
json.dumps(d, sort_keys=True) (served minus trailing newline) 2adcb1149b5e2db9…
canonical_json_text(d) b3db0a91406f4288… ← advertised

GET /public/v1/artifacts/6c1df2a6… → 404, confirming the store is keyed by the canonical digest and only the response is re-serialized.

This affects every artifact kind, including CTV manifests and manifest-sets — they are only "unaffected" for a verifier that re-canonicalizes the parsed document; byte-level verification (sha256(response body) == {sha256}) fails for all kinds. Tracking issue: SwapLabsInc/qbit-mining-bootstrap#182 (scope corrected there accordingly).

Fix

Serve the exact bytes the hash was computed over. The ledger already persists them for the manifest kinds — manifest_json / manifest_set_json are written next to the JSONB copies at record time, by the same call that computes the hash:

  • share_ledger: new dashboard_public_artifact_canonical_json() on both backends returns the persisted canonical text for CTV manifests and manifest sets, None for audit bundles.
  • public_api.artifact(): verifies sha256(canonical bytes) == {sha256} and returns them as a RawJsonBody; any mismatch (a store-integrity fault) falls back to the legacy re-serialized response, so the endpoint can never serve "exact" bytes that contradict the content address.
  • audit_http.write_json: writes RawJsonBody verbatim — no re-serialization, no trailing newline, Content-Type: application/json. Cache headers (immutable, CDN TTLs) and the public response cache behave as before, and Content-Length now equals the byte_length advertised by settlement artifact_links.

No hash definition changes; historical hashes stay valid. The response parses to the identical document (keys were already sorted on both sides — only separators and the trailing newline differ), so dashboard clients are unaffected.

What is and isn't covered

  • Fixed now: CTV fanout manifests and manifest sets — byte-exact and self-verifying. This is the artifact class dashboards' artifact viewers consume.
  • Not yet: audit bundles. Their hash covers the Rust struct-declaration-order canonicalization (qbit-prism-audit-canonicalize); those bytes are produced and verified at persist time but not stored (the external body store writes compact v2/segmented layouts). Bundles keep the legacy response, and the regression suite pins that gap with an expectedFailure test to be flipped by the follow-up. Proposed follow-up (detailed in the tracking issue): persist the canonical bundle bytes at hash time — they are already in hand there — rather than re-deriving tens of MB via subprocess per request on a public endpoint, which would also silently invalidate historical hashes if struct declaration order ever changed.

Other endpoints checked: settlement-artifacts and fanout responses embed only links (sha256 + url + byte_length), never artifact bodies. The /audit/* bundle and manifest-set endpoints return metadata envelopes, which are not content-addressed; their embedded *_json string fields already carry the canonical text.

Tests

  • PublicArtifactByteExactnessTests (the regression coverage that was missing): asserts sha256(response body) == advertised hash for each manifest kind over real HTTP; byte-exactness across public-cache hits (with the immutable CDN header); uppercase-hash request paths; tampered canonical text falling back to legacy serving; audit-bundle byte-exactness as expectedFailure.
  • Memory-ledger end-to-end: real persist_ctv_fanout_manifest_set → HTTP responses hash to the advertised digests for both kinds.
  • Ledger-level: memory-backend canonical getter returns exactly canonical_json_text(...); Psql getter reads manifest_set_json / manifest_json (canned-query harness).
  • Docs: OpenAPI + public-dashboard README now state the byte-exact contract per artifact kind.

Full unittest discovery matches the base commit (the test_prism_job_builder spool/splice failures on macOS are pre-existing and unrelated; verified identical on 2.x.x HEAD without this change).

Release-line note

Production runs the 1.x line, so this fix does not reach the live pool from 2.x.x alone. The commit cherry-picks onto origin/1.x.x with one mechanical relocation — the write_json hunk lands in prism_coordinator.py's handler (audit_http.py does not exist there) — and the full dashboard + ledger test modules pass on that branch (verified locally). Backport PR ready to open on request.

🤖 Generated with Claude Code


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

GET /public/v1/artifacts/{sha256} re-serialized every artifact through the
generic write_json path (json.dumps sort_keys=True, default separators, plus
a trailing newline), while manifest and manifest-set hashes are computed over
canonical_json_text (compact separators). sha256(response body) therefore
never matched the advertised hash, so no external verifier could confirm any
artifact byte-for-byte.

The ledger already persists the exact hashed text (manifest_json /
manifest_set_json) next to the JSONB copies. Serve it:

- share_ledger: dashboard_public_artifact_canonical_json on both backends
  returns the persisted canonical text for CTV manifests and manifest sets,
  None for audit bundles (their Rust struct-order canonical bytes are not
  stored).
- public_api.artifact: wrap the canonical text as RawJsonBody after
  verifying sha256(bytes) == the requested hash; fall back to the legacy
  re-serialized response on any mismatch so a store-integrity fault can
  never serve bytes that contradict the content address.
- audit_http.write_json: write RawJsonBody bytes verbatim with
  Content-Type: application/json; no re-serialization, no trailing newline.

No hash definition changes; historical hashes stay valid. Audit bundles keep
the legacy response until their canonical bytes are persisted at hash time;
the expectedFailure regression marker documents that remaining gap.

Co-Authored-By: Claude Fable 5 <[email protected]>
@djh58

djh58 commented Aug 19, 2026

Copy link
Copy Markdown
Member Author

@cursor review, @codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6f3bd7fd67

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread lab/prism/share_ledger.py Resolved

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 6f3bd7f. Configure here.

Review follow-up: the standalone canonical-json lookup duplicated the
legacy artifact query's predicates and added a second sequential read per
uncached request — and since the response cache stores only 2xx results,
arbitrary 404 probes against the unauthenticated endpoint paid both
statements (four unindexed table probes) every time.

Replace both reads with one dashboard_public_artifact_document() read
model returning {payload, canonical_json} from a single statement: the
audit/set/artifact lookups become shared CTEs selecting the JSONB copy and
its persisted canonical text together, so every request — hit, miss, or
audit bundle — touches each artifact table at most once, exactly like the
pre-change query. dashboard_public_artifact() delegates to it, and
public_api.artifact() consumes the document with the same sha256
self-verification and legacy fallback semantics.

Co-Authored-By: Claude Fable 5 <[email protected]>
@djh58

djh58 commented Aug 19, 2026

Copy link
Copy Markdown
Member Author

Addressed the double-lookup finding in 375b2c2: the canonical text now rides the existing artifact query instead of a second statement. dashboard_public_artifact_document() returns {payload, canonical_json} from one statement whose audit/set/artifact lookups are shared CTEs selecting the JSONB copy and its persisted canonical text together — so every request (hit, 404 probe, or audit bundle) touches each artifact table at most once, identical to the pre-change scan count, and the duplicated predicates are gone. dashboard_public_artifact() delegates to it for compatibility.

Deliberately not adding indexes on manifest_set_sha256 / manifest_sha256 here: that is a production DDL change, the tables grow by one set row and a handful of artifact rows per found block, and the pre-existing query has always probed them unindexed. If growth ever warrants it, it belongs with the audit-bundle follow-up.

@djh58
djh58 merged commit 050f300 into 2.x.x Aug 19, 2026
11 checks passed
kiwidream added a commit that referenced this pull request Aug 19, 2026
… tier

Rebasing the read-tier extraction onto 2.x.x put it on top of #154, which
landed while this PR was in review. Git merged the two textually, but the
result was semantically broken in both directions:

- audit_http kept #154's `public_api.RawJsonBody` branch in write_json while
  the extraction removed the public-API import, so every audit response
  raised NameError. GET /public/v1/artifacts/{sha256} moved out of this
  listener, so no route reaching it can carry pre-serialized bytes: the
  branch is dead here and is removed, restoring the module's import
  isolation.
- public_read_service.write_json re-serialized every payload with sorted
  keys and a trailing newline. The artifacts route moved into this process,
  so #154's fix silently regressed: sha256(response body) would no longer
  match the advertised artifact hash. The RawJsonBody branch moves here with
  the route it serves.

The two byte-exactness tests #154 added now exercise the extracted handler
rather than the coordinator's audit handler, which is what pins the
regression: they fail without the branch above.
kiwidream added a commit that referenced this pull request Aug 19, 2026
* Extract the PRISM public read tier into its own process (#145)

The coordinator served its public dashboard API on the same in-process
listener as its operator endpoints, under the same GIL that acknowledges
shares and lands blocks, against the same primary Postgres the
lease-holding writer commits through. Read traffic scales with public
interest rather than hashrate, so it was the one workload whose volume the
pool does not control -- and it sat on the money path.

Exactly the 13 /public/v1 routes classified Disposition.EXTRACT move.
/healthz, /metrics, /audit/*, /owed* and the miner/payout status aliases
stay on the coordinator, per docs/prism-public-operator-endpoint-split.md.

Sever the two writer-lock reads on public routes first; without this the
move would relocate GIL contention and keep lock contention:

- PsqlShareLedger.dashboard_miner_owed_balance_bits filters one recipient
  in SQL through _run_read_json, replacing owed_balance_for_recipient's
  scan of every recipient's balance under the writer lock. That made
  /public/v1/miners/{recipient_id}, the most-polled route on the surface,
  a fenced read.
- PsqlShareLedger.dashboard_direct_coinbase_settlement takes the
  direct-coinbase settlement branch off audit_bundle(), resolving the body
  through the existing _resolve_audit_bundle_row sha256 verification.

public_api prefers both through the same duck-typed pattern as every other
read model, keeping the old paths as in-memory-ledger fallbacks. Both were
verified against real Postgres to return exactly what they replace,
including multi-program recipients, negative balances, and quoted
recipient ids.

The new service is read-only in three independent ways: PsqlShareLedger
gains read_only=True, which skips writer-lease acquisition and swaps the
writer lock for a gate that refuses to be acquired at all; the audit
artifact store gains read_only=True so it holds no publication lock and
works against the :ro volume mount; and the container receives no writer,
signing, or block-submission configuration. It refuses to start without
PRISM_PUBLIC_STRATUM_URL (the fallback would advertise 127.0.0.1:3340 to
miners) or on the in-memory ledger (whose missing dashboard_* read models
would send public_api's fallbacks back onto writer-lock reads).

Staleness becomes a contract, following observability.py's cached /metrics
precedent: Endpoint gains max_staleness_seconds, derived as
max(3 * (cache_ttl + underlying_cache), 15) rather than hand-picked, and
every response publishes X-Prism-Staleness-Budget-Seconds beside Age and
returns 503 rather than serve past it. /public/v1/artifacts/{sha256} is
exempt via an explicit immutable_content flag.

AuditHttpFacade's lifecycle machinery is untouched; audit_http no longer
imports public_api at all, and an unknown /public/v1 request reaches its
ordinary unknown-endpoint 404.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Apply the PR #152 review fixes: deployment seam, stratum env, doc claims

REQUEST_CHANGES findings from the Fable review of the public read tier
extraction, applied on top of the extraction rebased onto the hardened
endpoint-registry base:

- Blocker 1: make up-prism-pool and every mainnet runbook bring-up path
  (config/pull/up service lists and the lane table) started only the
  coordinator, so a pool brought up through the documented seam had no
  public API at all. prism-public-api is now part of each of them.

- Blocker 2: PRISM_STRATUM_PORT and PRISM_STRATUM_HIGHDIFF_PORT never
  reached the prism-public-api container, so the rendered
  /public/v1/mining-configuration silently dropped the High-diff
  endpoint the coordinator was actually listening on. Both now pass
  through the compose environment; the compose-profile suite pins the
  pass-through and a contract-equality case pins the High-diff endpoint
  in the served body against public_api.dispatch with the env set.

- Should-fix 3: the dashboard README told operators to raise a route's
  staleness budget alongside its cache TTL, but no budget knob exists --
  the budgets are constants in lab/prism/endpoint_registry.py. The
  paragraph now names the cache TTL knobs that do exist and says the
  registry constant is what changes with them.

- Should-fix 4: the extraction moved the process, not the read-replica
  back-end, so the read-service test docstring no longer equates the
  move with all of issue #145; the replica remains a follow-up and the
  service still reads the primary Postgres.

Co-Authored-By: Claude Fable 5 <[email protected]>

* Carry #154's content-addressed artifact bytes into the extracted read tier

Rebasing the read-tier extraction onto 2.x.x put it on top of #154, which
landed while this PR was in review. Git merged the two textually, but the
result was semantically broken in both directions:

- audit_http kept #154's `public_api.RawJsonBody` branch in write_json while
  the extraction removed the public-API import, so every audit response
  raised NameError. GET /public/v1/artifacts/{sha256} moved out of this
  listener, so no route reaching it can carry pre-serialized bytes: the
  branch is dead here and is removed, restoring the module's import
  isolation.
- public_read_service.write_json re-serialized every payload with sorted
  keys and a trailing newline. The artifacts route moved into this process,
  so #154's fix silently regressed: sha256(response body) would no longer
  match the advertised artifact hash. The RawJsonBody branch moves here with
  the route it serves.

The two byte-exactness tests #154 added now exercise the extracted handler
rather than the coordinator's audit handler, which is what pins the
regression: they fail without the branch above.

---------

Co-authored-by: Alex <[email protected]>
Co-authored-by: Claude Opus 5 <[email protected]>
Co-authored-by: Alex <[email protected]>
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.

1 participant