← Back to Pull requests

feat(insight): serve the census views from stored builds (wave d, foundry#56) #434

Merged
gurnben merged 15 files (690 lines) on Nov 12, 2026 23:48 UTC
View on GitHub
gurnben gurnben commented on Nov 12, 2026 18:46 UTC
Author

What

Wave (d) of the performance lane (foundry#56): the four census insight views — findings-rollup, coverage, remediation-index, findings-trend — stop being folded on demand and start being served from stored builds.

  • InsightService.record_builds() folds the four once at the GLOBAL scope and publishes them as one insight-builds artifact (contracts #143, the SLA-policy imported-document pattern — no new table, no DDL). The dashboards lane's fast insight_builds pack asset runs it at a 5–15 minute cadence (the traust/SCI PRs).

  • InsightService.serve() — the door behind GET /v1/insights/{name} — serves the newest build for an unscoped read and folds on demand for: a scoped filter, ?refresh, a view the census does not carry, the first request before any build, a build a person's judgement postdates, and a build older than the 30-minute serving bound.

  • X-Traust-View-Built-At names the moment the served census was read; absent means the read folded.

  • The measured point (the audit, 2026-11-12, integration + production): the cold insight fold was 72–134 s per build, five builds per dashboard load, refolded at every TTL expiry — the fold that starved core's own healthz (11 core ReplicaSets in 32 h). The stored-build serve reads one indexed artifact row plus the freshness bound: 5–9 ms end-to-end on the verification below, the plan-gated query cost in .perf/report.md.
  • The decisions

  • Qodo's review of this PR (6 findings) — 4 fixed, 2 declined with reasoning (the follow-up commit 62ee6812):

  • - Fixed (finding 2, backdated judgements): the freshness bound now compares recording time (decision.created_at, the database's clock) against the build's publication (the artifact row's created_at — also the database's), so a statement recorded after a build supersedes it whatever moment it claims. newest_person_statement reads the new partial index idx_decision_person_recorded (contracts #143's second commit).
    - Fixed (finding 3, re-parsed per request): the parse cache is real now — ParsedBuilds is owned by the Context (which lives for the process) and injected into every per-request wiring, with a lock; a regression test proves one parse serves two wirings. The first 38b3c5f9 shape had it on the service instance, which is rebuilt per request — Qodo was right, and the first end-to-end receipts' "5–9 ms" was only true because the fixture was tiny.
    - Fixed (finding 4, unreadable build → 500): the fetch-and-parse is inside the fallback — an unreadable build (corrupt bytes, schema drift after a pin bump) is remembered as unreadable (negative-cached by row id) and every read folds until the next publication. Regression test corrupts the stored bytes and asserts the fold.
    - Fixed (finding 5, the freshness walk): the partial index over human rows makes the per-serve read an index head read however sparse people are among the machines — an estate with no human judgement at all reads an empty index, not the table.
    - Declined (finding 1, the four folds are not one snapshot): true, and unchanged from today — the on-demand path folds each view independently per request at whatever moment it runs. Holding one repeatable-read transaction across minutes of folds would be worse, and a retry-on-interleaved-write protocol is machinery the plan does not ask for; the person-judgement bound covers the write that matters.
    - Declined (finding 6, the post-decide window folds per request): this window is exactly today's behaviour (every read folds today, always), bounded by the cadence, and SCI's 30 s single-flight cache bounds the fold rate on the read side. Core-side single-flight across processes would need advisory locks and a shared fold result — the plan accepts the window knowingly ("either rebuild the affected views on those writes or accept and document the window"; this PR rebuilds at the next read), and wave (e) shrinks the fold's cost.
  • Round 2 (Qodo's update on the fix commit + Michele's P2 inline) — 2 fixed, 1 addressed-and-marked, 1 already fixed, 2 declined (commits 43ad5f46/438a7499):

  • - Fixed (Qodo #1 / Michele's P2, decides during a build): the freshness bound is now a pre-fold watermark. record_builds reads the newest person decision's recording time before the fold begins and publishes it in the artifact as folded_after; serve refuses the build when the current newest person decision is at or after that watermark. A decide committed after the watermark — including mid-fold, exactly the interleaving Michele reproduced (stored open-critical 1 vs fresh 0) — is unverifiable in the build and never served stale. Both values are decision.created_at: one table, one clock, no cross-clock comparison at all. Regression: test_a_decide_during_the_fold_supersedes_the_build (a decision commits between the watermark read and publication; the build is refused).
    - Addressed (Qodo #2, storage growth) — corrected after measuring: the envelope carries no moment of its own (the artifact row's created_at is the publication; the database owns time), but that does not dedupe builds: the coverage and trend models stamp their fold moment (population.as_of / as_of, part of their view contracts), so every build's document differs even on an unchanged census — verified live, two consecutive builds over identical counts produced different digests. Storage therefore grows one census-sized artifact per cadence period (~144/day at 10 minutes). The artifact table is append-only and no cadence-published kind has retention, so the growth is marked NEED(artifacts: cadence retention) at record_builds with this rate documented — a platform mechanism (the existing NEED(artifacts: orphaned object GC) covers rollback orphans, not cadence growth), not a bespoke pruner here.
    - Fixed (Qodo #9, lockfile): re-locked with uv 0.13.x — the diff is now revision 5 against development's, containing only the traust-contracts pin change.
    - Already fixed (Qodo #6, the freshness walk): the finding's text predates the fix commit — newest_person_statement reads the new partial index idx_decision_person_recorded (Qodo's own recommended alternative), an index head read however sparse people are; the perf case pins it (Index Only Scan … 0.005 ms at 250k decisions).
    - Declined (Qodo #4/#7 and the first round's #1/#6, unchanged): the mid-fold snapshot mismatch and the post-decide fold window are today's behaviour, bounded by the cadence and by SCI's 30 s single-flight cache; see the round-1 disposition below.
  • One GLOBAL build serves every scope; no permission data in core. The audit verified SCI enforces authz per request by joining core's unscoped views to the caller's items, on every surface, no leak path — the per-user projection is milliseconds. The boundary stays at SCI (foundry#56, "The authz finding"): a synced principal→scope map in core was explicitly rejected as a security regression. A scoped filter therefore folds (today's behaviour), and the stored census is post-filtered by each caller exactly as the fold's always was.

  • The freshness contract (the plan's option: rebuild-on-write, realized at the read): the census can be one cadence stale, but a build a person's judgement was recorded after never serves — after a countersign decide (the write that matters) the next read folds with the moved counts, and the next cadence build re-arms serving. The signal is the newest human decision's recording time (decision.created_at) against the build's publication time (the artifact row's created_at) — both the database's clock, so no cross-clock skew, and a backdated statement still counts. A machine statement never flips serving. A build older than SERVE_STALE_AFTER (30 min — the cadence's ceiling times slack) also folds: a stalled builder fails safe to today's behaviour instead of serving a stale census. The console already accepts 30 s staleness by design; the route's docstring and README document the widened window.

  • The parse is once per publication, never per request. _newest() reads the newest imported artifact row (history(..., 1), idx_artifact_imported_kind) and hands the bytes to the Context-owned ParsedBuilds cache, keyed by the row id with a lock (services are wired per request; the cache outlives them) — each view's model is re-validated as that view's. A build that cannot be read or parsed is negative-cached as unreadable and the reads fold until the next publication — never a 500.

  • The round-trip wart, handled precisely: a model's computed fields (e.g. FindingTally.tracked) dump as output the strict models refuse as input. _revalidate drops exactly the paths pydantic reports as extra_forbidden and retries — no blanket extra=ignore, no hand-copied field lists; a stored field is never stripped.

  • The trend view rides the same cadence ("the same treatment", the plan's first option): one artifact, one coherent census snapshot; wave (e)'s SQL aggregation lands the builder's own speed-up later.
  • Reviewer checks

  • Targets development

  • No new tables, columns or row models; the one new named query (DecisionRepository.newest_person_statement) is on the owning table's repository

  • New SQL has a perf case (test_newest_person_statement_walks_the_occurred_index_backwards) and the serving path has one (test_a_stored_census_serve_reads_the_build_and_the_freshness_bound_only)

  • Tests: behaviour on SQLite and Postgres via uow/seed (test_insight_builds.py, the decision query cases in test_findings.py, the REST cases in test_insights.py)

  • Comments only for non-obvious whys; make lint-fix && make test green
  • Changed tests

    New only; no existing assertion, fixture, skip or expectation changed:

  • tests/v1/services/test_insight_builds.py (new, 13 cases × SQLite/Postgres): record→serve identity with the fold, every census view stored and served, first-read-before-build folds, scoped filter folds, a non-census view folds, a person's judgement recorded after the build supersedes it and the next build re-arms, a backdated judgement recorded after the build still supersedes it, a machine judgement does not, the newest build is served, the 30-minute bound folds, no-store refuses with ConfigError, an unreadable build folds instead of failing the read, and one parse serves two wirings.

  • tests/v1/repositories/tables/test_findings.py: two cases for newest_person_statement (human-only actors; None without a human judgement).

  • tests/v1/rest/insight/test_insights.py: three route cases (stored serve with the header; ?refresh folds; first read folds).

  • perf/queries/test_findings.py, perf/queries/test_insights.py: the two new perf cases.
  • Verification

  • make lint-fix green.

  • make test 13,784 passed, 2 skipped (the push hook's own full changed-suite run, re-run on the corrected commit).

  • make test-integration (Postgres) 4,024 passed, 6 skipped.

  • Two test_assessment_prepare.py caller-cap tests fail on pristine origin/development on this workstation and pass in CI on the same commits — the fixture allows ctags while asserting the builtin extractor's output, and this host has Universal Ctags installed; under CI's environment (no usable ctags on PATH) they pass. Unrelated to this diff; noted for whoever owns that suite.

  • make perf — the two new cases green (see the excerpt below); the plan-key lines and timings are in .perf/report.md.

  • End-to-end on the real binary path (real traust-server, the real census leg of traust dashboard refresh as the pack asset runs it, Postgres, the artifact store):

  • 1. first read before any build → 200, no header (folded — today's behaviour);
    2. dashboard refresh --census → {"outcome":"succeeded","written":["4af7eb44-…"]};
    3. next reads → 200 in 9.3 / 5.4 / 6.8 ms with x-traust-view-built-at, body byte-identical to the on-demand fold's;
    4. ?refresh=true → 200, no header (fold), identical counts; a scoped product_id read → folded (the RBAC shape);
    5. a countersign decide → the next unscoped read folds with the moved counts (open critical 1→0, risk_accepted 0→1) — the stored build was superseded;
    6. the census leg again → the route serves the new build (new built_at), the decide now inside the stored census.
  • Commit signed (2002C3B23CAFBB9D), verified. Normal push only.
  • Perf excerpt (.perf/report.md, at the suite's production volume: 10,000 repositories, 250,000 decisions)

    | test_newest_person_statement_reads_the_person_partial_index | Index Scan using idx_decision_person_recorded on decision (partial, human actors) | see below |
    | test_a_stored_census_serve_reads_the_build_and_the_freshness_bound_only | Index Scan using idx_artifact_imported_kind on artifact | 0.051 ms |
    | test_a_stored_census_serve_reads_the_build_and_the_freshness_bound_only | Index Scan using artifact_pkey on artifact | 0.026 ms |
    | test_a_stored_census_serve_reads_the_build_and_the_freshness_bound_only | Index Scan Backward using idx_decision_occurred on decision | 0.330 ms |
    

    Three statements serve a stored census — the newest artifact row, its bytes, the freshness bound — every one an index hit, no whole-scope read. The serve's wall clock on the first read after a publication includes the once-per-publication parse of the stored models (~0.9 s at this volume); every read after it is the cached parse (the 5–9 ms measured end-to-end below). The make perf run's three failures (test_an_assets_open_orders_by_index[page], test_prepare_reads_bounded_batches_by_index, and one flaky hot-repository budget) are pre-existing on pristine origin/development against the same shared database — reproduced before any of my changes were applied; both new cases here are green.

    Human review required: this changes what a GET serves (stored, within the documented window). Do not auto-merge.

    🤖 Generated with Crush

    Assisted-by: Crush:rits/zai-org/glm-5-3

    Diff: 690 lines (+680 / -10) across 15 files Reviewer: chubirka Review duration: 301m
    All Vouch review confidence checks passed
    Residual risk 0.07 = Change Risk (0.63) × (1 − Review Confidence (0.88)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.63 · 690 lines diff across 15 files
    0.63
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.93 · 5 substantive comment(s)
    0.93
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    88%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.391
    Real PR Conversation Timeline
    11 items
    qodo-code-review[bot] qodo-code-review[bot] commented on Nov 12, 2026 18:51 UTC
    Bot

    <h3>Code Review by Qodo</h3>

    <code>🐞 Bugs (11)</code> <code>📘 Rule violations (0)</code> <code>📜 Skill insights (0)</code>

    <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">

    <br/>

    <img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">

    <details>
    <summary> 1. Rebuilds can serve obsolete census data <code>🐞 Bug</code> <code>≡ Correctness</code></summary>

    <br/>

    <details open>

    ><summary>Description</summary>
    ><br/>
    ><pre>

    ><b><i>record_builds()</i></b> publishes content-only bytes, so <b><i>publish_artifact()</i></b> reuses an earlier imported
    >row when a census digest repeats instead of recording a new publication. If the data changes from A
    >to B and back to A, <b><i>serve()</i></b> keeps selecting B; if it remains unchanged, its row passes the
    >30-minute bound and every read refolds despite successful cadence runs.
    ></pre>
    ></details>

    <details>

    ><summary>Code</summary>
    ><br/>
    ><code>[src/traust_core/v1/services/insight.py[R403-407]](https://github.com/traust-security/traust-core/pull/434/files#diff-33baccc4b7229ac6a008e1deb9111adb23d99dc4414fb04187a3db0db1ce0f73R403-R407)</code>

    >
    >+        return self._builds.publish_artifact(
    >+            InsightBuildsArtifact.from_document(
    >+                {
    >+                    "folded_after": None if folded_after is None else folded_after.isoformat(),
    >+                    "views": {n.value: m.model_dump(mode="json") for n, m in models.items()},
    >

    ></details>

    <details>

    ><summary>Evidence</summary>
    ><br/>
    ><pre>

    >The new document contains a watermark and view output but no per-run identity. Imported-artifact
    >insertion returns an existing row for an existing digest; history orders by row creation time, and
    >the new serving path both selects that history head and expires it by that same time.
    ></pre>
    > <code>[src/traust_core/v1/services/insight.py\[399-409\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/services/insight.py/#L399-L409)</code>

    <code>[src/traust_core/v1/repositories/traust/assessments/artifact.py\[77-116\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/repositories/traust/assessments/artifact.py/#L77-L116)</code>

    <code>[src/traust_core/v1/repositories/traust/assessments/artifact.py\[147-159\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/repositories/traust/assessments/artifact.py/#L147-L159)</code>

    <code>[src/traust_core/v1/services/insight.py\[412-438\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/services/insight.py/#L412-L438)</code>

    ></details>

    <details>

    ><summary>Agent prompt</summary>
    ><br/>
    >
    >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
    >
    >## Issue description
    >A repeat census digest reuses an old artifact row. That leaves a reverted census behind a newer row and prevents an unchanged build from renewing the serving bound.
    >
    >## Fix Focus Areas
    >- src/traust_core/v1/services/insight.py[395-409]
    >- src/traust_core/v1/services/insight.py[412-438]
    >
    >## Recommended Fix
    >Give each successful build a distinct, database-owned publication record without treating the document digest as its publication identity. Ensure newest-row selection and the serving bound use that record. Add regression coverage for both unchanged consecutive builds past 30 minutes and an A→B→A return to earlier census content.
    >

    <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>

    ></details>

    Dismiss ↗ | View ↗

    <hr/>
    </details>

    <details>
    <summary> 2. <s>Decides during a build stay hidden on dashboards</s> <code>✓ Resolved</code></summary>

    <br/>

    <p><b>Resolving commit:</b> <a href="https://github.com/traust-security/traust-core/commit/438a749960613934cfa9771dedc9903dce03f6f2"><code>438a749</code></a></p>

    <details>

    ><summary>Resolution reason</summary>
    ><br/>
    ><pre>

    >At head, the freshness check compares the newest person statement against the watermark read before
    >the fold (folded_after), not against the publication row&#x27;s created_at, so a decision committed
    >mid-fold supersedes the build and the read folds.
    ></pre>
    ></details>

    <!-- qodo-finding-reference
    <code>↗ src/traust_core/v1/services/insight.py[R377-378]</code>
    -->

    <details>

    ><summary>Description</summary>
    ><br/>
    ><pre>

    ><b><i>serve</i></b> passes the artifact row’s publication-time <b><i>created_at</i></b> to <b><i>_superseded</i></b>, although
    ><b><i>record_builds</i></b> reads decisions while folding the rollup before that row is inserted. A countersign
    >committed after the decision read but before publication is absent from the build yet predates the
    >row, so subsequent unscoped reads can keep serving pre-decision counts until the next cadence build.
    ></pre>
    ></details>

    <hr/>
    </details>

    <br/>

    <img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">

    <details>
    <summary> 3. Overlapping builders replace newer results <code>🐞 Bug</code> <code>≡ Correctness</code></summary>

    <br/>

    <details open>

    ><summary>Description</summary>
    ><br/>
    ><pre>

    ><b><i>record_builds()</i></b> folds before calling <b><i>publish_artifact()</i></b>, which has no predecessor check on the
    >build it replaces. If an earlier-started fold finishes after a later-started fold that saw newer
    >machine-generated data, its older result receives the later publication timestamp and becomes the
    >census selected by <b><i>serve()</i></b>.
    ></pre>
    ></details>

    <details>

    ><summary>Code</summary>
    ><br/>
    ><code>[src/traust_core/v1/services/insight.py[R402-403]](https://github.com/traust-security/traust-core/pull/434/files#diff-33baccc4b7229ac6a008e1deb9111adb23d99dc4414fb04187a3db0db1ce0f73R402-R403)</code>

    >
    >+        models = {name: self.build(name, ViewFilter()) for name in CENSUS_VIEWS}
    >+        return self._builds.publish_artifact(
    >

    ></details>

    <details>

    ><summary>Evidence</summary>
    ><br/>
    ><pre>

    >The new build path has no ordering guard across its fold and publication. Ordinary publication
    >passes no successor constraint, while the artifact repository orders imported rows by publication
    >time; the serving path reads only that newest row.
    ></pre>
    > <code>[src/traust_core/v1/services/insight.py\[399-423\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/services/insight.py/#L399-L423)</code>

    <code>[src/traust_core/v1/services/artifact_publishing.py\[150-166\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/services/artifact_publishing.py/#L150-L166)</code>

    <code>[src/traust_core/v1/services/artifact_publishing.py\[415-438\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/services/artifact_publishing.py/#L415-L438)</code>

    <code>[src/traust_core/v1/repositories/traust/assessments/artifact.py\[147-159\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/repositories/traust/assessments/artifact.py/#L147-L159)</code>

    ></details>

    <details>

    ><summary>Agent prompt</summary>
    ><br/>
    >
    >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
    >
    >## Issue description
    >Concurrent builds can publish in the opposite order from their folds, making an older result the newest stored census.
    >
    >## Fix Focus Areas
    >- src/traust_core/v1/services/insight.py[384-410]
    >
    >## Recommended Fix
    >Capture the current publication before folding and publish with a predecessor check that rejects a build if another publication has won in the meantime. Add a concurrency regression in which the later-started build publishes first and the older build must not replace it.
    >

    <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>

    ></details>

    Dismiss ↗ | View ↗

    <hr/>
    </details>

    <details>
    <summary> 4. A brief store hiccup disables the stored census <code>🐞 Bug</code> <code>☼ Reliability</code></summary>

    <br/>

    <details open>

    ><summary>Description</summary>
    ><br/>
    ><pre>

    ><b><i>ParsedBuilds.parse</i></b> catches any <b><i>TraustError</i></b>, <b><i>ValueError</i></b> or <b><i>KeyError</i></b> raised by <b><i>read()</i></b> and
    >caches <b><i>None</i></b> against the row id, so a transient object-store or database failure is cached the same
    >way as corrupt bytes. Every unscoped census read in that process then runs the 72–134 s cold fold
    >until the next publication, and the lock is held during the fetch and the ~0.9 s parse, so a slow
    >store also stalls every concurrent census read in the process.
    ></pre>
    ></details>

    <details>

    ><summary>Code</summary>
    ><br/>
    ><code>[src/traust_core/v1/services/insight.py[R330-340]](https://github.com/traust-security/traust-core/pull/434/files#diff-33baccc4b7229ac6a008e1deb9111adb23d99dc4414fb04187a3db0db1ce0f73R330-R340)</code>

    >
    >+            try:
    >+                parsed: InsightBuilds | None = _parse_builds(read())
    >+            except (TraustError, ValueError, KeyError) as e:
    >+                log.warning(
    >+                    "stored insight build %s is unreadable (%s); folding until the next one",
    >+                    row_id,
    >+                    type(e).__name__,
    >+                )
    >+                parsed = None
    >+            self._by_row = (row_id, parsed)
    >+            return parsed
    >

    ></details>

    <details>

    ><summary>Evidence</summary>
    ><br/>
    ><pre>

    ><b><i>read</i></b> is <b><i>lambda: json.loads(self._builds.get(row.id).payload)</i></b>, which does I/O against the object
    >store and the database. Any <b><i>TraustError</i></b> from it, a transient connectivity failure included, falls
    >into the same branch as a schema failure, and <b><i>self._by_row = (row_id, None)</i></b> is stored. Line 328
    >then returns the cached <b><i>None</i></b> for every later call with that row id. <b><i>serve</i></b> folds whenever
    ><b><i>_newest()</i></b> returns <b><i>None</i></b>, which is the cold path this PR exists to avoid. Everything runs inside
    ><b><i>with self._lock</i></b>, so concurrent requests queue behind the fetch.
    ></pre>
    > <code>[src/traust_core/v1/services/insight.py\[326-340\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/services/insight.py/#L326-L340)</code>

    <code>[src/traust_core/v1/services/insight.py\[412-423\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/services/insight.py/#L412-L423)</code>

    <code>[src/traust_core/v1/services/insight.py\[374-382\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/services/insight.py/#L374-L382)</code>

    ></details>

    <details>

    ><summary>Agent prompt</summary>
    ><br/>
    >
    >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
    >
    >## Issue description
    >The stored-build parse cache stores `None` for any failure, transient store errors included, so a single blip makes the process fold on every census read until the next publication. The fetch also runs under the cache lock.
    >
    >## Fix Focus Areas
    >- src/traust_core/v1/services/insight.py[326-340]
    >- src/traust_core/v1/services/insight.py[412-423]
    >
    >## Recommended Fix
    >Split the fetch from the parse. Run the object-store/DB read outside the lock (or under a per-row single-flight). On a transient error, such as connectivity or store-unavailable errors, return `None` for this request without caching. Negative-cache only deterministic failures: an integrity/digest mismatch, a JSON decode error, or a schema/validation error. Optionally retry a negative entry after a short backoff. Add a test where the first read raises a transient error and the second read serves the build.
    >

    <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>

    ></details>

    Dismiss ↗ | View ↗

    <hr/>
    </details>

    <details>
    <summary> 5. A decide can slip past the build&#x27;s freshness check <code>🐞 Bug</code> <code>≡ Correctness</code></summary>

    <br/>

    <details open>

    ><summary>Description</summary>
    ><br/>
    ><pre>

    ><b><i>_superseded</i></b> treats the build as fresh when <b><i>newest_person_statement()</i></b> is not greater than
    ><b><i>folded_after</i></b>. <b><i>decision.created_at</i></b> is <b><i>statement_timestamp()</i></b>, the time of the INSERT, not of the
    >commit, so a human decide whose INSERT ran before the watermark read but which committed after it is
    >missed when another human decide with a later or equal timestamp committed first. In that
    >interleaving the newest committed timestamp equals the watermark, the build never saw the late
    >decide, and unscoped reads keep serving the old counts until the next cadence build, even though the
    >README says a mid-fold decide is &#x27;never served stale&#x27;.
    ></pre>
    ></details>

    <details>

    ><summary>Code</summary>
    ><br/>
    ><code>[src/traust_core/v1/services/insight.py[R430-433]](https://github.com/traust-security/traust-core/pull/434/files#diff-33baccc4b7229ac6a008e1deb9111adb23d99dc4414fb04187a3db0db1ce0f73R430-R433)</code>

    >
    >+        if self._decisions is None:
    >+            return False
    >+        newest = self._decisions.newest_person_statement()
    >+        return newest is not None and (folded_after is None or newest > folded_after)
    >

    ></details>

    <details>

    ><summary>Evidence</summary>
    ><br/>
    ><pre>

    >The decision table&#x27;s <b><i>created_at</i></b> defaults to <b><i>_DbNow()</i></b>, which Postgres compiles to
    ><b><i>statement_timestamp()</i></b> and SQLite to the insert-time <b><i>strftime</i></b>. Both are taken when the statement
    >runs, not at commit. Example: T1 inserts at t=10 and commits at t=20; T2 inserts at t=12 and commits
    >at t=13; the watermark read at t=15 gives 12. After T1 commits, the newest value is still 12, so
    ><b><i>newest &gt; folded_after</i></b> is false and the build is served without T1. The strict <b><i>&gt;</i></b> also misses an
    >equal-timestamp decide (millisecond precision on SQLite), even though the docstrings and README say
    >&#x27;at or after&#x27;. <b><i>test_a_decide_during_the_fold_supersedes_the_build</i></b> only covers one decide that
    >commits fully inside the fold.
    ></pre>
    > <code>[src/traust_core/v1/repositories/sql.py\[111-125\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/repositories/sql.py/#L111-L125)</code>

    <code>[src/traust_core/v1/repositories/sql.py\[150-159\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/repositories/sql.py/#L150-L159)</code>

    <code>[src/traust_core/v1/services/insight.py\[399-402\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/services/insight.py/#L399-L402)</code>

    <code>[src/traust_core/v1/services/insight.py\[425-433\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/services/insight.py/#L425-L433)</code>

    ></details>

    <details>

    ><summary>Agent prompt</summary>
    ><br/>
    >
    >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
    >
    >## Issue description
    >The freshness watermark compares the INSERT statement timestamps of human decisions. A human decide whose INSERT ran before the watermark read but which committed after the fold's reads can be hidden behind a concurrent decide that has a later or equal timestamp, so the stale build keeps serving.
    >
    >## Fix Focus Areas
    >- src/traust_core/v1/services/insight.py[399-402]
    >- src/traust_core/v1/services/insight.py[425-433]
    >- src/traust_core/v1/repositories/traust/findings/decision.py[177-187]
    >
    >## Recommended Fix
    >Use a watermark that only grows, in commit order. One option is to compare the count of human decisions (or the max of a sequence or id assigned at commit) taken before the fold with the same value read at serve time. Another is to subtract a safety margin longer than the longest decide transaction from `folded_after`, so any decide whose INSERT ran near the watermark read supersedes the build. Make the docstrings' 'at or after' match whichever comparison you choose. Add a test with two interleaved human decides, where the earlier-stamped one commits after the watermark read.
    >

    <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>

    ></details>

    Dismiss ↗ | View ↗

    <hr/>
    </details>

    <details><summary><ins><strong>View medium (7)</strong></ins></summary><br/>
    <details>
    <summary> 6. Every cadence build is kept in storage forever <code>🐞 Bug</code> <code>☼ Reliability</code></summary>

    <br/>

    <details open>

    ><summary>Description</summary>
    ><br/>
    ><pre>

    ><b><i>record_builds</i></b> publishes a new imported <b><i>insight-builds</i></b> artifact on each run, and every payload is
    >unique because it embeds <b><i>built_at</i></b>. Each run therefore always inserts a new artifact row and writes
    >a new object holding the whole GLOBAL census. Nothing in this PR prunes old builds, and the serve
    >path only ever reads the newest (<b><i>history(..., 1)</i></b>). A 5–15 minute cadence leaves roughly 100–290
    >multi-view census documents per day in the database and object store, growing without bound.
    ></pre>
    ></details>

    <details>

    ><summary>Code</summary>
    ><br/>
    ><code>[src/traust_core/v1/services/insight.py[R389-395]](https://github.com/traust-security/traust-core/pull/434/files#diff-33baccc4b7229ac6a008e1deb9111adb23d99dc4414fb04187a3db0db1ce0f73R389-R395)</code>

    >
    >+        built_at = self._clock.now()
    >+        models = {name: self.build(name, ViewFilter()) for name in CENSUS_VIEWS}
    >+        return self._builds.publish_artifact(
    >+            InsightBuildsArtifact.from_document(
    >+                {
    >+                    "built_at": built_at.isoformat(),
    >+                    "views": {n.value: m.model_dump(mode="json") for n, m in models.items()},
    >

    ></details>

    <details>

    ><summary>Evidence</summary>
    ><br/>
    ><pre>

    ><b><i>stage</i></b> writes <b><i>artifacts/{schema}/{sha256(payload)}.json</i></b> to the object store. <b><i>_publish_staged</i></b>
    >inserts a row unless the digest already exists, and because <b><i>built_at</i></b> changes on every call the
    >digest never repeats. <b><i>history</i></b>/<b><i>list_imported</i></b> read only the newest row. No retention or GC path
    >exists for imported artifacts (the code itself carries a <b><i>NEED(artifacts: orphaned object GC)</i></b>
    >note). The PR&#x27;s own figure of about 0.9 s to parse one build at production volume points to
    >documents of several MB each.
    ></pre>
    > <code>[src/traust_core/v1/services/artifact_publishing.py\[442-466\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/services/artifact_publishing.py/#L442-L466)</code>

    <code>[src/traust_core/v1/services/artifact_publishing.py\[531-545\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/services/artifact_publishing.py/#L531-L545)</code>

    <code>[src/traust_core/v1/repositories/traust/assessments/artifact.py\[151-160\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/repositories/traust/assessments/artifact.py/#L151-L160)</code>

    ></details>

    <details>

    ><summary>Agent prompt</summary>
    ><br/>
    >
    >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
    >
    >## Issue description
    >Each `record_builds` run stores a new full-census artifact row plus its object bytes, and nothing ever removes the older ones, even though only the newest is ever served.
    >
    >## Fix Focus Areas
    >- src/traust_core/v1/services/insight.py[384-398]
    >
    >## Recommended Fix
    >Add a bounded retention policy for `insight-builds`, for example keeping the newest N builds or the last X hours. Either prune older rows and objects after a successful publish, or register the kind with an existing artifact retention/GC mechanism. If retention is deliberately deferred, add a tracked `NEED(...)` marker and document the expected growth rate.
    >

    <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>

    ></details>

    Dismiss ↗ | View ↗

    <hr/>
    </details>

    <details>
    <summary> 7. <s>An unreadable stored build breaks census reads</s> <code>✓ Resolved</code></summary>

    <br/>

    <p><b>Resolving commit:</b> <a href="https://github.com/traust-security/traust-core/commit/62ee6812e71b274ca7f1d28b4267195d68e53d8f"><code>62ee681</code></a></p>

    <details>

    ><summary>Resolution reason</summary>
    ><br/>
    ><pre>

    >The PR&#x27;s current code no longer has the cited latest_build/unguarded read path. In _newest(), the
    >read is wrapped by ParsedBuilds.parse(), which catches (TraustError, ValueError, KeyError) around
    >both the object read (self._builds.get) and _parse_builds(json), logs a warning with the row id and
    >exception class only, and caches None so serve() folds on demand. Per-view validation failures in
    >_parse_builds are also caught (ValueError) and dropped. Tests in test_insight_builds.py cover the
    >corrupted-bytes fallback (test_an_unreadable_build_folds_instead_of_failing_the_read).
    >Missing-object and schema-failure tests are not explicitly listed, but the guarded fallback
    >addresses the issue at the current location.
    ></pre>
    ></details>

    <!-- qodo-finding-reference
    <code>↗ src/traust_core/v1/services/insight.py[R363-366]</code>
    -->

    <details>

    ><summary>Description</summary>
    ><br/>
    ><pre>

    ><b><i>latest_build</i></b> calls <b><i>self._builds.get(row_id)</i></b>, then reads <b><i>document[&quot;views&quot;]</i></b> and
    ><b><i>document[&quot;built_at&quot;]</i></b>, without any fallback. A failure there propagates out of <b><i>serve</i></b>: missing or
    >corrupt object bytes, a contracts-schema validation failure after a pin bump, or a malformed
    >document. Every unscoped census GET then returns a 500 instead of falling back to the fold, and this
    >lasts until a newer build is published (which may not happen if the builder fails the same way).
    ></pre>
    ></details>

    <hr/>
    </details>

    <details>
    <summary> 8. Each countersign brings back the cold fold <code>🐞 Bug</code> <code>☼ Reliability</code></summary>

    <br/>

    <details open>

    ><summary>Description</summary>
    ><br/>
    ><pre>

    >Once <b><i>_superseded</i></b> is true, every unscoped census read calls <b><i>self.build(view, filter)</i></b>, the 72-134
    >s cold fold, until the next cadence build runs. Nothing collapses concurrent folds into one, so each
    >human decide during working hours brings back up to one cadence (5-15 min) of the per-dashboard-load
    >refolding that starved healthz, and a stalled builder (<b><i>_expired</i></b>) does the same with no time limit.
    ></pre>
    ></details>

    <details>

    ><summary>Code</summary>
    ><br/>
    ><code>[src/traust_core/v1/services/insight.py[R326-336]](https://github.com/traust-security/traust-core/pull/434/files#diff-33baccc4b7229ac6a008e1deb9111adb23d99dc4414fb04187a3db0db1ce0f73R326-R336)</code>

    >
    >+        if not refresh and view in CENSUS_VIEWS and filter == ViewFilter():
    >+            build = self.latest_build()
    >+            if (
    >+                build is not None
    >+                and not self._superseded(build.built_at)
    >+                and not self._expired(build.built_at)
    >+            ):
    >+                model = build.views.get(view)
    >+                if model is not None:
    >+                    return ServedInsight(model=model, built_at=build.built_at)
    >+        return ServedInsight(model=self.build(view, filter))
    >

    ></details>

    <details>

    ><summary>Evidence</summary>
    ><br/>
    ><pre>

    ><b><i>serve</i></b> has no single-flight lock, no back-off and no reuse of a fold result: every request that
    >misses the build folds on its own. The PR description reports the cold fold at 72-134 s per build
    >with five builds per dashboard load, and names it as the cause of the healthz starvation. Human
    >countersigns trigger this window on purpose, so the incident pattern returns whenever people triage.
    ></pre>
    > <code>[src/traust_core/v1/services/insight.py\[319-336\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/services/insight.py/#L319-L336)</code>

    <code>[src/traust_core/v1/services/insight.py\[382-393\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/services/insight.py/#L382-L393)</code>

    ></details>

    <details>

    ><summary>Agent prompt</summary>
    ><br/>
    >
    >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
    >
    >## Issue description
    >When a person's judgement supersedes the stored build, or the build expires, every unscoped census request runs the full cold fold on its own until the cadence rebuilds.
    >
    >## Fix Focus Areas
    >- src/traust_core/v1/services/insight.py[319-336]
    >
    >## Recommended Fix
    >On a superseded or expired build, trigger one `record_builds()`, guarded by a process-wide lock or an advisory lock, and have concurrent unscoped readers wait for it or share its result, instead of each running its own fold. Alternatively, have the decide path enqueue an immediate rebuild.
    >

    <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>

    ></details>

    Dismiss ↗ | View ↗

    <hr/>
    </details>

    <details>
    <summary> 9. <s>Backdated judgements leave stale census counts</s> <code>✓ Resolved</code></summary>

    <br/>

    <p><b>Resolving commit:</b> <a href="https://github.com/traust-security/traust-core/commit/62ee6812e71b274ca7f1d28b4267195d68e53d8f"><code>62ee681</code></a></p>

    <details>

    ><summary>Resolution reason</summary>
    ><br/>
    ><pre>

    >The superseding check now uses the human decision&#x27;s recording time (created_at) via
    >newest_person_statement, compared with the build&#x27;s publication created_at using &gt;=, so a backdated
    >human statement recorded after publication forces the next serve to fold.
    ></pre>
    ></details>

    <!-- qodo-finding-reference
    <code>↗ src/traust_core/v1/services/insight.py[R385-388]</code>
    -->

    <details>

    ><summary>Description</summary>
    ><br/>
    ><pre>

    ><b><i>_superseded</i></b> compares the newest human decision’s <b><i>occurred_at</i></b> with <b><i>built_at</i></b>, even though
    ><b><i>occurred_at</i></b> can be caller-supplied or taken from an earlier forge comment rather than reflecting
    >when the row was recorded. When a human statement is recorded after a build but dated at or before
    ><b><i>built_at</i></b>, the unscoped route can keep serving the old counts until another build or the serving
    >bound expires, despite an unscoped fold counting the statement.
    ></pre>
    ></details>

    <hr/>
    </details>

    <details>
    <summary> 10. Freshness check can scan all decisions per read <code>🐞 Bug</code> <code>➹ Performance</code></summary>

    <br/>

    <details open>

    ><summary>Description</summary>
    ><br/>
    ><pre>

    ><b><i>newest_person_statement</i></b> walks <b><i>idx_decision_occurred</i></b> backwards and filters each row on actor
    >LIKE &#x27;human:%&#x27;
    . Because human statements are sparse, the walk is long: the further back the newest
    >human row sits, the more rows it visits, and with no human decision at all it visits the entire
    >index and heap. This runs on every unscoped census GET, so an estate that is mostly or entirely
    >machine-judged pays a near-full-table scan on each dashboard read.
    ></pre>
    ></details>

    <details>

    ><summary>Code</summary>
    ><br/>
    ><code>[src/traust_core/v1/repositories/traust/findings/decision.py[R177-185]](https://github.com/traust-security/traust-core/pull/434/files#diff-d05c15c6b2e504891e2e2a3d2ba97106bd583e309ac8ea7dfdf0133311a31462R177-R185)</code>

    >
    >+        # A person's judgements are sparse among the machines'; the occurred_at index walks
    >+        # backwards to the newest one instead of scanning the table.
    >+        c = self.table.c
    >+        stmt = (
    >+            sa.select(c.occurred_at)
    >+            .where(c.actor.startswith(f"{ActorKind.HUMAN}:"))
    >+            .order_by(c.occurred_at.desc())
    >+            .limit(1)
    >+        )
    >

    ></details>

    <details>

    ><summary>Evidence</summary>
    ><br/>
    ><pre>

    >The query has no predicate the index can use. <b><i>ORDER BY occurred_at DESC LIMIT 1</i></b> only stops early
    >once it reaches a matching row, so the cost grows with the number of non-human rows newer than the
    >newest human one. The perf case seeds a mix of human and machine statements and so does not cover
    >the zero-human or rare-human estate. The comment and the PR description claim the opposite (&quot;sparse,
    >so no defeat mode&quot;).
    ></pre>
    > <code>[src/traust_core/v1/repositories/traust/findings/decision.py\[176-186\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/repositories/traust/findings/decision.py/#L176-L186)</code>

    <code>[src/traust_core/v1/services/insight.py\[382-388\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/services/insight.py/#L382-L388)</code>

    ></details>

    <details>

    ><summary>Agent prompt</summary>
    ><br/>
    >
    >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
    >
    >## Issue description
    >The per-request freshness query walks the occurred_at index backwards until it finds a human actor. When human rows are rare or absent, it reads nearly all decisions on every unscoped census read.
    >
    >## Fix Focus Areas
    >- src/traust_core/v1/repositories/traust/findings/decision.py[176-186]
    >- perf/queries/test_findings.py[658-663]
    >
    >## Recommended Fix
    >Bound the walk with a lower limit, e.g. add `occurred_at > built_at - SERVE_STALE_AFTER` (pass `since` in) so only the serving window is scanned; with the recording-time fix, bound on `created_at` instead. Alternatively, add a partial index on human actors. Add a perf case with zero human decisions among 250k machine decisions.
    >

    <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>

    ></details>

    Dismiss ↗ | View ↗

    <hr/>
    </details>

    <details>
    <summary> 11. Dashboards show mismatched census views <code>🐞 Bug</code> <code>≡ Correctness</code></summary>

    <br/>

    <details open>

    ><summary>Description</summary>
    ><br/>
    ><pre>

    ><b><i>record_builds</i></b> builds the four views sequentially through separate repository read scopes rather
    >than one database snapshot. If source data changes during the folds, the published artifact can
    >contain views reflecting different states, which unscoped requests then serve together until it is
    >replaced or expires.
    ></pre>
    ></details>

    <details>

    ><summary>Code</summary>
    ><br/>
    ><code>[src/traust_core/v1/services/insight.py[R343-345]](https://github.com/traust-security/traust-core/pull/434/files#diff-33baccc4b7229ac6a008e1deb9111adb23d99dc4414fb04187a3db0db1ce0f73R343-R345)</code>

    >
    >+        built_at = self._clock.now()
    >+        models = {name: self.build(name, ViewFilter()) for name in CENSUS_VIEWS}
    >+        return self._builds.publish_artifact(
    >

    ></details>

    <details>

    ><summary>Evidence</summary>
    ><br/>
    ><pre>

    ><b><i>record_builds</i></b> invokes <b><i>self.build</i></b> separately for each view before publishing. The findings census
    >uses repository reads, and the unit of work opens and closes outer read scopes independently; the
    >later artifact commit does not make those earlier reads a shared snapshot.
    ></pre>
    > <code>[src/traust_core/v1/services/insight.py\[338-352\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/services/insight.py/#L338-L352)</code>

    <code>[src/traust_core/v1/services/insight.py\[1179-1191\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/services/insight.py/#L1179-L1191)</code>

    <code>[src/traust_core/v1/repositories/sql.py\[192-243\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/repositories/sql.py/#L192-L243)</code>

    <code>[src/traust_core/v1/services/artifact_publishing.py\[527-540\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/services/artifact_publishing.py/#L527-L540)</code>

    ></details>

    <details>

    ><summary>Agent prompt</summary>
    ><br/>
    >
    >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
    >
    >## Issue description
    >The four sequential folds can observe commits at different times, producing one artifact whose census views disagree.
    >## Fix Focus Areas
    >- src/traust_core/v1/services/insight.py[338-352]
    >- tests/v1/services/test_insight_builds.py[74-82]
    >## Recommended Fix
    >Compute all four views against a consistent database snapshot, or use a build protocol that detects intervening source changes and retries before publication. Add a regression case with a source write between folds that checks cross-view consistency.
    >

    <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>

    ></details>

    Dismiss ↗ | View ↗

    <hr/>
    </details>

    <details>
    <summary> 12. <s>Stored builds are re-parsed on every request</s> <code>✓ Resolved</code></summary>

    <br/>

    <p><b>Resolving commit:</b> <a href="https://github.com/traust-security/traust-core/commit/62ee6812e71b274ca7f1d28b4267195d68e53d8f"><code>62ee681</code></a></p>

    <details>

    ><summary>Resolution reason</summary>
    ><br/>
    ><pre>

    >Moved the parsed-build cache into a ParsedBuilds holder exposed as a Context cached_property and
    >injected into every per-request InsightService, so the parse is shared across requests keyed by
    >publication row id.
    ></pre>
    ></details>

    <!-- qodo-finding-reference
    <code>↗ src/traust_core/v1/services/insight.py[R363-364]</code>
    -->

    <details>

    ><summary>Description</summary>
    ><br/>
    ><pre>

    ><b><i>self._parsed</i></b> lives on the <b><i>InsightService</i></b> instance, but <b><i>Context.services()</i></b> builds a new
    ><b><i>_wire(...)</i></b> graph, and so a new <b><i>InsightService</i></b>, for every request (<b><i>deps.services</i></b>: &quot;One unit of
    >work per request&quot;). As a result, every unscoped census GET re-reads the object bytes, re-hashes
    >them, JSON-schema-validates the whole census through <b><i>ArtifactDocument.parse</i></b>, <b><i>json.loads</i></b> it
    >again, and deep-copies and pydantic-revalidates every view, so the cache never hits and the PR&#x27;s
    >&quot;parse once per publication&quot; claim is false.
    ></pre>
    ></details>

    <hr/>
    </details>

    </details>
    <br/>

    <img src="https://img.shields.io/badge/Low-634FD1?style=flat-square" height="20px" alt="Informational">

    <details>
    <summary> 13. Two comments disagree on whether unchanged builds dedupe <code>🐞 Bug</code> <code>⚙ Maintainability</code> <code>⭐ New</code></summary>

    <br/>

    <details open>

    ><summary>Description</summary>
    ><br/>
    ><pre>

    >The <b><i>NEED(artifacts: cadence retention)</i></b> comment in <b><i>record_builds</i></b> says the coverage and trend
    >models stamp their fold moment, so even an unchanged census gets a new digest and a new row on every
    >run. The docstring a few lines above (and the README and PR description) says the opposite: an
    >unchanged census republishes as the same digest and the same row. A later maintainer can&#x27;t tell from
    >these which storage-growth and row-reuse behaviour is real, and the two cases behave differently for
    ><b><i>history(..., 1)</i></b> and the 30-minute <b><i>_expired</i></b> bound.
    ></pre>
    ></details>

    <details>

    ><summary>Code</summary>
    ><br/>
    ><code>[src/traust_core/v1/services/insight.py[R395-399]](https://github.com/traust-security/traust-core/pull/434/files#diff-33baccc4b7229ac6a008e1deb9111adb23d99dc4414fb04187a3db0db1ce0f73R395-R399)</code>

    >
    >+        # NEED(artifacts: cadence retention): every build publishes a new row and new bytes —
    >+        # the coverage and trend models stamp their fold moment, so even an unchanged census
    >+        # yields a new digest — and nothing prunes old builds of any cadence-published kind.
    >+        # Growth is roughly one census-sized artifact per cadence period (about 144/day at
    >+        # 10 minutes).
    >

    ></details>

    <details>

    ><summary>Evidence</summary>
    ><br/>
    ><pre>

    >Lines 390-392 claim that unchanged bytes reuse the same digest and row. Lines 395-399 claim every
    >build produces a new digest because the coverage and trend models embed their fold moment. Both
    >statements cannot be true, and the PR description repeats the &#x27;same digest, same row&#x27; claim.
    ></pre>
    > <code>[src/traust_core/v1/services/insight.py\[384-411\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/services/insight.py/#L384-L411)</code>

    ></details>

    <details>

    ><summary>Agent prompt</summary>
    ><br/>
    >
    >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
    >
    >## Issue description
    >The `record_builds` docstring says an unchanged census republishes as the same digest and row. The NEED comment below it says the coverage and trend models stamp their fold moment, so every build gets a new digest.
    >
    >## Fix Focus Areas
    >- src/traust_core/v1/services/insight.py[384-411]
    >- README.md[220-222]
    >
    >## Recommended Fix
    >Check whether `CoverageDashboard` / `FindingsTrend` dumps include a fold timestamp. Then keep only the true statement in both the docstring and the NEED comment, and update the README to match.
    >

    <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>

    ></details>

    Dismiss ↗ | View ↗

    <hr/>
    </details>

    <details>
    <summary> 14. Header overstates how fresh the census is <code>🐞 Bug</code> <code>◔ Observability</code></summary>

    <br/>

    <details open>

    ><summary>Description</summary>
    ><br/>
    ><pre>

    ><b><i>serve</i></b> sets <b><i>built_at</i></b> (and so <b><i>X-Traust-View-Built-At</i></b>) to the artifact row&#x27;s <b><i>created_at</i></b>, which
    >is stamped only after <b><i>record_builds</i></b> has run all four folds in sequence. The route docstring says
    >the header names &#x27;the moment the served census was read&#x27;, but the census reads happened up to
    >several minutes earlier at the measured 72–134 s per fold, and <b><i>_expired</i></b> measures the 30-minute
    >bound from that same later moment.
    ></pre>
    ></details>

    <details>

    ><summary>Code</summary>
    ><br/>
    ><code>[src/traust_core/v1/rest/insight/insights.py[R54-55]](https://github.com/traust-security/traust-core/pull/434/files#diff-c32b1b7b51b81d7962688c9a2ed5db3186149325103a38abe009c07bd269cb81R54-R55)</code>

    >
    >+    be recorded (the first read folds). `X-Traust-View-Built-At` names the moment the served
    >+    census was read. A scoped filter, or `refresh`, folds on demand."""
    >

    ></details>

    <details>

    ><summary>Evidence</summary>
    ><br/>
    ><pre>

    ><b><i>record_builds</i></b> runs <b><i>self.build(...)</i></b> for every census view, then <b><i>publish_artifact</i></b>, so the row&#x27;s
    ><b><i>created_at</i></b> (DB default) is the time after all folds. <b><i>serve</i></b> returns <b><i>built_at=row.created_at</i></b>,
    >and <b><i>_expired(row.created_at)</i></b> uses the same value. The data can therefore be older than the header
    >says, and older than 30 minutes when served, by the full fold duration.
    ></pre>
    > <code>[src/traust_core/v1/services/insight.py\[399-410\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/services/insight.py/#L399-L410)</code>

    <code>[src/traust_core/v1/services/insight.py\[377-381\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/src/traust_core/v1/services/insight.py/#L377-L381)</code>

    ></details>

    <details>

    ><summary>Agent prompt</summary>
    ><br/>
    >
    >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
    >
    >## Issue description
    >`X-Traust-View-Built-At` and the serving bound use the publication time, which comes after a multi-minute fold, while the route docstring says it is when the census was read.
    >
    >## Fix Focus Areas
    >- src/traust_core/v1/rest/insight/insights.py[47-55]
    >- src/traust_core/v1/services/insight.py[384-410]
    >
    >## Recommended Fix
    >Either correct the docstring to say 'publication moment, after the fold', or record the fold start time in the document (for example `folded_at`), use it for the header and for `_expired`, and accept that the digest then changes on every build.
    >

    <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>

    ></details>

    Dismiss ↗ | View ↗

    <hr/>
    </details>

    <details>
    <summary> 15. Lockfile was regenerated with an older uv <code>🐞 Bug</code> <code>⚙ Maintainability</code></summary>

    <br/>

    <details open>

    ><summary>Description</summary>
    ><br/>
    ><pre>

    ><b><i>uv.lock</i></b> drops from <b><i>revision = 5</i></b> to <b><i>revision = 3</i></b> and rewrites the resolution markers for
    ><b><i>httpcore2</i></b> dependencies. That means it was relocked with an older uv than the one that produced the
    >base lockfile, beyond the intended traust-contracts pin bump. Developers or CI on the newer uv will
    >rewrite it again (or fail <b><i>uv lock --check</i></b>), so the lockfile keeps changing back and forth across
    >PRs.
    ></pre>
    ></details>

    <details>

    ><summary>Code</summary>
    ><br/>
    ><code>[uv.lock[2]](https://github.com/traust-security/traust-core/pull/434/files#diff-84321598744d84dbee2318e634c74c9aae39a1c253f1c4bd17ebf9ef2f807b11R2-R2)</code>

    >
    >+revision = 3
    >

    ></details>

    <details>

    ><summary>Evidence</summary>
    ><br/>
    ><pre>

    >The uv.lock patch shows <b><i>-revision = 5</i></b> / <b><i>+revision = 3</i></b> and new platform markers on
    ><b><i>h11</i></b>/<b><i>truststore</i></b>, which are unrelated to the only intended dependency change (the traust-contracts
    >git rev in pyproject.toml).
    ></pre>
    > <code>[pyproject.toml\[26-26\]](https://github.com/traust-security/traust-core/blob/438a749960613934cfa9771dedc9903dce03f6f2/pyproject.toml/#L26-L26)</code>

    ></details>

    <details>

    ><summary>Agent prompt</summary>
    ><br/>
    >
    >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
    >
    >## Issue description
    >uv.lock was regenerated by an older uv (revision 5 -> 3, marker rewrites), adding churn unrelated to the contracts pin bump.
    >
    >## Fix Focus Areas
    >- uv.lock[1-10]
    >
    >## Recommended Fix
    >Restore the base uv.lock, then run `uv lock` with the uv version the repository uses (revision 5), so the diff contains only the traust-contracts rev change.
    >

    <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>

    ></details>

    Dismiss ↗ | View ↗

    <hr/>
    </details>

    <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">

    <!-- qodo-self-review-slot -->

    <!-- qodo-context:start -->
    <details><summary><strong>Context sources</strong></summary>

    <div>&#x2705; Linked PRs:</div>
    <div>&nbsp;&nbsp;<code>🌐 PR #143</code></div>
    <div>&nbsp;&nbsp;<code>🌐 PR #1</code></div>
    <div>&nbsp;&nbsp;<code>🌐 PR #2</code></div>
    <div>&#x26A0;&#xFE0F; Tickets: not configured — No linear integration is connected for the linked tickets</div>
    <div>Review mode: <code>Auto: 🧠 Deep</code>: Dense stored-build, freshness, artifact, concurrency, and authorization behavior changes.</div>
    <!-- qodo-context:end -->
    </details>

    <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">

    <!-- https://github.com/traust-security/traust-core/commit/438a749960613934cfa9771dedc9903dce03f6f2 -->

    <!-- qodo-summary-omitted-findings -->
    <pre>⚠️ Warning | Comment size exceeded, non finding content trimmed <a href="https://docs.qodo.ai/code-review/comment-size-limits">Learn more</a></pre>

    <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">

    <a href="https://www.qodo.ai"><img src="https://www.qodo.ai/wp-content/uploads/2025/03/qodo-logo.svg" width="80" alt="Qodo Logo"></a>

    gurnben gurnben commented on Nov 12, 2026 19:24 UTC
    Author

    Qodo review disposition (thank you — findings 2, 3, 4 and 5 were real and are fixed in 62ee6812; the receipts were re-run end-to-end after the fixes):

  • #2 (backdated judgements) — fixed. newest_person_statement now returns the recording time (decision.created_at), and serve compares it against the build's publication time (the artifact row's created_at) — both database clocks, no cross-clock skew. A backdated forge comment imported today supersedes yesterday's build. Regression: test_a_backdated_judgement_recorded_after_the_build_still_supersedes_it; end-to-end receipt R7 below.

  • #3 (re-parsed per request) — fixed, and you were right that the original claim was false. ParsedBuilds is a Context-owned cache (the Context lives for the process; services() re-wires per request), injected into every wiring, lock-guarded. Regression: test_the_parse_is_once_per_publication_across_wirings (one underlying read serves two wirings).

  • #4 (unreadable build → 500) — fixed. The fetch-and-parse sits inside the fallback; a failure is negative-cached by row id and every read folds until the next publication. Regression: test_an_unreadable_build_folds_instead_of_failing_the_read (the stored bytes are corrupted through the public object-store interface).

  • #5 (the freshness walk) — fixed. idx_decision_person_recorded (a partial index over actor LIKE 'human:%' on created_at DESC, contracts #143) makes the per-serve read an index head read however sparse people are; an estate with no human judgement reads an empty index.

  • #1 (the four folds are not one snapshot) — declined. Unchanged from today: the on-demand path folds each view independently, per request, at whatever moment it runs. A minutes-long repeatable-read transaction would be worse, and a retry-on-interleaved-write protocol is machinery beyond the plan's ask; the person-judgement bound covers the write the plan names.

  • #6 (the post-decide window folds per request) — declined. That window is exactly today's behaviour — every read folds today, always — bounded by the cadence and by SCI's 30 s single-flight cache on the read side. The plan accepts it knowingly ("either rebuild the affected views on those writes or accept and document the window"); this PR rebuilds at the next read. Wave (e) shrinks the fold's own cost.
  • End-to-end receipts after the fixes (real traust-server, the real --census leg, Postgres, the artifact store):

    1. first read before any build → 200, no header (folded — today's behaviour);
    2. dashboard refresh --census → {"outcome":"succeeded","written":["15513d8b-…"]};
    3. four reads → 200 in 18.6 / 16.2 / 15.9 / 23.8 ms, all x-traust-view-built-at, body byte-identical to the on-demand fold's (the parse happened once — the timings are flat across reads);
    4. ?refresh=true → no header (fold); a scoped product_id read → folded (the RBAC shape);
    5. a countersign decide → the next unscoped read folds with the moved counts (open critical 1→0, risk_accepted 0→1);
    6. the census leg again → the route serves the new build, the decide inside it;
    7. a judgement recorded now, claiming a moment 30 days ago → still supersedes (no header; the counts moved) — the #2 fix, live.

    Gates after the fixes: make lint-fix green; make test 13,782 passed, 2 skipped; make test-integration 4,024 passed, 6 skipped; make perf — the two new cases green (report in the PR body).

    🤖 Generated with Crush

    Assisted-by: Crush:rits/zai-org/glm-5-3

    qodo-code-review[bot] qodo-code-review[bot] commented on Nov 12, 2026 19:31 UTC
    Bot
    chubirka chubirka commented on code on Nov 12, 2026 20:23 UTC
    Code Review
    src/traust_core/v1/services/insight.py:1
    @@ -238,23 +249,181 @@ def _accepts_window(view: View) -> bool:
         return bool(getattr(view, "accepts_window", getattr(view, "windowed", False)))
     
     
    +class LatestStatement(Protocol):
    +    """When a person last judged a finding: the stored census builds' freshness bound."""
    +
    +    def newest_person_statement(self) -> datetime | None: ...
    +
    +
    +# The census views the dashboards cadence stores: the dashboard's whole-scope folds, one GLOBAL
    +# build serving every scope (the caller's authorization filters the served model per request).
    +# A build serves while the cadence's promise holds: the dashboards lane's fast asset runs at a
    +# 5-15 minute cadence, so a build older than this missed its cycles and the read folds (today's
    +# behaviour) until the asset runs again.
    +SERVE_STALE_AFTER = timedelta(minutes=30)
    +CENSUS_VIEWS: Mapping[ViewName, type[ViewModel]] = {
    +    ViewName.FINDINGS_ROLLUP: FindingsRollup,
    +    ViewName.COVERAGE: CoverageDashboard,
    +    ViewName.REMEDIATION_INDEX: RemediationIndex,
    +    ViewName.FINDINGS_TREND: FindingsTrend,
    +}
    +
    +
    +def _revalidate(model: type[M], document: Any) -> M:
    +    """The stored document as the view's model. A model's computed fields dump as output the
    +    strict models refuse as input, so exactly the rejected paths are dropped and validation
    +    retried; anything else a stored build fails to validate stays a failure."""
    +    for _ in range(3):
    +        try:
    +            return model.model_validate(document)
    +        except ModelValidationError as rejected:
    +            extra = [e["loc"] for e in rejected.errors() if e["type"] == "extra_forbidden"]
    +            if not extra:
    +                raise
    +            document = _without(document, extra)
    +    return model.model_validate(document)
    +
    +
    +def _without(document: Any, paths: Iterable[tuple[object, ...]]) -> Any:
    +    pruned = copy.deepcopy(document)
    +    for path in paths:
    +        node: Any = pruned
    +        for step in path[:-1]:
    +            node = node[step]
    +        with contextlib.suppress(KeyError, IndexError, TypeError):
    +            del node[path[-1]]  # a path another rejection already removed
    +    return pruned
    +
    +
    +def _parse_builds(document: Any) -> InsightBuilds:
    +    """A stored build's document as the census models, each view re-validated as that view's; a
    +    view this core cannot name or validate is dropped (that view folds, the rest serve)."""
    +    views: dict[ViewName, ViewModel] = {}
    +    for name, model in document["views"].items():
    +        try:
    +            view = ViewName(name)
    +            model_type = CENSUS_VIEWS[view]
    +        except (ValueError, KeyError):
    +            log.warning("stored insight build carries view %s this core does not store", name)
    +            continue
    +        try:
    +            views[view] = _revalidate(model_type, model)
    +        except ValueError:
    +            log.warning("stored insight build view %s no longer validates", name)
    +    return InsightBuilds(built_at=document["built_at"], views=views)
    +
    +
    +class ParsedBuilds:
    +    """The parsed stored census, once per publication: a service is wired per request, the cache
    +    is owned by the Context and outlives them, so a process parses a build when it is published —
    +    never per request. A build that cannot be read or parsed is remembered as unreadable (the
    +    reads fold) until a newer publication replaces it."""
    +
    +    def __init__(self) -> None:
    +        self._lock = threading.Lock()
    +        self._by_row: tuple[UUID, InsightBuilds | None] | None = None
    +
    +    def parse(self, row_id: UUID, read: Callable[[], Any]) -> InsightBuilds | None:
    +        with self._lock:
    +            if self._by_row is not None and self._by_row[0] == row_id:
    +                return self._by_row[1]
    +            try:
    +                parsed: InsightBuilds | None = _parse_builds(read())
    +            except (TraustError, ValueError, KeyError) as e:
    +                log.warning(
    +                    "stored insight build %s is unreadable (%s); folding until the next one",
    +                    row_id,
    +                    type(e).__name__,
    +                )
    +                parsed = None
    +            self._by_row = (row_id, parsed)
    +            return parsed
    +
    +
     class InsightService:
    -    """Dashboards are derived views: built on demand and rendered, never stored."""
    +    """Dashboards are derived views: built on demand and rendered; the census views are also
    +    stored as rebuilt builds the route serves instead of folding per request."""
     
         def __init__(
             self,
             views: Sequence[View],
             clock: Clock,
             *,
             sla_policies: ArtifactPublisher | None = None,
    +        builds: ArtifactPublisher | None = None,
    +        decisions: LatestStatement | None = None,
    +        parsed: ParsedBuilds | None = None,
         ) -> None:
             self._views = {v.name: v for v in views}
             self._clock = clock
             self._sla_policies = sla_policies
    +        self._builds = builds
    +        self._decisions = decisions
    +        self._parsed = parsed or ParsedBuilds()
     
         def build(self, view: ViewName, filter: ViewFilter) -> ViewModel:
             return self._view(view, filter).build(filter)
     
    +    def serve(self, view: ViewName, filter: ViewFilter, *, refresh: bool = False) -> ServedInsight:
    +        """The route's read: the newest stored census build, else the on-demand fold.
    +
    +        The stored build is the GLOBAL census, so only an unscoped request reads it; a scoped
    +        filter, `refresh`, a view the census does not carry, a build a person's judgement was
    +        recorded after, a build past the serving bound, and the first request before any build
    +        all fold on demand (the current behaviour)."""
    +        if not refresh and view in CENSUS_VIEWS and filter == ViewFilter():
    +            newest = self._newest()
    +            if newest is not None:
    +                row, build = newest
    +                if not self._superseded(row.created_at) and not self._expired(build.built_at):

    [P2] Base freshness on the fold input, not later publication

    A human decision committed after the rollup fold but before artifact insertion is missing from the stored result yet older than row.created_at, so this check accepts it. Reproduced stored open-critical=1 versus fresh=0. Use a pre-fold source watermark/version that detects this interleaving before serving the build.

    chubirka chubirka commented on Nov 12, 2026 20:23 UTC
    Reviewer

    One reproduced P2 freshness defect remains: a human decision committed during construction can be omitted from a stored build that is nevertheless served as current. SQLite reproduction returned stored open-critical=1 versus fresh=0.

    qodo-code-review[bot] qodo-code-review[bot] commented on Nov 12, 2026 21:52 UTC
    Bot
    gurnben gurnben commented on code on Nov 12, 2026 22:04 UTC
    Code Review
    src/traust_core/v1/services/insight.py:1
    @@ -238,23 +249,181 @@ def _accepts_window(view: View) -> bool:
         return bool(getattr(view, "accepts_window", getattr(view, "windowed", False)))
     
     
    +class LatestStatement(Protocol):
    +    """When a person last judged a finding: the stored census builds' freshness bound."""
    +
    +    def newest_person_statement(self) -> datetime | None: ...
    +
    +
    +# The census views the dashboards cadence stores: the dashboard's whole-scope folds, one GLOBAL
    +# build serving every scope (the caller's authorization filters the served model per request).
    +# A build serves while the cadence's promise holds: the dashboards lane's fast asset runs at a
    +# 5-15 minute cadence, so a build older than this missed its cycles and the read folds (today's
    +# behaviour) until the asset runs again.
    +SERVE_STALE_AFTER = timedelta(minutes=30)
    +CENSUS_VIEWS: Mapping[ViewName, type[ViewModel]] = {
    +    ViewName.FINDINGS_ROLLUP: FindingsRollup,
    +    ViewName.COVERAGE: CoverageDashboard,
    +    ViewName.REMEDIATION_INDEX: RemediationIndex,
    +    ViewName.FINDINGS_TREND: FindingsTrend,
    +}
    +
    +
    +def _revalidate(model: type[M], document: Any) -> M:
    +    """The stored document as the view's model. A model's computed fields dump as output the
    +    strict models refuse as input, so exactly the rejected paths are dropped and validation
    +    retried; anything else a stored build fails to validate stays a failure."""
    +    for _ in range(3):
    +        try:
    +            return model.model_validate(document)
    +        except ModelValidationError as rejected:
    +            extra = [e["loc"] for e in rejected.errors() if e["type"] == "extra_forbidden"]
    +            if not extra:
    +                raise
    +            document = _without(document, extra)
    +    return model.model_validate(document)
    +
    +
    +def _without(document: Any, paths: Iterable[tuple[object, ...]]) -> Any:
    +    pruned = copy.deepcopy(document)
    +    for path in paths:
    +        node: Any = pruned
    +        for step in path[:-1]:
    +            node = node[step]
    +        with contextlib.suppress(KeyError, IndexError, TypeError):
    +            del node[path[-1]]  # a path another rejection already removed
    +    return pruned
    +
    +
    +def _parse_builds(document: Any) -> InsightBuilds:
    +    """A stored build's document as the census models, each view re-validated as that view's; a
    +    view this core cannot name or validate is dropped (that view folds, the rest serve)."""
    +    views: dict[ViewName, ViewModel] = {}
    +    for name, model in document["views"].items():
    +        try:
    +            view = ViewName(name)
    +            model_type = CENSUS_VIEWS[view]
    +        except (ValueError, KeyError):
    +            log.warning("stored insight build carries view %s this core does not store", name)
    +            continue
    +        try:
    +            views[view] = _revalidate(model_type, model)
    +        except ValueError:
    +            log.warning("stored insight build view %s no longer validates", name)
    +    return InsightBuilds(built_at=document["built_at"], views=views)
    +
    +
    +class ParsedBuilds:
    +    """The parsed stored census, once per publication: a service is wired per request, the cache
    +    is owned by the Context and outlives them, so a process parses a build when it is published —
    +    never per request. A build that cannot be read or parsed is remembered as unreadable (the
    +    reads fold) until a newer publication replaces it."""
    +
    +    def __init__(self) -> None:
    +        self._lock = threading.Lock()
    +        self._by_row: tuple[UUID, InsightBuilds | None] | None = None
    +
    +    def parse(self, row_id: UUID, read: Callable[[], Any]) -> InsightBuilds | None:
    +        with self._lock:
    +            if self._by_row is not None and self._by_row[0] == row_id:
    +                return self._by_row[1]
    +            try:
    +                parsed: InsightBuilds | None = _parse_builds(read())
    +            except (TraustError, ValueError, KeyError) as e:
    +                log.warning(
    +                    "stored insight build %s is unreadable (%s); folding until the next one",
    +                    row_id,
    +                    type(e).__name__,
    +                )
    +                parsed = None
    +            self._by_row = (row_id, parsed)
    +            return parsed
    +
    +
     class InsightService:
    -    """Dashboards are derived views: built on demand and rendered, never stored."""
    +    """Dashboards are derived views: built on demand and rendered; the census views are also
    +    stored as rebuilt builds the route serves instead of folding per request."""
     
         def __init__(
             self,
             views: Sequence[View],
             clock: Clock,
             *,
             sla_policies: ArtifactPublisher | None = None,
    +        builds: ArtifactPublisher | None = None,
    +        decisions: LatestStatement | None = None,
    +        parsed: ParsedBuilds | None = None,
         ) -> None:
             self._views = {v.name: v for v in views}
             self._clock = clock
             self._sla_policies = sla_policies
    +        self._builds = builds
    +        self._decisions = decisions
    +        self._parsed = parsed or ParsedBuilds()
     
         def build(self, view: ViewName, filter: ViewFilter) -> ViewModel:
             return self._view(view, filter).build(filter)
     
    +    def serve(self, view: ViewName, filter: ViewFilter, *, refresh: bool = False) -> ServedInsight:
    +        """The route's read: the newest stored census build, else the on-demand fold.
    +
    +        The stored build is the GLOBAL census, so only an unscoped request reads it; a scoped
    +        filter, `refresh`, a view the census does not carry, a build a person's judgement was
    +        recorded after, a build past the serving bound, and the first request before any build
    +        all fold on demand (the current behaviour)."""
    +        if not refresh and view in CENSUS_VIEWS and filter == ViewFilter():
    +            newest = self._newest()
    +            if newest is not None:
    +                row, build = newest
    +                if not self._superseded(row.created_at) and not self._expired(build.built_at):

    Fixed in 43ad5f46 — the bound is now a pre-fold watermark rather than any publication-time comparison.

    record_builds reads newest_person_statement() before the first view folds and publishes the value in the artifact as folded_after (the envelope's one freshness field; the artifact row's created_at remains the publication moment). serve refuses the build when the current newest person decision stands at or after that watermark:

    return newest is not None and (folded_after is None or newest > folded_after)
    

    Your interleaving is exactly the case the watermark closes: a decision committed after the watermark read but before publication has created_at above the watermark regardless of when the row was inserted, so the build is refused and the next read folds with the moved counts. Both values are decision.created_at — one table, one clock — which also retires the cross-clock skew a publication-time comparison carried (and keeps the backdated-statement fix from round 1: a forge comment imported today, claiming last month, still lands above the watermark).

    Regression in your reproduction's shape: test_a_decide_during_the_fold_supersedes_the_build wraps the rollup view so a decision commits between the watermark read and the artifact publication, then asserts the route folds (the stored build would say open-critical 1 where the fresh fold says 0). The end-to-end receipts were re-run after the change: a decide mid-session still flips the next read to the fold, and the cadence rebuild re-arms serving with the decide inside the census.

    One deliberate conservatism to name: a decision that commits mid-fold and is in fact included by the later view reads still refuses the build — the fold cannot prove which views saw the commit, so serving refuses on "unverifiable" rather than "probably fine." That costs one extra fold cycle per mid-fold decide; the alternative (per-view watermarks) is not worth the machinery for a window measured in fold-seconds.

    🤖 Generated with Crush

    Assisted-by: Crush:rits/zai-org/glm-5-3

    gurnben gurnben commented on Nov 12, 2026 22:05 UTC
    Author

    Round 2 disposition (on 43ad5f46; the three ⭐ new findings fixed, #6 was already fixed, #4/#7 declined — details in the PR body's "Round 2" section):

  • #1 (decides during a build) — fixed. The freshness bound is now a pre-fold watermark: record_builds reads the newest person decision's recording time before the fold begins and publishes it as the artifact's folded_after; serve refuses the build when the current newest person decision is at or after it. A decide committed between the fold's reads and the publication — the review's interleaving — is unverifiable in the build and never served. Both values are decision.created_at (one clock, no publication-time comparison at all). Regression: test_a_decide_during_the_fold_supersedes_the_build. (This also covers Michele's P2 inline, same reproduction — replied on that thread.)

  • #2 (storage growth) — fixed to the extent this PR can, and the rest is marked. The envelope no longer embeds a moment — the artifact row's created_at is the publication — so an unchanged census republishes as the same digest and the same row: a quiet estate's storage is flat rather than one multi-megabyte artifact per cadence. The residual (one artifact per distinct census on a changing estate) is real and unbounded: the artifact table is append-only and no cadence-published kind has retention today, so it is marked NEED(artifacts: cadence retention) at record_builds with the growth rate documented — a platform mechanism, not a bespoke pruner here.

  • #9 (lockfile revision 3 vs 5) — fixed. Re-locked with uv 0.13.x; the diff against development is revision 5 and contains only the traust-contracts pin change.

  • #6 (the freshness walk) — already fixed; the finding's text predates the fix commit. newest_person_statement reads the new partial index idx_decision_person_recorded — the review's own recommended alternative ("add a partial index on human actors") — landed in contracts #143 and pinned here. The perf case pins the plan: Index Only Scan using idx_decision_person_recorded … 0.005 ms at 250k decisions; an estate with no human judgement reads an empty index.

  • #4 (post-decide cold fold) and #7 (mismatched census views) — declined, unchanged from round 1: both describe today's behaviour (every read folds today, each view at its own moment), bounded by the cadence and by SCI's 30 s single-flight cache on the read side; the plan accepts the window knowingly, and wave (e) shrinks the fold's own cost.
  • Gates after the round: make test 13,784 passed; make test-integration 4,024 passed. (Two test_assessment_prepare.py caller-cap tests fail on pristine development on this workstation and pass in CI on the same commits — the fixture allows ctags while asserting the builtin extractor's output, and this host has Universal Ctags; under CI's environment they pass. Not this diff's.)

    🤖 Generated with Crush

    Assisted-by: Crush:rits/zai-org/glm-5-3

    gurnben gurnben commented on Nov 12, 2026 22:13 UTC
    Author

    Correction to the round-2 disposition above (storage, your #2): the "unchanged census republishes as the same digest and the same row" claim in my earlier reply is wrong, and I've corrected it in the PR body. Measured live after posting it: two consecutive --census builds over byte-identical counts produced different artifacts — the coverage and trend models stamp their fold moment (population.as_of / as_of, both part of their landed view contracts), so every build's document differs regardless of data change.

    What stands: the envelope carries no publication timestamp of its own (the artifact row's created_at is the publication — one clock, and the route's X-Traust-View-Built-At reads it), and the growth is one census-sized artifact per cadence period (~144/day at 10 minutes), marked NEED(artifacts: cadence retention) at record_builds with that rate in the comment — the existing NEED(artifacts: orphaned object GC) covers rollback orphans, not cadence growth, and a bespoke pruner against an append-only table would be a second mechanism where the platform needs one.

    If the growth rate matters to the reviewers, the two in-PR levers are the cadence (10m → 15m cuts it a third) and wave (e)'s SQL aggregation shrinking the artifact itself; retention proper is the platform mechanism the NEED marker names.

    🤖 Generated with Crush

    Assisted-by: Crush:rits/zai-org/glm-5-3

    qodo-code-review[bot] qodo-code-review[bot] commented on Nov 12, 2026 22:14 UTC
    Bot

    <h3>Qodo is busy working</h3>

    Check back in a few minutes. Qodo's code review agents are on it.

    <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">

    <img src="https://www.qodo.ai/wp-content/uploads/2026/01/anteater-looking-at-ants-01-transparent-bg-croped-ezgif.com-optimize-1.gif" width="30%">

    Reviewers
    Assignees
    gurnben gurnben
    Labels
    risk: low confidence: 88.3% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 62.6% (MEDIUM) · Higher = larger blast radius
    62.6%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 88.3% · Lower = rushed or shallow review
    88.3%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 7.3% · Safe to merge
    7.3%