← Back to Pull requests

feat(insight): the census tallies folded from narrow SQL rows #435

Closed
unknown closed this pull request without merging on Nov 12, 2026 23:48 UTC
View on GitHub
unknown unknown commented on Nov 12, 2026 19:12 UTC
Author

What

Wave (e) of the performance lane (traust-foundry#56, plans/standardization-closeout/features/2026-11-performance-lane.md): the aggregation push-down under the stored-build design. The read-efficiency audit measured the cold insight fold at 72–134 s per build — the census fold materializing 230k+ rows as models (findings, decisions, occurrences, assessments, labels, then a FindingView per finding) is what pinned core's CPU until its own healthz starved. This makes the tally itself cheap, so the wave (d) builder inherits the win for free and the ?refresh path benefits identically.

  • The census tallies from narrow SQL rows — the findings-rollup's per-repository disposition counts, severities, category labels and the top cut fold from one narrow column set per table (FindingCensus: findings, decisions, occurrence windows, category labels, line assessments), the disposition policy run over tuples — never a model per row. FindingService.census delivers each bounded batch of whole repositories to the counter, the shape census_fold established; census_fold itself stays for consumers that read view fields (the worklist's count_in, the in-flight executive-summary panel).

  • One statement per table per batch, not one per 500 ids — CensusReads (the composite AssessmentReads pattern, batched by repository): decisions ⋈ finding, the category labels ⋈ finding, and one windowed occurrence read that carries each finding's latest report (the views' own report order) with its first report's time — the SLA clock — in a single pass. A batch closes once it holds ten thousand findings (the fold's own whole-repository _FACTS_BATCH discipline, sized for narrow rows), so memory stays bounded by findings, never by repository count; a scope with no findings reads its counts and nothing else.

  • The policy stays the single owner it was — Disposition.fold gains a normalize parameter (models by default; the census supplies the crosswalk over its rows through the same normalize_classifiers), finding_state/claim_fold/kind_of/newest_first_key are extracted beside their owners so the census and the views read one implementation, and _Counting counts census rows for the rollup, the executive summary and _tally alike (the adapter _census_row maps a held view onto the same row).
  • The compatibility contract holds: the rollup's stored model is byte-identical before/after on the same data — verified on the seeded estate (10,000 repositories, 350,100 findings, 250,100 false-positive decisions + 100,000 confirmed: models dumped and diffed, zero differences) and on the 3,588-repository candidate snapshot the audit measured (50,622 findings / 54,029 decisions / 71,603 occurrences / 17,619 categories / 4,504 top findings: zero differences, verified through every review round's fixes). The candidate's tied top findings are what forced the fold's own newest-first order into the census — the estate-scale parity caught the tie break the unit seeds could not.

    Against the same data, fresh process, before → after:

    | Estate | Wall (median) | Statements |
    |---|---|---|
    | seeded perf estate (10k repos, 350k findings) | 72.0 s → 17.1 s | 3,211 → 177 |
    | candidate snapshot (3,588 repos, 50,622 findings) | 14.8 s → 7.2 s | 78 → 78 (local; the win is the ~110k rows never materialized as models) |

    What remains of the candidate-snapshot build is no longer the tally: ~5.4 s of it is the contract validation of the model's own size (17.6k category rows through jsonschema), which the stored-build cadence amortizes and which is the wave (d) builder's own follow-up, not the fold's.

    The other two tallies the plan names: the coverage view's population rows already fold in SQL (counts_for_refs / latest_per_ref_and_kind, #423 — verified unchanged here); the remediation index's tallies are row-derived (by_status counts the index's own rows; items_in is already the one-batched-walk shape), so nothing in them is left to push down without changing the model.

    The work_mem note (an app-interface change, deliberately not made here): the audit measured 1.24 GB of temp-file sort spill on a 209 MB database — the folds' DISTINCT/ORDER BY. The census removes the fold's own sorts, but the occurrence window's sort still spills at volume (visible in perf/ plans, written buffers on the batch reads). A work_mem bump on the parameter groups (e.g. 64–256 MB for core's role) would keep those in memory; that is the RDS parameter-group owner's call, recorded here per the plan.

    Qodo pass (five review rounds, all findings resolved or outdated)

    | Round | Finding | Outcome |
    |---|---|---|
    | 1 | _kind_of's cache keyed by full validity histories grows unbounded | Fixed — kind_of/normalize_kind/validity_kind_pairs extracted to the models with per-value caches bounded by the vocabulary; regression test asserts the bound (test_census.py) |
    | 1 | The labels read fetched every taxonomy to use one | Fixed — the read filters taxonomy = 'category' in SQL |
    | 3 | Fixed repository slices no longer bound findings per batch (the OOM class the waves fixed) | Fixed — batches close on a findings count (census_counts_for_repositories, one narrow GROUP BY), a single over-bound repository its own whole batch; regression test |
    | 3 | An unused _TOP duplicated the rollup's | Deleted |
    | 4 | Batched statements labelled the scope size, not the batch | Fixed — labels name len(batch) |
    | 4 | A pass-through _kind_of wrapper | Deleted — the census calls the models' kind_of directly |
    | 5 | An empty scope ran the estate-wide claim-candidate query | Fixed — the claims read is gated on a scope with findings; regression test |
    | 2/4 | A second copy of the bind-batch chunker | Fixed — batches() is the one owner in repositories/tables.py, both callers use it |

    Dev verification

    The dev cluster's (dev-20261104) lease is live but its kubeconfig tokens expired (refresh needs an interactive oc login --web SSO round this session could not complete), so the live probe could not be run; the counts' identity and the timing above stand on the candidate snapshot — the audit's own estate data — and the seeded perf database, both before/after on the same data with the models diffed. The previous census wave's dev receipts (insight_census_validation_20261111 in the environment's state file) remain the live baseline to compare against once this deploys.

    Environmental notes (this session's host crashed mid-review; recorded for the next session):

  • The crash wiped the shared traust-postgres and sci-candidate-pg containers (--rm); the perf seed was rebuilt deterministically, the candidate snapshot's container was not recoverable — its verification receipts above predate the final two cosmetic rounds (statement labels, a pass-through wrapper), which are behavior-neutral and covered by the rebuilt-seed parity.

  • The crash-window system update installed Universal Ctags 6.2.1, which the symbol index prefers over its builtin extractors; its Go package tags and JSON ordering break tests/v1/services/test_assessment_prepare.py on every branch (verified on pristine development; CI is green on the builtin engine). A session-scoped ~/.opencode/bin/ctags wrapper hides the Universal-Ctags marker to restore the pre-update engine selection — core should pin or filter the kind itself (a separate fix, not hidden here).
  • Checklist

  • Targets development (rebased on #431/#432)

  • Only this domain's services and their sections' repositories changed; other domains reached through their services (the census composes the uow's own composite reads; CensusReads follows the AssessmentReads pattern)

  • No new tables, columns or row models (the census read shapes are NamedTuples the models layer owns beside their rows, not Entity/AppendOnly)

  • New SQL is a named query on the owning table's repository, or a composite read where the join spans sections (CensusReads, the AssessmentReads pattern)

  • No reads of files or databases outside the contract tables and ObjectStore; no in-memory stand-ins in src/

  • Duplicated responsibility touched by this change moved to its owner, copy deleted (normalize_classifiers extracted from normalize_decision; judgement_order from effective_decisions; finding_state from FindingView.state; claim_fold from the view's own claim selection; kind_of/validity_kind_pairs/normalize_kind from normalize_finding; newest_first_key from the service; batches unified in repositories/tables.py; _Counting/_tally now share the census row)

  • Tests: behaviour on SQLite (+ Postgres for new queries) via uow / seed

  • Legacy code deleted only with a parity diff attached (nothing user-visible deleted; the rollup's model diffed byte-identical on both estates)

  • Comments only for non-obvious whys; docstrings one or two lines

  • No reinvented functions (searched src/); shared logic is one helper

  • Tests cover edge cases; integration tests use sanitized copies of real data

  • Diff is as small as it can be

  • make lint-fix && make test green (13,780 passed), make test-integration green (4,019 passed), make perf green for the census and insights cases, CI green on 67a2dc8c (lint, coverage, integration, the drift ratchet — which initially flagged the census's direct uow.repository_refs/uow.assessments touches; fixed by routing through the owners' doors: Inventory.census_refs_of, AssessmentLog.census_by_ids); perf/queries/test_ops.py::test_an_assets_open_orders_by_index[page] fails identically on the base tree post-crash (environmental: the rebuilt container's planner state — 12.9 ms against a 5 ms budget on a cold run_order page)
  • Changed tests

  • tests/v1/services/findings/test_census.py · new · the census row's identity with the view's counted facts over a full disposition spread (open, accepted, refuted, resolved, hardening by validity and by kind, proven, unverified, top with SLA and CVSS), the as_of cut, the bounded batching (by findings, monorepo-safe), the newest-first order the top cut's stable-sort ties break on (the estate parity catch), the vocabulary-bounded kind cache, and the empty scope's claim gate · new surface

  • tests/v1/repositories/tables/test_findings.py · added the findings census read (newest-first narrow columns, batching), the findings count read (the batch bound), and the joined decisions read (judgement order, until cut, the fold's own columns) and category-labels read (first in recorded order) · new queries

  • tests/v1/repositories/tables/test_assessments.py · added census_by_ids (line columns) and the windowed occurrence read (latest report by the views' order, same-time tie-break, first report's time, until cut) · new queries

  • tests/v1/repositories/tables/test_inventory.py · added the refs census read · new query

  • tests/v1/services/test_insight.py · FakeFindings gained census (delegates to the views through the production adapter) · test double for the new fold

  • tests/v1/services/test_insight_findings_views.py · the rollup-tallies-the-same-through-the-census-fold test now proves the SQL census's numbers against the full views' on a real fold · changed guarantee

  • perf/queries/test_finding_census.py · new · the census legs at volume: repository-keyed legs on their indexes, joined legs under budget (a batch's decisions can be a wide fraction of the table; the planner's scan is the documented trade), statements bounded by the scope's repositories · new queries
  • Plan: traust-foundry plans/standardization-closeout/features/2026-11-performance-lane.md (wave e) · Tracker: foundry#56

    💘 Generated with Crush

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

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: chubirka Review duration: 276m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    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.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #435"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% 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: 52% (MEDIUM) · Higher = larger blast radius
    52%
    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: 60.5% · Lower = rushed or shallow review
    60.5%
    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: 20.5% · Safe to merge
    20.5%