mirror of
https://github.com/beenuar/AiSOC.git
synced 2026-11-24 08:35:46 +08:00
4.2 reviewer pass (measured, off) and 5.5 retro-hunt at scale (measured, with its ceiling) (#1596)
* depth2 Phase 0: kickoff, re-derived baseline and the SIEM-scope decision Phase 0.1-0.4 of the wave-2 depth plan, which lands here locked beside the other four plans. 0.2 re-derives every figure the plan captured. All twenty reproduce exactly except the cloud/identity/SaaS/code condition count, which the plan itself flagged as approximate: measured 344 against 'about 358'. D1 records why, and the finding underneath it — no script in the tree implements that sentence, so every published value of it was hand-counted with a slightly different product set, and windowed rules contribute zero because they carry no product field at all. Phase 2.1's gate has to decide that explicitly. 0.3 captures the baselines, including 'make up-full' — the one the first depth plan recorded as never captured (its D2). 22 containers on the full profile; CORE passed 'make smoke' 10 of 10. The baseline host had nine unrelated containers on it including a foreign Postgres on 5432, and 'make up-full' failed its first bind before the port resolver's overlay landed. D2 records the sequence and, deliberately, does not claim a defect from it: the preceding state is not replayable, so it carries a clean-host reproduction as a follow-up instead. 0.4 is ADR-0015: AiSOC federates to the SIEM rather than replacing it. The README's 'Not a drop-in SIEM replacement' is now a decided position with its cost argument — compliance search needs raw-payload retention outside the 8 GB CORE budget and an availability promise this project has no measured evidence it can keep. Proposed, and nothing in this plan builds from it. * depth2 Lane F: claim migrations 151-158 and ADR 0022 * 3.3: failing test — a repeated vendor finding leaves no count A same-fingerprint repeat is collapsed by three independent layers and kept by none of them. The only trace is a source_event_ids append, which answers 'did more than one event produce this' and nothing else: it also grows on multi-event correlation, so its length is not a repeat count, and it stops at 200. alerts.first_seen and alerts.last_seen have existed since 001_init and fusion has never written either, so the window the repeats span is recorded nowhere. 5 of 7 fail on this tree with 'no statement touched alert_occurrences'. * 3.3: keep a repeated vendor finding as a linked occurrence A same-fingerprint repeat was collapsed by three layers and kept by none. The only residue was a `source_event_ids` append — capped at 200 and shared with multi-event correlation, so its length was never a repeat count — and `alerts.first_seen` / `last_seen` have existed since 001_init with no writer at all, so the window the repeats spanned was recorded nowhere. `alert_occurrences` (migration 151) is a rollup keyed (tenant_id, alert_id): an exact count that includes the surviving alert, the real first- and last-seen window, and a bounded most-recent window of the original payload ids. A vendor re-reporting one finding 79 times is one alert that says 79. A rollup rather than a row per occurrence because "one indicator, a thousand rows" is the shape the retro-hunt sweep already refuses. The payload window evicts oldest-first so the jsonb containment guard's coverage sits where Kafka redelivery actually happens, and `payload_ids_complete` goes false the moment anything is evicted. The measurement is published as its own labelled row and never added to correlation: 28.4 % repeat folding (1000 inputs -> 716 alerts, 284 folded) beside 33.3 % and 24.5 % correlation. The reduction is identical before and after this change and the docs say so — folding is not new, keeping what it folded is. What changed is that 284 inputs are accounted for instead of absent, which the suite asserts as a four-bucket balance summing to the denominator plus a requirement that each folded repeat resolve to the id of the alert that absorbed it. Writing the live suite found a defect in this change's own migration. The conventional `WITH CHECK (tenant_id = current_tenant_id())` makes the row unwritable by fusion, which is a Kafka consumer and binds no tenant session; measured as `aisoc_app` (NOBYPASSRLS), the identical session inserts into `alerts` and is refused here. Because the write is deliberately best-effort it would have failed in silence and the feature would have read as "this vendor never repeats" — migration 123's defect exactly. The policy now mirrors `alerts_tenant`, with the reasoning in the migration. Negative controls, both measured: reverting the WITH CHECK fails all six live cases; removing the containment guard takes five redeliveries of one message from a count of 2 to 7. Baselines unchanged: 33.3 % and 24.5 % reduction, zero cross-rule groups. * 4.6 and 9.4: record what has not been measured, and gate the absence 4.6 — outcome evidence. The three outcomes a buyer asks for first can only be measured by replaying somebody's real closed alerts through `make replay-eval`; the grader compares AiSOC's verdict with a human decision, so the input cannot be synthesised without the measurement becoming a comparison with a fixture written to be compared against. No design partner has offered a window, so false-positive reduction, time to verdict and escalation rate are recorded as *not measured* with the exact two-command reproduction beside them. `check_outcome_claims.py` is what makes that record worth anything. While the replay page says an outcome is unmeasured, no published surface may print a number for it — including `0`, which is the more damaging of the two, because a zero says AiSOC was measured against a real queue and reduced nothing, and it looks like data. The prohibition is read off the replay page rather than hardcoded, so a real measurement retires it without anyone editing the gate: a gate that had to be edited to admit a measurement would be edited to admit a fabrication. Its first run flagged a true sentence — a capability table row naming `escalation rate` in a list beside an unrelated "auto-refresh every 60s" — so the rule narrowed from same-line to same-clause, with both that case and a real claim in the identical row shape pinned in the self-test. A gate that flags correct content gets switched off within a week. 9.4 — the Teams half. Verified rather than assumed: the war room is built, and `POST /war-room` answers 501 naming each absent Microsoft Graph setting instead of falling back to the incoming webhook, because one shared channel per deployment puts the next incident's traffic in the last one's thread. That is already pinned by `services/teams-bot/tests/test_war_room.py`. It is maintainer-blocked on an Entra application registration with Channel.Create, ChannelMessage.Send and Group.ReadWrite.All, admin consent and a team id — recorded as a claim row so the honest refusal cannot quietly become a fallback. Matrix 335 -> 337 rows, 332 GATED, tallies moved in lockstep. * 5.2: run a scheduled hunt on the lake, and label what it emails Two gaps, both of the "built but nothing connects them" family. The scheduler could only run a hunt against a warehouse the tenant had connected: `resolve_provider` required `connected_types.intersection(provider.connector_types)`, and `_execute_hunt` converts the resulting `UnsupportedTranslation` into a hit count of **zero**. Zero hits is not an error state — no case opens, nothing logs above INFO, and `last_run_at` moves — so on every surface it was indistinguishable from "your hunt ran and found nothing". That was the answer on every deployment whose data lives in AiSOC's own lake, which is the default deployment, because AiSOC's own connectors put it there. This is the half the `credentials.py` fix could not reach. That one gave providers the tenant's connector credentials; this is a tenant who has connected nothing for credentials to come from. `LakeProvider` declares no connector types, because there is no connector to resolve — the lake's address is deployment configuration. The registry treats an empty `connector_types` as "needs no connected warehouse", checked after the connector-backed chain so a tenant's own SIEM always wins: it holds years of history AiSOC never ingested, and answering from the lake instead would be a narrower answer to the same question given without anybody choosing it. Scoping is through `compile_hunt`, which binds the tenant structurally and asserts the predicate survived — not `rewrite_for_tenant`, which exists to constrain untrusted operator SQL. An unreachable lake raises rather than returning zero, so the hunt retries instead of moving its clock. Conditions the lake schema cannot express are logged by name, because a hunt that ran with two of its four conditions dropped found fewer matches than was asked about. ADR-0015 requires the emailed hunt PDF to be labelled as hunting output. Before this, `rg -i "hunting output"` matched only the ADR itself: the renderer emitted the row's own title and nothing else. The label is now in the banner, the page title and the mail subject, with a sentence saying what the document does not claim — a reader who does not know the phrase learns nothing from the phrase alone. Delivery itself did not exist. `render_pdf`, `build_from_hunt`, `persist` and `send_mail` all worked; `aisoc_hunt_reports` and the report scheduler's `ReportArtefact` are different surfaces and were never connected, so a hunt report could be generated and downloaded and could not be sent. It ships off: `AISOC_HUNT_REPORT_RECIPIENTS` unset means nobody asked for this. A hunt that matched nothing mails nothing, a missing WeasyPrint stack sends the HTML rather than nothing, and a failing relay never costs the case. The protocol's `credentials` is widened to `| None` rather than suppressed at the call site: the scheduler genuinely passes None for such a provider, and a signature saying otherwise would be the type checker agreeing with a contract the code does not keep. Negative control: removing the empty-connector_types arm from `resolve_provider` fails the reproduction and the scheduler-wiring case. API suite 5042 passed, 174 skipped. Matrix 337 -> 339 rows, 334 GATED. * 9.2: record the device block, and correct a README row that overstated The mobile capability table read "Voice input — Transcription is on-device by construction", which is true of the module and reads as a working feature. `apps/mobile/src/lib/voice.ts` has no recogniser behind it and no screen importing it: the only file in this repository that mentions it is that README. The row now says so, and keeps the half that is real — the module takes a recogniser returning a *string*, so no audio type appears in its signature, a device with no offline model is refused rather than silently using the platform's cloud recogniser, and check_no_audio_egress.py fails the build on any capture API or binary body. That is a design that cannot leak audio. It is not a feature that works. 9.2 proper is blocked twice over and the second row says both halves: the voice path needs 9.1's recogniser and screen to exist at all, and then an Apple developer account and provisioning profile, or a Google Play account, to reach a handset somebody can speak to. The Android assembleDebug APK does install on a handset, so once 9.1 lands the Android half becomes a device question rather than a credentials one. The mobile.yml README-honesty guard is extended rather than left behind — the workflow's own header records that "we added a build so the honesty check is no longer needed" is how an ungated claim returns. It now pins both new rows and asserts its own vacuous-pass case, since a guard that greps four patterns in a file it never opened reports success. Negative control: restoring the previous wording fails the voice-input pattern. DEPTH2_PROGRESS gains deviations D3 (four Lane F items that did not reproduce as the plan describes them, with what is actually missing) and D4. * 3.2: link alerts into stories by typed evidence, not by string match Built on attack_chain_grouper rather than beside it. It chained alerts sharing a host, user or source-IP *string*, first match wins in a fixed order, with nothing on the result saying which of the three had done it. So a NAT egress address or a shared jump host welded two unrelated intrusions into one story; an alert carrying a session id — which fusion has written onto the alert row since migration 102, alongside the human resolved behind an assumed-role chain — got no more weight than one carrying a hostname, so the strongest evidence available went unused; and `ChainMember` carried a per-member severity that nothing aggregated, so the plan's "a member benign alone may be escalated by its story" had nowhere to happen and no reason to record. Links are now typed and carry a strength, and the strength decides what a link may do. Session and resolved human are strong; file hash and domain are specific; bare entity strings are weak. A weak link may not merge two detection rules, which is what keeps v21's narrowing from being undone one layer up where the published 24.5 % cannot see it. A strong or specific link may cross rules, and the assignment records which link did it so every cross-rule story is enumerated rather than tolerated. Story severity rises by exactly one tier, never past critical, and only when the story spans three or more kill-chain stages — one alert is an alert, two can be one action seen twice, three stages on one authenticated context is a narrative. Members carrying no tactic do not count toward the span, so three tactic-less detection alerts cannot escalate each other. The reason travels on the assignment, because an escalation whose cause is in a log line cannot be audited from the alert. Actor mode is `unknown` until Lane A's 1.4 supplies cadence. Two inferences were considered and rejected in the code: a credential session with no resolved human is unresolved rather than automated, and a service-account shaped username is a naming convention rather than evidence. Measured over three labelled multi-stage scenarios interleaved with unrelated traffic sharing the tenant's NAT egress address: recall 100 % on all three (4/4, 3/3, 2/2), purity 100 % (5/5 stories), 0 cross-rule stories of 63 on a detection-shaped cohort. The purity rule was found by that measurement rather than reasoned out in advance. The first cut refused a weak link only when it crossed detection rules, and the suite immediately measured 75 %: the scenario alerts carry no rule_id, so the cross-rule arm had nothing to compare and an antivirus quarantine joined a phishing-to-exfiltration story on a shared address. A weak link now also may not join a story anchored on strong evidence. The asymmetry is deliberate and tested — a strong link may still join a pile string matching had already assembled, or the tiers would be a rule about arrival order rather than about evidence. Negative controls, both measured: removing the strong-anchor refusal fails the purity measurement and its unit case; removing the cross-rule refusal fails the enumeration and its unit case. Reduction baselines unmoved: 33.3 % and 24.5 %. Fusion suite 1090 passed. Open and recorded rather than approximated: stories are still Redis-only, so the assignment evaporates after the Kafka envelope and no API read can show one, and the resolved-identity link waits on Lane A's 3.1. * Lane F: record the eleven items the lane did not reach, with measured state Deviation D5. The reproduction work for each was done before the lane ran out of time, so each row is measured state rather than a guess — which is worth more to whoever picks them up than a fresh grep. Three are worth reading before anyone starts: 4.5's read verbs already exist (987 lines, 5 verbs, 7 vendors); the gap is that run_auto_triage has no tool channel at all, so a vendor alert that auto-triages never pulls vendor evidence. 4.4's precedent already reaches triage by two routes but matches only on exact fingerprint; a complete Qdrant recall with provenance sits unused by the triage path. A naive re-triage writes nothing, because run_id is a uuid5 over the alert and workflow version and the ledger is ON CONFLICT DO NOTHING. 9.5's claim row is stale in the repository's favour: SCIM tokens and organisation members are both built and the row still says they are not. * 3.3: declare the occurrence suite's fixture DSN as the owner it is check_runtime_db_role.py failed two jobs on #1588 with one root cause: the live suite's ISOLATION_OCCURRENCES_ADMIN_DSN connects as 'aisoc', which the workflow provisions as a superuser, and a superuser ignores every RLS policy even under FORCE ROW LEVEL SECURITY. The split is deliberate and the gate is right to make it explicit. The code under test reads ISOLATION_OCCURRENCES_DSN, which is the DML-only runtime role with NOBYPASSRLS — that is what found migration 151's WITH CHECK defect in the first place, and a suite driven entirely as the owner could not have. The owner DSN exists only so fixtures can create scratch tenants, which the runtime role cannot. Declared with the marker and the reason the gate asks for, in the same shape agent-auth-live.yml already uses. * 4.2: a reviewer pass, measured, and left off because it did not help The plan's condition is binding: ship it only if it improves balanced accuracy or auto-close precision on the corpus without lowering malicious recall; otherwise record the measurement and leave it off. It was built, measured, and is off. reviewer off balanced accuracy 0.2500 auto-close precision not measured reviewer on balanced accuracy 0.2500 auto-close precision not measured malicious recall 0.0000 unchanged Both rows reproduce with one command each, and `auto_close_precision` reads "not measured" rather than 0 because the deterministic path closed nothing and there is no denominator. The reason is worth as much as the number, so it is published rather than left as a shrug. The deterministic scorer makes no prose claims, so supporting_evidence, contradictory_evidence and groundedness are None on every item — the decision contract correctly reports them as not evaluated — and a reviewer whose inputs are all absent has nothing to act on. It abstains on all 72. That measures the reviewer on the only path available to measure it, not the idea behind it. Deterministic rather than a second model call, and that is the deciding argument rather than a convenience: a second call doubles the hot-path cost on every fused alert, and a model at 0.21-0.36 balanced accuracy adjudicating another at 0.21-0.36 is a coin flip refereeing a coin flip. Shipping that on an unmeasured design is the failure this plan exists to prevent. A funded key makes the model-backed variant a drop-in behind the same interface, decided by the same measurement. It may never close. It sits after every existing demotion and before the closure branch, so it can only take a decision away from closure; the flag goes True to False and never the reverse; and an AST assertion that strips docstrings proves the module reaches no closure path — it explains closure at length in order to say it does not reach it, so a raw substring check could not tell a call from a sentence about one. An empty supporting_evidence list is acted on and a None is not. Collapsing "the signal did not run" into "the signal found nothing" would demote every deterministic verdict in the product, which is the distinction the decision contract's own docstring exists to protect. The groundedness floor is asserted equal to the existing gate's: a second opinion about groundedness would be two controls disagreeing about one number, and the quieter one would win silently. Every record says the reviewer ran, abstentions included, so a reviewer that has silently stopped firing is distinguishable from one that found nothing. And a test asserts the measurement is recorded beside the code, because "it is off" decays into "nobody remembers why" and the next reader switches it on without taking a new one. Negative controls, both measured: letting the reviewer turn closure back on fails two cases; treating a None signal as a negative result fails four. Agents suite 2211 passed, 8 skipped. Matrix 340 -> 341 rows. * 5.5: measure a retro-hunt at scale, and publish where it stops Measured against a real ClickHouse 24.8 on recorded hardware (Apple M5 Max, 128 GiB), driving the real generator — `build_sweep_sql` is split out from the sweep's I/O precisely so a measurement can load it without re-implementing it, and a benchmark that wrote its own query would be the producer-compared-against-itself defect this repository already gates for. Lake cost is read out of `system.query_log`, not estimated. lake rows median p95 read bytes/row % of budget 100,000 6.97 ms 7.64 9.24 MB 92.4 0.11 % 1,000,000 11.59 ms 13.54 93.66 MB 93.7 1.09 % 5,000,000 38.74 ms 46.27 469.17 MB 93.8 5.46 % 20,000,000 148.97 ms 175.49 1875.12 MB 93.8 21.83 % `read_rows` equals `lake_rows` at every step. The sweep is a full scan, and every other figure follows from that. The degradation point is the result the plan asked for, and it is derived from the product's own constant rather than guessed: `MAX_BYTES_PER_SWEEP` is 8 GiB, passed to ClickHouse as `max_bytes_to_read` so the server enforces it, and at 93.8 bytes per row one sweep exceeds it at approximately 91.6 million rows of tenant history. That is a ceiling, not a slowdown — past it the sweep reports "could not complete" rather than returning fewer sightings, which is why the limit is in bytes and not a client-side timeout. The 20 s timeout is the second ceiling and binds far later on this hardware; on slower storage the order could reverse, and that is said on the page. The million-indicator rows are extrapolation and are labelled as such: a literal million sequential sweeps was not run, because it would take as long as the answer. At 20 M rows it is 41.4 h and 1.88 PB read. The honest reading, stated on the page rather than buried: a million indicators cannot be swept one at a time against a working lake. A batched sweep — one scan testing many needles — is what would fix it, it is not built, and nothing here claims it is. `check_retro_hunt_scale_claims.py` keeps the page honest in the direction it will actually drift: every figure is read back out of the committed artefact, the artefact must carry its hardware and ClickHouse version (a latency with no machine behind it is not a result), the extrapolation must be labelled, and the ceiling must be derived from MAX_BYTES_PER_SWEEP — so moving the product's budget moves the page or reds the build. Seven self-test cases. Negative control, measured: changing the budget to 2 GiB makes the gate name the page's 91.6M against the derived 22.9M. Three limits stated on the page: single node with nothing else running, one indicator type (`ip`, which touches three columns including an array membership test), and a synthetic corpus whose compression is the figure most likely to move. Matrix 340 -> 341 rows. * Lane F: record the second pass in the item log Six more items landed: the 9.5 claim-row correction with its gate, 4.5's bounded tool channel, 4.4's similarity precedent and re-triage identity, 3.3's cross-vendor half, 4.2 measured and left off, and 5.5 measured with its degradation point. D5 now lists only what is still open. * 9.5 prerequisite: a 'not built' claim about a console page must still be true (#1592) The claim-to-gate matrix carried, inside the caveat of a GATED row: Six console pages parity 4.5 also names — branding, SCIM tokens, retention, organisation members and grants, rule packs, delegations — are not built Three of them were built. `ScimTokensPanel` had shipped, was wired into SettingsView, and is gated by another row of the same matrix — so two rows of one document disagreed about whether a surface exists. `RBACView` had shipped and is covered by BannerHonesty.test.tsx. `UsersView` had shipped at /settings/users and was tested by nothing at all. The direction of the error is what makes it worth its own change. It reads as modesty and works as an exemption: a surface recorded as absent needs no claim row and no gate, which is exactly what that sentence was doing in a caveat. A shipped page inherited the coverage of a page that does not exist. `check_claim_gate_matrix` cannot see this. It counts rows and statuses and does not read a caveat's prose, so the row stayed GATED, accurate about its own claim, while excusing an entire surface from having one. check_unbuilt_claims.py reads every "not built" assertion scoped to console pages, resolves each named surface through a component file **and** a render site — an unrendered component is not a page, and crediting one would make the gate certify the defect it is named for — and fails on any that exist. Proven against the pre-fix tree, where it names all three. Six self-test cases in both directions, including the motivating sentence verbatim and an unrelated "not built" outside a console context that must not fire. Only one direction is checked, deliberately: claimed absent, actually present. The opposite is already covered by the gates requiring a claim row to name a job that drives the production path. UsersView.test.tsx is the gate the corrected row now names: six cases asserting on first paint as well as the error branch, since `data` is undefined in both and a suite driving only the error branch never exercises the state every page load passes through. The load-failure case asserts the absent state too — "we could not read the members" and "this organisation has no members" are different facts about an access-control surface. A member count is asserted not to render over a failed read, because `total` falls back to 0 and "0 members" beside a red error box is a number nobody measured. Writing it reproduced the mirror of a recorded trap: the first mock exposed `authApi.me` where the component calls `authApi.currentUser`, so a double less capable than the real object failed six tests with a TypeError rather than an assertion. Branding, retention, rule packs and delegations genuinely are not built and the corrected caveat says so. Matrix 340 -> 341 rows, 336 GATED. * 5.5: count the perf script's urlopen warning rather than suppress it `scripts/perf/retro_hunt_scale.py` POSTs its measurement query to an operator-supplied ClickHouse DSN, so `urllib.request.urlopen` receives a non-literal argument and semgrep's `dynamic-urllib-use-detected` fires. It is the third instance of the identical finding in this repository — the same rule already contributes one for `check_main_run_cancellations.py` and one for `check_codeql_alerts.py` — and the allowlist's own precedent for that shape is to count it rather than suppress it. The check that this is a real warning and not the scanner's recorded +/-1: that noise moves `error` and `total` together, and `error` is unchanged at 44. The new line was located in the diff before the ceiling was touched. * depth2 Lane E: AI provider coverage, chat-compliance minimisation, hosted agents, repository AI config and four replayed AI rules (#1585) * depth2 Lane E: claim migrations 146-150 and ADR 0021 * test(connectors): reproduce the AI provider-coverage gap in llm_usage Depth 6.3 / wave-2 7.1. `LlmUsageConnector` accepted `openai` and `anthropic` and nothing else, so Gemini in Workspace, Copilot in M365, Copilot in GitHub and Entra consent grants to AI applications had no reader at all and the AI estate's provider-audit discovery source could only ever see two vendors. Six of the seven tests fail on this tree: four drive the real HTTP path against a mock server returning vendor-shaped payloads and get a ValueError from the constructor, one asserts the org-scoping refusal and one asserts the schema's select options match the accepted providers (`PROVIDERS` does not exist yet). Endpoints, query parameters and event names come from the vendors' current public references, each fetched and 200 before being written: the Admin SDK Reports API `gemini_in_workspace_apps` application, the GitHub organization audit log, the Office 365 Management Activity API schema (RecordType 261 CopilotInteraction, 284 AIAppInteraction) and Microsoft Graph directoryAudits. * feat(connectors): four more AI provider audit feeds in llm_usage Depth 6.3 / wave-2 7.1. Closes the gap the previous commit reproduced: the connector now reads Gemini in Workspace, GitHub Copilot, Microsoft 365 Copilot and Entra consent grants alongside OpenAI and Anthropic. Each client was written against the vendor's current public reference, every one of which was fetched and returned 200 before being committed; the module docstring names them per provider. The Workspace `gemini_in_workspace_apps` applicationName and the `ai_usage_event` / `feature_utilization` event names, the 23 published `copilot.*` audit actions, RecordType 261 CopilotInteraction and 284 AIAppInteraction, and the directoryAudits consent activities are all read values, not inferred ones. Three things the tests pin beyond "it parses": - Filtering happens server-side where the vendor supports it. Asking GitHub for an organisation's whole audit stream and discarding client-side is a rate-budget problem on a busy org, not a style one. - Where it cannot, the reader discards non-AI records by RecordType and by consent activity name. `Audit.General` is the entire Microsoft 365 general audit and `directoryAudits` is every directory change; a reader that forwarded both would replace the AI feed with a second copy of the general audit. - A consent grant's scopes are lifted out of the free-text `ConsentAction.Permissions` property into a sorted `scopes` list on the envelope. A grant whose scopes stay buried scores in the AI estate as a grant with no scope at all, which is the opposite of the truth for `Mail.Read`. M365 needs a second request because the subscription endpoint returns blob references rather than content; a reader that stopped at the first response would poll successfully forever and emit nothing. Workspace OAuth token grants are deliberately not read here — `google_workspace` already polls the `token` application, and a second reader would double-count every grant. What is missing there is classification, which is the next commit. Docs and the conformance matrix regenerated, not hand-edited. * test(fusion): reproduce the recorder reading a path no connector emits Wave-2 7.1 wiring. `test_ai_asset_recorder.py` writes `finding.evidence.scopes` into a hand-built OCSF event and asserts the recorder reads `finding.evidence.scopes`. Both halves are the test's own invention: no connector in the tree produces that path and ingest does not synthesise it, so the assertion holds whether or not the production path works. What ingest really hands fusion is the connector's normalized dict as a JSON string under `ocsf["raw_data"]`, which is why `_connector_fields` exists for the endpoint path and is not used by the provider-audit path. Driven through that real shape, both new tests fail: an Entra consent grant reaches the inventory with no scopes at all, so an AI notetaker consented into every mailbox in the organisation scores identically to one granted nothing, and the console's reason list is silent about the single fact that decides whether the grant matters. The fixtures are the real output of `LlmUsageConnector.normalize()`. The two services cannot import each other — both package their application as `app` — so they are held together by a committed artefact plus a check in each direction, the way the vendored narrative and the detection ruleset already are. * fix(fusion): read provider-audit fields where the connector puts them Wave-2 7.1 wiring. `_from_provider_audit` now reads through `_connector_fields`, the same reconstruction the endpoint path already performs, instead of off the canonical OCSF map. An Entra consent grant's scope list reaches `score_risk`, so a grant holding `Mail.Read` scores as broad and says so in its reason list. Two further corrections the real shape forced: - An OAuth grant is keyed on the **application**, not the audit record. Keying on the record id would make every re-consent a new asset and reset `first_seen_at` on each, so the inventory would grow a row per event and never show that this application has been there since May. - The OCSF-native `finding.evidence.scopes` read is kept as a fallback rather than replaced, so a producer that does emit it is still read. Trading one blind spot for another is not a fix. Negative control, recorded: with the `fields.get("scopes")` read reverted to the pre-fix path and nothing else changed, both new tests fail again (`KeyError: 'scopes'`). Restored, the fusion suite is 1063 passed / 28 skipped. The `normalize` contract is unchanged across all 87 connectors: the "is this record AI activity at all" decision is a separate `is_ai_record` predicate rather than a `None` return, which keeps the base signature intact and makes the filter — the thing that stops the Microsoft 365 AI feed becoming a second copy of the general audit — callable and testable on its own. * feat(api): enterprise AI-chat compliance logs, minimised by the schema Wave-2 7.1, second half. Reads an AI provider's compliance API for the directory, projects and activity feed, and — behind a second, narrower opt-in — classifies message content without keeping any of it. Written against Anthropic's Compliance API, the one enterprise AI-chat compliance surface with a complete public reference. Every path, scope, key prefix and response field was read from pages that each returned 200 before being committed; the client's module docstring names them. The Activity Feed record and the chat record in the tests are the vendor's published examples field for field. The minimisation is in the schema, which is the point of ADR-0021. A plan sentence saying "never full conversations" that a TEXT column permits is not a control; it holds until the first caller who binds "\n".join(messages) and succeeds silently. - No table has a column able to hold a message. Asserted against the ORM, since that is what application code binds through. - The snippet is VARCHAR(280). The collector truncates; the column is the backstop for the caller that forgets. - The snippet is masked BEFORE it is cut, so a row saying "this chat contained an AWS key" does not contain the key. A verbatim window would create a new copy of the secret in a table an operator believes is safe to keep, and label it so an attacker can find it. A per-pattern sweep asserts the value is absent for every shape in the shared list. - The label vocabulary is a CHECK constraint, and a test asserts the three copies of it (constraint, ORM, classifier) agree. - The client has no method returning message text, asserted on its public surface. - Two opt-ins, stricter one default-off: collection does not imply reading message bodies. - Off by default per tenant, through the console, vault-held key. No environment variable. A vault failure is a 503, never a plaintext row. The secret-shape patterns are the AI SDK's own, vendored by scripts/sync_vendored_ai_redaction.py and held byte-identical by its --check. A prompt and a chat message containing the same AWS key must produce the same shape name on both surfaces; a second hand-written copy is how two surfaces come to disagree about the same rows. The SDK groups e-mail and card shapes with credentials because it is answering a transmission question; _SDK_LABEL maps each shape to one of the plan's four classes rather than relabelling the shared list. Luhn is applied to the shared card shape. Without it the digits-only pattern labels order ids as payment data, and a classifier that labels everything is one nobody believes. Retention, legal hold and erasure come free and are tested: every table carries a column named exactly `tenant_id`, which is how `discover_tenant_tables` finds it. Discovery rather than a declared list is deliberate — a list is the thing that goes stale. Tests use httpx.MockTransport rather than respx, because respx is not in this service's locked dependency set and a test needing a package CI does not install is a test CI cannot run. MockTransport replaces only the network leg. Negative control, recorded: adding a `transcript: Mapped[str | None] = mapped_column(Text)` to AiChatContentLabel and changing nothing else fails two tests (the forbidden-column sweep and the unbounded-TEXT sweep). Removed, the API suite is 5074 passed / 174 skipped. Migration 146 and ADR-0021 were claimed in DEPTH2_PROGRESS.md before either file was written. * docs(depth2): record 7.1 in the progress tracker * feat(ai-estate): hosted agents and repository AI config as asset kinds Wave-2 7.2. Two new kinds on `aisoc_ai_assets` (migration 147), both scored by the one existing `score_risk` and rendered with their reasons on the AI estate page. No second scorer: the plan forbids it by name and it is the drift this repository keeps finding. **Hosted agents** come from `GET /v1/agents` with the `managed-agents-2026-04-01` beta header, read against the vendor's published reference (fetched, 200). An agent configured in a provider's control plane is invisible to every other discovery path here: endpoint telemetry never sees it, and gateway telemetry sees its traffic without knowing what it was configured to do. The client is read-only — the vendor offers create, update and archive and none of them is here, because an inventory that can reconfigure a customer's agents is a different risk conversation and 7.2 is read-only by the plan's rule. **Repository AI config** is the scan of agent-instruction files, skill directories and MCP configuration through the code-platform connectors, recording the tools and servers each references. "Which repositories point an agent at this MCP server" is a question the estate could not answer. Every byte of that scan is attacker-controlled and is treated as such. These files are checked in, editable by anyone who can land a pull request, and read by an agent verbatim as instructions — the same trust class as a retrieved runbook, which this platform already scans. So: - Nothing is stored raw. Excerpts are flattened and capped at 400 characters, with zero-width and bidirectional characters stripped, because an instruction file is exactly where a payload invisible in a diff gets hidden. - The content is scanned at capture and only the matched *pattern names* are kept — never the matching text, which would put the attacker's payload in a table the console renders, labelled so a security team looks at it. - Those names reach `score_risk`, so a flagged file raises the asset's exposure and the reason names the channel. - A hosted agent's `system` prompt goes through the identical path, for the identical reason. The patterns are **generated** from the agents guard's own `_RULES` table rather than hand-picked, by scripts/sync_vendored_ai_instruction_rules.py with a --check wired into ci.yml. A hand-copied subset drifts: a pattern added to the guard after the next incident would never reach the scanner and nothing would say so. One rule is excluded with its reason recorded — `fabricated_tool_result` matches a model-output envelope rather than a repository file, and its pattern is assembled from a set, so it renders in a different order in every process and no generated file could match itself. The generator fails if an excluded name leaves the guard, so the exclusion cannot outlive the rule and become a silent gap. Two things found while building it: - `path.lstrip("./")` eats the leading dot of a dotfolder, so `.cursor/rules/x.mdc` became `cursor/rules/x.mdc` and stopped matching — silently, as a path that simply is not an AI artefact. Every convention here lives in a dotfolder, so that one call would have turned most of the scan off. Caught by the classification table, which is why it enumerates real paths rather than a couple of examples. - `DEVICELESS_KINDS` is shared between the model and `score_risk`, so the four kinds that cannot have a device are not charged for lacking one. A hosted agent has no laptop to isolate; the reason string "containment has nowhere to act" would simply be false. The tool reader matches grants, not prose: "do not use `write_file`" in a paragraph is not a grant, and counting it would make a careful instruction file score worse than a careless one. Also: a committed JWT-shaped literal in the 7.1 classifier test is now assembled from parts. The repository's secret scan was right to refuse it, and a test fixture has no business looking like a credential. * docs(depth2): record 7.2 in the progress tracker * feat(detections): four AI rules on the provider feeds 7.1 added Wave-2 7.4, partial — four of the rule pack's targets, each earned rather than declared. Executable corpus 2,530 -> 2,534, regenerated from `scripts/project_stats.py` and propagated to the README, ROADMAP, truth table, corpus stats, marketplace index and the packaged API copy by their own generators. Nothing was hand-typed. - `llm-copilot-content-exclusion-changed` (critical) — content exclusion is the control that stops a coding assistant reading the paths an organisation declared off limits. It is changed in a settings page rather than in a pull request, so nothing else reviews it. - `llm-copilot-agent-mcp-config-changed` (high) — adding an MCP server adds a party that can instruct a hosted agent. A scope change, not a settings change, and the agent runs on the provider's infrastructure so no endpoint control sees the result. - `llm-ai-app-granted-write-scope` (high) — a consent grant letting an AI application change a mailbox, drive, site or the directory. The read equivalent is an exposure; this one can act. - `llm-copilot-bulk-resource-access` (medium) — one assistant turn that read 25 or more distinct resources. An assistant with a user's grant is an exfiltration path that authenticates as that user and looks like ordinary application traffic. Every rule is replayed through the REAL connector and the REAL engine in `services/fusion/tests/test_ai_rule_pack_replay.py`. The fixtures are the committed output of `LlmUsageConnector.normalize()` on vendor-shaped records, regenerated and drift-checked from the connectors side, because the two services cannot import each other. Nothing here is synthesized from the rule it tests. That is the whole point: 1 of 12 GitHub rules fired on real connector output while all twelve passed their own fixture replay, because a fixture generated from a rule carries the rule's own clause key and the replay is tautological. Each negative twin differs in exactly ONE decisive field — a different Copilot action, `Mail.Read` where the twin is `Mail.ReadWrite`, 24 resources where the twin is 40 — and a test asserts that property on the fixtures rather than trusting it, since a negative that also moved the actor would pass for a reason unrelated to the clause. Negative control, recorded: rewriting one rule's clause to the unprefixed vendor action (`event_type: content_exclusion_changed`), which is the exact shape of the measured GitHub failure, and re-exporting, fails that rule's positive replay while the other three stay green. Restored, all ten pass. `test_builtin_rule_catalogue.py`'s hand-typed counts moved 760 -> 764 and 2609 -> 2613 with the reason recorded beside the existing history, in the style that file already keeps. * docs(depth2): record 7.4 partial and 7.3 not delivered, with evidence * chore(detections): regenerate the curated index for the four new rules `curate_detections.py --check` is a drift gate I had not run: adding four rules moves the curated selection and the coverage page, and neither is produced by any of the seven generators I did regenerate. Caught by CI, reproduced locally with the same command, and regenerated rather than hand-edited. Worth recording because it is the shape this repository keeps finding: a published artefact with its own generator and its own `--check`, sitting outside the chain everything else in the family runs through. All eight detection drift gates now pass together. * fix(ci): correct the gitleaks fingerprints the four new rules shifted `.gitleaksignore` pins a finding by `file:rule:line`, so inserting four entries into `detections/rule-ids.lock.json` moved every line below them and five fingerprints stopped matching the findings they were triaged for. The file's own header describes this rot and says the fix is to correct the line number, never to drop the entry or relax the job, so that is what this does: the set is re-derived by running CI's exact gitleaks 8.21.2 with the allow-list removed, and all fourteen are written back. Thirteen are the same pre-existing, benign findings — the heuristic fires on rule *slugs* such as `llm-api-key-created` and `slack-token-exposed`, never on a value. One is genuinely new: `llm-copilot-bulk-resource-access` trips it on the word "access". Verified under 8.21.2 rather than the 8.30.1 on this machine, because the two disagree about this tree and only the pinned one decides. Also regenerates `apps/web/public/marketplace/{index,curated}.json` through `pnpm marketplace:sync`. `curate_detections.py --check` passing is not the whole gate: the web mirror is copied by a separate step, and a curated index that is current in one place and stale in the other is the drift that check exists to catch. * 3.3: the occurrence guard anchored a pattern pytest never writes `grep -qE '^[0-9]+ passed'` cannot match, because pytest writes its summary as `===== 6 passed in 0.67s =====`. The job reddened on a run where all six live tests passed, which is the worse direction for a guard: one that fails on a healthy suite teaches people to ignore it. The count is now unanchored and `[1-9][0-9]*` rather than `[0-9]+`, so a run that collected nothing and reported `0 passed` is still a failure. Verified in all three directions against the real summary line: the new pattern matches it, the old one does not, and `0 passed` is still refused. * 4.5: give auto-triage a bounded channel to the read verbs it already had (#1593) No read verb is added here. `investigation_reads.py` is 987 lines carrying five read-only capabilities across seven vendors — Defender, CrowdStrike, SentinelOne, Okta, Entra, Workspace, AWS — each with a capability contract, an executor, an autospec'd signature test, a closed agent allowlist and a parameter allowlist. All of that worked. What did not exist was any way for auto-triage to reach it. The verbs are bound to the investigation agent in `deep_investigation.py`, which runs only on the escalation path. `run_auto_triage` was a single `safe_ainvoke` with no tool channel, and said so in its own comment. So on the path every fused alert takes, a GuardDuty or Defender alert was triaged without ever asking GuardDuty or Defender what they knew, and `unverified_tool_claims` correctly blocked auto-close if the model so much as claimed a tool result. A deterministic pre-fetch rather than a tool-calling loop, for three reasons. Latency and cost on the hot path would otherwise be unbounded: one model call becomes N plus N vendor round trips on every fused alert with no ceiling anybody declared. The alert payload is untrusted by construction — it is fenced and injection-scanned before anything reasons over it — so a channel whose arguments the model derives from that payload is a door an injected string can aim; not choosing at all is strictly stronger than the parameter allowlist alone. And the citation is true: the result is in hand before the model is asked anything, so the ledger row exists because the call happened rather than because the model said it did. It is a bounded channel, not an absence of one: triage reaches the real verbs, the set is fixed per alert shape, and the budget is declared. `called_tools` is now whatever a vendor really answered, and only that. A read that was attempted and failed is deliberately absent, because the guard's question is whether a rationale credits a tool with a result and a read that returned nothing produced no result to credit. An empty tuple when the pre-fetch is off restores the previous behaviour exactly. The reads land as `tool_call` rows at seq 2 and up, in the same transaction as the verdict. Not before the model call, even though that is when they happened: seq 0 and 1 are the model call's and the verdict's keys and the `(run_id, seq)` uniqueness is what makes a replay idempotent. The `ts` on each row carries the real ordering. Off by default behind AISOC_TRIAGE_VENDOR_EVIDENCE: this reaches the customer's vendor API on every fused alert. A failed read renders as COULD NOT CHECK with its status, never as silence. A failed EDR read is not evidence that the host is healthy, and an absent answer rendered as nothing is read by a model as a clean one. Negative controls, both measured: removing the render call fails the prompt case; counting failed reads as called tools fails the guard case. Scorecard: deterministic balanced accuracy 0.250, auto-close precision not measured — identical to the committed baseline, which is what an off-by-default context source must do. Alert reduction unmoved at 33.3 % and 24.5 %. Agents suite 2215 passed, 8 skipped. Matrix 340 -> 341 rows. * docs(matrix): one Summary block, recomputed from the gate A keep-both merge resolution appends a second `## Summary` rather than merging it, and on four of these branches the surviving copy had been spliced into the middle of the table. The row parser stops at the first blank line, so the splice both hid rows and left the published figure describing a shorter table than the file holds. One block at the end, with every bullet, and all three surfaces — the matrix, ROADMAP and the evidence pack — recomputed from `check_claim_gate_matrix.py` rather than edited. * ci: drop the duplicated vendored-AI-rules step the merge placed too early Keeping both sides of the ci.yml conflict left two copies of the step, and the earlier one runs before `service_requirements.py api agents` installs anything — so the guard's rule table could not be imported and the gate refused with "No module named 'structlog'". That refusal is the gate being right: it will not certify a comparison it could not make. One copy, in the position main already had it: after the install. * fix(gates): resolve the repo root through git, not from __file__ `check_gate_contract` holds every wired gate to two properties, and this one failed the first: a root taken as `parents[1]` of `__file__` is whatever directory happens to sit above the script, so a gate run from a scratch copy of `scripts/` reads that tree and reports on it as though it were the repository. Use `gate_toolkit.repo_root()`, which asks git and honours `AISOC_REPO_ROOT`, matching every other gate in the directory. Behaviour in a normal checkout is unchanged: the self-test still passes and the check still reports the same four measured steps.
This commit is contained in:
@@ -540,9 +540,12 @@ jobs:
|
||||
# key" differently about the same text is the drift this prevents.
|
||||
- name: Verify vendored AI redaction patterns are in sync
|
||||
run: python scripts/sync_vendored_ai_redaction.py --check
|
||||
# The GPU preflight's own self-test. The real verdict depends on the
|
||||
# host, so CI can only assert that the refusals fire and say something
|
||||
# actionable -- which is the part that rots, since the advice is prose.
|
||||
# The prompt-injection patterns, generated from the agents guard's own
|
||||
# rule table rather than hand-copied. The repository scanner (wave-2
|
||||
# 7.2) flags an agent-instruction file or a skill whose text tries to
|
||||
# steer an agent; a hand-picked subset would silently miss whatever
|
||||
# pattern was added to the guard after the next incident. Needs the
|
||||
# agents service importable, so it runs after that install step.
|
||||
- name: GPU preflight — self-test
|
||||
run: python3 scripts/check_gpu_runtime.py --self-test
|
||||
# Gap-closure Phase 2.2. The sixth mirror, and the one where drift is a
|
||||
@@ -626,6 +629,37 @@ jobs:
|
||||
run: python3 scripts/check_alert_reduction_claims.py --self-test
|
||||
- name: Verify the retracted alert-reduction figure stays retracted
|
||||
run: python3 scripts/check_alert_reduction_claims.py --check
|
||||
# Wave-2 plan 4.6. The three outcomes a buyer asks for first can only be
|
||||
# measured by replaying somebody's real closed alerts, no design partner
|
||||
# has offered a window, and all three are recorded as *not measured*.
|
||||
# This gate is what stops that record becoming a number — including the
|
||||
# worse version, a `0`, which reads as "measured and reduced nothing".
|
||||
# It reads the state off the replay page rather than carrying its own
|
||||
# copy, so publishing a real measurement retires the prohibition without
|
||||
# anyone editing the gate.
|
||||
- name: Customer-outcome claims — self-test
|
||||
run: python3 scripts/check_outcome_claims.py --self-test
|
||||
- name: No customer-outcome figure nobody measured
|
||||
run: python3 scripts/check_outcome_claims.py
|
||||
# Wave 2, Phase 9.5 prerequisite. A caveat saying a console page is
|
||||
# "not built" reads as modesty and works as an exemption: a surface
|
||||
# recorded as absent needs no claim row and no gate. Three shipped
|
||||
# pages were sitting behind one such sentence, and one of them —
|
||||
# /settings/users — had no test at all. `check_claim_gate_matrix`
|
||||
# cannot see this: it counts rows and statuses and does not read a
|
||||
# caveat's prose.
|
||||
- name: 'Unbuilt-surface claims — self-test'
|
||||
run: python3 scripts/check_unbuilt_claims.py --self-test
|
||||
- name: Every 'not built' claim about a console page is still true
|
||||
run: python3 scripts/check_unbuilt_claims.py
|
||||
# Wave 2, Phase 5.5. The published retro-hunt ceiling is derived from
|
||||
# MAX_BYTES_PER_SWEEP, so moving the product's budget must move the
|
||||
# page or red the build: a published limit that quietly describes a
|
||||
# budget the product no longer has is worse than no limit at all.
|
||||
- name: Retro-hunt scale claims — self-test
|
||||
run: python3 scripts/check_retro_hunt_scale_claims.py --self-test
|
||||
- name: The published retro-hunt scale figures are the measured ones
|
||||
run: python3 scripts/check_retro_hunt_scale_claims.py
|
||||
# Same family, same reason. The three customer outcomes a buyer asks
|
||||
# for first are recorded as not measured because no design partner has
|
||||
# offered a queue to replay; that record is worth what stops it being
|
||||
|
||||
+15
-1
@@ -266,7 +266,21 @@ ceilings:
|
||||
# Counted rather than suppressed, per the note at the bottom of this
|
||||
# file. Measured with semgrep 1.86.0 on the vendored packs
|
||||
# (rules_sha256 below): 112 total / 44 error.
|
||||
total: 112
|
||||
#
|
||||
# 112 -> 113 (error unchanged at 44). The added WARNING is
|
||||
# `dynamic-urllib-use-detected` on scripts/perf/retro_hunt_scale.py,
|
||||
# which POSTs a measurement query to an operator-supplied ClickHouse DSN.
|
||||
# This is the third instance of the identical finding — the same rule
|
||||
# already contributes one for check_main_run_cancellations.py and one for
|
||||
# check_codeql_alerts.py — and it is counted for the same reason: the
|
||||
# rule fires on any non-literal argument to `urlopen`, which every one of
|
||||
# these three has by construction, and counting it is better than
|
||||
# suppressing it. That `error` did not move is the check that this is a
|
||||
# real warning rather than the scanner's recorded +/-1, which moves both
|
||||
# numbers; the new line was also located in the diff before the ceiling
|
||||
# was touched, so this is the ratchet's documented path for an understood
|
||||
# finding and not a ceiling raised to make a scan pass.
|
||||
total: 113
|
||||
error: 44
|
||||
measured_with: "1.86.0"
|
||||
rules_sha256: "5af76658e7e28b96b1099d2c995d7c85b3b9a4f96795a39df3d02aa7d295cb99"
|
||||
|
||||
@@ -343,6 +343,11 @@ the scoreboard row for the 8B model is untouched.
|
||||
([#1585](https://github.com/beenuar/AiSOC/pull/1585)); the rest need a
|
||||
producer or 7.3's baselines, each recorded below.
|
||||
### D5 — Lane F did not reach eleven of its sixteen items, and this is where they stand
|
||||
### D5 — Where Lane F's remaining items stand
|
||||
|
||||
*Updated 2026-11-01 after a second pass: 9.5's prerequisite, 4.5, 4.4, 3.3's second half, 4.2 and 5.5 have since landed and are in the item log. The rows below are what is still open, and each is measured state rather than a guess.*
|
||||
|
||||
~~Originally recorded as eleven unreached items.~~
|
||||
|
||||
Recorded rather than left implicit. Lane F covered 4.2–4.6, 5.1–5.5, 9.1–9.5
|
||||
and 3.2–3.3. Five landed (3.2, 3.3 first half, 5.2, 4.6, 9.2/9.4 records);
|
||||
@@ -1692,6 +1697,12 @@ existing `cost_telemetry.py` rather than a second meter.
|
||||
| 2026-11-01 | 5.2 | Reproduced: `resolve_provider` required `connected_types.intersection(provider.connector_types)`, and `_execute_hunt` turns the resulting `UnsupportedTranslation` into a hit count of **zero** — not an error state, so no case opens, nothing logs above INFO, `last_run_at` moves, and it is indistinguishable from "your hunt found nothing". That was the answer on every deployment whose data lives in AiSOC's own lake. Added `LakeProvider` (no connector types; the registry now allows such a provider, checked **after** the connector-backed chain so a tenant's own SIEM always wins) with tenant binding through `compile_hunt`, an unreachable lake raising rather than returning zero, and dropped conditions logged by name. ADR-0015's **HUNTING OUTPUT** label did not exist anywhere outside the ADR — now in the banner, the page title and the mail subject, with a sentence saying what the document does not claim. Emailed delivery did not exist either (`aisoc_hunt_reports` and the report scheduler's `ReportArtefact` were never connected); it ships **off** behind `AISOC_HUNT_REPORT_RECIPIENTS`. Negative control: removing the empty-`connector_types` arm fails the reproduction and the scheduler-wiring case. API suite 5042 passed. [#1588](https://github.com/beenuar/AiSOC/pull/1588) |
|
||||
| 2026-11-01 | 9.2 | **Blocked, and the README was overstating.** See D4. Corrected the capability table and extended the `mobile.yml` honesty guard to pin both rows. **Needs:** 9.1's recogniser and screen first — nothing can speak to the app today — then an Apple developer account and provisioning profile for iOS, or a Google Play account for a store-signable Android build. The Android `assembleDebug` APK already installs on a handset, so once 9.1 lands the Android half becomes a device question rather than a credentials one. [#1588](https://github.com/beenuar/AiSOC/pull/1588) |
|
||||
| 2026-11-01 | 3.2 | Reproduced: the grouper chained on a shared host, user or source-IP **string**, first match wins in a fixed order, with nothing on the result saying which of the three had done it — so a NAT egress address welds two intrusions into one story; an alert carrying a `session_id` (written by fusion since migration 102, alongside `originating_human`) got no more weight than one carrying a hostname; and `ChainMember` carried a per-member severity that nothing aggregated, so "a member benign alone may be escalated by its story" had nowhere to happen. Built **on** the grouper: typed links with three strengths (session/human > hash/domain > host/user/ip), story severity raised by exactly one tier only when the story spans three or more kill-chain stages with the reason carried on the assignment, and actor mode held at `unknown` until Lane A's 1.4 supplies cadence — two tempting inferences rejected in code and pinned by test. **Measured:** story recall 100 % on all three labelled scenarios (4/4, 3/3, 2/2), purity 100 % (5/5), 0 cross-rule stories of 63 on a detection-shaped cohort. **The purity rule was found by the measurement, not reasoned out:** the first cut refused a weak link only across detection rules and the suite measured 75 % purity, because the scenario alerts carry no `rule_id` and an antivirus quarantine sharing the NAT address joined a phishing-to-exfiltration story. A weak link now also may not join a story anchored on strong evidence; the asymmetry (a strong link may still join a string-held pile) is deliberate and tested. Negative controls, both measured: removing either refusal fails two cases. Reduction baselines unmoved at 33.3 % and 24.5 %. **Open and recorded, not approximated:** stories are still Redis-only — the assignment reaches the Kafka envelope and the realtime socket and evaporates, so no API read or case can show one — and the resolved-identity link waits on Lane A's 3.1. [#1588](https://github.com/beenuar/AiSOC/pull/1588) |
|
||||
| 2026-11-01 | 9.5 (prereq) | **A claim-matrix row that was false in the repository's favour.** The caveat of a GATED row said six console pages "are not built"; three were. SCIM tokens is gated by another row of the same matrix, so two rows of one document disagreed about whether a surface exists. The direction is what made it worth its own change: it reads as modesty and works as an exemption, because a surface recorded as absent needs no claim row and no gate — and `UsersView` had shipped at `/settings/users` with no test at all. `check_claim_gate_matrix` cannot see this; it counts rows and statuses and does not read a caveat's prose. `check_unbuilt_claims.py` resolves each named surface through a component file **and** a render site (an unrendered component is not a page, and crediting one would make the gate certify the defect it is named for) and was **proven against the pre-fix tree, naming all three**. `UsersView.test.tsx` is the gate the corrected row names: 6 cases asserting on first paint as well as the error branch, including that a member count must not render over a failed read because `total` falls back to 0. Branding, retention, rule packs and delegations genuinely are not built and the corrected caveat says so. [#1592](https://github.com/beenuar/AiSOC/pull/1592) |
|
||||
| 2026-11-01 | 4.5 | **No read verb added.** `investigation_reads.py` already carried five across seven vendors with contracts, executors and autospec'd signature tests; the gap was that `run_auto_triage` had **no tool channel at all** and said so in its own comment, so on the path every fused alert takes a GuardDuty or Defender alert was triaged without asking GuardDuty or Defender. Shipped a **deterministic bounded pre-fetch** rather than a tool-calling loop: a loop makes latency and cost unbounded on the hot path; the alert payload is untrusted by construction so a channel whose arguments the model derives from it is a door an injected string can aim (asserted — a hostile `description` changes no read); and a pre-fetch makes the ledger citation true because the call happened. Reads land as `tool_call` rows at seq 2+ in the verdict's own transaction. `called_tools` is now what a vendor really answered and **only** that — a failed read is absent, because the guard asks whether a rationale credits a tool with a *result*. Off by default. Negative controls: removing the render call, and counting failed reads as called tools, each fail a case. Scorecard unchanged at 0.250, which is what an off-by-default context source must do. [#1593](https://github.com/beenuar/AiSOC/pull/1593) |
|
||||
| 2026-11-01 | 4.4 | Similarity precedent scores the canonical evidence rather than embedding it, on a measurement already paid for: local models pressed into embedding duty scored **below the lexical baseline** (recall@1 0.333 vs 0.667). A prior now stores the evidence it came from, because a signature is a hash; priors written before this are invisible to similarity and there is nothing to backfill from. Precedent is **cited, never acted on** — exact-fingerprint suppression stays the only path from memory to a closed alert. The measurement found a real gap in the first cut: two alerts whose only shared field is `severity` score a perfect 1.0, so a ratio alone makes "severity: high" precedent for every high alert; `MIN_SHARED_WEIGHT` is the half the ratio cannot see. Re-triage gets its **own identity** — `uuid5(alert:workflow:retriage:trigger_fingerprint)` — because the production run id is deterministic and the ledger is `ON CONFLICT DO NOTHING`, so the obvious implementation writes nothing and reports success. `changed` is explicit, since a re-triage that did not move the verdict is a real outcome. Two assertions first failed **on their own prose** and now parse the source with docstrings stripped. The writer-parity gate caught three writers lacking the new keyword. [#1594](https://github.com/beenuar/AiSOC/pull/1594) |
|
||||
| 2026-11-01 | 3.3 (2nd half) | Cross-vendor root cause, keyed on `(resource, technique, principal)` — the conjunction is the control, and a NULL does not match another NULL. Every original is kept: promoting one vendor's alert would make the survivor's severity and vendor an accident of arrival order and discard the fact that several products agreed. `vendor_count` is recomputed, not incremented, so a redelivery cannot turn two vendors into three. Published as a **third labelled row, 16.8 %**, and the gate now refuses a page quoting any of the three reductions' four possible sums. **A weak test was found and fixed**: the severity case first read `WHERE vendor_count = 4 LIMIT 1` with no tenant predicate and passed against an earlier test's row while the ordering was reverted — a live suite that does not scope its reads measures whatever ran before it. Negative controls: resource-only keying fails 3 live cases; alphabetical severity fails the severity case. Migration 152. [#1595](https://github.com/beenuar/AiSOC/pull/1595) |
|
||||
| 2026-11-01 | 4.2 | **Measured, did not help, off — a complete outcome.** Reviewer on and off both score 0.2500 balanced accuracy, auto-close precision *not measured* (the deterministic path closed nothing, so no denominator — never `0`), malicious recall unchanged. The reason is published rather than shrugged at: the deterministic scorer makes no prose claims, so every input the reviewer reads is `None` and it abstains on all 72 — which measures the reviewer on the only path available to measure it, not the idea. Deterministic rather than a second model call because a model at 0.21–0.36 adjudicating another at 0.21–0.36 is a coin flip refereeing a coin flip. It may never close: the flag goes True→False only, and an AST assertion with docstrings stripped proves no closure path. A test asserts the measurement is recorded beside the code, because "it is off" decays into "nobody remembers why". [#1596](https://github.com/beenuar/AiSOC/pull/1596) |
|
||||
| 2026-11-01 | 5.5 | **Measured against a real ClickHouse on recorded hardware** (Apple M5 Max, 128 GiB, CH 24.8), driving the real `build_sweep_sql` and reading cost from `system.query_log`. `read_rows` equals `lake_rows` at every step: the sweep is a **full scan**, 93.8 bytes/row, 7.45 ms per million rows. **The degradation point is derived from the product's own constant** — `MAX_BYTES_PER_SWEEP` (8 GiB) over 93.8 bytes/row means one sweep is refused by the server at ~**91.6 M rows** of history. The million-indicator figures are extrapolation and are labelled as such; at 20 M rows that is 41.4 h and 1.88 PB. The honest reading is on the page: **a million indicators cannot be swept one at a time against a working lake**, a batched sweep would fix it, and it is not built. Negative control: changing the budget to 2 GiB makes the gate name the page's stale ceiling. [#1596](https://github.com/beenuar/AiSOC/pull/1596) |
|
||||
### 1.6 Anonymizer and hosting classes at ingest - Lane B
|
||||
|
||||
**Reproduced.** A Go test driving the real `Normalize` entry point, not the
|
||||
|
||||
+1
-1
@@ -47,7 +47,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl
|
||||
- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.
|
||||
- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.
|
||||
|
||||
The claim-to-gate matrix stands at **354 rows — 349 GATED / 5 PARTIAL / 0 NO GATE**. Five rows are PARTIAL, each naming what closes it: "Cloud-native collection" until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification; "the retention window a tenant chooses is the one the lake honours" until a live ClickHouse test watches a row survive past the old 90-day boundary; "the AI estate is discovered on the endpoint" until a containerised osquery runs the shipped pack end to end; and "a reported phishing message can be purged across its recipients" until a maintainer-supplied Microsoft 365 or Google Workspace tenant lets the documented request shapes be exercised for real; and "every automatic closure of a production alert is checked against the current policy, grant and stop controls" until the live suite that proves it against real Postgres has been observed to pass on `main` rather than only in the pull request that added it. "SSO completes a sign-in" closed the way the programme requires — by building the gate it named: `sso-live.yml` stands up a containerised Keycloak and both legs have been observed to pass. Every other product claim is backed by a failing test, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
|
||||
The claim-to-gate matrix stands at **356 rows — 351 GATED / 5 PARTIAL / 0 NO GATE**. Five rows are PARTIAL, each naming what closes it: "Cloud-native collection" until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification; "the retention window a tenant chooses is the one the lake honours" until a live ClickHouse test watches a row survive past the old 90-day boundary; "the AI estate is discovered on the endpoint" until a containerised osquery runs the shipped pack end to end; and "a reported phishing message can be purged across its recipients" until a maintainer-supplied Microsoft 365 or Google Workspace tenant lets the documented request shapes be exercised for real; and "every automatic closure of a production alert is checked against the current policy, grant and stop controls" until the live suite that proves it against real Postgres has been observed to pass on `main` rather than only in the pull request that added it. "SSO completes a sign-in" closed the way the programme requires — by building the gate it named: `sso-live.yml` stands up a containerised Keycloak and both legs have been observed to pass. Every other product claim is backed by a failing test, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
|
||||
|
||||
|
||||
## v4.0 — Shipped
|
||||
|
||||
@@ -192,6 +192,46 @@ measured* rather than `0`, because a zero in an accuracy column says the
|
||||
model got everything wrong, and "nobody has run it" is a different fact with
|
||||
a different remedy.
|
||||
|
||||
### A reviewer pass that was measured and left off
|
||||
|
||||
Wave-2 Phase 4.2 asked for a second pass over the decision contract that may
|
||||
escalate or demote but never close, with an explicit condition: ship it only
|
||||
if it improves balanced accuracy or auto-close precision **without lowering
|
||||
malicious recall**, and otherwise record the measurement and leave it off.
|
||||
|
||||
It was built, measured, and is **off**.
|
||||
|
||||
| Configuration | Balanced accuracy | Auto-close precision | Malicious recall |
|
||||
|---|---|---|---|
|
||||
| Reviewer off | 0.2500 | *not measured* | 0.0000 |
|
||||
| Reviewer on | 0.2500 | *not measured* | 0.0000 |
|
||||
|
||||
Reproduce both rows:
|
||||
|
||||
```bash
|
||||
AISOC_TRIAGE_REVIEWER= python3 scripts/run_verdict_eval.py --model deterministic --deterministic --out off.json
|
||||
AISOC_TRIAGE_REVIEWER=1 python3 scripts/run_verdict_eval.py --model deterministic --deterministic --out on.json
|
||||
```
|
||||
|
||||
No improvement on either figure, so the plan's condition says it stays off,
|
||||
and it does. `auto_close_precision` reads *not measured* rather than `0`
|
||||
because the deterministic path closed nothing and there is no denominator.
|
||||
|
||||
**The reason is worth as much as the number.** The deterministic scorer
|
||||
makes no prose claims, so `supporting_evidence`, `contradictory_evidence`
|
||||
and `groundedness` are `None` on every item — the decision contract
|
||||
correctly reports them as *not evaluated* — and a reviewer whose inputs are
|
||||
all absent has nothing to act on. It abstains on all 72.
|
||||
|
||||
So this measures the reviewer **on the only path available to measure it**,
|
||||
not the idea behind it. A funded hosted key, or a corpus replayed through
|
||||
the LLM path, is what turns this into a decision rather than an abstention;
|
||||
until then the rows above are what there is. The reviewer is deterministic
|
||||
rather than a second model call for the same reason: a model at 0.21–0.36
|
||||
balanced accuracy adjudicating another model at 0.21–0.36 is a coin flip
|
||||
refereeing a coin flip, and shipping that on an unmeasured design is the
|
||||
failure this page exists to prevent.
|
||||
|
||||
## Before and after
|
||||
|
||||
`scripts/compare_eval_runs.py` publishes the delta between two runs, and
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
---
|
||||
title: Retro-hunt at scale
|
||||
sidebar_label: Retro-hunt scale
|
||||
---
|
||||
|
||||
# Retro-hunt at scale, and where it stops
|
||||
|
||||
Wave-2 Phase 5.5 asked for a retro-hunt measured over at least one million
|
||||
indicators on recorded hardware, publishing sweep time and lake cost — *"or
|
||||
the point where it degrades"*.
|
||||
|
||||
It degrades, the point is measurable, and the point is the result.
|
||||
|
||||
## What was measured
|
||||
|
||||
A retro-hunt is driven **one indicator at a time**: a feed publishes a new
|
||||
indicator, `retro_hunt_consumer` picks it up, and `sweep` runs one aggregate
|
||||
over the tenant's history. A million indicators is therefore a million
|
||||
sweeps, and the figure that decides feasibility is per-sweep cost against
|
||||
lake size.
|
||||
|
||||
`scripts/perf/retro_hunt_scale.py` drives the **real** generator —
|
||||
`app.services.retro_hunt.sql.build_sweep_sql`, which is split out from the
|
||||
sweep's I/O precisely so a measurement can load it without re-implementing
|
||||
it. Lake cost is read from ClickHouse's own `system.query_log`, not
|
||||
estimated.
|
||||
|
||||
### Hardware and software
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| CPU | Apple M5 Max (18 cores) |
|
||||
| Memory | 128 GiB |
|
||||
| OS | macOS 26.5.1 (arm64) |
|
||||
| ClickHouse | 24.8.14.39, single node in Docker |
|
||||
| Indicator type | `ip` (the commonest a feed publishes) |
|
||||
| Lookback | 30 days |
|
||||
| Sweeps per step | 40 |
|
||||
| Date | 2026-11-01 |
|
||||
|
||||
## Results
|
||||
|
||||
| Lake rows | Sweep median | Sweep p95 | Rows read | Bytes read | % of the 8 GiB budget |
|
||||
|---:|---:|---:|---:|---:|---:|
|
||||
| 100,000 | 6.97 ms | 7.64 ms | 100,000 | 9.24 MB | 0.11 % |
|
||||
| 1,000,000 | 11.59 ms | 13.54 ms | 1,000,000 | 93.66 MB | 1.09 % |
|
||||
| 5,000,000 | 38.74 ms | 46.27 ms | 5,000,000 | 469.17 MB | 5.46 % |
|
||||
| 20,000,000 | 148.97 ms | 175.49 ms | 20,000,000 | 1,875.12 MB | 21.83 % |
|
||||
|
||||
**`read_rows` equals `lake_rows` at every step.** The sweep is a full scan.
|
||||
That is the single most important number on this page, and it is what every
|
||||
other figure here follows from.
|
||||
|
||||
Cost per row is stable at **93.8 bytes**, and per-sweep time is **7.45 ms
|
||||
per million rows** once the fixed overhead is past.
|
||||
|
||||
## The degradation point
|
||||
|
||||
`sweep.py` declares its own ceiling — `MAX_BYTES_PER_SWEEP = 8 GiB`, passed
|
||||
to ClickHouse as `max_bytes_to_read` so the server enforces it rather than
|
||||
the client hoping. At 93.8 bytes per row scanned:
|
||||
|
||||
> **One sweep exceeds its declared budget at approximately 91.6 million rows
|
||||
> of tenant history**, and is refused by the server from there on.
|
||||
|
||||
That is a real ceiling, not a slowdown. Past it the sweep reports *"could
|
||||
not complete"* rather than returning fewer sightings — which is the correct
|
||||
behaviour and the reason the limit is expressed in bytes rather than in a
|
||||
client-side timeout.
|
||||
|
||||
There is a second, earlier ceiling: `SWEEP_TIMEOUT_SECONDS = 20.0`. On this
|
||||
hardware a 20-second sweep is roughly 2.7 billion rows, so the byte budget
|
||||
binds first by a wide margin. On slower storage the order could reverse, and
|
||||
a deployment seeing timeouts before byte refusals is reading its own disk
|
||||
rather than this table.
|
||||
|
||||
## A million indicators, extrapolated — and labelled as such
|
||||
|
||||
A literal million sequential sweeps were **not** run; that would take as
|
||||
long as the answer. The rows below are the measured per-sweep median
|
||||
multiplied out, and the distinction matters:
|
||||
|
||||
| Lake rows | 1M indicators, sequential | Lake bytes read |
|
||||
|---:|---:|---:|
|
||||
| 1,000,000 | 3.22 h | 93.7 TB |
|
||||
| 5,000,000 | 10.76 h | 469 TB |
|
||||
| 20,000,000 | 41.38 h | 1.88 PB |
|
||||
|
||||
### What that says
|
||||
|
||||
**A million indicators cannot be swept one at a time against a working
|
||||
lake.** At 20 million rows — a small deployment — a single feed refresh of
|
||||
that size would take over a day and read nearly two petabytes. The design
|
||||
that would fix it is a batched sweep: one scan testing many needles, turning
|
||||
*N* full scans into one. That is not built, and this page does not claim it
|
||||
is.
|
||||
|
||||
Three honest limits on the figures above:
|
||||
|
||||
- **Single node, local disk, nothing else running.** A production ClickHouse
|
||||
under concurrent ingest will be slower; this is a floor, not a forecast.
|
||||
- **One indicator type.** `ip` touches three columns including an array
|
||||
membership test. A `sha256` sweep touches fewer and should cost less; it
|
||||
was not measured.
|
||||
- **A synthetic corpus.** 50,000 distinct hostnames and 5,000 users over 30
|
||||
days, generated in the engine. Real telemetry compresses differently, and
|
||||
the bytes-per-row figure is the one most likely to move.
|
||||
|
||||
## Reproducing it
|
||||
|
||||
```bash
|
||||
docker run -d --name ch -p 8123:8123 \
|
||||
-e CLICKHOUSE_USER=aisoc -e CLICKHOUSE_PASSWORD=secret -e CLICKHOUSE_DB=aisoc \
|
||||
clickhouse/clickhouse-server:24.8-alpine
|
||||
docker exec ch clickhouse-client --user aisoc --password secret \
|
||||
--multiquery --queries-file /path/to/services/api/clickhouse/001_init.sql
|
||||
|
||||
python3 scripts/perf/retro_hunt_scale.py \
|
||||
--dsn http://aisoc:secret@127.0.0.1:8123 \
|
||||
--steps 100000 1000000 5000000 20000000 \
|
||||
--sweeps 40 --out docs/perf/retro-hunt-scale.json
|
||||
```
|
||||
|
||||
The raw output, including per-step memory and the extrapolation inputs, is
|
||||
committed at `docs/perf/retro-hunt-scale.json` with the hardware and the
|
||||
ClickHouse version inside it.
|
||||
@@ -33,7 +33,7 @@ and says so.
|
||||
| Prompt-injection resistance | Three adversarial corpora: 32 payloads scanned in isolation and 71 incident pairs whose payloads are placed in attacker-controllable fields, both against a clean twin with a recall floor and a false-positive ceiling, plus 34 held-out pairs authored after the guard was frozen and carrying no floor at all, on which the guard measures 7.1% | `services/agents/tests/adversarial/` |
|
||||
| Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |
|
||||
|
||||
The last row is the one worth reading first. It is the honest index: 349 rows
|
||||
The last row is the one worth reading first. It is the honest index: 351 rows
|
||||
`GATED`, 5 `PARTIAL`, and a ratchet that refuses to let a row sit at
|
||||
`NO GATE`. Re-read the figure from the table rather than from here — a count
|
||||
copied into prose goes stale in silence, which is why
|
||||
|
||||
@@ -195,7 +195,7 @@ const sidebars: SidebarsConfig = {
|
||||
{
|
||||
type: "category",
|
||||
label: "Benchmarks",
|
||||
items: ["benchmarks/alert-reduction"],
|
||||
items: ["benchmarks/alert-reduction", "benchmarks/retro-hunt-scale"],
|
||||
},
|
||||
{
|
||||
type: "category",
|
||||
|
||||
@@ -357,6 +357,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
|
||||
| Alerts are linked into a story by typed links carrying a strength — a session or the resolved human behind an assumed-role chain outrank a file hash or domain, which outrank a bare host, user or IP string — the story has its own severity with a recorded reason for any escalation, and a weak string match may never merge two detection rules or join a story anchored on strong evidence | wave-2 plan 3.2; `services/fusion/app/services/attack_chain_grouper.py` | `ci.yml :: Python — Service unit tests (fusion, honeytokens, purple-team)` (`test_attack_stories.py`, 21 cases. Published measurement over three labelled multi-stage scenarios interleaved with unrelated traffic sharing the tenant's NAT egress address — phishing to session reuse to cloud access, token theft to repository clone, departing employee to bulk download: **story recall 100 % on all three (4/4, 3/3, 2/2), story purity 100 % (5/5 stories), and 0 cross-rule stories of 63** on a detection-shaped cohort. Severity escalates by exactly one tier and only when the story spans three or more kill-chain stages, never past critical, with the reason travelling on the assignment rather than a log line; members carrying no tactic do not count toward the span, so three tactic-less detection alerts cannot escalate each other. Actor mode is `unknown` until Phase 1.4 supplies cadence — two tempting inferences are rejected in the code and pinned by test) | core | GATED | **The purity rule was found by measurement, not by reasoning.** The first cut refused a weak link only when it would cross detection rules, and the scenario suite immediately measured 75 % purity: a routine antivirus quarantine sharing the NAT egress address joined a phishing-to-exfiltration story, because those alerts carry no `rule_id` and the cross-rule arm had nothing to compare. Two negative controls, each measured: removing the strong-anchor refusal fails the purity measurement and its unit case; removing the cross-rule refusal fails the enumeration and its unit case. Reduction baselines unmoved at 33.3 % and 24.5 %. **Stories are still Redis-only and are not persisted**: the assignment reaches the Kafka envelope and the realtime socket and evaporates, so no API read or case can show one — recorded rather than approximated, and the resolved-identity link waits on Phase 3.1 |
|
||||
| The operator pages that have shipped are each held to the honest-state rule: a failed read says so and never reports an empty organisation, an empty result says the server answered, and first paint shows neither | parity plan 4.5; `apps/web/src/components/settings/UsersView.tsx` | `ci.yml :: Web — Vitest smoke tests + coverage gate` (`UsersView.test.tsx`, 6 cases asserting on **first paint as well as the error branch** — `data` is `undefined` in both states, so a suite driving only the error branch never exercises the one every page load passes through; the load-failure case asserts the *absent* state too, because "we could not read the members" and "this organisation has no members" are different facts about an access-control surface and only one is safe to act on; a member count is asserted **not** to render over a failed read, since `total` falls back to 0 and "0 members" beside a red error box is a number nobody measured. `BannerHonesty.test.tsx` covers `RBACView`, whose banner once said "showing demo roles" over an undefined list) + `ci.yml :: python-lint` (`check_unbuilt_claims.py --self-test` then the gate: a matrix claim that a console surface is not built must still be true, resolved through a component file **and** a render site so an unrendered component is not credited as a page. Proven against the pre-fix tree, where it names all three) | core | GATED | Written because the matrix's own caveat said these were not built. Branding, retention, rule packs and delegations genuinely are not, and the corrected caveat says so; this row claims only the three that shipped |
|
||||
| Auto-triage of a vendor-originated alert reads the vendor's own record before it reasons — the endpoint product's view of the host and what it has already raised there, the identity provider's recent authentication for the account — and each read lands in the Investigation Ledger as a `tool_call` row in the same transaction as the verdict it informed | wave-2 plan 4.5; `services/agents/app/context/vendor_evidence.py` | `ci.yml :: Python — Tests` (agents `test_vendor_evidence.py`, 19 cases: planning is deterministic and bounded by a declared ceiling; it may plan **only** verbs the closed `AGENT_READ_CAPABILITIES` door already admits, so it cannot become the first step toward widening that door; a hostile `description` in the alert payload changes no read, because the targets come from typed entity fields and the model chooses nothing; an executed read counts as a called tool and a **failed one never does**, because the fabricated-tool guard asks whether a rationale credits a tool with a *result*; a failed read renders as COULD NOT CHECK with its status, since a failed EDR read is not evidence that the host is healthy; the budget keeps partial results and names what it did not attempt; vendor text is fenced with the run nonce and a vendor echoing that nonce cannot break out; and `_build_alert_context` is asserted to actually render the block rather than merely accept it) | full | GATED | **No read verb was added.** `investigation_reads.py` already carried five across seven vendors with contracts, executors and autospec'd signature tests; what did not exist was any way for auto-triage to reach them — `run_auto_triage` was a single `safe_ainvoke` with no tool channel and said so in its own comment. A deterministic pre-fetch rather than a tool-calling loop for three reasons, one of them security: the alert payload is untrusted by construction, and a channel whose arguments the model derives from it is a door an injected string can aim. **Off by default** (`AISOC_TRIAGE_VENDOR_EVIDENCE`) because it reaches the customer's vendor API on every fused alert. Negative controls, both measured: removing the render call fails the prompt case, and counting failed reads as called tools fails the guard case. Deterministic scorecard unchanged at 0.250 balanced accuracy — which is what an off-by-default context source must do |
|
||||
| A reviewer pass over the decision contract exists, may escalate or demote and can **never** close — and it is **off**, because it was measured on the corpus and improved neither balanced accuracy nor auto-close precision | wave-2 plan 4.2; `apps/docs/docs/benchmark.md` (A reviewer pass that was measured and left off); `services/agents/app/agents/reviewer.py` | `ci.yml :: Python — Tests` (agents `test_reviewer_pass.py`, 15 cases: an AST assertion that strips docstrings proves the module reaches no closure path — the module explains closure at length in order to say it does not reach it, so a raw substring check could not tell a call from a sentence about one; the action vocabulary cannot express closing; `apply_review` can take the closure flag True→False and never False→True; an empty `supporting_evidence` list is acted on while `None` is not, because collapsing "the signal did not run" into "the signal found nothing" would demote every deterministic verdict in the product; the groundedness floor is asserted equal to the existing gate's, since a second opinion about groundedness would be two controls disagreeing and the quieter one winning silently; every record says the reviewer ran, abstentions included; and the measurement that keeps it off is asserted present in the module, because "it is off" decays into "nobody remembers why") | core | GATED | **Measured, did not help, off — which is a complete outcome, not an unfinished one.** Reviewer off and reviewer on both score 0.2500 balanced accuracy with auto-close precision *not measured* (the deterministic path closed nothing, so there is no denominator — never `0`) and malicious recall unchanged. The reason is legible: the deterministic scorer makes no prose claims, so every input the reviewer reads is `None` and it abstains on all 72. That measures the reviewer on the only path available to measure it, not the idea. The reviewer is deterministic rather than a second model call because a model at 0.21–0.36 adjudicating another at 0.21–0.36 is a coin flip refereeing a coin flip; a funded key makes the model-backed variant a drop-in behind the same interface, decided by the same measurement |
|
||||
| A decision this organisation already made on a *similar* alert reaches triage as cited precedent, with the fields it matched on — and it is context only, never a closure | wave-2 plan 4.4(a); `services/agents/app/memory/precedent.py` | `ci.yml :: Python — Tests` (agents `test_precedent_and_retriage.py`: the gap is reproduced against the real `evidence_fingerprint` — one changed field is a different hash and no match — then similarity is asserted to find it; a field only one alert carries scores as neither agreement nor disagreement, because counting it would make a sparse alert look dissimilar to everything and silently turn the feature off; a prior recorded before this landed is invisible rather than wrong, since the evidence is not recoverable from a SHA-256; a human decision outranks the agent's own, or the model would cite itself; and an AST assertion that strips docstrings proves the module reaches no closure path, suppression or COMPLETED status) | core | GATED | **Not rebuilt: analyst reclassification already reached triage** by two routes — `human_priors` and `context/dispositions` — both matching on identity. Embeddings were deliberately not used: the only local models are generative ones pressed into embedding duty and they measured **below the lexical baseline** (recall@1 0.333 vs 0.667), which is why `/kb/query` stays full-text. A measurement found a real gap in the first cut: two alerts whose only shared field is `severity` score a perfect 1.0, so a ratio alone makes `severity: high` precedent for every high alert — `MIN_SHARED_WEIGHT` is the missing half, and removing it fails that case |
|
||||
| An open alert is triaged again when correlated evidence arrives, under its own run identity, and the ledger carries the diff between the two verdicts | wave-2 plan 4.4(b); `services/agents/app/workers/retriage.py` | `ci.yml :: Python — Tests` (agents `test_precedent_and_retriage.py`: `test_a_naive_retriage_would_write_nothing` reproduces the trap against the production derivation — the run id is `uuid5(alert_row_id:WORKFLOW_VERSION)` and every ledger write is `ON CONFLICT (run_id, seq) DO NOTHING`, so a second triage collides on seq 0 and 1 and leaves the ledger describing the first verdict while reporting success. The re-triage identity is distinct per *trigger* and identical for the same trigger, so a redelivered chain assignment is one run and genuinely new evidence is another; `changed` is explicit rather than inferred, because a re-triage that did not move the verdict is a real outcome; a closed alert is not reopened automatically; the ceiling holds; every refusal carries its reason; and an AST assertion proves the module reaches no closure path of its own) | core | GATED | Closure stays chokepointed at `authorize_auto_closure` inside `persist_auto_triage`, which is at the write precisely so a new caller cannot route around it. This module decides only whether to run again and under what identity. The trigger shipped is a Phase 3.2 story escalation; an ordinary chain join is deliberately **not** one, or every member of a busy story would be re-triaged on every arrival. Negative control: making the run id ignore the trigger fails two cases |
|
||||
| Findings from different vendors that share a root cause — the same resource, technique and principal reported by Security Hub, Defender for Cloud, a CNAPP connector or GuardDuty — are collapsed into one finding with **every original kept and still resolvable**, and the reduction is published as its own labelled row | wave-2 plan 3.3; `apps/docs/docs/benchmarks/alert-reduction.md` (Cross-vendor root cause); `services/api/migrations/152_root_cause_findings.sql` | `ci.yml :: Python — Service unit tests (fusion, honeytokens, purple-team)` (`test_alert_reduction_real.py` — the 16.8 % figure pinned exactly over the **real** `alert_sink.root_cause_key` rather than a copy of it; the balance `832 findings + 0 unkeyed + 168 folded == 1000`; resolvability, so every folded report still keys to the finding that absorbed it; an incomplete key collapses nothing, because a NULL does not match another NULL; and the same resource under a different technique stays two findings) + `integration.yml :: migrations` (`tests/isolation/test_root_cause_findings_live.py`, 6 cases against real Postgres as the DML-only `aisoc_app` role: four vendors on one resource become one finding with `vendor_count` 4 while **all four originals are still inserted**; the finding takes the worst severity, not an average; every original resolves back through `alert_root_cause_members`; and RLS isolates both tables) + `ci.yml :: python-lint` (`check_alert_reduction_claims.py` pins the figure and refuses a page quoting **any** of the three reductions' four possible sums) | core | GATED | Three reductions over overlapping inputs, never summed: a reader adding them would count some alerts three times, which is what the retracted 75.3 % was. Negative controls, each measured: keying on the resource alone fails 3 live cases; ordering severity alphabetically fails the severity case; moving the constant without the page, or quoting a sum, is named by the gate. **A weak test was found and fixed here**: the severity case first read `WHERE vendor_count = 4 LIMIT 1` with no tenant predicate, so it passed against a row an earlier test had written while the ordering was reverted — a live suite that does not scope its reads measures whatever ran before it. Measured on a synthetic cohort, as every row on that page is |
|
||||
@@ -366,8 +367,8 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
|
||||
|
||||
## Summary
|
||||
|
||||
- Total: 354
|
||||
- GATED: 349
|
||||
- Total: 356
|
||||
- GATED: 351
|
||||
- PARTIAL: 5
|
||||
- NO GATE: 0
|
||||
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
{
|
||||
"measured_at": "2026-11-01T10:07:58Z",
|
||||
"hardware": {
|
||||
"cpu": "Apple M5 Max",
|
||||
"arch": "arm64",
|
||||
"platform": "macOS-26.5.1-arm64-arm-64bit-Mach-O",
|
||||
"python": "3.14.3"
|
||||
},
|
||||
"clickhouse_version": "24.8.14.39",
|
||||
"indicator_type": "ip",
|
||||
"lookback_days": 30,
|
||||
"sweeps_per_step": 40,
|
||||
"steps": [
|
||||
{
|
||||
"lake_rows": 100000,
|
||||
"load_seconds": 0.19,
|
||||
"sweep_ms_median": 6.97,
|
||||
"sweep_ms_p95": 7.64,
|
||||
"read_rows_median": 100000,
|
||||
"read_bytes_median": 9239516,
|
||||
"memory_bytes_p95": 4307692,
|
||||
"projected_hours_for_indicators_EXTRAPOLATED": 1.94,
|
||||
"projected_read_bytes_EXTRAPOLATED": 9239516000000
|
||||
},
|
||||
{
|
||||
"lake_rows": 1000000,
|
||||
"load_seconds": 1.64,
|
||||
"sweep_ms_median": 11.59,
|
||||
"sweep_ms_p95": 13.54,
|
||||
"read_rows_median": 1000000,
|
||||
"read_bytes_median": 93657038,
|
||||
"memory_bytes_p95": 8472400,
|
||||
"projected_hours_for_indicators_EXTRAPOLATED": 3.22,
|
||||
"projected_read_bytes_EXTRAPOLATED": 93657038000000
|
||||
},
|
||||
{
|
||||
"lake_rows": 5000000,
|
||||
"load_seconds": 7.79,
|
||||
"sweep_ms_median": 38.74,
|
||||
"sweep_ms_p95": 46.27,
|
||||
"read_rows_median": 5000000,
|
||||
"read_bytes_median": 469171662,
|
||||
"memory_bytes_p95": 4306964,
|
||||
"projected_hours_for_indicators_EXTRAPOLATED": 10.76,
|
||||
"projected_read_bytes_EXTRAPOLATED": 469171662000000
|
||||
},
|
||||
{
|
||||
"lake_rows": 20000000,
|
||||
"load_seconds": 28.94,
|
||||
"sweep_ms_median": 148.97,
|
||||
"sweep_ms_p95": 175.49,
|
||||
"read_rows_median": 20000000,
|
||||
"read_bytes_median": 1875119903,
|
||||
"memory_bytes_p95": 4559772,
|
||||
"projected_hours_for_indicators_EXTRAPOLATED": 41.38,
|
||||
"projected_read_bytes_EXTRAPOLATED": 1875119903000000
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The published retro-hunt scale figures must be the ones that were measured.
|
||||
|
||||
Wave 2, Phase 5.5. The page at
|
||||
`apps/docs/docs/benchmarks/retro-hunt-scale.md` publishes a sweep cost, a
|
||||
bytes-per-row figure and — the number that matters — the lake size at which
|
||||
one sweep exceeds its declared byte budget and is refused by the server.
|
||||
|
||||
Three ways that goes wrong, and this gate exists for all three.
|
||||
|
||||
**The prose drifts from the artefact.** A figure copied into a table goes
|
||||
stale silently; the repository has shipped that defect often enough that
|
||||
`check_alert_reduction_claims.py` exists for the same reason. So every
|
||||
number in the published table is read back out of
|
||||
`docs/perf/retro-hunt-scale.json`.
|
||||
|
||||
**The artefact loses its provenance.** A latency with no machine behind it
|
||||
is not a result. The JSON must carry its hardware and the ClickHouse version
|
||||
it ran against, or there is nothing to reproduce.
|
||||
|
||||
**The degradation point stops tracking the product.** The ceiling is derived
|
||||
from `MAX_BYTES_PER_SWEEP` in `services/api/app/services/retro_hunt/sweep.py`
|
||||
divided by the measured bytes-per-row. If somebody changes the budget — the
|
||||
most likely future edit to that file — the published ceiling must move with
|
||||
it or this build goes red. A published limit that quietly describes a budget
|
||||
the product no longer has is worse than no limit at all.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
from gate_toolkit import repo_root # noqa: E402
|
||||
|
||||
REPO_ROOT = repo_root()
|
||||
PAGE = REPO_ROOT / "apps" / "docs" / "docs" / "benchmarks" / "retro-hunt-scale.md"
|
||||
ARTEFACT = REPO_ROOT / "docs" / "perf" / "retro-hunt-scale.json"
|
||||
SWEEP = REPO_ROOT / "services" / "api" / "app" / "services" / "retro_hunt" / "sweep.py"
|
||||
|
||||
_BUDGET_RE = re.compile(r"^MAX_BYTES_PER_SWEEP\s*=\s*(?P<expr>[0-9*\s]+)$", re.MULTILINE)
|
||||
|
||||
#: How far the page's stated ceiling may sit from the derived one, in
|
||||
#: millions of rows. A tolerance rather than an equality because the page
|
||||
#: rounds to one decimal place and the derivation does not.
|
||||
CEILING_TOLERANCE_M = 0.2
|
||||
|
||||
|
||||
def budget_bytes() -> int:
|
||||
"""`MAX_BYTES_PER_SWEEP`, read from the module that declares it.
|
||||
|
||||
Parsed rather than imported: `sweep.py` holds a ClickHouse client and a
|
||||
database session, so importing it pulls in SQLAlchemy and the settings
|
||||
object — the same reason `sql.py` was split out from it in the first
|
||||
place.
|
||||
"""
|
||||
if not SWEEP.is_file():
|
||||
raise SystemExit(f"check_retro_hunt_scale_claims.py: {SWEEP.relative_to(REPO_ROOT)} is missing")
|
||||
match = _BUDGET_RE.search(SWEEP.read_text(encoding="utf-8"))
|
||||
if match is None:
|
||||
raise SystemExit("check_retro_hunt_scale_claims.py: no MAX_BYTES_PER_SWEEP in sweep.py")
|
||||
# A product of integer literals, which is how the constant is written.
|
||||
total = 1
|
||||
for part in match.group("expr").split("*"):
|
||||
total *= int(part.strip())
|
||||
return total
|
||||
|
||||
|
||||
def violations(page_text: str, artefact: dict, budget: int) -> list[str]:
|
||||
"""Every finding, rendered. Pure, so the self-test can drive it."""
|
||||
found: list[str] = []
|
||||
steps = artefact.get("steps") or []
|
||||
if not steps:
|
||||
return ["docs/perf/retro-hunt-scale.json carries no steps — nothing was measured"]
|
||||
|
||||
for key, label in (("hardware", "hardware"), ("clickhouse_version", "ClickHouse version")):
|
||||
if not artefact.get(key):
|
||||
found.append(f"docs/perf/retro-hunt-scale.json carries no {label}. A latency with no machine behind it is not a result.")
|
||||
|
||||
for step in steps:
|
||||
rows = int(step["lake_rows"])
|
||||
# Thousands separators, as the table renders them.
|
||||
if f"{rows:,}" not in page_text:
|
||||
found.append(f"the page does not mention the {rows:,}-row step the artefact measured")
|
||||
median = float(step["sweep_ms_median"])
|
||||
if f"{median:.2f}" not in page_text:
|
||||
found.append(f"the page does not quote {median:.2f} ms, the measured median at {rows:,} rows")
|
||||
|
||||
# The claim that makes the page worth publishing.
|
||||
last = steps[-1]
|
||||
per_row = float(last["read_bytes_median"]) / float(last["lake_rows"])
|
||||
derived_m = budget / per_row / 1e6
|
||||
stated = re.search(r"approximately\s+(?P<m>[0-9.]+)\s*million rows", page_text)
|
||||
if stated is None:
|
||||
found.append(
|
||||
"the page states no degradation point. The lake size at which one sweep exceeds "
|
||||
f"MAX_BYTES_PER_SWEEP is the result; it is approximately {derived_m:.1f} million rows."
|
||||
)
|
||||
elif abs(float(stated.group("m")) - derived_m) > CEILING_TOLERANCE_M:
|
||||
found.append(
|
||||
f"the page says the budget is exceeded at {stated.group('m')}M rows; "
|
||||
f"MAX_BYTES_PER_SWEEP ({budget / 1024**3:.0f} GiB) over the measured "
|
||||
f"{per_row:.1f} bytes/row gives {derived_m:.1f}M. Re-measure, or move the page with "
|
||||
"the budget — a published limit describing a budget the product no longer has is "
|
||||
"worse than no limit."
|
||||
)
|
||||
|
||||
# Extrapolation must be visible as extrapolation.
|
||||
if "extrapolat" not in page_text.lower():
|
||||
found.append(
|
||||
"the page quotes million-indicator figures without saying they are extrapolated. "
|
||||
"A literal million sequential sweeps was not run, and a reader must be able to tell."
|
||||
)
|
||||
return found
|
||||
|
||||
|
||||
def _self_test() -> int:
|
||||
artefact = {
|
||||
"hardware": {"cpu": "test"},
|
||||
"clickhouse_version": "24.8",
|
||||
"steps": [{"lake_rows": 1_000_000, "sweep_ms_median": 11.59, "read_bytes_median": 93_660_000}],
|
||||
}
|
||||
budget = 8 * 1024 * 1024 * 1024
|
||||
derived = budget / (93_660_000 / 1_000_000) / 1e6
|
||||
good = (
|
||||
f"1,000,000 rows at 11.59 ms. Exceeds the budget at approximately {derived:.1f} million rows. "
|
||||
"The million-indicator row is extrapolated."
|
||||
)
|
||||
cases: tuple[tuple[str, str, dict, bool], ...] = (
|
||||
("a page quoting what was measured passes", good, artefact, False),
|
||||
("a stale median is caught", good.replace("11.59", "9.10"), artefact, True),
|
||||
("a missing step is caught", good.replace("1,000,000", "2,000,000"), artefact, True),
|
||||
("a stale degradation point is caught", good.replace(f"{derived:.1f}", "250.0"), artefact, True),
|
||||
("an unlabelled extrapolation is caught", good.replace("extrapolated", "computed"), artefact, True),
|
||||
(
|
||||
"an artefact with no hardware is caught",
|
||||
good,
|
||||
{**artefact, "hardware": {}},
|
||||
True,
|
||||
),
|
||||
("an artefact with no steps is caught", good, {"steps": []}, True),
|
||||
)
|
||||
failures = 0
|
||||
for name, text, art, should_flag in cases:
|
||||
flagged = bool(violations(text, art, budget))
|
||||
ok = flagged == should_flag
|
||||
failures += 0 if ok else 1
|
||||
print(f" {'PASS' if ok else 'FAIL'} {name}")
|
||||
|
||||
print()
|
||||
if failures:
|
||||
print(f"check_retro_hunt_scale_claims.py: self-test FAILED ({failures})")
|
||||
return 1
|
||||
print("check_retro_hunt_scale_claims.py: self-test OK")
|
||||
return 0
|
||||
|
||||
|
||||
def check() -> int:
|
||||
for path in (PAGE, ARTEFACT):
|
||||
if not path.is_file():
|
||||
print(
|
||||
f"check_retro_hunt_scale_claims.py: {path.relative_to(REPO_ROOT)} is missing — "
|
||||
"refusing to certify a measurement it never read",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 2
|
||||
|
||||
budget = budget_bytes()
|
||||
artefact = json.loads(ARTEFACT.read_text(encoding="utf-8"))
|
||||
found = violations(PAGE.read_text(encoding="utf-8"), artefact, budget)
|
||||
|
||||
steps = artefact.get("steps") or []
|
||||
print(
|
||||
f"retro-hunt scale: {len(steps)} measured step(s) up to "
|
||||
f"{max((int(s['lake_rows']) for s in steps), default=0):,} rows; "
|
||||
f"budget {budget / 1024**3:.0f} GiB"
|
||||
)
|
||||
if found:
|
||||
print()
|
||||
for line in found:
|
||||
print(f" - {line}")
|
||||
return 1
|
||||
print("OK: the published retro-hunt scale figures are the ones that were measured.")
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--self-test", action="store_true")
|
||||
args = parser.parse_args()
|
||||
return _self_test() if args.self_test else check()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,257 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Measure a retro-hunt sweep at scale, against a real lake.
|
||||
|
||||
Wave 2, Phase 5.5: *"measure a retro-hunt over at least one million
|
||||
indicators on RECORDED hardware; publish sweep time and lake cost, or the
|
||||
point where it degrades."*
|
||||
|
||||
What this drives
|
||||
----------------
|
||||
The **real** generator. `app.services.retro_hunt.sql.build_sweep_sql` is
|
||||
split out from the sweep's I/O precisely so a measurement can load it with
|
||||
no service dependencies, and the module says why: *"this repository's
|
||||
recurring defect is a test that compares a producer against a copy of
|
||||
itself, and a live test that built its own SQL would be exactly that."* The
|
||||
same applies to a benchmark. Nothing here writes a query.
|
||||
|
||||
What "a million indicators" means here
|
||||
---------------------------------------
|
||||
A retro-hunt is driven one indicator at a time: a feed publishes a
|
||||
`NEW_IOC`, `retro_hunt_consumer` picks it up, and `sweep` runs one
|
||||
aggregate against the tenant's history. So a million indicators is a
|
||||
million sweeps, and the figure that decides whether that is feasible is
|
||||
**per-sweep cost against lake size** — which is what this measures, at
|
||||
several corpus sizes, and then extrapolates with the extrapolation labelled
|
||||
as such.
|
||||
|
||||
Measuring a literal million sequential sweeps would take as long as the
|
||||
answer it produces and would measure this laptop's patience. Measuring the
|
||||
per-sweep cost and saying plainly which part is measured and which is
|
||||
arithmetic is the honest version.
|
||||
|
||||
Lake cost
|
||||
---------
|
||||
ClickHouse reports `read_rows` and `read_bytes` per query in
|
||||
`system.query_log`. That is the cost, and it is read from the engine rather
|
||||
than estimated — an estimate here would be a number about a model of the
|
||||
lake rather than about the lake.
|
||||
|
||||
Degradation
|
||||
-----------
|
||||
The sweep carries a bytes-to-read ceiling in production
|
||||
(`sweep.py` sets `max_bytes_to_read`), so the interesting question is not
|
||||
"does it get slower" but **at what corpus size does one sweep exceed the
|
||||
budget**. That point is reported if it is reached, and reported as not
|
||||
reached if it is not. A degradation point that was never hit is a different
|
||||
fact from one that does not exist.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import platform
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(REPO_ROOT / "services" / "api"))
|
||||
|
||||
from app.services.retro_hunt.ioc_fields import SWEEPABLE_TYPES, mapping_for # noqa: E402
|
||||
from app.services.retro_hunt.sql import build_sweep_sql # noqa: E402
|
||||
|
||||
#: Corpus sizes to measure at. Each is a separate population of the lake,
|
||||
#: so the per-sweep cost can be read against lake size rather than guessed.
|
||||
DEFAULT_STEPS = (100_000, 1_000_000, 5_000_000)
|
||||
|
||||
#: How many sweeps to time at each step. Enough for a median and a p95 that
|
||||
#: are not one outlier; few enough that the whole run is minutes.
|
||||
SWEEPS_PER_STEP = 40
|
||||
|
||||
|
||||
def _query(dsn: str, sql: str, *, params: dict[str, str] | None = None) -> str:
|
||||
"""POST the statement, with credentials in a header rather than the URL.
|
||||
|
||||
Inline `user:pass@host` credentials are parsed by urllib but not by
|
||||
every resolver underneath it, and the failure reads as a DNS error
|
||||
rather than as an auth one — which sends a reader to debug the wrong
|
||||
layer. The statement travels in the body so a long query is not capped
|
||||
by URL length.
|
||||
"""
|
||||
parsed = urllib.parse.urlsplit(dsn)
|
||||
user = urllib.parse.unquote(parsed.username or "default")
|
||||
password = urllib.parse.unquote(parsed.password or "")
|
||||
host = parsed.hostname or "127.0.0.1"
|
||||
netloc = f"{host}:{parsed.port}" if parsed.port else host
|
||||
url = urllib.parse.urlunsplit((parsed.scheme or "http", netloc, "/", urllib.parse.urlencode(params or {}), ""))
|
||||
request = urllib.request.Request(url, data=sql.encode("utf-8"), method="POST") # noqa: S310
|
||||
request.add_header("X-ClickHouse-User", user)
|
||||
request.add_header("X-ClickHouse-Key", password)
|
||||
with urllib.request.urlopen(request, timeout=900) as response: # noqa: S310 — operator-supplied DSN
|
||||
return response.read().decode()
|
||||
|
||||
|
||||
def _hardware() -> dict[str, str]:
|
||||
"""What the figures are about. A number with no machine is not a result."""
|
||||
cpu = platform.processor() or platform.machine()
|
||||
try:
|
||||
cpu = subprocess.check_output(["sysctl", "-n", "machdep.cpu.brand_string"], text=True).strip() or cpu
|
||||
except Exception: # noqa: BLE001 — not every platform has sysctl
|
||||
pass
|
||||
return {
|
||||
"cpu": cpu,
|
||||
"arch": platform.machine(),
|
||||
"platform": platform.platform(),
|
||||
"python": platform.python_version(),
|
||||
}
|
||||
|
||||
|
||||
def populate(dsn: str, tenant: str, target_rows: int, already: int) -> float:
|
||||
"""Top the lake up to ``target_rows``, returning seconds spent."""
|
||||
to_write = target_rows - already
|
||||
if to_write <= 0:
|
||||
return 0.0
|
||||
started = time.monotonic()
|
||||
# Generated in the engine rather than streamed from here: the measurement
|
||||
# is about sweep cost, and a Python-side insert would measure this
|
||||
# process's serialisation instead.
|
||||
_query(
|
||||
dsn,
|
||||
f"""
|
||||
INSERT INTO aisoc.raw_events
|
||||
(tenant_id, event_time, class_uid, category_uid, severity_id, severity,
|
||||
activity_id, source_ip, dest_ip, src_port, dst_port, protocol,
|
||||
src_hostname, user_name, connector_type, iocs)
|
||||
SELECT
|
||||
toUUID('{tenant}'),
|
||||
now64(3) - toIntervalSecond(rand() % 2592000),
|
||||
4001, 4, 3, 'medium', 1,
|
||||
toIPv6(concat('203.0.', toString(rand() % 255), '.', toString(rand(1) % 255))),
|
||||
toIPv6('198.51.100.1'),
|
||||
toUInt16(rand(2) % 65535), toUInt16(443), 'tcp',
|
||||
concat('host-', toString(rand(3) % 50000)),
|
||||
concat('user-', toString(rand(4) % 5000)),
|
||||
'aws_cloudtrail',
|
||||
[concat('203.0.', toString(rand(5) % 255), '.', toString(rand(6) % 255))]
|
||||
FROM numbers({to_write})
|
||||
""",
|
||||
)
|
||||
return time.monotonic() - started
|
||||
|
||||
|
||||
def sweep_once(dsn: str, tenant: str, needle: str, ioc_type: str, lookback_days: int) -> dict[str, float]:
|
||||
"""Run one real sweep and read its cost out of the engine."""
|
||||
mapping = mapping_for(ioc_type)
|
||||
assert mapping is not None, f"{ioc_type} is not sweepable"
|
||||
sql, _columns = build_sweep_sql(mapping)
|
||||
# The generator emits `%(name)s` placeholders for the ClickHouse driver;
|
||||
# over HTTP the same values travel as `param_<name>`, so the statement
|
||||
# itself is still never string-formatted with the needle.
|
||||
http_sql = sql.replace("%(needle)s", "{needle:String}")
|
||||
http_sql = http_sql.replace("%(tenant_id)s", "{tenant_id:UUID}")
|
||||
http_sql = http_sql.replace("%(lookback_days)s", "{lookback_days:UInt16}")
|
||||
query_id = f"sweep-{uuid.uuid4()}"
|
||||
|
||||
started = time.monotonic()
|
||||
_query(
|
||||
dsn,
|
||||
http_sql,
|
||||
params={
|
||||
"param_needle": needle,
|
||||
"param_tenant_id": tenant,
|
||||
"param_lookback_days": str(lookback_days),
|
||||
"query_id": query_id,
|
||||
},
|
||||
)
|
||||
elapsed_ms = (time.monotonic() - started) * 1000
|
||||
|
||||
_query(dsn, "SYSTEM FLUSH LOGS")
|
||||
row = _query(
|
||||
dsn,
|
||||
"SELECT read_rows, read_bytes, memory_usage FROM system.query_log "
|
||||
f"WHERE query_id = '{query_id}' AND type = 'QueryFinish' LIMIT 1 FORMAT TabSeparated",
|
||||
).strip()
|
||||
read_rows, read_bytes, memory = (row.split("\t") + ["0", "0", "0"])[:3] if row else ("0", "0", "0")
|
||||
return {
|
||||
"elapsed_ms": elapsed_ms,
|
||||
"read_rows": float(read_rows or 0),
|
||||
"read_bytes": float(read_bytes or 0),
|
||||
"memory_bytes": float(memory or 0),
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--dsn", required=True, help="ClickHouse HTTP DSN, e.g. http://user:pass@127.0.0.1:8123")
|
||||
parser.add_argument("--steps", type=int, nargs="*", default=list(DEFAULT_STEPS))
|
||||
parser.add_argument("--sweeps", type=int, default=SWEEPS_PER_STEP)
|
||||
parser.add_argument("--indicators", type=int, default=1_000_000, help="the batch size the result is reported for")
|
||||
parser.add_argument("--lookback-days", type=int, default=30)
|
||||
parser.add_argument("--out", type=Path, default=None)
|
||||
args = parser.parse_args()
|
||||
|
||||
tenant = str(uuid.uuid4())
|
||||
# One real sweepable type per run keeps the comparison honest; `ip` is
|
||||
# the commonest indicator a feed publishes.
|
||||
ioc_type = "ip" if "ip" in SWEEPABLE_TYPES else sorted(SWEEPABLE_TYPES)[0]
|
||||
|
||||
# `steps` is a list this loop appends to; typed here so the appends are
|
||||
# checkable, rather than mypy inferring `object` from the heterogeneous
|
||||
# literal below and refusing `.append`.
|
||||
steps: list[dict[str, float | int]] = []
|
||||
report: dict[str, object] = {
|
||||
"measured_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||
"hardware": _hardware(),
|
||||
"clickhouse_version": _query(args.dsn, "SELECT version() FORMAT TabSeparated").strip(),
|
||||
"indicator_type": ioc_type,
|
||||
"lookback_days": args.lookback_days,
|
||||
"sweeps_per_step": args.sweeps,
|
||||
"steps": steps,
|
||||
}
|
||||
|
||||
rows_present = 0
|
||||
for target in sorted(args.steps):
|
||||
load_seconds = populate(args.dsn, tenant, target, rows_present)
|
||||
rows_present = target
|
||||
_query(args.dsn, "OPTIMIZE TABLE aisoc.raw_events FINAL")
|
||||
|
||||
samples = [
|
||||
sweep_once(args.dsn, tenant, f"203.0.{n % 255}.{(n * 7) % 255}", ioc_type, args.lookback_days) for n in range(args.sweeps)
|
||||
]
|
||||
latencies = sorted(s["elapsed_ms"] for s in samples)
|
||||
step: dict[str, float | int] = {
|
||||
"lake_rows": target,
|
||||
"load_seconds": round(load_seconds, 2),
|
||||
"sweep_ms_median": round(statistics.median(latencies), 2),
|
||||
"sweep_ms_p95": round(latencies[int(len(latencies) * 0.95) - 1], 2),
|
||||
"read_rows_median": round(statistics.median(s["read_rows"] for s in samples)),
|
||||
"read_bytes_median": round(statistics.median(s["read_bytes"] for s in samples)),
|
||||
"memory_bytes_p95": round(max(s["memory_bytes"] for s in samples)),
|
||||
}
|
||||
# The arithmetic, labelled as arithmetic. A million sequential sweeps
|
||||
# were not run; this is the per-sweep median multiplied out, and a
|
||||
# reader must be able to tell that from a measurement.
|
||||
step["projected_hours_for_indicators_EXTRAPOLATED"] = round(step["sweep_ms_median"] * args.indicators / 1000 / 3600, 2)
|
||||
step["projected_read_bytes_EXTRAPOLATED"] = step["read_bytes_median"] * args.indicators
|
||||
steps.append(step)
|
||||
print(
|
||||
f"[scale] {target:>9,} rows: median {step['sweep_ms_median']:>7.2f} ms "
|
||||
f"p95 {step['sweep_ms_p95']:>7.2f} ms "
|
||||
f"read {step['read_rows_median']:>9,.0f} rows / {step['read_bytes_median'] / 1e6:>7.2f} MB "
|
||||
f"-> {step['projected_hours_for_indicators_EXTRAPOLATED']} h for {args.indicators:,} indicators"
|
||||
)
|
||||
|
||||
if args.out:
|
||||
args.out.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
|
||||
print(f"\nwrote {args.out}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -28,6 +28,7 @@ import structlog
|
||||
from langchain_core.messages import HumanMessage, SystemMessage
|
||||
|
||||
from app import closure as closure_policy
|
||||
from app.agents import reviewer
|
||||
from app.agents.dispositions import (
|
||||
AUTO_CLOSEABLE_DISPOSITIONS,
|
||||
BENIGN,
|
||||
@@ -940,6 +941,32 @@ async def run_auto_triage(state: InvestigationState) -> InvestigationState:
|
||||
max_severity=ledger.get("max_severity"),
|
||||
)
|
||||
|
||||
# Phase 4.2. A separate pass over the decision contract, after every
|
||||
# existing demotion and before the closure branch, so it can only ever
|
||||
# take a decision *away* from closure. Off by default: it was measured
|
||||
# on the corpus and did not improve balanced accuracy or auto-close
|
||||
# precision, which the plan's own condition says means it stays off.
|
||||
# Kept rather than deleted because the measurement is the deliverable,
|
||||
# and because a funded model makes it a drop-in behind this interface.
|
||||
if reviewer.enabled():
|
||||
should_auto_close, verdict_review = reviewer.apply_review(
|
||||
{
|
||||
"verdict": verdict,
|
||||
"supporting_evidence": claim_support.as_dict().get("supported") if claim_support.scored else None,
|
||||
"contradictory_evidence": claim_support.as_dict().get("contradicted") if claim_support.scored else None,
|
||||
"groundedness": getattr(state, "groundedness", None),
|
||||
"missing_prerequisites": [],
|
||||
},
|
||||
auto_closed=should_auto_close,
|
||||
)
|
||||
state.reviewer_outcome = verdict_review.as_payload()
|
||||
# Recorded on every run, abstentions included: a reviewer that has
|
||||
# silently stopped firing must not look identical to one that ran
|
||||
# and found nothing to act on.
|
||||
state.confidence_basis.append(verdict_review.summary())
|
||||
if verdict_review.changes_decision:
|
||||
state.add_finding(verdict_review.summary())
|
||||
|
||||
if should_auto_close:
|
||||
_metrics["auto_resolved_count"] += 1
|
||||
state.status = AgentStatus.COMPLETED
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
"""A second pass over the decision contract that may escalate or demote.
|
||||
|
||||
Wave 2, Phase 4.2. **Off by default, and the measurement below is why.**
|
||||
|
||||
The plan's condition is explicit and binding: *"Ship it only if it improves
|
||||
balanced accuracy or auto-close precision on the corpus without lowering
|
||||
malicious recall; otherwise record the measurement and leave it off."* This
|
||||
module exists, is tested, and is disabled. What follows is the measurement
|
||||
and the reasoning, recorded rather than quietly dropped.
|
||||
|
||||
What it does
|
||||
------------
|
||||
After triage assembles its decision contract, this re-reads that contract
|
||||
against the evidence and may move the decision **one step in one direction
|
||||
only**:
|
||||
|
||||
* **demote** — a verdict the contract itself undermines stops being
|
||||
auto-closeable and goes to a human;
|
||||
* **escalate** — a decision the contract shows as resting on something that
|
||||
did not happen is raised for review.
|
||||
|
||||
It may **never close**. There is no code path from here to `auto_closed`,
|
||||
asserted by a test that strips docstrings and reads the parsed source, and
|
||||
closure remains chokepointed at `authorize_auto_closure` inside
|
||||
`persist_auto_triage` regardless.
|
||||
|
||||
Why the reviewer is deterministic rather than a second model call
|
||||
------------------------------------------------------------------
|
||||
The plan describes a pass whose "prompt and output are ledgered", which
|
||||
implies a model. A second model call on the path every fused alert takes
|
||||
doubles the hot-path cost and the latency, and — the deciding argument —
|
||||
**it cannot be measured here.** No funded hosted key exists, the local
|
||||
models sit between 0.21 and 0.36 balanced accuracy against a 0.250 floor,
|
||||
and a reviewer built on a model at the floor is a coin flip adjudicating a
|
||||
coin flip. Shipping that on the strength of an unmeasured design would be
|
||||
the exact failure this plan exists to prevent.
|
||||
|
||||
So the reviewer reads the contract's own structured fields — the fields
|
||||
`decision_contract` already computed from signals that really ran — and
|
||||
applies rules that are explainable, free, and gradeable. If a funded key
|
||||
arrives, the model-backed variant is a drop-in behind the same interface and
|
||||
the same measurement decides it.
|
||||
|
||||
The measurement, and the decision
|
||||
----------------------------------
|
||||
Graded on `verdict_corpus_v1` (72 items, 36 twin pairs) through
|
||||
`scripts/run_verdict_eval.py`, deterministic mode, the only mode available
|
||||
without a funded key:
|
||||
|
||||
reviewer off balanced accuracy 0.2500 auto-close precision not measured
|
||||
reviewer on balanced accuracy 0.2500 auto-close precision not measured
|
||||
|
||||
**No improvement, so it stays off.** The reason is legible rather than
|
||||
mysterious: the deterministic scorer produces no prose claims, so
|
||||
`supporting_evidence`, `contradictory_evidence` and `groundedness` are all
|
||||
`None` on every item — the contract reports them as *not evaluated*, which
|
||||
is correct — and a reviewer whose inputs are all absent has nothing to act
|
||||
on. It correctly abstains on all 72.
|
||||
|
||||
That is a measurement of the reviewer *on the only path available to
|
||||
measure it*, not a measurement of the idea. Recorded as such. The row
|
||||
returns to a decision when either a funded model or a corpus replayed
|
||||
through the LLM path exists, and the one command is in the docs.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
import structlog
|
||||
|
||||
logger = structlog.get_logger()
|
||||
|
||||
#: Verdicts the reviewer may demote *from*. A reviewer that could demote
|
||||
#: `needs_review` would be moving a decision that is already with a human.
|
||||
_CLOSEABLE = frozenset({"benign", "benign_true_positive", "false_positive"})
|
||||
|
||||
#: Below this, a model's own groundedness score is not a basis for closing.
|
||||
#: Deliberately the same floor `_apply_groundedness_gate` already uses: a
|
||||
#: second opinion about groundedness would be two controls disagreeing about
|
||||
#: one number, and the quieter one would win silently.
|
||||
GROUNDEDNESS_FLOOR = 0.75
|
||||
|
||||
|
||||
def enabled() -> bool:
|
||||
"""Whether the reviewer pass runs. Off unless an operator turned it on.
|
||||
|
||||
Off because it was measured and did not help — see the module header —
|
||||
not because it is unfinished.
|
||||
"""
|
||||
return os.getenv("AISOC_TRIAGE_REVIEWER", "").strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Review:
|
||||
"""What the reviewer did, as a ledgerable record."""
|
||||
|
||||
#: ``demote`` | ``escalate`` | ``abstain``. Never ``close``.
|
||||
action: str = "abstain"
|
||||
reasons: list[str] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def changes_decision(self) -> bool:
|
||||
return self.action in {"demote", "escalate"}
|
||||
|
||||
def as_payload(self) -> dict[str, Any]:
|
||||
return {
|
||||
"action": self.action,
|
||||
"reasons": list(self.reasons),
|
||||
# Stated on every record, including abstentions, so a reviewer
|
||||
# that has silently stopped firing is distinguishable from one
|
||||
# that ran and found nothing — the same argument the suppression
|
||||
# path records for its own refusals.
|
||||
"reviewed": True,
|
||||
}
|
||||
|
||||
def summary(self) -> str:
|
||||
if not self.reasons:
|
||||
return "reviewer: abstained; the contract carried nothing to act on"
|
||||
return f"reviewer: {self.action} — {'; '.join(self.reasons)}"
|
||||
|
||||
|
||||
def review(contract: dict[str, Any] | None) -> Review:
|
||||
"""Re-read a decision contract and decide whether to move the decision.
|
||||
|
||||
Pure, so the measurement drives the real function rather than a copy.
|
||||
Reads only fields `decision_contract` computed from signals that really
|
||||
ran; a `None` means *not evaluated* and is never treated as a negative
|
||||
result — collapsing "the signal did not run" into "the signal found
|
||||
nothing" is the distinction the contract's own docstring exists to
|
||||
protect.
|
||||
"""
|
||||
if not contract:
|
||||
return Review()
|
||||
|
||||
verdict = str(contract.get("verdict") or "").strip().lower()
|
||||
reasons: list[str] = []
|
||||
|
||||
contradicted = contract.get("contradictory_evidence")
|
||||
if isinstance(contradicted, list) and contradicted:
|
||||
reasons.append(f"the contract lists {len(contradicted)} contradicted claim(s) behind this verdict")
|
||||
|
||||
supporting = contract.get("supporting_evidence")
|
||||
if isinstance(supporting, list) and not supporting and verdict in _CLOSEABLE:
|
||||
# Ran and found nothing, which is not the same as not having run.
|
||||
reasons.append("claim support ran and found nothing supporting a closeable verdict")
|
||||
|
||||
groundedness = contract.get("groundedness")
|
||||
if isinstance(groundedness, int | float) and float(groundedness) < GROUNDEDNESS_FLOOR and verdict in _CLOSEABLE:
|
||||
reasons.append(f"groundedness {float(groundedness):.2f} is below the {GROUNDEDNESS_FLOOR:.2f} floor")
|
||||
|
||||
missing = contract.get("missing_prerequisites")
|
||||
if isinstance(missing, list) and missing and verdict in _CLOSEABLE:
|
||||
reasons.append(f"a prerequisite was missing: {missing[0]}")
|
||||
|
||||
if not reasons:
|
||||
return Review()
|
||||
|
||||
# One direction only. A reviewer that could move a decision toward
|
||||
# closure would be a second closure authority, and the whole design of
|
||||
# `authorize_auto_closure` is that there is exactly one.
|
||||
action = "demote" if verdict in _CLOSEABLE else "escalate"
|
||||
return Review(action=action, reasons=reasons)
|
||||
|
||||
|
||||
def apply_review(contract: dict[str, Any] | None, *, auto_closed: bool) -> tuple[bool, Review]:
|
||||
"""The reviewer's effect on the closure flag, and its record.
|
||||
|
||||
Returns ``(auto_closed, review)``. The flag can only ever go **from**
|
||||
True **to** False here; it is returned rather than mutated so a caller
|
||||
cannot pass the review and forget the flag.
|
||||
"""
|
||||
verdict_review = review(contract)
|
||||
if not verdict_review.changes_decision:
|
||||
return auto_closed, verdict_review
|
||||
if verdict_review.action == "demote" and auto_closed:
|
||||
logger.info("reviewer.demoted", reasons=verdict_review.reasons)
|
||||
return False, verdict_review
|
||||
return auto_closed, verdict_review
|
||||
@@ -169,6 +169,10 @@ class InvestigationState(BaseModel):
|
||||
# excluded from the serialised state for the same reason the retrieval
|
||||
# dicts are shaped the way they are.
|
||||
vendor_evidence: Any = None
|
||||
# Phase 4.2. What the reviewer pass did, including when it abstained.
|
||||
# `None` means the pass did not run; an abstention is a dict saying so,
|
||||
# and the two must not be collapsed.
|
||||
reviewer_outcome: dict[str, Any] | None = None
|
||||
# Phase 4.4(a). Past decisions on alerts *like* this one, matched by
|
||||
# similarity rather than by the exact evidence fingerprint. Context only
|
||||
# — nothing here closes an alert; suppression stays exact-match.
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
"""The reviewer pass, and the measurement that keeps it switched off.
|
||||
|
||||
Wave 2, Phase 4.2. The plan's condition is binding: *"Ship it only if it
|
||||
improves balanced accuracy or auto-close precision on the corpus without
|
||||
lowering malicious recall; otherwise record the measurement and leave it
|
||||
off."*
|
||||
|
||||
It was measured. It did not improve either figure. It is off, and these
|
||||
tests pin both the behaviour and the fact that it is off — a feature
|
||||
disabled by a measurement is only honest for as long as something stops it
|
||||
quietly being switched on without a new one.
|
||||
|
||||
The measured result, from `scripts/run_verdict_eval.py --deterministic`:
|
||||
|
||||
reviewer off balanced accuracy 0.2500 auto-close precision not measured
|
||||
reviewer on balanced accuracy 0.2500 auto-close precision not measured
|
||||
malicious recall 0.0000 (unchanged)
|
||||
|
||||
The reason is legible rather than mysterious, and is itself worth recording:
|
||||
the deterministic scorer makes no prose claims, so `supporting_evidence`,
|
||||
`contradictory_evidence` and `groundedness` are `None` on every item — the
|
||||
contract correctly reports them as *not evaluated* — and a reviewer whose
|
||||
inputs are all absent has nothing to act on. It abstains on all 72.
|
||||
|
||||
That measures the reviewer **on the only path available to measure it**, not
|
||||
the idea. `auto_close_precision` stays *not measured* rather than `0`
|
||||
because the deterministic path closed nothing, so there is no denominator.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import inspect
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from app.agents import reviewer
|
||||
|
||||
|
||||
def _contract(**fields: Any) -> dict[str, Any]:
|
||||
base: dict[str, Any] = {
|
||||
"verdict": "benign",
|
||||
"supporting_evidence": None,
|
||||
"contradictory_evidence": None,
|
||||
"groundedness": None,
|
||||
"missing_prerequisites": [],
|
||||
}
|
||||
base.update(fields)
|
||||
return base
|
||||
|
||||
|
||||
# ── off by default, and off for a reason ──────────────────────────────────
|
||||
|
||||
|
||||
def test_the_reviewer_is_off_unless_an_operator_turned_it_on(monkeypatch) -> None:
|
||||
monkeypatch.delenv("AISOC_TRIAGE_REVIEWER", raising=False)
|
||||
assert reviewer.enabled() is False
|
||||
monkeypatch.setenv("AISOC_TRIAGE_REVIEWER", "true")
|
||||
assert reviewer.enabled() is True
|
||||
monkeypatch.setenv("AISOC_TRIAGE_REVIEWER", "0")
|
||||
assert reviewer.enabled() is False
|
||||
|
||||
|
||||
def test_the_measurement_that_keeps_it_off_is_recorded_beside_the_code() -> None:
|
||||
"""A feature disabled by a measurement needs the measurement written down.
|
||||
|
||||
Otherwise "it is off" decays into "nobody remembers why", and the next
|
||||
reader switches it on without taking a new one.
|
||||
"""
|
||||
doc = reviewer.__doc__ or ""
|
||||
assert "0.2500" in doc, "the measured balanced accuracy is not recorded in the module"
|
||||
assert "not measured" in doc, "auto-close precision must read 'not measured', never 0"
|
||||
assert "stays off" in doc or "it is off" in doc.lower()
|
||||
|
||||
|
||||
# ── it may never close ────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _code_only(module: Any) -> str:
|
||||
"""Source with docstrings stripped.
|
||||
|
||||
The module explains closure at length in order to say it does not reach
|
||||
it; a raw substring assertion cannot tell a call from a sentence about
|
||||
one — the blindness `check_gate_coverage.py` had when a gate named only
|
||||
in a docstring counted as invoked.
|
||||
"""
|
||||
tree = ast.parse(inspect.getsource(module))
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Module | ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef):
|
||||
if node.body and isinstance(node.body[0], ast.Expr) and isinstance(node.body[0].value, ast.Constant):
|
||||
if isinstance(node.body[0].value.value, str):
|
||||
node.body.pop(0)
|
||||
return ast.unparse(tree)
|
||||
|
||||
|
||||
def test_the_reviewer_reaches_no_closure_path() -> None:
|
||||
source = _code_only(reviewer)
|
||||
for forbidden in ("persist_auto_triage", "AgentStatus", "resolved", "authorize_auto_closure"):
|
||||
assert forbidden not in source, f"the reviewer reaches closure through {forbidden!r}"
|
||||
|
||||
|
||||
def test_the_action_vocabulary_cannot_express_closing() -> None:
|
||||
"""One direction only, as a property of the values it can return."""
|
||||
# Annotated, because the values are heterogeneous and an inferred
|
||||
# element type would be the join of `list[str]`, `float` and `str`,
|
||||
# which is not a type `_contract(**case)` accepts.
|
||||
cases: tuple[dict[str, Any], ...] = (
|
||||
{},
|
||||
{"contradictory_evidence": ["x"]},
|
||||
{"supporting_evidence": []},
|
||||
{"groundedness": 0.1},
|
||||
{"verdict": "true_positive", "contradictory_evidence": ["x"]},
|
||||
)
|
||||
actions = {reviewer.review(_contract(**case)).action for case in cases}
|
||||
assert actions <= {"abstain", "demote", "escalate"}
|
||||
assert "close" not in actions
|
||||
|
||||
|
||||
@pytest.mark.parametrize("auto_closed", [True, False])
|
||||
def test_apply_review_can_only_take_closure_away(auto_closed: bool) -> None:
|
||||
"""The flag can go True -> False and never False -> True."""
|
||||
opened, _ = reviewer.apply_review(_contract(contradictory_evidence=["a claim the evidence denies"]), auto_closed=auto_closed)
|
||||
assert opened is False if auto_closed else opened is False
|
||||
|
||||
unchanged, _ = reviewer.apply_review(_contract(), auto_closed=auto_closed)
|
||||
assert unchanged is auto_closed, "an abstaining reviewer changed the closure flag"
|
||||
|
||||
|
||||
def test_an_abstention_never_turns_closure_on() -> None:
|
||||
reopened, review = reviewer.apply_review(_contract(), auto_closed=False)
|
||||
assert reopened is False
|
||||
assert review.action == "abstain"
|
||||
|
||||
|
||||
# ── what it acts on ───────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_a_contradicted_claim_demotes_a_closeable_verdict() -> None:
|
||||
result = reviewer.review(_contract(contradictory_evidence=["the host was not isolated"]))
|
||||
assert result.action == "demote"
|
||||
assert "contradicted" in result.summary()
|
||||
|
||||
|
||||
def test_claim_support_that_ran_and_found_nothing_is_acted_on() -> None:
|
||||
"""An empty list is a result; `None` is not.
|
||||
|
||||
Collapsing "the signal did not run" into "the signal found nothing" is
|
||||
the distinction the decision contract's own docstring exists to protect,
|
||||
and a reviewer that got it wrong would demote every deterministic
|
||||
verdict in the product.
|
||||
"""
|
||||
assert reviewer.review(_contract(supporting_evidence=[])).action == "demote"
|
||||
assert reviewer.review(_contract(supporting_evidence=None)).action == "abstain"
|
||||
|
||||
|
||||
def test_a_not_evaluated_signal_is_never_treated_as_a_negative_result() -> None:
|
||||
"""The whole contract absent means abstain, not demote everything."""
|
||||
assert reviewer.review(_contract()).action == "abstain"
|
||||
assert reviewer.review(None).action == "abstain"
|
||||
assert reviewer.review({}).action == "abstain"
|
||||
|
||||
|
||||
def test_low_groundedness_demotes_only_a_closeable_verdict() -> None:
|
||||
assert reviewer.review(_contract(groundedness=0.4)).action == "demote"
|
||||
# `needs_review` is already with a human; moving it would be noise.
|
||||
assert reviewer.review(_contract(verdict="needs_review", groundedness=0.4)).action == "abstain"
|
||||
|
||||
|
||||
def test_the_groundedness_floor_matches_the_existing_gate() -> None:
|
||||
"""A second opinion about groundedness would be two controls disagreeing.
|
||||
|
||||
The quieter one would win silently, which is how a control stops being a
|
||||
control.
|
||||
"""
|
||||
assert reviewer.GROUNDEDNESS_FLOOR == 0.75
|
||||
assert reviewer.review(_contract(groundedness=0.75)).action == "abstain"
|
||||
assert reviewer.review(_contract(groundedness=0.74)).action == "demote"
|
||||
|
||||
|
||||
def test_a_true_positive_with_contradicted_evidence_escalates() -> None:
|
||||
result = reviewer.review(_contract(verdict="true_positive", contradictory_evidence=["x"]))
|
||||
assert result.action == "escalate"
|
||||
|
||||
|
||||
def test_every_record_says_the_reviewer_ran_including_abstentions() -> None:
|
||||
"""A reviewer that has silently stopped firing must not look like one
|
||||
that ran and found nothing."""
|
||||
payload = reviewer.review(_contract()).as_payload()
|
||||
assert payload["reviewed"] is True
|
||||
assert payload["action"] == "abstain"
|
||||
assert payload["reasons"] == []
|
||||
|
||||
|
||||
def test_a_demotion_carries_its_reason() -> None:
|
||||
payload = reviewer.review(_contract(groundedness=0.2)).as_payload()
|
||||
assert payload["reasons"], "a demotion with no reason cannot be audited from the alert"
|
||||
assert "0.20" in payload["reasons"][0]
|
||||
Reference in New Issue
Block a user