Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

fix(wave5): hunting, intel, sandbox and operations wiring (5.1-5.8) (#1120)

Beenu Arora92aef462e79f
diff --git a/.env.example b/.env.example
index 1e1b9861f..517444a19 100644
--- a/.env.example
+++ b/.env.example
@@ -457,3 +457,10 @@ REALTIME_INTERNAL_TOKEN=
# Unset means no ChatOps notification is sent; the approval is still durable
# and visible in the console.
AISOC_INTERNAL_TOKEN=
+
+# Retro-hunt sweeps: when a new indicator arrives, look back over history for
+# anything that already matched it. Off by default -- a sweep reads a tenant's
+# past events, which is both a cost and a privacy decision. Turning this on
+# starts the consumer; each tenant must still opt in from its own settings
+# (PUT /api/v1/retro-hunts/settings), so this switch alone sweeps nobody.
+RETRO_HUNT_ENABLED=false
diff --git a/.github/workflows/agent-auth-live.yml b/.github/workflows/agent-auth-live.yml
index e0c320acf..88b48585a 100644
--- a/.github/workflows/agent-auth-live.yml
+++ b/.github/workflows/agent-auth-live.yml
@@ -138,6 +138,18 @@ jobs:
ISOLATION_CLOSURE_DSN: ${{ env.LIVE_DSN }}
run: python -m pytest ../../tests/isolation/test_closure_grant_live.py -v --tb=short -rs
+ - name: A tenant can opt itself into retro-hunts
+ working-directory: services/api
+ env:
+ ISOLATION_RETRO_HUNT_DSN: ${{ env.LIVE_DSN }}
+ run: python -m pytest ../../tests/isolation/test_retro_hunt_settings_live.py -v --tb=short -rs
+
+ - name: KEV exposure answers from scanner data, end to end
+ working-directory: services/api
+ env:
+ ISOLATION_KEV_DSN: ${{ env.LIVE_DSN }}
+ run: python -m pytest ../../tests/isolation/test_kev_exposure_has_data_live.py -v --tb=short -rs
+
- name: No suite may report success having skipped
run: |
set -euo pipefail
@@ -146,4 +158,4 @@ jobs:
exit 1
fi
echo "LIVE_DSN was set, and the cross-service step sets ISOLATION_CROSS_SERVICE,"
- echo "so none of the three suites took its skip path."
+ echo "so none of the five suites took its skip path."
diff --git a/.github/workflows/chaos.yml b/.github/workflows/chaos.yml
index 93b1377ae..4d63b2dac 100644
--- a/.github/workflows/chaos.yml
+++ b/.github/workflows/chaos.yml
@@ -134,3 +134,85 @@ jobs:
- name: Logs, on failure
if: failure()
run: docker compose logs --tail 200
+
+ # `fusion_restart.py` is the grader behind the claim "a fusion replica can be
+ # destroyed mid-stream and every accepted event still becomes exactly one
+ # alert row". Until this job existed the workflow ran only its `--self-test`,
+ # which exercises the grading arithmetic against fixtures and proves nothing
+ # about fusion -- the live run had happened once, by hand, which is a
+ # measurement with no expiry and no witness.
+ #
+ # Scheduled rather than per-PR for the same reason the store outages are:
+ # it boots the spine, pushes thousands of events and kills a container
+ # mid-stream, which is minutes, not seconds.
+ #
+ # `integration.yml`'s kill test is not a substitute: it posts a single event
+ # while fusion is down and checks only for loss. One event cannot show a
+ # duplicate, and duplicates are the half that an at-least-once consumer gets
+ # wrong.
+ fusion-restart:
+ name: Kill fusion mid-stream (live)
+ if: github.event_name != 'pull_request'
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.11"
+ - uses: actions/setup-go@v5
+ with:
+ go-version: "1.26"
+
+ - name: Build the producer
+ run: go build -o /tmp/demo-producer .
+ working-directory: services/demo-producer
+
+ - name: Bring up the spine
+ run: |
+ set -euo pipefail
+ python3 scripts/ensure_env.py
+ docker compose up -d postgres redis zookeeper kafka ingest-worker fusion api
+ for _ in $(seq 1 60); do
+ if docker compose ps --format '{{.Name}} {{.Health}}' | grep -q 'aisoc-api healthy'; then break; fi
+ sleep 10
+ done
+ docker compose ps
+
+ - name: Mint an ingest credential
+ id: token
+ run: |
+ set -euo pipefail
+ token="$(docker compose run --rm -T api python -m app.scripts.mint_ingest_token --quiet | tail -1 | tr -d '\r')"
+ test -n "$token"
+ echo "::add-mask::$token"
+ echo "token=$token" >> "$GITHUB_OUTPUT"
+
+ - name: Destroy fusion mid-stream and grade loss *and* duplicates
+ env:
+ AISOC_INGEST_TOKEN: ${{ steps.token.outputs.token }}
+ AISOC_PRODUCER_BIN: /tmp/demo-producer
+ run: |
+ set -euo pipefail
+ python3 scripts/chaos/fusion_restart.py \
+ --target compose \
+ --events 3000 --target-eps 60 --workers 4 --batch 25 \
+ --kill-at 0.5 \
+ --drain-timeout 420 \
+ --out /tmp/fusion-restart.json
+
+ - name: Publish the verdict
+ if: always()
+ run: |
+ {
+ echo "## Fusion destroyed mid-stream"
+ echo ""
+ echo '```json'
+ cat /tmp/fusion-restart.json 2>/dev/null || echo '{"note": "the grader produced no report"}'
+ echo '```'
+ } >> "$GITHUB_STEP_SUMMARY"
+
+ - name: Logs, on failure
+ if: failure()
+ run: docker compose logs --tail 200 fusion ingest-worker kafka || true
+
diff --git a/.github/workflows/perf.yml b/.github/workflows/perf.yml
index d8579b51b..3b7adc7f8 100644
--- a/.github/workflows/perf.yml
+++ b/.github/workflows/perf.yml
@@ -157,12 +157,26 @@ jobs:
echo "::add-mask::$token"
echo "token=$token" >> "$GITHUB_OUTPUT"
- # The floors are two orders of magnitude below what the published run
- # measured (177 alerts/s and a 1.1 s p95 on a laptop). A shared,
- # throttled GitHub runner is not that machine, and a gate tuned close to
- # a measurement gets disabled the first week it flaps. This fires on a
- # catastrophic regression: an I/O call on the promote hot path, a
- # consumer that stops committing, a sink that starts failing.
+ # The thresholds are derived from the published compose **steady-state**
+ # figures, not picked. That page measured 80.1 alerts/s and a 1,091 ms
+ # p95, and calls steady state "the row to plan against"; saturation is a
+ # backlog measurement, so a floor set from it would describe the queue
+ # rather than the pipeline.
+ #
+ # floor = 11 events/s -> 7.3x below the published 80.1 alerts/s
+ # ceiling = 21,000 ms -> 19.2x above the published 1,091 ms p95
+ #
+ # Deliberately generous: a shared, throttled GitHub runner is not the
+ # machine those figures came off, and a gate tuned close to a measurement
+ # flaps and gets switched off within a week. But bounded, and bounded
+ # *by the claim*: the previous `5` and `120000` sat 16x below and 110x
+ # above the published numbers, which is a constant that relates to
+ # nothing -- when the published figure moves, it does not, and nobody can
+ # say what regression it would have caught.
+ #
+ # tests/test_perf_gate_is_related_to_the_claims.py parses both this file
+ # and the published page and fails if the ratio drifts, in either
+ # direction.
- name: Measure, with a generous regression floor
env:
AISOC_INGEST_TOKEN: ${{ steps.token.outputs.token }}
@@ -171,9 +185,39 @@ jobs:
python3 scripts/perf/load_harness.py \
--target compose --events 4000 --workers 4 --batch 25 \
--target-eps 60 --drain-timeout 420 \
- --assert-eps-floor 5 --assert-p95-ceiling-ms 120000 --assert-no-loss \
+ --assert-eps-floor 11 --assert-p95-ceiling-ms 21000 --assert-no-loss \
--out /tmp/perf-e2e.json
+ # Two measurement tools shipped with no caller at all (fix-pass item
+ # 5.8), so the three-stage split they exist to publish had never been
+ # computed from a real run. `load_profiles.py` describes the sustained,
+ # diurnal and spike shapes the burst harness cannot produce;
+ # `throughput_claims.py` separates ingest from the alert path, which
+ # differ by two orders of magnitude -- quoting one figure as "the
+ # throughput" understates the product or misrepresents it depending which
+ # stage it came from.
+ #
+ # They could not be pointed at a real run because the harness recorded
+ # none of the context they require; it now records the load's shape
+ # (batch size, workers, host count, commit) and `--from-harness`
+ # translates it.
+ #
+ # `--allow unqualified-throughput` is the one known gap, stated rather
+ # than absorbed: the harness does not measure what fraction of pushed
+ # events the rule engine evaluated, and an ingest rate published without
+ # that beside it reads as "every event was fully analysed". The problem is
+ # still printed every run. Remove the flag when the harness reports
+ # detection coverage.
+ - name: Grade the run against the published claims
+ if: always()
+ run: |
+ set -euo pipefail
+ python3 scripts/perf/load_profiles.py --list
+ python3 scripts/perf/throughput_claims.py \
+ --from-harness /tmp/perf-e2e.json --check \
+ --allow unqualified-throughput
+
+
- name: Publish the run
if: always()
run: |
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 908d26901..6d3946c6a 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -646,11 +646,47 @@ jobs:
# tests/test_release_channel_tags.py runs this exact block under bash
# with each combination, because a tag-selection rule expressed only in
# a workflow is a rule nothing checks.
+ # Which major is `stable` on right now? Ask the registry, not the
+ # repository: a tag is a registry fact, and a tree can be any commit.
+ # Resolved per image because a republish or a half-release can leave one
+ # image's channel behind the others, and each must be judged on its own.
+ #
+ # A miss is not a failure. No `stable` tag yet is the ordinary state of a
+ # first release and must leave the value empty so the channel is taken;
+ # a registry hiccup is reported and also leaves it empty, which is the
+ # safe direction -- the worst case is `stable` advancing within the major
+ # it is already on.
+ - id: stable-major
+ env:
+ IMAGE: ${{ matrix.image }}
+ IS_DEMO: ${{ matrix.demo }}
+ run: |
+ set -uo pipefail
+ major=""
+ if [ "${IS_DEMO}" != "true" ]; then
+ current=$(docker buildx imagetools inspect "${IMAGE}:stable" \
+ --format '{{ index .Image.Config.Labels "org.opencontainers.image.version" }}' \
+ 2>/dev/null || true)
+ case "${current}" in
+ v[0-9]*|[0-9]*)
+ major="${current#v}"
+ major="${major%%.*}"
+ ;;
+ *)
+ echo "::notice::no resolvable \`stable\` tag for ${IMAGE} (got '${current}'); treating as a first release"
+ ;;
+ esac
+ fi
+ echo "major=${major}" >> "$GITHUB_OUTPUT"
+ echo "stable channel for ${IMAGE} is on major '${major:-<none>}'"
+
+
- id: image-tags
env:
VERSION: ${{ inputs.tag || github.ref_name }}
REPUBLISH: ${{ github.event_name == 'workflow_dispatch' }}
PROMOTE_STABLE: ${{ inputs.promote_stable }}
+ STABLE_MAJOR: ${{ steps.stable-major.outputs.major }}
IMAGE: ${{ matrix.image }}
IS_DEMO: ${{ matrix.demo }}
run: |
@@ -660,7 +696,23 @@ jobs:
IS_MAJOR=false
case "${VERSION#v}" in
*.0.0) IS_MAJOR=true ;;
- esac
+ esac
+ # Blocking `vX.0.0` alone is not enough, and this is the bug that
+ # carried `stable` to v12, v13 and v15. `v16.0.0` correctly refuses
+ # the tag; `v16.1.0` is a minor, so it took it the next day and the
+ # channel crossed the major with nobody deciding to. The channel has
+ # to know which major it is *on*, not only whether the incoming
+ # version is itself a major.
+ #
+ # STABLE_MAJOR is resolved from the registry by the step above. An
+ # empty value means no `stable` tag exists yet, which is a first
+ # release and must take the channel rather than read as a mismatch.
+ INCOMING_MAJOR="${VERSION#v}"
+ INCOMING_MAJOR="${INCOMING_MAJOR%%.*}"
+ SAME_MAJOR=true
+ if [ -n "${STABLE_MAJOR:-}" ] && [ "${STABLE_MAJOR}" != "${INCOMING_MAJOR}" ]; then
+ SAME_MAJOR=false
+ fi
{
echo 'tags<<EOF'
if [ "$IS_DEMO" = "true" ]; then
@@ -673,7 +725,7 @@ jobs:
# dispatch arm is the only way `stable` ever reaches a major,
# and it is separate from the republish arm above so repairing
# an old tag cannot drag `stable` backwards with it.
- if { [ "$REPUBLISH" != "true" ] && [ "$IS_MAJOR" != "true" ]; } || [ "$PROMOTE_STABLE" = "true" ]; then
+ if { [ "$REPUBLISH" != "true" ] && [ "$IS_MAJOR" != "true" ] && [ "$SAME_MAJOR" = "true" ]; } || [ "$PROMOTE_STABLE" = "true" ]; then
echo "${IMAGE}:stable"
fi
fi
@@ -1113,6 +1165,58 @@ jobs:
set -euo pipefail
helm show chart "oci://ghcr.io/beenuar/charts/aisoc" --version "${{ steps.package.outputs.version }}"
+ # The chart channel the release policy promised alongside the image one.
+ # It was scoped as "a `stable` image tag and chart channel" and only the
+ # image half was built, so `helm install` with no `--version` has always
+ # resolved to whatever the registry hands back.
+ #
+ # The rule is the image rule, keyed on the *chart's* own major rather than
+ # the application's: the break an operator is protected from here is a
+ # values-schema break, and the chart versions independently of
+ # `appVersion`. `helm push` cannot write a non-SemVer tag, so the channel
+ # is a manifest copy with buildx, which is already on the runner.
+ - name: Move the `stable` chart channel
+ id: chart-channel
+ if: github.event_name == 'push'
+ env:
+ CHART_VERSION: ${{ steps.package.outputs.version }}
+ PROMOTE_STABLE: ${{ inputs.promote_stable }}
+ run: |
+ set -uo pipefail
+ CHART=oci://ghcr.io/beenuar/charts/aisoc
+ REF=ghcr.io/beenuar/charts/aisoc
+
+ incoming_major="${CHART_VERSION%%.*}"
+ is_major=false
+ case "$CHART_VERSION" in
+ *.0.0) is_major=true ;;
+ esac
+
+ # Where the channel is now. A chart tagged `stable` reports its own
+ # version, which is the only thing that can answer this.
+ current=$(helm show chart "$CHART" --version stable 2>/dev/null \
+ | awk '$1 == "version:" { print $2 }')
+ channel_major=""
+ case "$current" in
+ [0-9]*) channel_major="${current%%.*}" ;;
+ esac
+
+ same_major=true
+ if [ -n "$channel_major" ] && [ "$channel_major" != "$incoming_major" ]; then
+ same_major=false
+ fi
+
+ if { [ "$is_major" != "true" ] && [ "$same_major" = "true" ]; } || [ "${PROMOTE_STABLE}" = "true" ]; then
+ docker buildx imagetools create --tag "${REF}:stable" "${REF}:${CHART_VERSION}"
+ helm show chart "$CHART" --version stable >/dev/null
+ echo "::notice title=Helm::stable chart channel now resolves to ${CHART_VERSION}"
+ echo "moved=true" >> "$GITHUB_OUTPUT"
+ else
+ echo "::notice title=Helm::stable chart channel left at ${current:-<none>}; chart ${CHART_VERSION} crosses a major. Dispatch with promote_stable: true to move it."
+ echo "moved=false" >> "$GITHUB_OUTPUT"
+ fi
+
+
- name: Explain a packaged-but-unpushed chart
if: github.event_name != 'push'
run: |
diff --git a/.github/workflows/upgrade-test.yml b/.github/workflows/upgrade-test.yml
index 9e3a745fa..f27e7bf55 100644
--- a/.github/workflows/upgrade-test.yml
+++ b/.github/workflows/upgrade-test.yml
@@ -131,8 +131,20 @@ jobs:
- name: Record what is there before the upgrade
run: |
set -euo pipefail
- psql -v ON_ERROR_STOP=1 -tA "postgresql://aisoc_app:[email protected]:5432/aisoc" \
- -c "\copy (select 'alerts', count(*) from alerts union all select 'cases', count(*) from cases union all select 'tenants', count(*) from tenants union all select 'users', count(*) from users order by 1) to '/tmp/before.tsv'"
+ # Which case table the previous release has depends on which release
+ # it is: 083 renames `cases` and consolidates into `aisoc_cases`, so a
+ # pinned name is right on exactly one side of that boundary. Resolve
+ # it -- the count is what this snapshot is for, not the name.
+ DSN="postgresql://aisoc_app:[email protected]:5432/aisoc"
+ CASES=$(psql -v ON_ERROR_STOP=1 -tA "$DSN" -c \
+ "select coalesce(to_regclass('public.aisoc_cases')::text, to_regclass('public.cases')::text, '')")
+ if [ -z "$CASES" ]; then
+ echo "::error::the previous release has neither \`aisoc_cases\` nor \`cases\`" >&2
+ exit 1
+ fi
+ echo "previous release holds its cases in: $CASES"
+ psql -v ON_ERROR_STOP=1 -tA "$DSN" \
+ -c "\copy (select 'alerts', count(*) from alerts union all select 'cases', count(*) from ${CASES} union all select 'tenants', count(*) from tenants union all select 'users', count(*) from users order by 1) to '/tmp/before.tsv'"
cat /tmp/before.tsv
# Leg two: this tree's chain, applied by the release's own runner.
@@ -199,8 +211,20 @@ jobs:
"select title from aisoc_cases where id = '22222222-2222-2222-2222-222222222222'" | grep -q 'pre-upgrade case'
# And the archive still holds what it held, so a consolidation
# that lost a row is detectable after the fact.
- psql -v ON_ERROR_STOP=1 -tA "postgresql://aisoc_app:[email protected]:5432/aisoc" -c \
- "select count(*) from cases_pre_consolidation" >/dev/null
+ # `cases_pre_consolidation` only exists when 083 ran during *this*
+ # upgrade. Once the previous release is itself 16.x the rename
+ # happened before this test started, so its absence is then the
+ # correct state and not a regression. Assert on it only when it is
+ # there, and say out loud which case was taken, because "the check
+ # silently did nothing" is the failure mode this whole workflow is
+ # about.
+ if [ -n "$(psql -tA "postgresql://aisoc_app:[email protected]:5432/aisoc" -c "select to_regclass('public.cases_pre_consolidation')")" ]; then
+ psql -v ON_ERROR_STOP=1 -tA "postgresql://aisoc_app:[email protected]:5432/aisoc" -c \
+ "select count(*) from cases_pre_consolidation" >/dev/null
+ echo "083 ran during this upgrade; the pre-consolidation archive is intact."
+ else
+ echo "the previous release already carried the consolidation; no archive expected."
+ fi
echo "OK: the rows that were there before the upgrade are still there, by id."
# The runtime role is what every service connects as, and a migration
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b90e04309..7eb892f26 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -22,6 +22,50 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
governed equivalent is `POST /api/v1/detection-proposals`, which writes to a
real table and carries separation of duties.
+### Added
+
+- **Retro-hunts can be turned on.** `RETRO_HUNT_ENABLED` decides whether the
+ consumer runs, and it appeared in no compose file and no `.env.example` --
+ compose passes only the variables it names, so setting it in a shell did
+ nothing and the consumer could not start on any compose deployment. The
+ tenant's half, `retro_hunt_settings.enabled`, defaults to FALSE under a
+ comment reading "Off until a tenant asks", and there was nowhere to ask: no
+ route and no console surface touched the table, so opting a tenant in meant
+ an UPDATE issued by hand. Both halves now exist --
+ `GET`/`PUT /api/v1/retro-hunts/settings` and a panel in Settings -> Autonomy
+ guardrails -- and both switches must be on before anything is swept. The
+ sweep budget is deliberately read-only through the tenant surface: it is the
+ operator's ceiling on what one tenant can cost the deployment.
+- **The Helm chart has the `stable` channel the release policy promised.** It
+ was scoped as "a `stable` image tag and chart channel" and only the image
+ half was built, so `helm install` with no `--version` resolved to whatever
+ the registry handed back. The chart channel follows the **chart's** major,
+ not the application's, because the break it protects against is a
+ values-schema break.
+
+### Changed
+
+- **Retracted claims for schema that nothing reads.** Migration 084's
+ detection lifecycle (`environment`, `shadow_until`, `detection_rule_versions`,
+ `detection_shadow_matches`) and migration 087's enterprise IAM
+ (`workload_identities`, `privilege_grants`, `permission_conditions`,
+ `narrow_by_conditions`) each have **zero readers** in `services/`. A rule set
+ to `dev` still raises alerts, a future `shadow_until` still pages, and there
+ is no rollback route. Separation of duties on detection proposals is real and
+ the claim for it stands. The docs page, README and changelog now say which
+ half is which.
+- **Three docs-portal overclaims corrected.** Qdrant holds the MITRE technique
+ corpus for lookup, which is a reference index and not agent memory; there is
+ no coverage advisor that recommends rules for uncovered techniques and no
+ one-click generation route; and `GET /taxii/collections` calls `_demo_only()`
+ and returns a fixed list, so TAXII collection management is demo-only and the
+ intel sharing is one-way.
+- **The phishing playbook no longer claims a retraction it cannot perform.**
+ Its "Retract phishing email fleet-wide" step posts to `${EMAIL_GATEWAY_URL}`,
+ which no compose file or `.env.example` sets, under `on_failure: continue`.
+ The step and the playbook description now say the message is not retracted
+ when the gateway is unconfigured.
+
### Removed
- **`POST /api/v1/detection-loop/suggest` and its two sibling routes.** They
@@ -54,31 +98,120 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`/detection-proposals/{id}/decide`, so an approver clicking through would
have written a rule with no detection logic into the engine. `/decide` now
refuses such a body, and the auto-tuner no longer seeds the queue by default.
-
-### Changed
-
-- **Retracted claims for schema that nothing reads.** Migration 084's
- detection lifecycle (`environment`, `shadow_until`, `detection_rule_versions`,
- `detection_shadow_matches`) and migration 087's enterprise IAM
- (`workload_identities`, `privilege_grants`, `permission_conditions`,
- `narrow_by_conditions`) each have **zero readers** in `services/`. A rule set
- to `dev` still raises alerts, a future `shadow_until` still pages, and there
- is no rollback route. Separation of duties on detection proposals is real and
- the claim for it stands. The docs page, README and changelog now say which
- half is which.
-- **Three docs-portal overclaims corrected.** Qdrant holds the MITRE technique
- corpus for lookup, which is a reference index and not agent memory; there is
- no coverage advisor that recommends rules for uncovered techniques and no
- one-click generation route; and `GET /taxii/collections` calls `_demo_only()`
- and returns a fixed list, so TAXII collection management is demo-only and the
- intel sharing is one-way.
-- **The phishing playbook no longer claims a retraction it cannot perform.**
- Its "Retract phishing email fleet-wide" step posts to `${EMAIL_GATEWAY_URL}`,
- which no compose file or `.env.example` sets, under `on_failure: continue`.
- The step and the playbook description now say the message is not retracted
- when the gateway is unconfigured.
-
-### Fixed
+- **`stable` crossed a major on its own, which is how it reached v12, v13 and
+ v15.** The rule refused `vX.0.0` and nothing else, so `v16.0.0` correctly
+ declined the tag and `v16.1.0` -- a minor -- took it the next day, carrying
+ every deployment that pulls `stable` across the breaking change with no
+ operator action. The release workflow now resolves which major the channel is
+ *on*, from the registry rather than the tree, and moves it only within that
+ major. The test that backed the claim asked one release at a time, which is
+ why it always answered correctly; it now replays whole release ladders.
+- **The upgrade test would have broken the moment the previous release became
+ 16.x.** `scripts/upgrade_fixture.sql` inserted into `cases`, which migration
+ 083 renames, and the workflow's before-snapshot and archive assertion pinned
+ names that exist on exactly one side of that rename. All three now resolve
+ the table at run time and say which case was taken.
+- **The OpenAPI drift message named no cause.** It said only "out of date, run
+ `export_openapi.py`", which is the command that produced the rejected file.
+ The usual cause is a generator version disagreeing with the lockfile --
+ pydantic 2.13 emits `additionalProperties: true` where 2.8 did not, 252 lines
+ of diff across the spec and nothing to do with anyone's change -- so it now
+ names the mismatch, prints the `pip install` that fixes it, and shows the
+ first differing paths.
+- **The chaos grader behind "a fusion replica can be destroyed mid-stream" had
+ run live once, by hand.** `chaos.yml` ran only its `--self-test`, which
+ exercises the grading arithmetic against fixtures and proves nothing about
+ fusion, and `integration.yml`'s kill test posts a **single** event while
+ fusion is down and checks only for loss -- one event cannot show a duplicate,
+ and duplicates are the half an at-least-once consumer gets wrong. A
+ `fusion-restart` job now runs on the weekly schedule: it boots the spine,
+ pushes 3,000 events, destroys the fusion container at the halfway mark, and
+ asserts against the `alerts` table that every accepted sequence number
+ appears exactly once. The claim row's caveat said this needed a three-node
+ cluster; it does not, because the property under test is the consumer's
+ commit discipline and the sink's idempotency, and one replica killed
+ mid-stream exercises both.
+- **Not one of the 68 shipped hunts could be compiled against the lake.** The
+ README publishes the library as **Stable**, "replayed against tenant events".
+ Measured against `lake_hunt.py`'s field map the corpus used 114 distinct
+ field names and **zero** resolved to a lake column -- all 243 field uses were
+ reported unsupported, so every hunt returned either an unfiltered table or
+ nothing. Two causes: every one of the 68 filters on a bare `source`, which
+ the lake stores as `connector_type` and the map did not mention; and the
+ other 113 are vendor names like `EventID` and `CommandLine` that have no
+ column but which the stored payload carries, and nothing reached into
+ `raw_payload`. Both are fixed and all 114 now compile, through a column or a
+ payload extraction that also tries the `EventData` and `System` nestings
+ Windows uses -- the same nesting that once made 2,173 Sigma rules unable to
+ fire. The field name is bound as a query parameter and additionally refused
+ unless it is a plain identifier. Separately, the agents image shipped with no
+ ClickHouse driver (so `lake-live.yml` installed one by hand, proving
+ something about a package set the published image does not have) and the
+ `full` profile gave the agents container no ClickHouse address at all. The
+ README row now says "compiled against", because a payload extraction finds a
+ field if the event carries it, which is a property of the connector's output
+ rather than of this compiler.
+- **File analysis could not be configured, and when it was unconfigured the
+ product did not say so.** Compose passed neither `AISOC_AIRGAPPED` nor any
+ sandbox provider setting to the `api` service, and compose passes only the
+ variables it names -- so an operator with a CAPEv2 appliance had no way to
+ point the product at it. The air-gap overlay set the flag on `agents` alone,
+ while `AISOC_AIRGAPPED` is read by seventeen modules across four services
+ including the API's STIX publisher, both query runners and the sandbox
+ registry: a deployment that believed it was air-gapped had one service that
+ knew. And with only the mock provider answering, `_attachment_indicators` did
+ `if not block: continue`, so a phishing verdict carried **no attachment
+ indicator at all** -- which a reader takes for "checked and clean" rather
+ than "not checked". It now records that no provider is configured and says
+ plainly that this is not a clean verdict. Separately, the agent's sandbox
+ tool reported every 403 as *"Air-gapped mode permits local analysis providers
+ only"*, when a 403 is equally an expired token, a revoked scope or a tenant
+ policy -- so it named the deployment's networking posture while the fix was a
+ credential.
+- **The performance gate could not have caught a regression.** It asserted a
+ floor of 5 events/s and a ceiling of 120,000 ms against published figures of
+ **80.1 alerts/s** and a **1,091 ms** p95 -- 16x below and 110x above -- so a
+ regression had to be catastrophic by two orders of magnitude before the job
+ that said it was measuring noticed. The thresholds are now derived from those
+ figures (7.3x and 19.2x), with the arithmetic in the workflow and a test that
+ parses both the workflow and the published page and fails if the ratio drifts
+ in either direction. `check_perf_results.py` accepted a results directory
+ covering one of the two published deployments and had no freshness bound at
+ all; it now requires both and caps the newest result at 400 days.
+ `scripts/perf/load_profiles.py` and `scripts/perf/throughput_claims.py` had
+ no caller anywhere and could not be pointed at a real run, because the
+ harness recorded none of the context they require. The harness now records
+ the load's shape -- batch size, workers, target rate, host count, commit --
+ and `--from-harness` translates a result into claim shape, taking the
+ missing-context findings from eight to zero. The one remaining gap is stated
+ rather than absorbed: the harness does not measure what fraction of pushed
+ events the rule engine evaluated, so that problem is tolerated by an explicit
+ `--allow` naming it and is still printed on every run.
+- **KEV exposure had no data on any deployment, and three further defects sat
+ behind it.** `asset_vulnerabilities` had exactly one writer in the tree --
+ `POST /api/v1/assets/vulnerabilities`, a route a human calls by hand -- and
+ the Tenable connector, the only vulnerability scanner AiSOC integrates,
+ modelled its findings as alerts. `_tenant_has_vulnerability_data` exists to
+ tell "you are not exposed" apart from "nobody has told me what you run", so
+ with an empty table KEV exposure answered the second, forever. The data was
+ not merely unwritten: `fetch_alerts` calls `/workbenches/vulnerabilities`,
+ which returns plugin aggregates carrying neither a CVE nor an asset, and
+ `normalize()` sets `host: None`. The connector now fetches per-asset findings
+ and the plugin details that carry CVEs, capped at 60 plugin lookups so a
+ large workbench cannot turn a 5-minute schedule into a denial of service
+ against the customer's own scanner, and the connectors service writes the
+ rows itself -- not via the API, because the service principal is deliberately
+ read-only and widening it to close this would undo that for every route.
+
+ Creating the data for the first time then exposed three things downstream
+ that had never run: KEV exposure opened its case with `status="open"`, which
+ `aisoc_cases_status_check` rejects; `CaseTask` named `case_tasks` and
+ `CaseTimeline` named `case_timeline`, neither of which any migration creates
+ (the real tables are `aisoc_case_tasks` and `case_timeline_events`, with four
+ declared columns that do not exist); and the task status `"pending"` is not
+ one of the three `aisoc_case_tasks_status_check` allows. All three were
+ reachable only from data the product had no way to produce, which is why
+ nothing had noticed.
- **The MCP client could not complete a single real call, and every tool it
offered a model was rejected by the provider (fix pass, wave 2).**
diff --git a/FIX_PASS_PROGRESS.md b/FIX_PASS_PROGRESS.md
index 4b7600f89..a5d0ca14e 100644
--- a/FIX_PASS_PROGRESS.md
+++ b/FIX_PASS_PROGRESS.md
@@ -110,14 +110,22 @@ conditional `numpy` pins collide into an unresolvable install. Parse with
## Wave 5: Hunting, intel, sandbox and operations wiring
-- [ ] **5.1** Retro-hunts can be turned on
-- [ ] **5.2** KEV exposure gets data
-- [ ] **5.3** Hunts over the lake
-- [ ] **5.4** Sandbox and air-gap settings reach the API
-- [ ] **5.5** Release channel does not cross a major
-- [ ] **5.6** Upgrade fixture does not insert into the renamed `cases` table
-- [ ] **5.7** Chaos and HA run live in CI
-- [ ] **5.8** Performance honesty
+- [x] **5.1** Retro-hunts can be turned on
+ - Both halves built. `RETRO_HUNT_ENABLED` now passes through compose and is documented in `.env.example`, defaulting off; `GET`/`PUT /api/v1/retro-hunts/settings` plus a Settings panel give the tenant somewhere to opt in. Nine live tests against real Postgres; reverting the upsert to a plain UPDATE fails four.
+- [x] **5.2** KEV exposure gets data
+ - Connector now fetches per-asset findings plus plugin CVEs (capped at 60 lookups) and the connectors service writes `asset_vulnerabilities` directly -- not through the API, because the service principal is deliberately read-only. Seven live end-to-end tests. Creating the data first time exposed three more defects that had never run: a case status the CHECK rejects, two ORM models naming tables no migration creates, and a task status the CHECK rejects.
+- [x] **5.3** Hunts over the lake
+ - All three halves done. `clickhouse-driver` added to `services/agents` (lock regenerated with the pinned poetry 2.4.1); CLICKHOUSE_* mirrored onto the agents service in compose; and the field mapping went from **0 of 114** corpus fields resolvable to **114 of 114**, via `source` -> `connector_type` plus a parameterised `raw_payload` extraction covering the `EventData` and `System` nestings. README row narrowed from "replayed" to "compiled against", with the reason.
+- [x] **5.4** Sandbox and air-gap settings reach the API
+ - All four defects fixed: compose now passes `AISOC_AIRGAPPED` plus the CAPEv2 and MalwareAnalyzer settings to `api`; the air-gap overlay sets the flag on `api`, `threatintel` and `connectors` as well as `agents`; phishing records "no provider configured, this is not a clean verdict" instead of skipping an empty block; and the agent tool names a 403 as an authorisation problem with its three candidates rather than asserting air-gap mode. Both compose paths validate.
+- [x] **5.5** Release channel does not cross a major
+ - The channel now tracks which major it is on, resolved from the registry, so a minor cannot carry it across a major. Test replays release ladders rather than single releases. Helm chart gains the `stable` channel it was scoped with.
+- [x] **5.6** Upgrade fixture does not insert into the renamed `cases` table
+ - Fixture, before-snapshot and archive assertion all resolve the case table at run time. Reproduced against a fully-migrated database first: `relation "cases" does not exist`.
+- [x] **5.7** Chaos and HA run live in CI
+ - A `fusion-restart` job now runs the grader live on the weekly `chaos.yml` schedule -- 3,000 events, fusion destroyed at the halfway mark, graded against the `alerts` table for duplicates as well as loss. The claim row moves off its "not on a CI trigger" caveat: the three-node cluster it cited is not needed, because the property under test is the consumer's commit discipline and the sink's idempotency, and one replica killed mid-stream exercises both.
+- [x] **5.8** Performance honesty
+ - Thresholds now derived from the published compose steady-state figures (floor 11 = 7.3x below the published 80.1 alerts/s; ceiling 21,000 ms = 19.2x above the published 1,091 ms p95) instead of a constant 5 / 120,000 sitting 16x and 110x away. `check_perf_results.py` gained `REQUIRED_DEPLOYMENTS` and `MAX_RESULT_AGE_DAYS`. Both uncalled scripts are wired: the harness now records the load shape the claims tool requires, `--from-harness` translates it, and the one remaining gap (the harness does not measure detection coverage) is an explicit `--allow` with the problem still printed, not an absorbed failure.
## Wave 6: Retract what is not built
diff --git a/README.md b/README.md
index 3e9649c2b..fbe843e2f 100644
--- a/README.md
+++ b/README.md
@@ -200,7 +200,7 @@ Agents triage alerts and investigate incidents. What they can and cannot do:
| AI triage + Investigation Ledger | Stable | Live Postgres ledger + a PR-gated local-model agent run. No hosted provider has been exercised | Yes, copilot mode |
| Event lake + hunting (ClickHouse) | Stable | Live ClickHouse on the shipped DDL, with a negative control | Yes, `full` profile |
| Retro-hunts when new intel arrives | Stable | Live ClickHouse + Kafka with the flag on, with a negative control | Opt-in, `full` profile |
-| 68-hunt YAML library, replayed against tenant events | Stable | Live ClickHouse: scheduled hunts read tenant data and refuse to fall back to the fixture | Yes, `full` profile |
+| 68-hunt YAML library, compiled against tenant events in the lake | Stable | Live ClickHouse: scheduled hunts read tenant data and refuse to fall back to the fixture; all 114 field names the corpus filters on compile, via a lake column or the stored payload | Yes, `full` profile |
| SCIM 2.0, white-label, usage metering | Stable | Live Postgres through the real app, with a negative control | Yes |
| Entity graph (Neo4j) | Stable | Live Neo4j against the production reader, with a negative control | Yes, `full` profile |
| Governed response actions | Stable | Live socket: permits, refuses, never leaks a refusal, with a negative control | Human-approved only |
diff --git a/apps/docs/docs/operations/release-policy.md b/apps/docs/docs/operations/release-policy.md
index 3d3e38460..a0779a225 100644
--- a/apps/docs/docs/operations/release-policy.md
+++ b/apps/docs/docs/operations/release-policy.md
@@ -79,10 +79,19 @@ two channel tags.
`stable` exists because `latest` cannot be both "newest" and "safe to pull
unattended". A major stops `stable` where it is until a maintainer dispatches
-the release workflow with `promote_stable: true`. The rule is executed by
-`tests/test_release_channel_tags.py`, which lifts the tag-selection block out
-of `release.yml` and runs it under each combination rather than describing it
-a second time.
+the release workflow with `promote_stable: true`.
+
+**The rule is about a sequence, not a release.** Refusing `vX.0.0` is not
+enough on its own: `v16.0.0` correctly declines the tag and `v16.1.0` is a
+minor, so it took it the next day and the channel crossed the major with nobody
+deciding to. That is how `stable` reached v12, v13 and v15. The workflow now
+resolves which major the channel is *on* -- from the registry, because a tag is
+a registry fact -- and moves it only within that major.
+
+`tests/test_release_channel_tags.py` lifts the tag-selection block out of
+`release.yml` and runs it under bash rather than describing it a second time,
+and it replays whole release ladders, because every question asked one release
+at a time had the right answer while the sequence did not.
Neither channel tag is ever applied by a repair run. Re-publishing the images
for an older tag moves nothing, because handing a self-hoster older content on
@@ -93,10 +102,19 @@ the tag they pull by default is the defect this arrangement exists to prevent.
The chart is published to an OCI registry on every release:
```bash
-helm show chart oci://ghcr.io/beenuar/charts/aisoc
+helm show chart oci://ghcr.io/beenuar/charts/aisoc --version stable
helm install aisoc oci://ghcr.io/beenuar/charts/aisoc --version <chart-version> -n aisoc --create-namespace
```
+The chart has the same `stable` channel the images do, and it follows the
+**chart's** major rather than the application's -- the break it protects an
+operator from is a values-schema break, and the chart versions independently of
+`appVersion`. `--version stable` resolves to the newest chart within the major
+the channel is on; a chart major stops it until a maintainer dispatches with
+`promote_stable: true`, exactly as for images. Pin an explicit version in
+production; the channel is for the case where you would otherwise have pinned
+nothing at all.
+
The chart's `version` and its `appVersion` move independently. `appVersion`
names the images an unpinned install pulls; `version` is the chart's own. A
chart change that does not touch the services does not force a service
diff --git a/apps/web/src/components/settings/RetroHuntSettings.tsx b/apps/web/src/components/settings/RetroHuntSettings.tsx
new file mode 100644
index 000000000..b4131e0f6
--- /dev/null
+++ b/apps/web/src/components/settings/RetroHuntSettings.tsx
@@ -0,0 +1,190 @@
+'use client';
+
+/**
+ * Opt this tenant into retro-hunt sweeps.
+ *
+ * `retro_hunt_settings.enabled` has defaulted to FALSE since migration 070
+ * under a comment reading "Off until a tenant asks", and until this panel
+ * existed there was nowhere to ask: no route and no console surface touched
+ * the table, so opting in meant an UPDATE issued against the database by hand.
+ *
+ * Two switches have to be on. This is the tenant's. The operator's is
+ * `RETRO_HUNT_ENABLED`, which decides whether the consumer runs at all, and
+ * the panel says so rather than letting someone toggle this and conclude the
+ * feature is broken when nothing sweeps.
+ */
+
+import { useCallback, useState } from 'react';
+import useSWR from 'swr';
+
+import { retroHuntsApi, type RetroHuntSettings as Settings } from '@/lib/api';
+
+const MIN_LOOKBACK = 1;
+const MAX_LOOKBACK = 365;
+
+export function RetroHuntSettingsPanel() {
+ const { data, error, isLoading, mutate } = useSWR<Settings>(
+ 'settings:retro-hunts',
+ () => retroHuntsApi.getSettings(),
+ // No `fallbackData`: supplying one disables revalidation, so a mock would
+ // be what this panel *shows* rather than a first paint. There is no shape
+ // of invented settings better than saying the read failed -- a fabricated
+ // "off" reads as an answer.
+ { revalidateOnFocus: false, shouldRetryOnError: false },
+ );
+
+ const [saving, setSaving] = useState(false);
+ const [saveError, setSaveError] = useState<string | null>(null);
+
+ const save = useCallback(
+ async (patch: Partial<Pick<Settings, 'enabled' | 'lookback_days' | 'include_federated'>>) => {
+ if (!data) return;
+ const next = { ...data, ...patch };
+ setSaving(true);
+ setSaveError(null);
+ try {
+ const written = await retroHuntsApi.putSettings({
+ enabled: next.enabled,
+ lookback_days: next.lookback_days,
+ include_federated: next.include_federated,
+ });
+ await mutate(written, { revalidate: false });
+ } catch (err) {
+ // Do not leave the optimistic value on screen: a toggle that looks
+ // saved and is not is worse than one that visibly refused.
+ setSaveError(err instanceof Error ? err.message : 'Could not save.');
+ await mutate();
+ } finally {
+ setSaving(false);
+ }
+ },
+ [data, mutate],
+ );
+
+ if (isLoading) {
+ return <p className="text-sm text-muted-foreground">Reading retro-hunt settings…</p>;
+ }
+
+ if (error || !data) {
+ return (
+ <div className="rounded-md border border-destructive/40 bg-destructive/5 p-4">
+ <p className="text-sm font-medium">Could not read retro-hunt settings</p>
+ <p className="mt-1 text-sm text-muted-foreground">
+ {error instanceof Error ? error.message : 'The settings endpoint did not answer.'}
+ </p>
+ <button
+ type="button"
+ onClick={() => void mutate()}
+ className="mt-3 rounded-md border px-3 py-1.5 text-sm hover:bg-muted"
+ >
+ Try again
+ </button>
+ </div>
+ );
+ }
+
+ const s = data;
+
+ return (
+ <section className="space-y-6">
+ <header>
+ <h3 className="text-base font-semibold">Retro-hunt sweeps</h3>
+ <p className="mt-1 text-sm text-muted-foreground">
+ When a new indicator arrives, look back over your history for anything that already
+ matched it. Off until you ask, because a sweep reads your past events.
+ </p>
+ </header>
+
+ <label className="flex items-start gap-3">
+ <input
+ type="checkbox"
+ checked={s.enabled}
+ disabled={saving}
+ onChange={(e) => void save({ enabled: e.target.checked })}
+ className="mt-1"
+ />
+ <span>
+ <span className="text-sm font-medium">Sweep my history when new intel arrives</span>
+ <span className="mt-0.5 block text-sm text-muted-foreground">
+ Your operator must also have started the retro-hunt consumer
+ (<code>RETRO_HUNT_ENABLED</code>). Both switches have to be on before anything is
+ swept.
+ </span>
+ </span>
+ </label>
+
+ <label className="flex items-start gap-3">
+ <input
+ type="checkbox"
+ checked={s.include_federated}
+ disabled={saving || !s.enabled}
+ onChange={(e) => void save({ include_federated: e.target.checked })}
+ className="mt-1"
+ />
+ <span>
+ <span className="text-sm font-medium">Also sweep my connected SIEMs</span>
+ <span className="mt-0.5 block text-sm text-muted-foreground">
+ Separate from the switch above because it is a separate cost: sweeping the AiSOC lake
+ is free to you, and sweeping a connected SIEM may bill you per query.
+ </span>
+ </span>
+ </label>
+
+ <label className="block">
+ <span className="text-sm font-medium">Look back</span>
+ <span className="mt-1 flex items-center gap-2">
+ <input
+ type="number"
+ min={MIN_LOOKBACK}
+ max={MAX_LOOKBACK}
+ value={s.lookback_days}
+ disabled={saving || !s.enabled}
+ onChange={(e) => {
+ const days = Number(e.target.value);
+ if (days >= MIN_LOOKBACK && days <= MAX_LOOKBACK) void save({ lookback_days: days });
+ }}
+ className="w-24 rounded-md border px-2 py-1 text-sm"
+ />
+ <span className="text-sm text-muted-foreground">
+ days (1–{MAX_LOOKBACK}; the column enforces the same bound)
+ </span>
+ </span>
+ </label>
+
+ <div className="rounded-md border p-4">
+ <p className="text-sm font-medium">Your sweep budget</p>
+ <p className="mt-1 text-sm text-muted-foreground">
+ Set by your operator, not here: it is the ceiling on what one tenant can cost the
+ deployment.
+ </p>
+ <dl className="mt-3 grid grid-cols-2 gap-x-6 gap-y-1 text-sm">
+ <dt className="text-muted-foreground">This hour</dt>
+ <dd>
+ {s.sweeps_this_hour} of {s.max_sweeps_per_hour}
+ </dd>
+ <dt className="text-muted-foreground">Today</dt>
+ <dd>
+ {s.sweeps_today} of {s.max_sweeps_per_day}
+ </dd>
+ <dt className="text-muted-foreground">Declined for budget</dt>
+ <dd>{s.sweeps_skipped_budget}</dd>
+ </dl>
+ {s.sweeps_skipped_budget > 0 && (
+ <p className="mt-3 text-sm">
+ {s.sweeps_skipped_budget} sweep{s.sweeps_skipped_budget === 1 ? ' has' : 's have'} been
+ declined because a budget was exhausted. Surfaced because the symptom otherwise is
+ silence, which looks identical to a feed with nothing to report.
+ </p>
+ )}
+ </div>
+
+ {saveError && (
+ <p className="text-sm text-destructive" role="alert">
+ {saveError}
+ </p>
+ )}
+ </section>
+ );
+}
+
+export default RetroHuntSettingsPanel;
diff --git a/apps/web/src/components/settings/SettingsView.tsx b/apps/web/src/components/settings/SettingsView.tsx
index aaf6e5815..d61e175ac 100644
--- a/apps/web/src/components/settings/SettingsView.tsx
+++ b/apps/web/src/components/settings/SettingsView.tsx
@@ -46,6 +46,7 @@ import { Skeleton } from '@/components/ui/Skeleton';
import { ErrorState } from '@/components/ui/ErrorState';
import { EmptyState } from '@/components/ui/EmptyState';
import { AutonomyPolicyPanel } from '@/components/settings/AutonomyPolicy';
+import { RetroHuntSettingsPanel } from './RetroHuntSettings';
import { useTheme, type ThemePreference } from '@/components/theme/ThemeProvider';
import { canUseDemoData } from '@/lib/demoFallback';
@@ -402,7 +403,12 @@ export function SettingsView() {
{tab === 'profile' && <ProfilePanel />}
{tab === 'workspace' && <WorkspacePanel />}
{tab === 'integrations' && <IntegrationsPanel />}
- {tab === 'autonomy' && <AutonomyPolicyPanel />}
+ {tab === 'autonomy' && (
+ <div className="space-y-10">
+ <AutonomyPolicyPanel />
+ <RetroHuntSettingsPanel />
+ </div>
+ )}
{tab === 'api-keys' && <ApiKeysPanel />}
{tab === 'notifications' && <NotificationsPanel />}
{tab === 'appearance' && <AppearancePanel />}
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index ce9f53b3c..ece49c559 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -615,6 +615,45 @@ export const brandingApi = {
},
};
+export interface RetroHuntSettings {
+ enabled: boolean;
+ lookback_days: number;
+ include_federated: boolean;
+ max_sweeps_per_hour: number;
+ max_sweeps_per_day: number;
+ sweeps_this_hour: number;
+ sweeps_today: number;
+ sweeps_skipped_budget: number;
+}
+
+export const retroHuntsApi = {
+ /**
+ * This tenant's answer to "may AiSOC sweep my history".
+ *
+ * A tenant that has never opted in has no settings row, and the API returns
+ * the column defaults rather than a 404 -- "you have not opted in" is a
+ * state with a correct answer.
+ */
+ async getSettings(): Promise<RetroHuntSettings> {
+ return request<RetroHuntSettings>('/api/v1/retro-hunts/settings');
+ },
+
+ /**
+ * Opt in or out. The budget fields are read-only here by design: they are
+ * the operator's ceiling on what one tenant can cost the deployment.
+ */
+ async putSettings(body: {
+ enabled: boolean;
+ lookback_days: number;
+ include_federated: boolean;
+ }): Promise<RetroHuntSettings> {
+ return request<RetroHuntSettings>('/api/v1/retro-hunts/settings', {
+ method: 'PUT',
+ body: JSON.stringify(body),
+ });
+ },
+};
+
export const tenantsApi = {
/**
* Lightweight tenant identity for the SOC console TopBar.
diff --git a/docker-compose.yml b/docker-compose.yml
index 07ae7a160..afd8fdfae 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -480,6 +480,30 @@ services:
# is the container_name, not the DNS name on this network.
AISOC_ACTIONS_BASE_URL: http://actions:8085
AISOC_ACTIONS_SERVICE_TOKEN: ${AISOC_ACTIONS_SERVICE_TOKEN:-}
+ # Retro-hunt sweeps. `main.py` starts the consumer only when this is
+ # true, and compose passes only the variables it names -- so while this
+ # was absent, setting it in the host environment did nothing and the
+ # consumer could not start on any compose deployment.
+ #
+ # Off by default and deliberately: a sweep reads back over a tenant's
+ # history, which is a cost and a privacy decision, so it waits for both
+ # the operator here and the tenant in `retro_hunt_settings`.
+ RETRO_HUNT_ENABLED: "${RETRO_HUNT_ENABLED:-false}"
+ # File analysis and the air-gap posture. Compose passes only the
+ # variables it names, so while these were absent an operator with a
+ # CAPEv2 appliance had no way to point the product at it, and an
+ # air-gapped deployment had no way to tell the API -- which reads
+ # AISOC_AIRGAPPED in nine modules including the sandbox registry, the
+ # STIX publisher and three query runners.
+ #
+ # Unset means the registry serves the mock provider, which knows
+ # nothing and now says so rather than returning an empty result a
+ # reader takes for a clean verdict.
+ AISOC_AIRGAPPED: "${AISOC_AIRGAPPED:-false}"
+ AISOC_CAPEV2_BASE_URL: "${AISOC_CAPEV2_BASE_URL:-}"
+ AISOC_CAPEV2_API_TOKEN: "${AISOC_CAPEV2_API_TOKEN:-}"
+ MALWAREANALYZER_BASE_URL: "${MALWAREANALYZER_BASE_URL:-}"
+ MALWAREANALYZER_API_KEY: "${MALWAREANALYZER_API_KEY:-}"
# Phase 2.6 — use /readyz, not /health, so the orchestrator
# only routes traffic once the lifespan has finished wiring
# Postgres, Redis, Kafka, Qdrant, and Neo4j. (Not OpenSearch: this
@@ -754,6 +778,16 @@ services:
# each logging its own `no_service_token` warning and returning empty.
# `make env` generates it; it must match the value on `api` below.
AISOC_AGENTS_SERVICE_TOKEN: ${AISOC_AGENTS_SERVICE_TOKEN:-}
+ # The hunting agent reads the ClickHouse lake, and this block named
+ # none of it -- so in the `full` profile the agent had a driver-less
+ # image and no address to point it at. Mirrors the api service above,
+ # because both read the same lake and a second set of defaults is a
+ # second thing to drift.
+ CLICKHOUSE_HOST: "${CLICKHOUSE_HOST:-clickhouse}"
+ CLICKHOUSE_PORT: "${CLICKHOUSE_PORT:-9000}"
+ CLICKHOUSE_DATABASE: "${CLICKHOUSE_DATABASE:-aisoc}"
+ CLICKHOUSE_USER: "${CLICKHOUSE_USER:-aisoc}"
+ CLICKHOUSE_PASSWORD: "${CLICKHOUSE_PASSWORD:-aisoc_dev_secret}"
networks:
- aisoc
restart: unless-stopped
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 9d902b27b..eda3876ac 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -208,7 +208,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| Every tool call an investigation makes is in the Investigation Ledger | `plans/aisoc_gap_closure_plan.plan.md` (rules for every phase, LLM calls) | `ci.yml` agents job (`test_deep_investigation_customer_tools.py` captures what the driver hands `ledger.record_event` at the ledger's own function boundary and asserts one `tool_call` row per call in the trace, carrying the tool name **and its arguments**, because "the ledger shows every call" means an auditor can answer which host was read. Sequence numbers are asserted distinct and at or above 10,000: `record_event` carries `ON CONFLICT (run_id, seq) DO NOTHING`, so a collision with the graph runner's own numbering would be a silently dropped row, which is worse than an error because the ledger still looks complete) | core | GATED | `run_with_tools` built a trace and nothing carried it anywhere durable, so this is new rather than newly gated. The write is best-effort by design: a ledger failure must not take a completed investigation down, and `ledger_rows` on the result reports how many rows landed so "nothing to record" is distinguishable from "the ledger is not configured" |
| Sustained throughput and event-to-alert latency are measured end to end, on a named machine, on a named date | `apps/docs/docs/operations/performance.md`; `docs/perf/results/*.json` | `perf.yml :: published-results` (`check_perf_results.py`: every committed result must carry `measured_at` beginning with an ISO date, a `hardware` block naming a CPU, a container runtime or a CI runner rather than a bare core count, `not_a_production_slo: true` and disclaimer prose; the filename must begin with its own measurement date; and the docs page must mention every date a result carries, so the page cannot drift into presenting old figures under a new heading. Self-tested by injecting each of those nine violations and requiring each to be caught) + `perf.yml :: end-to-end` (the harness drives the real Compose spine nightly with `--assert-eps-floor`, `--assert-p95-ceiling-ms` and `--assert-no-loss`) + `ci.yml :: python-test` (root) `test_load_harness_contract.py` | core | GATED | The floors are two orders of magnitude below the published figures, deliberately: a shared GitHub runner is not the machine the numbers came off, and a gate tuned near a measurement flaps and gets disabled. A green perf job proves no catastrophic regression, not that any published figure still holds |
| A performance figure that was not measured reads "not measured", never `0` | `scripts/perf/load_harness.py`; `apps/docs/docs/operations/performance.md` (kind per-pod usage) | `perf.yml :: published-results` (`check_perf_results.py` rejects an unmeasured metric that carries a `value` key and one that carries no reason, and separately asserts a **measured** zero survives, since zero dead letters and zero drained lag are real results) + `ci.yml :: python-test` (root) `test_load_harness_contract.py` (the serialised form is asserted, because the renderer downstream sees JSON rather than the dataclass) | core | GATED | The kind run genuinely has no per-pod CPU or memory figures: `kubectl top` needs metrics-server and kind ships none. The committed JSON records the absence and the page says so in the same paragraph as the table |
-| A fusion replica can be destroyed mid-stream with no event lost and none duplicated | `apps/docs/docs/operations/ha-deployment.md`; `apps/docs/docs/operations/performance.md` (failure injection) | `scripts/chaos/fusion_restart.py` (asserts against the `alerts` table in PostgreSQL, never against anything the replacement pod reports about itself: every sequence number ingest accepted must appear exactly once, and a missing one and a repeated one fail separately and are named). Self-tested in both directions, including the case where a loss and a duplicate cancel out in the row count. Run against the Kubernetes deployment on 2026-09-27; the result is committed at `docs/perf/results/2026-09-27-kind-chaos.json` and `perf.yml :: published-results` requires it to carry a verdict | core | GATED | The self-test and the committed result are gated; the **execution** against a live cluster is not on a CI trigger, because it needs a three-node cluster with two fusion replicas and published images. `docs/audit/REPOSITORY_REALITY.md` records the date and shape of the run that was performed rather than implying it happens continuously |
+| A fusion replica can be destroyed mid-stream with no event lost and none duplicated | `apps/docs/docs/operations/ha-deployment.md`; `apps/docs/docs/operations/performance.md` (failure injection) | `scripts/chaos/fusion_restart.py` (asserts against the `alerts` table in PostgreSQL, never against anything the replacement pod reports about itself: every sequence number ingest accepted must appear exactly once, and a missing one and a repeated one fail separately and are named). Self-tested in both directions, including the case where a loss and a duplicate cancel out in the row count. Run against the Kubernetes deployment on 2026-09-27; the result is committed at `docs/perf/results/2026-09-27-kind-chaos.json` and `perf.yml :: published-results` requires it to carry a verdict | core | GATED | The self-test is gated on every PR touching the harness, and the **execution** now runs live on the weekly `chaos.yml` schedule: `fusion-restart` boots the compose spine, pushes 3,000 events, destroys the fusion container at the halfway mark and asserts against the `alerts` table that every accepted sequence number appears exactly once -- loss and duplicates both. The previous caveat was that this needed a three-node cluster; it does not, because the property under test is the consumer's commit discipline and the sink's idempotency, and a single replica killed mid-stream exercises both. A multi-replica run additionally exercises rebalance, and `docs/audit/REPOSITORY_REALITY.md` still records the date and shape of the one hand-run cluster test rather than implying it recurs |
| A Helm install connects the event spine, rather than installing every object and consuming nothing | `infra/helm/aisoc/values-ha.yaml`; `apps/docs/docs/operations/ha-deployment.md` | `helm.yml :: render` (`KAFKA_BOOTSTRAP_SERVERS` is asserted present in the rendered ConfigMap and to resolve to the release's own brokers when the chart deploys them; a three-replica render is asserted to carry all three KRaft quorum voters; `ueba.enabled=false` is asserted to render no UEBA object, which it previously did) | full | GATED | Rendering is gated. That the brokers then form a quorum and fusion attaches was exercised on kind on 2026-09-27 and is recorded as such, not as a continuous check |
| A cross-service route this program adds is asserted against the URL the serving side actually serves | `GAP_CLOSURE_PROGRESS.md` (D16) | `ci.yml` api job (`test_agent_tools.py` parses `services/api/app/main.py`, `api/v1/router.py` and the endpoint module with `ast`, composes all three prefix levels, and asserts each literal the agents service builds is in the served set. Proven able to fail from **both** sides: dropping `/api/v1` from the client's path, and renaming the router's own prefix. The helper raises rather than returning an empty set, so a parser that stopped matching cannot certify nothing. Also asserts the `impact` field the API filters on exists on `LiveActionDescriptor` **and** is populated from the contract rather than left at its default) | core | GATED | Covers the two routes this phase adds and the actions discovery route it consumes. It is not a repository-wide scan: the general version would need every client's URL construction to be statically resolvable, and several build theirs from settings |
| A tenant can author an investigation skill in the console and it changes the plan on matching alerts | `apps/docs/docs/console/tenant-skills.md`; `plans/aisoc_gap_closure_plan.plan.md` (6.1, 6.2) | `ci.yml` agents job (`test_tenant_skill_investigation.py::test_done_when_a_skill_changes_the_investigation_plan_on_a_matching_alert`: one alert run twice through the real `run_deep_investigation`, everything held constant except whether the tenant has an active skill, asserting on the **system prompt the tool loop was handed** rather than on the verdict, because a verdict can be unchanged by a plan that did change. The built-in the alert would otherwise select is asserted by name, so "the skill won" and "nothing selected anything" are told apart) + `ci.yml` gates job (`scripts/check_tenant_skill_contract.py`) | core | GATED | A skill supplies the plan **and** the triage guidance. A skill that only changed the pivot plan could not be backtested at all: the replay grades triage verdicts, so the delta would read zero on every run |
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index f360248fa..ad0ce8b06 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -15476,6 +15476,55 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
+ /api/v1/retro-hunts/settings:
+ get:
+ tags:
+ - retro_hunts
+ summary: This tenant's retro-hunt opt-in and budget
+ operationId: get_retro_hunt_settings_api_v1_retro_hunts_settings_get
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RetroHuntSettingsOut'
+ security:
+ - HTTPBearer: []
+ put:
+ tags:
+ - retro_hunts
+ summary: Opt this tenant in or out of retro-hunt sweeps
+ description: 'Write the tenant''s half of the switch.
+
+
+ The budget columns are deliberately not writable here. They are the
+
+ operator''s ceiling on what one tenant can cost the deployment, and a tenant
+
+ that could raise its own ceiling would not have one.'
+ operationId: put_retro_hunt_settings_api_v1_retro_hunts_settings_put
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RetroHuntSettingsIn'
+ required: true
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RetroHuntSettingsOut'
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ security:
+ - HTTPBearer: []
/api/v1/report-builder/validate:
post:
tags:
@@ -29860,6 +29909,70 @@ components:
title: Audit Days
type: object
title: RetentionUpdate
+ RetroHuntSettingsIn:
+ properties:
+ enabled:
+ type: boolean
+ title: Enabled
+ description: Whether AiSOC may sweep this tenant's history at all.
+ lookback_days:
+ type: integer
+ maximum: 365.0
+ minimum: 1.0
+ title: Lookback Days
+ description: How far back a sweep looks. Bounded so no settings row can
+ express 'scan everything'.
+ default: 30
+ include_federated:
+ type: boolean
+ title: Include Federated
+ description: 'Whether to go beyond AiSOC''s own lake into connected SIEMs.
+ Separate from `enabled` because it is a separate cost: a lake sweep is
+ free to you and a SIEM sweep may not be.'
+ default: true
+ type: object
+ required:
+ - enabled
+ title: RetroHuntSettingsIn
+ RetroHuntSettingsOut:
+ properties:
+ enabled:
+ type: boolean
+ title: Enabled
+ lookback_days:
+ type: integer
+ title: Lookback Days
+ include_federated:
+ type: boolean
+ title: Include Federated
+ max_sweeps_per_hour:
+ type: integer
+ title: Max Sweeps Per Hour
+ max_sweeps_per_day:
+ type: integer
+ title: Max Sweeps Per Day
+ sweeps_this_hour:
+ type: integer
+ title: Sweeps This Hour
+ sweeps_today:
+ type: integer
+ title: Sweeps Today
+ sweeps_skipped_budget:
+ type: integer
+ title: Sweeps Skipped Budget
+ type: object
+ required:
+ - enabled
+ - lookback_days
+ - include_federated
+ - max_sweeps_per_hour
+ - max_sweeps_per_day
+ - sweeps_this_hour
+ - sweeps_today
+ - sweeps_skipped_budget
+ title: RetroHuntSettingsOut
+ description: What this tenant has agreed to, and what its budget has been spent
+ on.
ReviewAction:
properties:
action:
diff --git a/infra/compose/docker-compose.airgap.yml b/infra/compose/docker-compose.airgap.yml
index b4f6a9e63..4bfc26c8a 100644
--- a/infra/compose/docker-compose.airgap.yml
+++ b/infra/compose/docker-compose.airgap.yml
@@ -85,3 +85,28 @@ services:
# Clear external keys so no stray outbound calls can be made
OPENAI_API_KEY: ""
ANTHROPIC_API_KEY: ""
+
+ # `AISOC_AIRGAPPED` is read by seventeen modules across four services, and
+ # this overlay used to set it on `agents` alone -- so a deployment that
+ # believed it was air-gapped had exactly one service that knew.
+ #
+ # The API reads it in `core/airgap.py`, `llm_status.py`, `stix_taxii.py`,
+ # `translation.py`, `alert_explain.py`, the sandbox registry and the ES|QL
+ # and SPL runners; threatintel reads it to decide whether to fetch feeds at
+ # all. Each of those is a path that can otherwise make an outbound call on a
+ # host that is not supposed to have one, which is the whole point of the
+ # posture.
+ api:
+ environment:
+ AISOC_AIRGAPPED: "true"
+ OPENAI_API_KEY: ""
+ ANTHROPIC_API_KEY: ""
+
+ threatintel:
+ environment:
+ AISOC_AIRGAPPED: "true"
+
+ connectors:
+ environment:
+ AISOC_AIRGAPPED: "true"
+
diff --git a/scripts/check_perf_results.py b/scripts/check_perf_results.py
index 20f5361dc..232eb704e 100644
--- a/scripts/check_perf_results.py
+++ b/scripts/check_perf_results.py
@@ -41,12 +41,27 @@ import argparse
import json
import re
import sys
+from datetime import UTC, datetime
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from gate_toolkit import repo_root, self_test_main # noqa: E402
+#: The deployments `apps/docs/docs/operations/performance.md` publishes a table
+#: for. A results directory covering one of them is not the page being
+#: supported: a reader comparing the two tables is comparing one measurement
+#: against a claim with nothing behind it. Matched against the result
+#: filenames, which are `<date>-<deployment>-<scenario>.json`.
+REQUIRED_DEPLOYMENTS: tuple[str, ...] = ("compose", "kind")
+
+#: How old the newest result may be before the page is presenting a figure
+#: nobody has re-measured. A year is deliberately loose -- this hardware does
+#: not change weekly and a tight bound would red the build for a reason no
+#: contributor can act on -- but it is a bound, and there was none: a figure
+#: taken in 2026 would still have been presented as current in 2030.
+MAX_RESULT_AGE_DAYS = 400
+
RESULTS_DIR = Path("docs/perf/results")
PAGE = Path("apps/docs/docs/operations/performance.md")
@@ -163,9 +178,44 @@ def check(root: Path) -> tuple[int, list[str]]:
"A page that has drifted from the files presents figures under the wrong date"
)
+ _check_deployment_coverage(files, findings)
+ _check_freshness(dates, findings)
+
return len(files), findings
+def _check_deployment_coverage(files: list[Path], findings: list[str]) -> None:
+ """Every published table needs a measurement behind it."""
+ names = " ".join(p.name for p in files)
+ for deployment in REQUIRED_DEPLOYMENTS:
+ if deployment not in names:
+ findings.append(
+ f"no committed result names `{deployment}`, but {PAGE} publishes a table for it. "
+ "A published figure with no result file behind it is the thing this gate exists to stop"
+ )
+
+
+def _check_freshness(dates: set[str], findings: list[str]) -> None:
+ """A figure with no expiry eventually describes a machine nobody runs."""
+ if not dates:
+ return
+ newest = max(dates)
+ try:
+ measured = datetime.strptime(newest, "%Y-%m-%d").replace(tzinfo=UTC)
+ except ValueError:
+ findings.append(f"the newest `measured_at` is {newest!r}, which is not a date")
+ return
+
+ age = (datetime.now(UTC) - measured).days
+ if age > MAX_RESULT_AGE_DAYS:
+ findings.append(
+ f"the newest committed result is {age} days old (limit {MAX_RESULT_AGE_DAYS}). "
+ f"{PAGE} is presenting it as the current performance of the product. "
+ "Re-run scripts/perf/load_harness.py and commit the result, or move the figures "
+ "to a dated historical section that says they are not current"
+ )
+
+
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--check", action="store_true", help="accepted for symmetry; this gate always renders a verdict")
diff --git a/scripts/mypy_baseline.json b/scripts/mypy_baseline.json
index 43ee34077..db764970c 100644
--- a/scripts/mypy_baseline.json
+++ b/scripts/mypy_baseline.json
@@ -480,9 +480,6 @@
"app/connectors/okta.py": {
"override": 1
},
- "app/connectors/tenable.py": {
- "arg-type": 1
- },
"tests/test_pipeline_filter_rules.py": {
"arg-type": 1
},
diff --git a/scripts/perf/load_harness.py b/scripts/perf/load_harness.py
index 91dc8ae1a..3e0cfe8e7 100644
--- a/scripts/perf/load_harness.py
+++ b/scripts/perf/load_harness.py
@@ -439,6 +439,22 @@ def sample_resources(target: Target) -> ResourceSample:
return sample
+def _git_sha(root: Path) -> str | None:
+ """The commit under test, when this is a checkout rather than a tarball."""
+ try:
+ done = subprocess.run(
+ ["git", "-C", str(root), "rev-parse", "HEAD"],
+ capture_output=True,
+ text=True,
+ timeout=5,
+ check=False,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return None
+ sha = done.stdout.strip()
+ return sha or None
+
+
def build_report(
*,
target: Target,
@@ -453,6 +469,7 @@ def build_report(
resources: list[ResourceSample],
drain_seconds: float,
settled: bool,
+ shape: dict[str, Any] | None = None,
) -> dict[str, Any]:
accepted = summary.accepted
seen: dict[int, int] = {}
@@ -534,6 +551,15 @@ def build_report(
"clock_offset_seconds": clock_offset,
"clock_offset_spread_seconds": clock_spread,
"producer": summary.raw,
+ # The shape of the load, not just its outcome.
+ #
+ # `scripts/perf/throughput_claims.py` refuses to publish a
+ # throughput figure without the context that makes it
+ # interpretable -- batch size, payload size, how many hosts, which
+ # commit -- and that tool had no caller partly because the harness
+ # recorded none of it. A rate with no batch size beside it is not a
+ # measurement anyone can reproduce or compare.
+ **({"shape": shape} if shape else {}),
},
"metrics": {name: m.as_dict() for name, m in sorted(metrics.items())},
"resources": [{"at": datetime.fromtimestamp(s.at, tz=UTC).isoformat(timespec="seconds"), "containers": s.rows} for s in resources],
@@ -668,6 +694,18 @@ def main(argv: list[str] | None = None) -> int:
except (RuntimeError, ValueError) as exc:
dead_letters, dl_reason = None, f"dead-letter table unreadable: {exc}"
+ # Everything the harness genuinely knows about the load it just applied.
+ # `hosts` is 1 for compose by construction; for kubernetes it is whatever
+ # the operator passed, and is omitted rather than guessed when unknown.
+ shape: dict[str, Any] = {
+ "batch_size": int(args.batch),
+ "workers": int(args.workers),
+ "target_eps": int(args.target_eps),
+ "commit_sha": os.environ.get("GITHUB_SHA") or _git_sha(root) or "unknown",
+ }
+ if args.target == "compose":
+ shape["hosts"] = 1
+
report = build_report(
target=target,
summary=summary,
@@ -681,6 +719,7 @@ def main(argv: list[str] | None = None) -> int:
resources=resources,
drain_seconds=drain_seconds,
settled=settled,
+ shape=shape,
)
report["run"]["total_wall_seconds"] = time.time() - push_started
diff --git a/scripts/perf/throughput_claims.py b/scripts/perf/throughput_claims.py
index 11f6aa284..98fcdccd0 100644
--- a/scripts/perf/throughput_claims.py
+++ b/scripts/perf/throughput_claims.py
@@ -184,6 +184,62 @@ class ClaimSet:
return "\n".join(lines)
+#: What `load_harness.py` calls a metric, against what this file calls a claim.
+#:
+#: The two shipped speaking different languages and this file had no caller at
+#: all (fix-pass item 5.8), so the split it exists to publish was never
+#: computed from a real run. Only the claims the harness actually measures are
+#: mapped: `lake_eps` is absent because the harness does not time the
+#: ClickHouse archive separately, and inventing a value for it -- or quietly
+#: reusing the ingest figure -- would be the exact misattribution this file was
+#: written to prevent.
+HARNESS_METRIC_BY_CLAIM: dict[str, str] = {
+ "ingest_eps": "ingest_accepted_eps",
+ "alert_path_aps": "pipeline_eps",
+}
+
+
+def claims_from_harness(payload: dict[str, Any]) -> dict[str, Any]:
+ """Translate a `load_harness.py` result into this file's claim shape.
+
+ A metric the harness reports as unmeasured, or does not report at all, is
+ left out entirely rather than carried through as zero -- the harness emits
+ measured-with-a-value or unmeasured-with-a-reason and never both, and that
+ property has to survive the translation or a reader sees `0.00` where the
+ truth is "not measured".
+ """
+ metrics = payload.get("metrics") or {}
+ measured_at = str(payload.get("measured_at", ""))
+
+ # `run.shape` is what the harness recorded about the load it applied:
+ # batch size, workers, the commit, and the host count where it can know
+ # it. Carried through verbatim, because the whole point of the required
+ # context is that a reader can reproduce the number -- a context key
+ # invented here would defeat that more quietly than omitting it.
+ shape = dict((payload.get("run") or {}).get("shape") or {})
+ hardware = payload.get("hardware") or {}
+ context: dict[str, Any] = {
+ "deployment": str(payload.get("deployment", "")),
+ **shape,
+ }
+ if hardware.get("cpu"):
+ context["hardware"] = f"{hardware.get('cpu')} / {hardware.get('runtime_cpus', '?')} runtime CPUs"
+
+ out: dict[str, Any] = {}
+ for claim, metric_name in HARNESS_METRIC_BY_CLAIM.items():
+ metric = metrics.get(metric_name)
+ if not isinstance(metric, dict) or not metric.get("measured") or "value" not in metric:
+ continue
+ out[claim] = {
+ "value": float(metric["value"]),
+ "measured_at": measured_at,
+ # `0` is a legitimate context value, so filter on None rather
+ # than on falsiness.
+ "context": {k: v for k, v in context.items() if v is not None and v != ""},
+ }
+ return {"measurements": out}
+
+
def load_claims(payload: dict[str, Any]) -> ClaimSet:
out = ClaimSet()
for key, raw in (payload.get("measurements") or {}).items():
@@ -290,24 +346,54 @@ def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--self-test", action="store_true")
parser.add_argument("--claims", help="JSON file of measurements to validate and render")
+ parser.add_argument(
+ "--from-harness",
+ help=(
+ "A scripts/perf/load_harness.py result to translate and grade. The harness and "
+ "this file name the same quantities differently, which is why this file had no "
+ "caller: there was no way to point it at a real run."
+ ),
+ )
parser.add_argument("--check", action="store_true", help="exit non-zero on any problem")
+ parser.add_argument(
+ "--allow",
+ action="append",
+ default=[],
+ metavar="KIND",
+ help=(
+ "A problem kind to tolerate under --check, e.g. `unqualified-throughput`. "
+ "Every use needs a reason in the caller, and the tolerated problems are still "
+ "printed: the point is that a known gap stays visible rather than being "
+ "silently absorbed, which is how a gate stops meaning anything."
+ ),
+ )
args = parser.parse_args(argv)
if args.self_test:
return _self_test()
- if not args.claims:
+ if not args.claims and not args.from_harness:
print(ClaimSet().render())
return 0
- with open(args.claims, encoding="utf-8") as handle:
- claims = load_claims(json.load(handle))
+ if args.from_harness:
+ with open(args.from_harness, encoding="utf-8") as handle:
+ claims = load_claims(claims_from_harness(json.load(handle)))
+ else:
+ with open(args.claims, encoding="utf-8") as handle:
+ claims = load_claims(json.load(handle))
print(claims.render())
problems = claims.problems()
if problems:
print("\nProblems:")
for problem in problems:
print(f" {problem}")
- return 1 if (problems and args.check) else 0
+
+ allowed = set(args.allow or [])
+ blocking = [p for p in problems if not any(f"[{kind}]" in p for kind in allowed)]
+ if allowed:
+ tolerated = len(problems) - len(blocking)
+ print(f"\nTolerated by --allow {sorted(allowed)}: {tolerated} of {len(problems)}")
+ return 1 if (blocking and args.check) else 0
if __name__ == "__main__":
diff --git a/scripts/upgrade_fixture.sql b/scripts/upgrade_fixture.sql
index c044e66aa..f21ea02cd 100644
--- a/scripts/upgrade_fixture.sql
+++ b/scripts/upgrade_fixture.sql
@@ -50,15 +50,43 @@ VALUES
'pre-upgrade alert (info)', 'Seeded before the migration chain ran.', 'info', 'closed', true)
ON CONFLICT (id) DO NOTHING;
-INSERT INTO cases (id, tenant_id, case_number, title, description)
-VALUES (
- '22222222-2222-2222-2222-222222222222',
- '00000000-0000-0000-0000-0000000000aa',
- 'CASE-UPGRADE-0001',
- 'pre-upgrade case',
- 'Seeded before the migration chain ran, so a case-table migration meets a populated table.'
-)
-ON CONFLICT (id) DO NOTHING;
+-- The case table is named differently on either side of 083, which renames
+-- `cases` to `cases_pre_consolidation` and consolidates into `aisoc_cases`.
+-- This fixture runs against *the previous release's* schema, so which name
+-- exists depends on which release that is: a hard-coded `cases` worked while
+-- the previous release was 15.x and breaks the moment it is 16.x, under
+-- `ON_ERROR_STOP=1`, with `relation "cases" does not exist`.
+--
+-- Resolving the name at run time rather than pinning either one keeps the
+-- fixture working across the rename in both directions, which matters because
+-- this is the one test whose whole job is to meet an older schema.
+DO $$
+DECLARE
+ target text := COALESCE(
+ to_regclass('public.aisoc_cases')::text,
+ to_regclass('public.cases')::text
+ );
+BEGIN
+ IF target IS NULL THEN
+ RAISE EXCEPTION 'neither `aisoc_cases` nor `cases` exists; the previous '
+ 'release applied no case table at all, which is not a '
+ 'shape this fixture can seed';
+ END IF;
+
+ EXECUTE format(
+ 'INSERT INTO %I (id, tenant_id, case_number, title, description) '
+ 'VALUES ($1, $2, $3, $4, $5) ON CONFLICT (id) DO NOTHING',
+ target
+ )
+ USING '22222222-2222-2222-2222-222222222222'::uuid,
+ '00000000-0000-0000-0000-0000000000aa'::uuid,
+ 'CASE-UPGRADE-0001',
+ 'pre-upgrade case',
+ 'Seeded before the migration chain ran, so a case-table migration meets a populated table.';
+
+ RAISE NOTICE 'upgrade fixture seeded one case into %', target;
+END
+$$;
COMMIT;
diff --git a/services/agents/app/tools/sandbox.py b/services/agents/app/tools/sandbox.py
index 1cb4a8c9b..3a153bffe 100644
--- a/services/agents/app/tools/sandbox.py
+++ b/services/agents/app/tools/sandbox.py
@@ -111,7 +111,17 @@ async def lookup_file_hash(sha256: str, *, tenant_id: str = "") -> dict[str, Any
if response.status_code == 404:
return _could_not_check("No file-analysis provider is configured for this deployment.", digest)
if response.status_code == 403:
- return _could_not_check("Air-gapped mode permits local analysis providers only, and none is configured.", digest)
+ # Deliberately does not name air-gap mode. A 403 is equally an expired
+ # service token, a revoked scope, or a tenant policy that forbids file
+ # analysis, and naming the deployment's networking posture sends an
+ # analyst to debug a network while the fix is a credential. Say what is
+ # known -- the request was refused -- and name the candidates.
+ return _could_not_check(
+ "The file-analysis service refused the request (HTTP 403). That is an authorisation "
+ "problem: an expired or unscoped service token, a tenant policy forbidding file "
+ "analysis, or an air-gapped deployment with no local provider configured.",
+ digest,
+ )
if response.status_code >= 400:
logger.warning("sandbox_tool.refused", status_code=response.status_code)
return _could_not_check(f"The file-analysis service returned HTTP {response.status_code}.", digest)
diff --git a/services/agents/poetry.lock b/services/agents/poetry.lock
index adc5bbba8..355432bd8 100644
--- a/services/agents/poetry.lock
+++ b/services/agents/poetry.lock
@@ -809,6 +809,114 @@ files = [
[package.dependencies]
colorama = {version = "*", markers = "platform_system == \"Windows\""}
+[[package]]
+name = "clickhouse-driver"
+version = "0.2.11"
+description = "Python driver with native interface for ClickHouse"
+optional = false
+python-versions = "<4,>=3.9"
+groups = ["main"]
+files = [
+ {file = "clickhouse_driver-0.2.11-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:585e75a5237112a1264538c5a104d4336b0e0a4a2049bf711aaed103313614a2"},
+ {file = "clickhouse_driver-0.2.11-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:3138437728c0696aa89bcc8a84bb41463db0799740a62e81ec5a2e1efec886df"},
+ {file = "clickhouse_driver-0.2.11-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:26d98ef103f62b37958c65b2d32b479678056d5616aadfd8db7c2a3f4061fe84"},
+ {file = "clickhouse_driver-0.2.11-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:0b05513fe6f37f04ee9ea5d589261a655fa3233e6c969067cadae589756e545d"},
+ {file = "clickhouse_driver-0.2.11-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:aa78eb67b367e33c1eef69349ba3fe15d1b4945e79c3df0226e5b03273fda9a7"},
+ {file = "clickhouse_driver-0.2.11-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ab9ef48660a6d1d0c258bf0506135aa7bb0a1cee915e0a06ef9f7fef491a99cb"},
+ {file = "clickhouse_driver-0.2.11-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:d384b8b8a57a0b81b12d748de5c9f8f17cfa99aadedc5e495896cb4990b5e99e"},
+ {file = "clickhouse_driver-0.2.11-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:795055072ae9ec1b9b5476f00ffae1a507a0ec7223aa8816c205906c3d54d91c"},
+ {file = "clickhouse_driver-0.2.11-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:779853738be8782553bab548a482ada6bc27584961c1482eeb29bb477b17abe3"},
+ {file = "clickhouse_driver-0.2.11-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:a2005eb046beefc33d9d4fa0be534fd605728d9eace88adea6b7385cd008d6ef"},
+ {file = "clickhouse_driver-0.2.11-cp310-cp310-win32.whl", hash = "sha256:c25b22d55f65a3bd9b80f24c381c95a376d30a6be9b2bcd42b03e336bbdfacea"},
+ {file = "clickhouse_driver-0.2.11-cp310-cp310-win_amd64.whl", hash = "sha256:771199953c92e48fa9c19382c2425752e2a3c65299e19cc9a8b659d3d2e57f07"},
+ {file = "clickhouse_driver-0.2.11-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:01baad49a7855ffa08e1825df385cb740a9f1bbef9b7768661245f1e85db1d63"},
+ {file = "clickhouse_driver-0.2.11-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:e5b0a62a79282ee0c801bcdcaebe8aa8e5cf2baee4f285b47c4245825b2e8d5d"},
+ {file = "clickhouse_driver-0.2.11-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:370ca56a6a8511559d623e776b6297b7a1bd9285928b56942442e296a5ff20a1"},
+ {file = "clickhouse_driver-0.2.11-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4b2520f767ef65e94edf91a5817ca55d0f4edbebd7fac4b48db008fb871b26e2"},
+ {file = "clickhouse_driver-0.2.11-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b665f3e8b0890e86891f90a1044c08f399e3be8db438eedb1b05eea5c0d8ec6f"},
+ {file = "clickhouse_driver-0.2.11-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e4ba6f49ab6acad604f8b2aaf5540c73a56fd0307a8f448cbc9542ac36227424"},
+ {file = "clickhouse_driver-0.2.11-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:3dccff8ba12b76965fbaa602b92e67ad92e9fb87d560af6269c00f3354e3698a"},
+ {file = "clickhouse_driver-0.2.11-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:b372b13a70040f454b1cbbd5475c1141d5ed594f9220daf5cdf530c450203f12"},
+ {file = "clickhouse_driver-0.2.11-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:0c50fef33562f31c253a8d9e89941ad98efd8e04d684532f49ce3f44d56ec9fa"},
+ {file = "clickhouse_driver-0.2.11-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:a8167090007e4a2d128914e3eebbd203d5a729c57d17f6696b9c4badad691aa7"},
+ {file = "clickhouse_driver-0.2.11-cp311-cp311-win32.whl", hash = "sha256:af6b5bc8ad395650600fb1fe75decbd52a78b37b4face681123a5adcb31fd8c5"},
+ {file = "clickhouse_driver-0.2.11-cp311-cp311-win_amd64.whl", hash = "sha256:72e0e3107b9133abf16f34fc619b1b2f9b915735191cd310a814583ea342902d"},
+ {file = "clickhouse_driver-0.2.11-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:9efb601aad3af8cfbc452c057d3a6fce60b467ceb0784fb470174c06f2939614"},
+ {file = "clickhouse_driver-0.2.11-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:da7bd9a548f956ade42468059086faa442867f19be43dfe0e1f4ad762bd188f9"},
+ {file = "clickhouse_driver-0.2.11-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:22f256a00d1ab464cec4f595ccde6d6ec9b7e75f5b1d43ef923bb4f7401c0400"},
+ {file = "clickhouse_driver-0.2.11-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:b409b1dbd305683e66433e93227338b37dd605eff7c2fba0f1cf1933e236342e"},
+ {file = "clickhouse_driver-0.2.11-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:17b95c81fbfec69139a5c9e0c40031b81c5d68f1881eeccca7d5afa7c8b5ba98"},
+ {file = "clickhouse_driver-0.2.11-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:02a2ed14043f5f6e0d7dc46543a5e7a6b3f56cde0c2cf8a03900d026f3ed3734"},
+ {file = "clickhouse_driver-0.2.11-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:5f0b1dd55589c0922e61583c8f84930e74eb1b5083ac920197636b248799dcff"},
+ {file = "clickhouse_driver-0.2.11-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:99564f8b20b510a14dc893b5195d97ea11640c27c01106ffba4eb2e11757094a"},
+ {file = "clickhouse_driver-0.2.11-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:7b7c408a842998c9aebfc5e80e18c81d620e59bc1b8e4a85040891d9639b3d02"},
+ {file = "clickhouse_driver-0.2.11-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:5355dfa2753a9170cd44bf715e3d01c7cec84e922ff20e3af8aa26f65c00064c"},
+ {file = "clickhouse_driver-0.2.11-cp312-cp312-win32.whl", hash = "sha256:dcae25aa09f491d839453eb6c11f8ddd44cce86fa8df2ae7d02681bc32eb628f"},
+ {file = "clickhouse_driver-0.2.11-cp312-cp312-win_amd64.whl", hash = "sha256:88e7a3a1fde16aedaff93ae8b8a834b5ee9da1d47c8f8395fe5031206a9e26b1"},
+ {file = "clickhouse_driver-0.2.11-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:837e9d98f5648342b3de60e2351117c5a1de299672611e97be56cbdeadeec7a0"},
+ {file = "clickhouse_driver-0.2.11-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:4b8d99cfc4f80a4f59721d07fcce98c3093d9bf9a630a3b13165cd6aec86360b"},
+ {file = "clickhouse_driver-0.2.11-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:228b3f958a0ef92b2e667207ebd9859e44ae2795f56155357c45397bc0a8035d"},
+ {file = "clickhouse_driver-0.2.11-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:36dfee7609fdadf2cce4c82c9cdb4c28025326680213fc2a07d094d9b35953d5"},
+ {file = "clickhouse_driver-0.2.11-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4240194b095159e3341202eb686efedbcbca34bde94a5808bd6c2378bef6d2b4"},
+ {file = "clickhouse_driver-0.2.11-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:01cf396d22154f668ccd9a8f2cae7d66ba6f0634d668cd2822f763089af50741"},
+ {file = "clickhouse_driver-0.2.11-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:2c7063bf76a6a01f0bbf94541b438038910a0c649a3c058ec3479e012d447a0a"},
+ {file = "clickhouse_driver-0.2.11-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:dccea82c4ebba9058ca75a4858aef77b96ea0bde3d01f5bdff119c7d6b94c5ea"},
+ {file = "clickhouse_driver-0.2.11-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:c71493ac95d86e3104f9c4cb46b89dbb9262bbacd6b849b64acf32232910bb8b"},
+ {file = "clickhouse_driver-0.2.11-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:98a6678a57398e585351988c35ce57969a6b382f79a150634d229564744917c4"},
+ {file = "clickhouse_driver-0.2.11-cp313-cp313-win32.whl", hash = "sha256:60797bd36a404abee1fc82b177a3dccb8043ec1105146377cbbbde54f999b24a"},
+ {file = "clickhouse_driver-0.2.11-cp313-cp313-win_amd64.whl", hash = "sha256:4775c1582dc9e09e2381700b61955b7f860411cfd0502a6beeee35eb4bd880ad"},
+ {file = "clickhouse_driver-0.2.11-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:3e1c3b08907e836de894054d4c66bcf1415cd0a3fe94e3e2c865abe43a635c82"},
+ {file = "clickhouse_driver-0.2.11-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:eb88ef5ed671e260a6493d7f16f12e21a4f2d04afcfb58c3200324f9621dc553"},
+ {file = "clickhouse_driver-0.2.11-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:47b72c26343a2b946e589a4d5de259c3705f6969facfd4b283a6c5015fc67c92"},
+ {file = "clickhouse_driver-0.2.11-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:fd3b1af7c7174428007b20bbec4c60699758e20cf6beba45c61039762a06116a"},
+ {file = "clickhouse_driver-0.2.11-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5540cfbae18997e625c4fd8ec9875da46c816143c6456cab9a11adfaed38cc34"},
+ {file = "clickhouse_driver-0.2.11-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d7c9152bfdfd4ebe0fb3b1c4320f39e3b88c8f4f3c6b3db625a5c0cb5b86f955"},
+ {file = "clickhouse_driver-0.2.11-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:2fa0a4a72618f06c0ee308117253fe351161a562aea8b31641fcbf7d9ad6080d"},
+ {file = "clickhouse_driver-0.2.11-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:94593758fa36195fe56199422fe8188cabd6403c3950140cd8cffbd89af34f24"},
+ {file = "clickhouse_driver-0.2.11-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:aa3961a892b94aaa83571e773347d7f36ab5e1334c6711bfd63f611b88c4c541"},
+ {file = "clickhouse_driver-0.2.11-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:0e09e4f2cff823027a222c5bd8d9b3b3ca7d70f26ef0dccd2e496820280333ed"},
+ {file = "clickhouse_driver-0.2.11-cp314-cp314-win32.whl", hash = "sha256:688a2cd31a7fd87a9f2a1bb669a04874b5ae17bbca22a373610e84aa241b1e9a"},
+ {file = "clickhouse_driver-0.2.11-cp314-cp314-win_amd64.whl", hash = "sha256:0a67ce59def2e08cbda1cf12d9e8a7a6879cee8048ee46bbd415e9111033f775"},
+ {file = "clickhouse_driver-0.2.11-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:7f43f32c72e2b70c62a0bbbad3c19b06c8239230a554ff7950fe0064988e4b67"},
+ {file = "clickhouse_driver-0.2.11-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:74688c82c8ddbcf344f4af7c48199b572126ff9ecd862d998776b458d8f577d1"},
+ {file = "clickhouse_driver-0.2.11-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:07e037f0f6079e70ea2eeb38a580a36ca87430d653145e0ef9849f9aa0ba0aed"},
+ {file = "clickhouse_driver-0.2.11-cp39-cp39-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8ac74e150ca15dea9c53867a07e56453833ea1fc3e83fef46c716822968df621"},
+ {file = "clickhouse_driver-0.2.11-cp39-cp39-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f21911817ea750fb648e0757d84601bfe3d700510b8c93f998a52539c14add76"},
+ {file = "clickhouse_driver-0.2.11-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9e8c97567403a135b3487fd2d7213602611663f889ab4be2feba511e7fe2abcf"},
+ {file = "clickhouse_driver-0.2.11-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:76b4fbc48a7255595ba45b916b2e796f7359b87bd3becc490cbddaa02c6dbee7"},
+ {file = "clickhouse_driver-0.2.11-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:bb7bc2e8468ab98316318043fa63d82690b3ca16086cca8568d3accc3d54a309"},
+ {file = "clickhouse_driver-0.2.11-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:176aac7d24326226927fe704a378a83d628e44e090ae68e3a299dd0f19711999"},
+ {file = "clickhouse_driver-0.2.11-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:66c5f741cb3ecaad02854a15fa86407282bfe94d88625cc5fdcc06a35a541466"},
+ {file = "clickhouse_driver-0.2.11-cp39-cp39-win32.whl", hash = "sha256:57497fa989ea559b282fb149eb7f7ca871c31725755974b2d49fdb319918436b"},
+ {file = "clickhouse_driver-0.2.11-cp39-cp39-win_amd64.whl", hash = "sha256:1d151553513e64124f18bba5aaba4d9e717b66f5427798d0d96da196358c2dfd"},
+ {file = "clickhouse_driver-0.2.11-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:a7b3ade6fb1b40fadffc2e1531873490dbb0be9b500a1205c8f52ed3b8a5023a"},
+ {file = "clickhouse_driver-0.2.11-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:8d840b85abf4cbe24372be02819d0e88aebfbf9774b340f69ae427c589d08b07"},
+ {file = "clickhouse_driver-0.2.11-pp310-pypy310_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ed1c5309c294250c5110fbe1131d29dab18aee6483ae13468f6d32a324bc9698"},
+ {file = "clickhouse_driver-0.2.11-pp310-pypy310_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c26c5cb0e767a0e3e02efe75c3fa738484bba5d8a1e9e6855c57d18ee0d404d8"},
+ {file = "clickhouse_driver-0.2.11-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:f12a4ae2a54303eb7e972edf132a8565bd73bcf29091845abe77d3af1a4b1398"},
+ {file = "clickhouse_driver-0.2.11-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:609bc8cb854e5bb9935cd509e4bd5cf728f1c776a4c7467248d38c16063c87aa"},
+ {file = "clickhouse_driver-0.2.11-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:e724b5240e4db4d35846cfe2a3c41de5467fdeccf58a655eb8dc56d2f3c57c77"},
+ {file = "clickhouse_driver-0.2.11-pp311-pypy311_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3e79fcdd128288a9634d3f7165910d4df7f60b45844ba915f4fd9269c75f7565"},
+ {file = "clickhouse_driver-0.2.11-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ef4410642a37cf87e11e04cfbf7f5b814e6d90fe1b850f3f096a74dac9d24cb5"},
+ {file = "clickhouse_driver-0.2.11-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:e2fe477f41fc48ac9c4effa1fb3f8d4b95333f84deb811bad993e277a8ee69e2"},
+ {file = "clickhouse_driver-0.2.11-pp39-pypy39_pp73-macosx_10_15_x86_64.whl", hash = "sha256:ac639896798ad1b47dce6e1039a861ec8dee83914f0d64c6da8ea44a9b4db95d"},
+ {file = "clickhouse_driver-0.2.11-pp39-pypy39_pp73-macosx_11_0_arm64.whl", hash = "sha256:679f13d3bda68a0ce9667c52c6ddcca23c46900e274ddd0d5d344b5fda277ec9"},
+ {file = "clickhouse_driver-0.2.11-pp39-pypy39_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cba6bb18174d3829ff9ebbdbd05484fa794c5c53cd2aba13b68e488efc795c28"},
+ {file = "clickhouse_driver-0.2.11-pp39-pypy39_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ed99d91c0f436375cbe196dfba3e54234106312fa149db53e669f724d007b78e"},
+ {file = "clickhouse_driver-0.2.11-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:d39fc7bf89a918587928c24ed61068ccc98bafc76dc75d9007789a75719b0bfc"},
+ {file = "clickhouse_driver-0.2.11.tar.gz", hash = "sha256:1bec70343bde9e9a55c2254c5960d34c682ff7d60256589226d96c67a112f95a"},
+]
+
+[package.dependencies]
+pytz = "*"
+tzlocal = "*"
+
+[package.extras]
+arrow = ["pyarrow (>=8.0.0)"]
+lz4 = ["clickhouse-cityhash (>=1.0.2.6)", "lz4 (<=3.0.1) ; implementation_name == \"pypy\"", "lz4 ; implementation_name != \"pypy\""]
+numpy = ["numpy (>=1.12.0)", "pandas (>=0.24.0)"]
+zstd = ["clickhouse-cityhash (>=1.0.2.6)", "zstd"]
+
[[package]]
name = "colorama"
version = "0.4.6"
@@ -3974,6 +4082,18 @@ files = [
{file = "python_multipart-0.0.32.tar.gz", hash = "sha256:be54b7f3fa167bb83e4fcd936b887b708f4e57fe75911c02aebf53efaf8d938e"},
]
+[[package]]
+name = "pytz"
+version = "2026.5"
+description = "World timezone definitions, modern and historical"
+optional = false
+python-versions = "*"
+groups = ["main"]
+files = [
+ {file = "pytz-2026.5-py2.py3-none-any.whl", hash = "sha256:e658af3757f9e26a9d25dd2aff38335acd92bc9104f890a894b2c1ba28311b03"},
+ {file = "pytz-2026.5.tar.gz", hash = "sha256:fa23724b9c486543b9ff54a327ee7569ac83ade54bb9afd0fc18676620401c86"},
+]
+
[[package]]
name = "pywin32"
version = "312"
@@ -5995,4 +6115,4 @@ cffi = ["cffi (>=1.17,<2.0) ; platform_python_implementation != \"PyPy\" and pyt
[metadata]
lock-version = "2.1"
python-versions = "^3.11"
-content-hash = "b9871f34c6841a6ce92f46aedb02d486b40e52bc711d44559e59fbf4a010331c"
+content-hash = "366b1393502469082f347102d07c71a8bba347b8c479b53576dfaee79f89dfa5"
diff --git a/services/agents/pyproject.toml b/services/agents/pyproject.toml
index 6f7688104..cd818feb9 100644
--- a/services/agents/pyproject.toml
+++ b/services/agents/pyproject.toml
@@ -98,6 +98,13 @@ cryptography = ">=46,<51"
# 4.x line that ships Draft 2020-12 support.
jsonschema = ">=4.21,<5.0"
+# The hunting agent reads the ClickHouse lake. The image shipped without a
+# driver, so `lake-live.yml` installed one by hand before its tests -- which
+# means the workflow proved something about a package set the published
+# image does not have. Same range as services/api, kept equal by
+# scripts/check_dependency_pins.py.
+clickhouse-driver = "^0.2.8"
+
[tool.poetry.group.dev.dependencies]
# Floored at 9.0.3 for GHSA advisory coverage; the caret pins excluded it.
# pytest-asyncio is widened to match — 0.23 predates pytest 9 and the two
diff --git a/services/api/app/api/v1/endpoints/phishing.py b/services/api/app/api/v1/endpoints/phishing.py
index 467be35f9..1c2751026 100644
--- a/services/api/app/api/v1/endpoints/phishing.py
+++ b/services/api/app/api/v1/endpoints/phishing.py
@@ -210,6 +210,21 @@ async def _attachment_indicators(hashes: list[str]) -> list[dict[str, Any]]:
indicators.append({"kind": "hash", "value": digest, "note": "attachment could not be checked: analysis provider unavailable"})
continue
if not block:
+ # An empty analysis block means no provider answered -- which on a
+ # deployment with nothing configured is every attachment. Skipping
+ # produced a phishing verdict carrying no attachment indicator at
+ # all, and a reader takes the absence of a finding for a clean one.
+ # "Not checked" is not a verdict, and has to be said.
+ indicators.append(
+ {
+ "kind": "hash",
+ "value": digest,
+ "note": (
+ "attachment was not analysed: no file-analysis provider is configured "
+ "for this deployment. This is not a clean verdict."
+ ),
+ }
+ )
continue
for unchecked in block.get("could_not_check") or []:
indicators.append(
diff --git a/services/api/app/api/v1/endpoints/retro_hunts.py b/services/api/app/api/v1/endpoints/retro_hunts.py
new file mode 100644
index 000000000..1cbc9f721
--- /dev/null
+++ b/services/api/app/api/v1/endpoints/retro_hunts.py
@@ -0,0 +1,188 @@
+"""A tenant's own answer to "may AiSOC sweep my history, and how much".
+
+Migration 070 creates `retro_hunt_settings` with `enabled` defaulting to FALSE
+under a comment reading "Off until a tenant asks". Until this module existed
+there was nowhere to ask: no route and no console surface touched the table, so
+the only way to opt a tenant in was an UPDATE issued against the database by
+hand. A feature that needs a direct SQL statement to enable is not a feature a
+customer has.
+
+Two switches, deliberately
+--------------------------
+`RETRO_HUNT_ENABLED` is the *operator's* switch and decides whether the
+consumer runs at all. `enabled` here is the *tenant's*, and both must be on
+before a sweep touches anything. They are separate because they answer
+different questions: the operator is deciding whether this deployment spends
+the compute, and the tenant is deciding whether its own history may be read
+back over. Neither can speak for the other.
+
+`include_federated` is split out for the same reason one layer down. A sweep
+of AiSOC's own lake costs the customer nothing; a sweep that fans out into
+their connected SIEMs may bill them per query.
+"""
+
+from __future__ import annotations
+
+from typing import Annotated
+
+import structlog
+from fastapi import APIRouter, Depends
+from pydantic import BaseModel, Field
+from sqlalchemy import text
+
+from app.api.v1.deps import AuthUser, require_permission
+from app.db.rls import TenantDBSession
+
+logger = structlog.get_logger(__name__)
+
+router = APIRouter(prefix="/retro-hunts", tags=["retro_hunts"])
+
+#: The column CHECK is `BETWEEN 1 AND 365` and the sweep service clamps to the
+#: same ceiling. Stating it here too means a caller gets a 422 naming the bound
+#: rather than a 500 out of Postgres.
+MIN_LOOKBACK_DAYS = 1
+MAX_LOOKBACK_DAYS = 365
+
+
+class RetroHuntSettingsOut(BaseModel):
+ """What this tenant has agreed to, and what its budget has been spent on."""
+
+ enabled: bool
+ lookback_days: int
+ include_federated: bool
+ max_sweeps_per_hour: int
+ max_sweeps_per_day: int
+
+ sweeps_this_hour: int
+ sweeps_today: int
+ sweeps_skipped_budget: int
+ """Sweeps declined because a budget was exhausted. Surfaced because a
+ tenant whose budget is too small sees *silence*, which is indistinguishable
+ from a feed with nothing to report."""
+
+
+class RetroHuntSettingsIn(BaseModel):
+ enabled: bool = Field(description="Whether AiSOC may sweep this tenant's history at all.")
+ lookback_days: int = Field(
+ default=30,
+ ge=MIN_LOOKBACK_DAYS,
+ le=MAX_LOOKBACK_DAYS,
+ description="How far back a sweep looks. Bounded so no settings row can express 'scan everything'.",
+ )
+ include_federated: bool = Field(
+ default=True,
+ description=(
+ "Whether to go beyond AiSOC's own lake into connected SIEMs. Separate from `enabled` "
+ "because it is a separate cost: a lake sweep is free to you and a SIEM sweep may not be."
+ ),
+ )
+
+
+_SELECT = text(
+ """
+ SELECT enabled, lookback_days, include_federated,
+ max_sweeps_per_hour, max_sweeps_per_day,
+ sweeps_this_hour, sweeps_today, sweeps_skipped_budget
+ FROM retro_hunt_settings
+ WHERE tenant_id = CAST(:tenant_id AS uuid)
+ """
+)
+
+#: Insert-or-update in one statement. A tenant that has never opted in has no
+#: row at all, so a plain UPDATE would silently affect nothing and report
+#: success -- which is exactly the shape of defect this fix pass is about.
+_UPSERT = text(
+ """
+ INSERT INTO retro_hunt_settings (tenant_id, enabled, lookback_days, include_federated)
+ VALUES (CAST(:tenant_id AS uuid), :enabled, :lookback_days, :include_federated)
+ ON CONFLICT (tenant_id) DO UPDATE
+ SET enabled = EXCLUDED.enabled,
+ lookback_days = EXCLUDED.lookback_days,
+ include_federated = EXCLUDED.include_federated,
+ updated_at = now()
+ RETURNING enabled, lookback_days, include_federated,
+ max_sweeps_per_hour, max_sweeps_per_day,
+ sweeps_this_hour, sweeps_today, sweeps_skipped_budget
+ """
+)
+
+
+def _defaults() -> RetroHuntSettingsOut:
+ """What a tenant with no row has agreed to, which is nothing.
+
+ Returned rather than a 404 because "you have not opted in" is a state with
+ a correct answer, and a 404 would read as "retro-hunts do not exist here".
+ The values mirror the column defaults in migration 070.
+ """
+ return RetroHuntSettingsOut(
+ enabled=False,
+ lookback_days=30,
+ include_federated=True,
+ max_sweeps_per_hour=120,
+ max_sweeps_per_day=1000,
+ sweeps_this_hour=0,
+ sweeps_today=0,
+ sweeps_skipped_budget=0,
+ )
+
+
+ "/settings",
+ response_model=RetroHuntSettingsOut,
+ summary="This tenant's retro-hunt opt-in and budget",
+)
+async def get_retro_hunt_settings(
+ db: TenantDBSession,
+ user: Annotated[AuthUser, Depends(require_permission("settings:read"))],
+) -> RetroHuntSettingsOut:
+ row = (await db.execute(_SELECT, {"tenant_id": str(user.tenant_id)})).mappings().first()
+ if row is None:
+ return _defaults()
+ return RetroHuntSettingsOut(**dict(row))
+
+
+ "/settings",
+ response_model=RetroHuntSettingsOut,
+ summary="Opt this tenant in or out of retro-hunt sweeps",
+)
+async def put_retro_hunt_settings(
+ body: RetroHuntSettingsIn,
+ db: TenantDBSession,
+ user: Annotated[AuthUser, Depends(require_permission("settings:write"))],
+) -> RetroHuntSettingsOut:
+ """Write the tenant's half of the switch.
+
+ The budget columns are deliberately not writable here. They are the
+ operator's ceiling on what one tenant can cost the deployment, and a tenant
+ that could raise its own ceiling would not have one.
+ """
+ row = (
+ (
+ await db.execute(
+ _UPSERT,
+ {
+ "tenant_id": str(user.tenant_id),
+ "enabled": body.enabled,
+ "lookback_days": body.lookback_days,
+ "include_federated": body.include_federated,
+ },
+ )
+ )
+ .mappings()
+ .first()
+ )
+ await db.commit()
+
+ assert row is not None # RETURNING on an upsert always yields a row
+ logger.info(
+ "retro_hunts.settings_updated",
+ tenant_id=str(user.tenant_id),
+ enabled=bool(body.enabled),
+ lookback_days=int(body.lookback_days),
+ include_federated=bool(body.include_federated),
+ )
+ return RetroHuntSettingsOut(**dict(row))
+
+
+__all__ = ["router", "RetroHuntSettingsIn", "RetroHuntSettingsOut"]
diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.py
index 693c1f1c3..cdd8b1bc5 100644
--- a/services/api/app/api/v1/router.py
+++ b/services/api/app/api/v1/router.py
@@ -75,6 +75,7 @@ from app.api.v1.endpoints import (
replay,
report_builder,
reports,
+ retro_hunts,
rule_tuning,
sandbox,
saved_hunts,
@@ -296,6 +297,7 @@ api_router.include_router(posture.router)
api_router.include_router(easm.router)
api_router.include_router(identity_graph.router)
api_router.include_router(reports.router)
+api_router.include_router(retro_hunts.router)
# Wave 7 — customizable dashboard / report builder
api_router.include_router(report_builder.router)
diff --git a/services/api/app/models/case.py b/services/api/app/models/case.py
index eda0647b5..a3266be9a 100644
--- a/services/api/app/models/case.py
+++ b/services/api/app/models/case.py
@@ -72,33 +72,76 @@ class Case(Base):
class CaseTask(Base):
- __tablename__ = "case_tasks"
+ """A task on a case.
+
+ The table is `aisoc_case_tasks`. This model named `case_tasks`, which no
+ migration creates, so every write through it raised
+ `UndefinedTableError` -- on the demo seed and on the KEV exposure path,
+ both of which are reached only with data that the rest of the product had
+ no way to produce. Fix-pass item 5.2 found it by creating that data.
+
+ Four of the declared columns did not exist either. `description`,
+ `completed_at` and a uuid `assigned_to_id` are gone; the real table stores
+ the assignee as text and the due date as `due_at`, and carries
+ `depends_on_task_id` and `blocked_reason`, which the model never had.
+ Attribute names that call sites already use are preserved by mapping them
+ onto the real column.
+ """
+
+ __tablename__ = "aisoc_case_tasks"
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
case_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("aisoc_cases.id"), nullable=False, index=True)
- tenant_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False, index=True)
- title: Mapped[str] = mapped_column(String(500), nullable=False)
- description: Mapped[str | None] = mapped_column(Text, nullable=True)
- status: Mapped[str] = mapped_column(String(20), default="pending")
- assigned_to_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True)
- due_date: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
- completed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
+ tenant_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True, index=True)
+ title: Mapped[str] = mapped_column(Text, nullable=False)
+ #: `todo` / `in_progress` / `done` -- what `aisoc_case_tasks_status_check`
+ #: allows. The model defaulted to "pending", which the constraint rejects,
+ #: so every insert through it would have failed even once the table name
+ #: was right.
+ status: Mapped[str] = mapped_column(Text, default="todo", nullable=False)
+ assignee: Mapped[str | None] = mapped_column(Text, nullable=True)
+ due_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
+ created_by: Mapped[str | None] = mapped_column(Text, nullable=True)
+ depends_on_task_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True)
+ blocked_reason: Mapped[str | None] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
+ updated_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), default=lambda: datetime.now(UTC), onupdate=lambda: datetime.now(UTC)
+ )
case: Mapped["Case"] = relationship("Case", back_populates="tasks")
class CaseTimeline(Base):
- __tablename__ = "case_timeline"
+ __tablename__ = "case_timeline_events"
+ """Same defect as `CaseTask` above: this named `case_timeline`, a table no
+ migration creates. The real one is `case_timeline_events`, and it stores
+ the text as `summary`, the payload as `detail`, and the actor as an
+ `actor_id` plus an `actor_type` rather than a `user_id` and an
+ `is_automated` flag.
+
+ The Python attribute names the three call sites use are kept and mapped
+ onto the real columns; `is_automated` becomes a property over `actor_type`
+ because the two carry the same fact and storing both invites them to
+ disagree."""
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
case_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("aisoc_cases.id"), nullable=False, index=True)
tenant_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False)
event_type: Mapped[str] = mapped_column(String(50), nullable=False) # comment/status_change/assignment/etc
- content: Mapped[str] = mapped_column(Text, nullable=False)
- event_metadata: Mapped[dict] = mapped_column("metadata", JSONB, default=dict)
- user_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True)
- is_automated: Mapped[bool] = mapped_column(default=False)
+ content: Mapped[str] = mapped_column("summary", Text, nullable=False)
+ event_metadata: Mapped[dict | None] = mapped_column("detail", JSONB, default=dict, nullable=True)
+ user_id: Mapped[uuid.UUID | None] = mapped_column("actor_id", UUID(as_uuid=True), nullable=True)
+ actor_type: Mapped[str | None] = mapped_column(String(32), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC), index=True)
+ @property
+ def is_automated(self) -> bool:
+ """Whether a machine wrote this event.
+
+ Derived rather than stored: the real table records `actor_type`, and a
+ second column meaning the same thing is a column that can disagree
+ with it."""
+ return (self.actor_type or "").lower() in {"system", "agent", "automation"}
+
case: Mapped["Case"] = relationship("Case", back_populates="timeline")
diff --git a/services/api/app/scripts/seed_demo.py b/services/api/app/scripts/seed_demo.py
index a70bfe9c1..abc698e39 100644
--- a/services/api/app/scripts/seed_demo.py
+++ b/services/api/app/scripts/seed_demo.py
@@ -2025,7 +2025,7 @@ async def _seed_realistic_incidents(session, tenant: Tenant) -> tuple[int, int,
"incident_key": incident["key"],
"alerts": [str(a.id) for a in incident_alerts],
},
- is_automated=True,
+ actor_type="system",
created_at=case_when,
)
)
@@ -2047,7 +2047,7 @@ async def _seed_realistic_incidents(session, tenant: Tenant) -> tuple[int, int,
"actor": "playbook-engine",
"playbook_run": playbook_run,
},
- is_automated=True,
+ actor_type="system",
created_at=case_when + timedelta(minutes=2),
)
)
@@ -2355,7 +2355,7 @@ async def _seed_alerts_and_cases(session, tenant: Tenant, *, alert_count: int =
event_type="created",
content="Case opened by AI alert fusion service.",
event_metadata={"actor": "system", "alerts": case.alert_ids},
- is_automated=True,
+ actor_type="system",
created_at=case.created_at,
)
)
@@ -2363,9 +2363,8 @@ async def _seed_alerts_and_cases(session, tenant: Tenant, *, alert_count: int =
CaseTask(
case_id=case.id,
tenant_id=case.tenant_id,
- title="Triage and contain",
- description="Confirm scope, isolate affected hosts, capture artifacts.",
- status="pending",
+ title="Triage and contain: confirm scope, isolate affected hosts, capture artifacts",
+ status="todo",
created_at=case.created_at,
)
)
@@ -3148,7 +3147,7 @@ async def _seed_demo_quick(
"connector_sources": incident["connector_sources"],
"alerts": [str(a.id) for a in incident_alerts],
},
- is_automated=True,
+ actor_type="system",
created_at=case_when,
)
)
diff --git a/services/api/app/services/lake_hunt.py b/services/api/app/services/lake_hunt.py
index 98f15e110..9ff104db1 100644
--- a/services/api/app/services/lake_hunt.py
+++ b/services/api/app/services/lake_hunt.py
@@ -30,6 +30,7 @@ to use it.
from __future__ import annotations
import json
+import re
from dataclasses import dataclass
from typing import Any
@@ -61,6 +62,10 @@ _FIELD_TO_COLUMN: dict[str, str] = {
"file.path": "file_path",
"file.hash.sha256": "hash_sha256",
"event.severity": "severity_id",
+ # Every one of the 68 shipped hunts filters on a bare `source`, and the
+ # lake stores it as `connector_type`. Without this line the corpus had
+ # zero resolvable fields against the lake.
+ "source": "connector_type",
"event.category": "connector_type",
"event.provider": "connector_type",
"network.protocol": "protocol",
@@ -107,6 +112,17 @@ class HuntCompileError(ValueError):
"""The IR could not be compiled into a safe lake query."""
+#: A vendor field name the lake has no column for, but which the stored
+#: payload may carry. Deliberately narrow: an identifier, nothing else.
+#:
+#: The name is bound as a query parameter, never interpolated, so a hunt
+#: cannot inject SQL through a field name -- but it is *also* validated here,
+#: because "the value is escaped" is not a reason to accept a field name that
+#: cannot be a field name, and refusing is cheaper than reasoning about every
+#: downstream use.
+_PAYLOAD_FIELD = re.compile(r"^[A-Za-z][A-Za-z0-9_]{0,63}$")
+
+
def _column_for(field: str) -> str | None:
if field in _FIELD_TO_COLUMN:
return _FIELD_TO_COLUMN[field]
@@ -116,6 +132,35 @@ def _column_for(field: str) -> str | None:
return None
+def _payload_expression(field: str, key: str) -> str | None:
+ """Reach a vendor field inside the stored payload, or give up honestly.
+
+ The lake keeps the whole original event in `raw_payload`, so a field with
+ no dedicated column is not necessarily out of reach: of the 114 distinct
+ fields the shipped hunt corpus filters on, exactly **zero** resolved to a
+ lake column, and most of the remainder are vendor names like `EventID`,
+ `CommandLine` or `eventName` that the payload does carry.
+
+ Three paths are tried because Windows nests its payload one level below
+ anything flat: `EventData` and `System`. That nesting is the same thing
+ that once made 2,173 Sigma rules unable to fire, and it is worth reaching
+ for rather than declaring the field unsupported.
+
+ Returns `None` for anything that is not a plain identifier, so the caller
+ reports it as unsupported rather than guessing.
+ """
+ if not _PAYLOAD_FIELD.match(field):
+ return None
+ name = f"%({key}_field)s"
+ return (
+ "coalesce("
+ f"nullIf(JSONExtractString(raw_payload, {name}), ''), "
+ f"nullIf(JSONExtractString(raw_payload, 'EventData', {name}), ''), "
+ f"nullIf(JSONExtractString(raw_payload, 'System', {name}), '')"
+ ")"
+ )
+
+
def _predicate(column: str, op: str, value: str, key: str) -> tuple[str, Any]:
"""Build one parameterised predicate. Never interpolates the value."""
placeholder = f"%({key})s"
@@ -134,7 +179,12 @@ def _predicate(column: str, op: str, value: str, key: str) -> tuple[str, Any]:
pattern = value if "%" in value else f"%{value}%"
return f"{column} ILIKE %({key})s", pattern
if op in _SCALAR_OPS:
- return f"{column} {_SCALAR_OPS[op]} {placeholder}", _coerce(column, value)
+ # A payload expression always yields a string, so the numeric coercion
+ # that `_coerce` applies by column name must not fire on it -- a bound
+ # integer against `JSONExtractString` matches nothing and would read as
+ # "no results" rather than as a type mismatch.
+ bound = value if column.startswith("coalesce(") else _coerce(column, value)
+ return f"{column} {_SCALAR_OPS[op]} {placeholder}", bound
raise HuntCompileError(f"unsupported operator {op!r}")
@@ -180,11 +230,17 @@ def compile_hunt(
unsupported: list[str] = []
for index, (field, op, value) in enumerate(getattr(intents, "filters", []) or []):
+ key = f"f{index}"
column = _column_for(str(field))
if column is None:
- unsupported.append(str(field))
- continue
- key = f"f{index}"
+ # No dedicated column, but the lake keeps the whole original event
+ # in `raw_payload`, so a vendor field name is often still reachable.
+ expression = _payload_expression(str(field), key)
+ if expression is None:
+ unsupported.append(str(field))
+ continue
+ column = expression
+ params[f"{key}_field"] = str(field)
clause, bound = _predicate(column, str(op), str(value), key)
where.append(clause)
params[key] = bound
diff --git a/services/api/app/services/retro_hunt/kev_exposure.py b/services/api/app/services/retro_hunt/kev_exposure.py
index f93ea9341..5b619ab14 100644
--- a/services/api/app/services/retro_hunt/kev_exposure.py
+++ b/services/api/app/services/retro_hunt/kev_exposure.py
@@ -309,22 +309,31 @@ async def _open_case_task(
case_type="vulnerability_exposure",
priority="high" if any(c in {"critical", "high"} for _n, c in assets) else "medium",
severity="high",
- status="open",
+ # `new`, not `open`. The `aisoc_cases_status_check` constraint allows
+ # exactly new/triaged/investigating/contained/resolved/closed, so the
+ # previous value meant this insert raised a CheckViolationError on
+ # every deployment -- which nothing noticed, because reaching it needs
+ # a tenant with real vulnerability data, and until fix-pass item 5.2
+ # the only writer of that table was a route a human calls by hand.
+ status="new",
tags=["kev", f"cve:{cve}", f"feed:{feed_source}"],
)
db.add(case)
await db.flush()
+ # `aisoc_case_tasks` has no `description` column, so the detail lives in
+ # the case description above and the task carries the instruction. The
+ # model used to declare one, against a table name no migration creates, so
+ # this insert had never succeeded.
task = CaseTask(
case_id=case.id,
tenant_id=tenant_id,
- title=f"Patch or mitigate {cve} on {len(assets)} asset(s)",
- description=(
- f"CISA lists {cve} as actively exploited. Your vulnerability data shows "
- f"{len(assets)} unremediated finding(s). Patch, mitigate, or record why the "
- f"affected assets are not reachable."
+ title=(
+ f"Patch or mitigate {cve} on {len(assets)} asset(s): CISA lists it as actively "
+ f"exploited and your scan data shows unremediated findings"
),
- status="pending",
+ status="todo",
+ created_by=feed_source,
)
db.add(task)
await db.flush()
diff --git a/services/api/tests/test_lake_hunts_can_reach_the_corpus_fields.py b/services/api/tests/test_lake_hunts_can_reach_the_corpus_fields.py
new file mode 100644
index 000000000..a192101bc
--- /dev/null
+++ b/services/api/tests/test_lake_hunts_can_reach_the_corpus_fields.py
@@ -0,0 +1,145 @@
+"""The shipped hunt corpus can actually be compiled against the lake.
+
+Fix pass item 5.3. See `plans/aisoc_fix_pass_plan.plan.md`.
+
+What was wrong
+--------------
+The README publishes "68-hunt YAML library, replayed against tenant events" as
+**Stable**. Measured against `lake_hunt.py`'s field map, the corpus used 114
+distinct field names and **zero** of them resolved to a lake column. All 243
+field uses were reported unsupported, so every hunt either returned an
+unfiltered table or nothing -- the library was not replayable against tenant
+events at all.
+
+Two causes. Every one of the 68 hunts filters on a bare `source`, which the
+lake stores as `connector_type` and the map did not mention. And the remaining
+113 are vendor names -- `EventID`, `CommandLine`, `eventName` -- that have no
+dedicated column but which the stored payload carries: the lake keeps the whole
+original event in `raw_payload`, and nothing reached into it.
+
+What "resolvable" means here, precisely
+---------------------------------------
+That the compiler can build a predicate for the field, not that the predicate
+will match. A payload extraction finds the field if the event carries it, and
+that is a property of the connector's output, not of this compiler. The honest
+claim is therefore "compiles against the lake", and the README says that rather
+than implying every hunt returns results.
+"""
+
+from __future__ import annotations
+
+import collections
+import glob
+from pathlib import Path
+
+import pytest
+import yaml
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+
+
+def _corpus_fields() -> collections.Counter:
+ counts: collections.Counter = collections.Counter()
+
+ def walk(node: object) -> None:
+ if isinstance(node, dict):
+ field = node.get("field")
+ if isinstance(field, str):
+ counts[field] += 1
+ for value in node.values():
+ walk(value)
+ elif isinstance(node, list):
+ for value in node:
+ walk(value)
+
+ for path in glob.glob(str(REPO_ROOT / "hunts" / "*.yaml")):
+ walk(yaml.safe_load(Path(path).read_text(encoding="utf-8")) or {})
+ return counts
+
+
+def _resolvable(field: str) -> bool:
+ from app.services.lake_hunt import _column_for, _payload_expression
+
+ return _column_for(field) is not None or _payload_expression(field, "k") is not None
+
+
+class TestTheCorpusResolves:
+ def test_every_field_the_corpus_filters_on_can_be_compiled(self) -> None:
+ fields = _corpus_fields()
+ assert fields, "no fields found in hunts/*.yaml; the corpus moved"
+
+ unresolved = sorted(f for f in fields if not _resolvable(f))
+
+ assert not unresolved, f"{len(unresolved)} of {len(fields)} field names cannot be compiled against the lake: {unresolved[:10]}"
+
+ def test_source_maps_to_the_column_the_lake_actually_has(self) -> None:
+ """All 68 hunts filter on it, and the lake calls it `connector_type`."""
+ from app.services.lake_hunt import _column_for
+
+ assert _column_for("source") == "connector_type"
+
+
+class TestTheFallbackCannotBeUsedToInject:
+ @pytest.mark.parametrize(
+ "field",
+ [
+ "evil') OR 1=1 --",
+ "a';DROP TABLE aisoc.raw_events;--",
+ "raw_payload, 'x') = '' OR (JSONExtractString(raw_payload",
+ "",
+ " ",
+ "1startswithadigit",
+ "has-a-hyphen",
+ "a" * 200,
+ ],
+ )
+ def test_a_field_name_that_is_not_an_identifier_is_refused(self, field: str) -> None:
+ """Refused, not escaped.
+
+ The name is bound as a query parameter and never interpolated, so this
+ is belt and braces -- but a field name that cannot be a field name has
+ no business reaching the query builder, and refusing is cheaper than
+ reasoning about every downstream use of the string.
+ """
+ from app.services.lake_hunt import _payload_expression
+
+ assert _payload_expression(field, "k") is None, f"{field!r} was accepted as a payload field"
+
+ def test_an_accepted_field_name_is_bound_not_interpolated(self) -> None:
+ """The negative control on the mechanism: the expression must contain a
+ placeholder, and must not contain the field name itself."""
+ from app.services.lake_hunt import _payload_expression
+
+ expression = _payload_expression("EventID", "f0")
+
+ assert expression is not None
+ assert "%(f0_field)s" in expression
+ assert "EventID" not in expression, "the field name was interpolated into the SQL"
+
+ def test_the_windows_nestings_are_reached(self) -> None:
+ """`EventData` and `System` are where Windows puts its payload, one
+ level below anything flat -- the same nesting that once made 2,173
+ Sigma rules unable to fire."""
+ from app.services.lake_hunt import _payload_expression
+
+ expression = _payload_expression("CommandLine", "f0")
+
+ assert expression is not None
+ assert "'EventData'" in expression
+ assert "'System'" in expression
+
+
+class TestTheCompilerStillRefusesWhatItShould:
+ def test_a_compiled_hunt_binds_the_payload_field_name(self) -> None:
+ from app.services.lake_hunt import compile_hunt
+
+ class _Intents:
+ filters = [("EventID", "==", "4625")]
+ group_by: list[str] = []
+ limit = 10
+
+ compiled = compile_hunt(_Intents(), tenant_id="11111111-1111-1111-1111-111111111111", hours=24)
+
+ assert compiled.params.get("f0_field") == "EventID"
+ assert "EventID" not in compiled.sql
+ assert not compiled.unsupported_fields
diff --git a/services/api/tests/test_retro_hunt_can_be_turned_on.py b/services/api/tests/test_retro_hunt_can_be_turned_on.py
new file mode 100644
index 000000000..239e79b8b
--- /dev/null
+++ b/services/api/tests/test_retro_hunt_can_be_turned_on.py
@@ -0,0 +1,92 @@
+"""Retro-hunts can be switched on by a deployment and by a tenant.
+
+Fix pass item 5.1. See `plans/aisoc_fix_pass_plan.plan.md`.
+
+What was wrong
+--------------
+Two halves of one switch, and neither could be reached.
+
+The *operator* half is `RETRO_HUNT_ENABLED`, which `main.py` consults to decide
+whether to start `retro_hunt_consumer.run_forever`. It appeared in **no compose
+file and no `.env.example`**, and compose passes only the variables it names --
+so on every `make up` deployment the consumer did not start and no amount of
+setting the variable in a shell could change that.
+
+The *tenant* half is `retro_hunt_settings.enabled`, which migration 070 creates
+with `DEFAULT FALSE` under a comment reading "Off until a tenant asks". There
+was no route and no console surface through which a tenant could ask, so the
+only way to turn it on was an UPDATE against the database by hand.
+
+A feature that needs a direct SQL statement to enable is not a feature a
+customer has.
+
+What this file asserts
+----------------------
+Both halves, from the artefacts a deployment actually reads: the compose file
+and the API's own route table.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+import yaml
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+
+
+def _compose_service(name: str) -> dict:
+ compose = yaml.safe_load((REPO_ROOT / "docker-compose.yml").read_text(encoding="utf-8"))
+ service = compose["services"].get(name)
+ assert service is not None, f"docker-compose.yml has no `{name}` service"
+ return service
+
+
+class TestTheOperatorHalf:
+ def test_compose_passes_the_switch_through_to_the_api(self) -> None:
+ """Compose passes only what it names, so an unnamed variable is
+ unreachable however the host environment is set."""
+ env = _compose_service("api").get("environment") or {}
+ names = set(env) if isinstance(env, dict) else {entry.split("=", 1)[0] for entry in env}
+
+ assert "RETRO_HUNT_ENABLED" in names, (
+ "docker-compose.yml does not pass RETRO_HUNT_ENABLED to the api service, "
+ "so the retro-hunt consumer can never start on a compose deployment"
+ )
+
+ def test_env_example_documents_it(self) -> None:
+ """`.env.example` is where an operator looks for what can be set. A
+ switch absent from it is a switch nobody knows exists."""
+ text = (REPO_ROOT / ".env.example").read_text(encoding="utf-8")
+
+ assert "RETRO_HUNT_ENABLED" in text, ".env.example does not mention RETRO_HUNT_ENABLED"
+
+ def test_it_defaults_off(self) -> None:
+ """The negative control. A sweep over a tenant's history is a cost and
+ a privacy decision, so the fix must not turn it on for everyone."""
+ env = _compose_service("api").get("environment") or {}
+ raw = env["RETRO_HUNT_ENABLED"] if isinstance(env, dict) else ""
+
+ assert ":-false}" in str(raw) or str(raw).strip() in {"false", "${RETRO_HUNT_ENABLED:-false}"}, (
+ f"RETRO_HUNT_ENABLED defaults to {raw!r}; it must default off"
+ )
+
+
+class TestTheTenantHalf:
+ @pytest.fixture(scope="class")
+ def paths(self) -> dict:
+ from app.main import app
+
+ return app.openapi()["paths"]
+
+ def test_a_tenant_can_read_its_retro_hunt_settings(self, paths: dict) -> None:
+ assert "/api/v1/retro-hunts/settings" in paths, (
+ "no route exposes retro_hunt_settings, so a tenant's only way to opt in is an UPDATE against the database by hand"
+ )
+ assert "get" in paths["/api/v1/retro-hunts/settings"]
+
+ def test_a_tenant_can_change_them(self, paths: dict) -> None:
+ operations = paths.get("/api/v1/retro-hunts/settings", {})
+
+ assert "put" in operations, "the settings route is read-only, so opting in is still impossible"
diff --git a/services/api/tests/test_sandbox_settings_reach_the_api.py b/services/api/tests/test_sandbox_settings_reach_the_api.py
new file mode 100644
index 000000000..0a9763034
--- /dev/null
+++ b/services/api/tests/test_sandbox_settings_reach_the_api.py
@@ -0,0 +1,106 @@
+"""Sandbox and air-gap configuration reaches the API, and absence is said out loud.
+
+Fix pass item 5.4. See `plans/aisoc_fix_pass_plan.plan.md`.
+
+Three defects, one theme: the deployment could not configure file analysis, and
+when it was unconfigured the product did not say so.
+
+1. **Compose passed neither `AISOC_AIRGAPPED` nor any sandbox provider
+ setting to the `api` service.** Compose passes only the variables it names,
+ so an operator with a CAPEv2 appliance had no way to point the product at
+ it, and an operator running air-gapped had no way to tell the API.
+
+2. **The air-gap overlay set the flag on `agents` alone.** `AISOC_AIRGAPPED`
+ is read by seventeen modules across four services, including the API's own
+ `airgap.py`, `llm_status.py`, `stix_taxii.py` and the sandbox registry. A
+ deployment that believed it was air-gapped had one service that knew.
+
+3. **With only the mock provider, phishing recorded nothing.**
+ `_attachment_indicators` does `if not block: continue`, so an unconfigured
+ deployment produced a verdict with no attachment indicator at all -- which a
+ reader takes as "the attachment was checked and was clean". The honest
+ output is "no analysis provider is configured", which is not a verdict.
+
+A fourth, in the agent's tool: a 403 was reported as *"Air-gapped mode permits
+local analysis providers only"* whatever the cause. A 403 is also what an
+expired token, a revoked scope or a tenant-policy refusal returns, so the model
+and the analyst were told the deployment's networking posture when the real
+answer was an authorisation problem they could fix.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+import yaml
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+
+
+def _env(compose: Path, service: str) -> set[str]:
+ doc = yaml.safe_load(compose.read_text(encoding="utf-8"))
+ block = (doc.get("services") or {}).get(service) or {}
+ env = block.get("environment") or {}
+ return set(env) if isinstance(env, dict) else {e.split("=", 1)[0] for e in env}
+
+
+class TestTheDeploymentCanConfigureFileAnalysis:
+ def test_compose_passes_the_airgap_flag_to_the_api(self) -> None:
+ names = _env(REPO_ROOT / "docker-compose.yml", "api")
+
+ assert "AISOC_AIRGAPPED" in names, (
+ "docker-compose.yml does not pass AISOC_AIRGAPPED to the api service, so an "
+ "air-gapped deployment has no way to tell the service that reads it in nine modules"
+ )
+
+ @pytest.mark.parametrize(
+ "variable",
+ ["AISOC_CAPEV2_BASE_URL", "MALWAREANALYZER_BASE_URL", "MALWAREANALYZER_API_KEY"],
+ )
+ def test_compose_passes_the_sandbox_provider_settings(self, variable: str) -> None:
+ """Without these an operator with a real sandbox cannot point the
+ product at it, and the registry falls back to the mock, which knows
+ nothing."""
+ names = _env(REPO_ROOT / "docker-compose.yml", "api")
+
+ assert variable in names, f"docker-compose.yml does not pass {variable} to the api service"
+
+ def test_the_airgap_overlay_sets_the_flag_on_every_service_that_reads_it(self) -> None:
+ overlay = REPO_ROOT / "infra" / "compose" / "docker-compose.airgap.yml"
+ doc = yaml.safe_load(overlay.read_text(encoding="utf-8"))
+ services = doc.get("services") or {}
+
+ carrying = {name for name, block in services.items() if "AISOC_AIRGAPPED" in ((block or {}).get("environment") or {})}
+
+ # The API reads it in `core/airgap.py`, `llm_status.py`, `stix_taxii.py`,
+ # `translation.py`, the sandbox registry and three runners.
+ assert "api" in carrying, (
+ f"the air-gap overlay sets AISOC_AIRGAPPED on {sorted(carrying)} only; the API reads it "
+ "in nine modules and would not know the deployment is air-gapped"
+ )
+
+
+class TestAnUnconfiguredDeploymentSaysSo:
+ def test_an_empty_analysis_block_is_recorded_not_skipped(self) -> None:
+ """`if not block: continue` produced a verdict with no attachment
+ indicator, which reads as "checked and clean" rather than "not
+ checked"."""
+ source = (REPO_ROOT / "services" / "api" / "app" / "api" / "v1" / "endpoints" / "phishing.py").read_text(encoding="utf-8")
+
+ assert "if not block:\n continue" not in source, (
+ "phishing still skips an empty analysis block, so an unconfigured deployment "
+ "returns a phishing verdict that looks like the attachment was cleared"
+ )
+
+
+class TestTheAgentToolDoesNotGuessWhyItWasRefused:
+ def test_a_403_is_not_reported_as_air_gap_mode(self) -> None:
+ source = (REPO_ROOT / "services" / "agents" / "app" / "tools" / "sandbox.py").read_text(encoding="utf-8")
+
+ offending = "Air-gapped mode permits local analysis providers only, and none is configured."
+ assert offending not in source, (
+ "a 403 is still reported as air-gap mode. A 403 is also an expired token, a revoked "
+ "scope or a tenant-policy refusal, and naming the wrong one sends an analyst to debug "
+ "networking when the fix is a credential"
+ )
diff --git a/services/connectors/app/connectors/tenable.py b/services/connectors/app/connectors/tenable.py
index 3097ca45c..af33fe75f 100644
--- a/services/connectors/app/connectors/tenable.py
+++ b/services/connectors/app/connectors/tenable.py
@@ -18,6 +18,49 @@ from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Fiel
logger = structlog.get_logger()
+#: Tenable.io publishes the CVSSv3 severity ladder as 0=Info .. 4=Critical.
+#: Shared by the alert path and the vulnerability path so the two cannot drift,
+#: and mapped straight onto AiSOC's five tiers: collapsing Tenable's Critical
+#: into `high` is the exact defect the connector conventions name.
+_SEVERITY_BY_INT: dict[Any, str] = {0: "info", 1: "low", 2: "medium", 3: "high", 4: "critical"}
+
+
+def _first(value: Any) -> str | None:
+ """Tenable returns these as lists even when there is one of them."""
+ if isinstance(value, list):
+ return str(value[0]) if value else None
+ return str(value) if value else None
+
+
+#: Plugin detail is one HTTP request per plugin against the customer's own
+#: scanner, so the fan-out is capped. An uncapped loop over a workbench with a
+#: few thousand plugins is a denial of service aimed at the customer, which is
+#: worse than not having the feature.
+MAX_PLUGIN_LOOKUPS = 60
+
+
+def _plugin_attribute(detail: dict[str, Any], name: str) -> str | None:
+ """Read one attribute out of Tenable's plugin-detail shape.
+
+ Attributes arrive as a list of `{attribute_name, attribute_value}` rather
+ than a mapping, and a plugin can repeat a name (several CVEs on one
+ plugin), so this returns the first and `_plugin_attributes` returns all.
+ """
+ for attribute in detail.get("attributes") or []:
+ if attribute.get("attribute_name") == name:
+ value = attribute.get("attribute_value")
+ return str(value) if value is not None else None
+ return None
+
+
+def _plugin_attributes(detail: dict[str, Any], name: str) -> list[str]:
+ return [
+ str(a.get("attribute_value"))
+ for a in detail.get("attributes") or []
+ if a.get("attribute_name") == name and a.get("attribute_value") is not None
+ ]
+
+
class TenableConnector(BaseConnector):
"""Tenable.io VM."""
@@ -110,14 +153,129 @@ class TenableConnector(BaseConnector):
logger.warning("tenable.fetch_exception", error=str(exc))
return []
+ async def fetch_vulnerability_findings(self) -> list[dict[str, Any]]:
+ """Per-asset findings carrying a CVE, which is what a vulnerability row needs.
+
+ `fetch_alerts` above calls `/workbenches/vulnerabilities`, which returns
+ plugin-level *aggregates*: no asset, no CVE. `normalize()` sets
+ `host: None` outright. So the alert path could never have produced a
+ row in `asset_vulnerabilities`, and that table's only writer was a
+ route a human calls by hand -- which is why
+ `_tenant_has_vulnerability_data` answered "nobody has told me what you
+ run" for every Tenable tenant, and KEV exposure reported nothing
+ forever.
+
+ Two calls, because Tenable splits the data:
+
+ * `/workbenches/assets/vulnerabilities` gives the asset and which
+ plugins fired on it.
+ * `/plugins/plugin/{id}` gives that plugin's CVE list.
+
+ The second is per plugin, so it is capped and the distinct plugin set
+ is resolved once rather than once per asset.
+ """
+ assets = await self._fetch_asset_workbench()
+ if not assets:
+ return []
+
+ plugin_ids: list[int] = []
+ for asset in assets:
+ for vuln in asset.get("vulnerabilities") or []:
+ pid = vuln.get("plugin_id")
+ if isinstance(pid, int) and pid not in plugin_ids:
+ plugin_ids.append(pid)
+
+ if len(plugin_ids) > MAX_PLUGIN_LOOKUPS:
+ logger.info(
+ "tenable.plugin_lookup_capped",
+ distinct_plugins=len(plugin_ids),
+ cap=MAX_PLUGIN_LOOKUPS,
+ )
+ plugin_ids = plugin_ids[:MAX_PLUGIN_LOOKUPS]
+
+ cves_by_plugin: dict[int, list[str]] = {}
+ titles_by_plugin: dict[int, str] = {}
+ for pid in plugin_ids:
+ detail = await self._fetch_plugin_detail(pid)
+ if detail is None:
+ continue
+ raw_cves = _plugin_attributes(detail, "cve")
+ cves_by_plugin[pid] = [c for c in raw_cves if c.upper().startswith("CVE-")]
+ titles_by_plugin[pid] = str(detail.get("name") or f"Tenable plugin {pid}")
+
+ findings: list[dict[str, Any]] = []
+ for asset in assets:
+ hostname = _first(asset.get("fqdn")) or _first(asset.get("netbios_name"))
+ ip = _first(asset.get("ipv4"))
+ for vuln in asset.get("vulnerabilities") or []:
+ pid = vuln.get("plugin_id")
+ if not isinstance(pid, int):
+ continue
+ for cve in cves_by_plugin.get(pid, []):
+ findings.append(
+ {
+ "cve_id": cve,
+ # Tenable's ladder is 0..4 and 4 is Critical. The
+ # five-tier map is shared with `normalize()` so a
+ # genuine Critical is not collapsed into `high`.
+ "severity": _SEVERITY_BY_INT.get(vuln.get("severity"), "info"),
+ "hostname": hostname,
+ "ip_address": ip,
+ "asset_ref": str(asset.get("id") or "") or None,
+ "title": titles_by_plugin.get(pid, f"Tenable plugin {pid}"),
+ "plugin_id": pid,
+ "source": "tenable_io",
+ }
+ )
+ return findings
+
+ async def _fetch_asset_workbench(self) -> list[dict[str, Any]]:
+ try:
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.get(
+ f"{self._base}/workbenches/assets/vulnerabilities",
+ headers=self._headers(),
+ )
+ if resp.status_code != 200:
+ logger.warning(
+ "tenable.asset_workbench_failed",
+ status=resp.status_code,
+ body=resp.text[:300],
+ )
+ return []
+ return list((resp.json() or {}).get("assets") or [])
+ except Exception as exc:
+ logger.warning("tenable.asset_workbench_exception", error=str(exc))
+ return []
+
+ async def _fetch_plugin_detail(self, plugin_id: int) -> dict[str, Any] | None:
+ try:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.get(
+ f"{self._base}/plugins/plugin/{plugin_id}",
+ headers=self._headers(),
+ )
+ if resp.status_code != 200:
+ # One plugin that will not resolve must not lose the whole
+ # sweep; the findings it would have carried are simply
+ # absent, and the count is visible in the log.
+ logger.info(
+ "tenable.plugin_detail_unavailable",
+ plugin_id=plugin_id,
+ status=resp.status_code,
+ )
+ return None
+ return dict(resp.json() or {})
+ except Exception as exc:
+ logger.info("tenable.plugin_detail_exception", plugin_id=plugin_id, error=str(exc))
+ return None
+
def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
# Tenable.io exposes the CVSSv3 severity ladder (0=Info, 1=Low,
# 2=Medium, 3=High, 4=Critical). Mirror it directly into AiSOC's
# five-tier ladder so genuine Critical vulnerabilities are not
# silently downgraded to High.
- sev_int = raw.get("severity")
- sev_map = {0: "info", 1: "low", 2: "medium", 3: "high", 4: "critical"}
- sev = sev_map.get(sev_int, "info")
+ sev = _SEVERITY_BY_INT.get(raw.get("severity"), "info")
return {
"source": "tenable_io",
"category": "cloud",
diff --git a/services/connectors/app/scheduler.py b/services/connectors/app/scheduler.py
index 97e94182b..f5be5bd5f 100644
--- a/services/connectors/app/scheduler.py
+++ b/services/connectors/app/scheduler.py
@@ -488,6 +488,18 @@ class ConnectorScheduler:
await self._record_failure(target.id)
return
+ # A scanner's findings are asset state, not events. The alert path
+ # above carries neither the asset nor the CVE a vulnerability row
+ # needs, which is why `asset_vulnerabilities` stayed empty on every
+ # deployment and KEV exposure answered "no vulnerability data" for
+ # every tenant whose scanner was Tenable. Connectors that can answer
+ # the question opt in by defining `fetch_vulnerability_findings`.
+ #
+ # Deliberately outside the `try` around `fetch_alerts` and in its own:
+ # a scanner sync that fails must not cost the poll its events, and a
+ # fetch that fails must not be reported as a successful sync.
+ await self._sync_vulnerability_findings(connector, target)
+
# Normalize defensively: connectors *should* normalize themselves
# in fetch_alerts, but we double-tap so a connector that returns
# raw events still produces consistent shapes downstream.
@@ -779,6 +791,54 @@ class ConnectorScheduler:
connector_id,
)
+ async def _sync_vulnerability_findings(self, connector: Any, target: Any) -> None:
+ """Materialise a scanner's findings as vulnerability rows, if it has any.
+
+ Fix-pass item 5.2. Written here rather than posted to the API because
+ the service principal is deliberately read-only -- its own docstring
+ says anything that changes the database is absent on purpose -- and
+ this service already holds both a database engine and the tenant id it
+ is polling for.
+ """
+ fetch = getattr(connector, "fetch_vulnerability_findings", None)
+ if fetch is None:
+ return
+
+ try:
+ findings = await fetch()
+ except Exception:
+ logger.exception(
+ "connector.scheduler.vulnerability_fetch_failed id=%s type=%s",
+ target.id,
+ target.connector_type,
+ )
+ return
+
+ if not findings:
+ return
+
+ try:
+ from app.vulnerabilities import sync_findings
+
+ counts = await sync_findings(
+ self._engine,
+ tenant_id=target.tenant_id,
+ findings=findings,
+ )
+ logger.info(
+ "connector.scheduler.vulnerabilities_synced id=%s inserted=%d touched=%d skipped=%d",
+ target.id,
+ counts["findings_inserted"],
+ counts["findings_touched"],
+ counts["skipped"],
+ )
+ except Exception:
+ logger.exception(
+ "connector.scheduler.vulnerability_sync_failed id=%s type=%s",
+ target.id,
+ target.connector_type,
+ )
+
async def _record_failure(self, connector_id: uuid.UUID) -> None:
if self._engine is None: # pragma: no cover
return
diff --git a/services/connectors/app/vulnerabilities.py b/services/connectors/app/vulnerabilities.py
new file mode 100644
index 000000000..4f51779ec
--- /dev/null
+++ b/services/connectors/app/vulnerabilities.py
@@ -0,0 +1,231 @@
+"""Materialise scanner findings as vulnerability rows.
+
+Fix pass item 5.2. See `plans/aisoc_fix_pass_plan.plan.md`.
+
+Why this lives in the connectors service
+----------------------------------------
+`asset_vulnerabilities` had exactly one writer in the tree: a route a human
+calls by hand. The Tenable connector modelled its findings as alerts, so the
+table stayed empty on every deployment whose vulnerability data came from a
+scanner -- and `_tenant_has_vulnerability_data` in the API's `kev_exposure`
+exists precisely to tell "you are not exposed" apart from "nobody has told me
+what you run". KEV exposure therefore answered *no data*, forever.
+
+The obvious fix is for the connector to POST to the API, and it is the wrong
+one: the service principal is a deliberately read-only credential whose own
+docstring says "anything that changes state at a vendor or in the database is
+absent on purpose". Granting it a write verb to close this would undo that
+decision for every route at once.
+
+This service already owns a database engine (it decrypts connector credentials
+at poll time) and already holds the tenant id the scheduler is polling for. So
+the write happens here, under the tenant it was polled for, with no new
+credential and no widened principal.
+
+Matching, and why there is no ON CONFLICT
+-----------------------------------------
+Neither `assets` nor `asset_vulnerabilities` carries a natural unique key, so
+there is nothing to conflict on. Matching is explicit: an asset by
+`(tenant_id, name)` and a finding by `(tenant_id, asset_id, cve_id, source)`.
+A re-poll moves `last_found` and leaves `first_found` alone, because "when did
+we first see this" is the question an exposure window is asked.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime
+from typing import Any
+
+import structlog
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import AsyncEngine
+
+logger = structlog.get_logger(__name__)
+
+#: One poll must not be able to write an unbounded number of rows: a
+#: misconfigured scan filter would otherwise turn a 5-minute schedule into a
+#: write amplifier against the shared database.
+MAX_FINDINGS_PER_SYNC = 2_000
+
+_FIND_ASSET = text(
+ """
+ SELECT id FROM assets
+ WHERE tenant_id = CAST(:tenant_id AS uuid)
+ AND lower(name) = lower(:name)
+ LIMIT 1
+ """
+)
+
+_INSERT_ASSET = text(
+ """
+ INSERT INTO assets (id, tenant_id, asset_type, name, fqdn, ip_addresses,
+ criticality, tags, last_seen, first_seen, metadata,
+ created_at, updated_at)
+ VALUES (:id, CAST(:tenant_id AS uuid), 'host', :name, :fqdn,
+ :ips, 'medium', CAST(ARRAY[]::text[] AS text[]), :now, :now,
+ CAST(:metadata AS jsonb), :now, :now)
+ RETURNING id
+ """
+)
+
+_FIND_VULN = text(
+ """
+ SELECT id FROM asset_vulnerabilities
+ WHERE tenant_id = CAST(:tenant_id AS uuid)
+ AND asset_id = CAST(:asset_id AS uuid)
+ AND cve_id = :cve_id
+ AND source = :source
+ LIMIT 1
+ """
+)
+
+_INSERT_VULN = text(
+ """
+ INSERT INTO asset_vulnerabilities
+ (id, tenant_id, asset_id, cve_id, title, description, severity,
+ is_exploited, source, external_id, first_found, last_found,
+ metadata, created_at)
+ VALUES (:id, CAST(:tenant_id AS uuid), CAST(:asset_id AS uuid), :cve_id,
+ :title, :description, :severity, false, :source, :external_id,
+ :now, :now, CAST(:metadata AS jsonb), :now)
+ """
+)
+
+#: `first_found` is deliberately untouched. A re-poll of a finding that has
+#: been present for a month must not reset the clock an exposure window is
+#: measured against.
+#:
+#: The `tenant_id` predicate is not redundant with the tenant-scoped SELECT
+#: that produced the id. How a row was *addressed* is irrelevant to whether the
+#: write is scoped -- an id arriving from anywhere else, now or after a later
+#: edit, would reach another tenant's row. `scripts/check_tenant_query_predicates.py`
+#: makes that the rule rather than a convention.
+_TOUCH_VULN = text(
+ """
+ UPDATE asset_vulnerabilities
+ SET last_found = :now,
+ severity = :severity,
+ title = :title
+ WHERE id = CAST(:id AS uuid)
+ AND tenant_id = CAST(:tenant_id AS uuid)
+ """
+)
+
+
+async def sync_findings(
+ engine: AsyncEngine,
+ *,
+ tenant_id: uuid.UUID | str,
+ findings: list[dict[str, Any]],
+ now: datetime | None = None,
+) -> dict[str, int]:
+ """Write one poll's findings for one tenant. Returns what it did.
+
+ Counts are returned rather than logged alone because "the sync ran" and
+ "the sync wrote something" are different facts, and only the second one
+ means KEV exposure will have an answer.
+ """
+ import json
+
+ if not findings:
+ return {"assets_created": 0, "findings_inserted": 0, "findings_touched": 0, "skipped": 0}
+
+ stamp = now or datetime.now(UTC)
+ tenant = str(tenant_id)
+
+ if len(findings) > MAX_FINDINGS_PER_SYNC:
+ logger.warning(
+ "vulnerabilities.sync_truncated",
+ tenant_id=tenant,
+ received=len(findings),
+ cap=MAX_FINDINGS_PER_SYNC,
+ )
+ findings = findings[:MAX_FINDINGS_PER_SYNC]
+
+ assets_created = inserted = touched = skipped = 0
+ asset_ids: dict[str, uuid.UUID] = {}
+
+ async with engine.begin() as conn:
+ for finding in findings:
+ cve = str(finding.get("cve_id") or "").strip().upper()
+ hostname = str(finding.get("hostname") or "").strip()
+ if not cve.startswith("CVE-") or not hostname:
+ # A finding with no CVE cannot be matched against KEV, and one
+ # with no host cannot be attached to an asset. Counted rather
+ # than dropped silently.
+ skipped += 1
+ continue
+
+ key = hostname.lower()
+ asset_id = asset_ids.get(key)
+ if asset_id is None:
+ row = (await conn.execute(_FIND_ASSET, {"tenant_id": tenant, "name": hostname})).first()
+ if row is not None:
+ asset_id = row[0]
+ else:
+ new_id = uuid.uuid4()
+ ip = finding.get("ip_address")
+ await conn.execute(
+ _INSERT_ASSET,
+ {
+ "id": new_id,
+ "tenant_id": tenant,
+ "name": hostname,
+ "fqdn": hostname,
+ # `ip_addresses` is text[], so asyncpg wants a
+ # Python list rather than a jsonb string or a
+ # Postgres array literal.
+ "ips": [str(ip)] if ip else [],
+ "now": stamp,
+ "metadata": json.dumps({"discovered_by": finding.get("source") or "scanner"}),
+ },
+ )
+ asset_id = new_id
+ assets_created += 1
+ asset_ids[key] = asset_id
+
+ source = str(finding.get("source") or "scanner")
+ existing = (
+ await conn.execute(
+ _FIND_VULN,
+ {"tenant_id": tenant, "asset_id": str(asset_id), "cve_id": cve, "source": source},
+ )
+ ).first()
+
+ params = {
+ "severity": str(finding.get("severity") or "info"),
+ "title": str(finding.get("title") or cve),
+ "now": stamp,
+ }
+ if existing is not None:
+ await conn.execute(_TOUCH_VULN, {**params, "id": str(existing[0]), "tenant_id": tenant})
+ touched += 1
+ else:
+ await conn.execute(
+ _INSERT_VULN,
+ {
+ **params,
+ "id": uuid.uuid4(),
+ "tenant_id": tenant,
+ "asset_id": str(asset_id),
+ "cve_id": cve,
+ "description": finding.get("title"),
+ "source": source,
+ "external_id": str(finding.get("plugin_id") or "") or None,
+ "metadata": json.dumps({"plugin_id": finding.get("plugin_id")}),
+ },
+ )
+ inserted += 1
+
+ result = {
+ "assets_created": assets_created,
+ "findings_inserted": inserted,
+ "findings_touched": touched,
+ "skipped": skipped,
+ }
+ logger.info("vulnerabilities.synced", tenant_id=tenant, **result)
+ return result
+
+
+__all__ = ["sync_findings", "MAX_FINDINGS_PER_SYNC"]
diff --git a/services/connectors/tests/test_tenable_writes_vulnerability_findings.py b/services/connectors/tests/test_tenable_writes_vulnerability_findings.py
new file mode 100644
index 000000000..f7aab3a22
--- /dev/null
+++ b/services/connectors/tests/test_tenable_writes_vulnerability_findings.py
@@ -0,0 +1,174 @@
+"""Tenable findings reach the vulnerability table, so KEV exposure has data.
+
+Fix pass item 5.2. See `plans/aisoc_fix_pass_plan.plan.md`.
+
+What was wrong
+--------------
+`asset_vulnerabilities` had exactly one writer in the whole tree:
+`POST /api/v1/assets/vulnerabilities`, a route a human calls by hand. The
+Tenable connector -- the only vulnerability scanner AiSOC integrates -- modelled
+its findings as **alerts** and never wrote a vulnerability row.
+
+`_tenant_has_vulnerability_data` in `kev_exposure.py` exists precisely to tell
+"you are not exposed" apart from "nobody has told me what you run", and it
+queries that table. So for any tenant whose vulnerability data came from
+Tenable, KEV exposure answered *"no vulnerability data"* forever, however many
+findings the connector had polled.
+
+The data was not merely unwritten, it was never fetched: `fetch_alerts` calls
+`/workbenches/vulnerabilities`, which returns plugin-level aggregates carrying
+neither a CVE nor an asset. `normalize()` sets `host: None` outright. A row in
+`asset_vulnerabilities` needs an asset and a CVE, and the connector asked
+Tenable for neither.
+
+What this file asserts
+----------------------
+The connector against a stubbed Tenable: that it asks for per-asset findings
+and for the plugin details that carry CVEs, and that it emits findings a
+vulnerability row can be built from. The fan-out is capped, because a plugin
+list of any size would otherwise become one HTTP request per plugin against a
+customer's scanner.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+
+def _connector():
+ from app.connectors.tenable import TenableConnector
+
+ return TenableConnector(
+ access_key="ak-test",
+ secret_key="sk-test",
+ )
+
+
+class _StubTenable:
+ """Enough of Tenable.io to answer the three calls the connector makes."""
+
+ def __init__(self) -> None:
+ self.paths: list[str] = []
+
+ async def get(self, url: str, **_: object):
+ self.paths.append(url)
+
+ if url.endswith("/workbenches/assets/vulnerabilities"):
+ return _Response(
+ 200,
+ {
+ "assets": [
+ {
+ "id": "asset-1",
+ "fqdn": ["web-01.corp.example"],
+ "ipv4": ["198.51.100.10"],
+ "severities": [{"name": "critical", "count": 2}],
+ "vulnerabilities": [
+ {"plugin_id": 12345, "severity": 4, "count": 1},
+ {"plugin_id": 67890, "severity": 3, "count": 1},
+ ],
+ }
+ ]
+ },
+ )
+
+ if "/plugins/plugin/12345" in url:
+ return _Response(
+ 200,
+ {
+ "id": 12345,
+ "name": "Log4Shell",
+ "attributes": [
+ {"attribute_name": "cve", "attribute_value": "CVE-2021-44228"},
+ {"attribute_name": "cvss3_base_score", "attribute_value": "10.0"},
+ ],
+ },
+ )
+
+ if "/plugins/plugin/67890" in url:
+ return _Response(
+ 200,
+ {
+ "id": 67890,
+ "name": "Some other finding",
+ "attributes": [{"attribute_name": "cve", "attribute_value": "CVE-2023-1111"}],
+ },
+ )
+
+ return _Response(404, {})
+
+
+class _Response:
+ def __init__(self, status_code: int, payload: dict) -> None:
+ self.status_code = status_code
+ self._payload = payload
+ self.text = str(payload)
+
+ def json(self) -> dict:
+ return self._payload
+
+
+def stubbed(monkeypatch):
+ stub = _StubTenable()
+
+ class _Client:
+ async def __aenter__(self):
+ return stub
+
+ async def __aexit__(self, *_):
+ return False
+
+ monkeypatch.setattr("app.connectors.tenable.httpx.AsyncClient", lambda **_: _Client())
+ return stub
+
+
+class TestItAsksTenableForWhatAVulnerabilityRowNeeds:
+ @pytest.mark.asyncio
+ async def test_it_fetches_per_asset_findings(self, stubbed) -> None:
+ """`/workbenches/vulnerabilities` returns plugin aggregates with no
+ asset at all, so no row could ever name what is affected."""
+ await _connector().fetch_vulnerability_findings()
+
+ assert any("/workbenches/assets/vulnerabilities" in p for p in stubbed.paths), (
+ f"never asked for per-asset findings; called {stubbed.paths}"
+ )
+
+ @pytest.mark.asyncio
+ async def test_it_fetches_the_plugin_details_that_carry_cves(self, stubbed) -> None:
+ """A KEV entry is a CVE. Tenable publishes the CVE list on the plugin,
+ not on the workbench row, so without this call every finding is
+ anonymous and `check_exposure` can match nothing."""
+ await _connector().fetch_vulnerability_findings()
+
+ assert any("/plugins/plugin/12345" in p for p in stubbed.paths), f"never asked for plugin details; called {stubbed.paths}"
+
+
+class TestTheFindingsCanBecomeRows:
+ @pytest.mark.asyncio
+ async def test_each_finding_names_an_asset_and_a_cve(self, stubbed) -> None:
+ findings = await _connector().fetch_vulnerability_findings()
+
+ assert findings, "no findings produced from a workbench with two"
+ log4shell = next((f for f in findings if f["cve_id"] == "CVE-2021-44228"), None)
+ assert log4shell is not None, f"the Log4Shell finding is missing: {findings}"
+ assert log4shell["hostname"] == "web-01.corp.example"
+ assert log4shell["severity"] == "critical"
+
+ @pytest.mark.asyncio
+ async def test_the_severity_ladder_is_preserved(self, stubbed) -> None:
+ """Tenable's 4 is Critical. Collapsing it into `high` is the defect the
+ connector conventions call out by name."""
+ findings = await _connector().fetch_vulnerability_findings()
+
+ assert {f["severity"] for f in findings} == {"critical", "high"}
+
+ @pytest.mark.asyncio
+ async def test_the_plugin_fan_out_is_capped(self, monkeypatch) -> None:
+ """The negative control on cost. One request per plugin against a
+ customer's scanner is a denial of service aimed at the customer, so an
+ unbounded loop here is worse than no feature."""
+ from app.connectors import tenable
+
+ assert isinstance(tenable.MAX_PLUGIN_LOOKUPS, int)
+ assert 0 < tenable.MAX_PLUGIN_LOOKUPS <= 200, f"MAX_PLUGIN_LOOKUPS is {tenable.MAX_PLUGIN_LOOKUPS}; that is not a cap"
diff --git a/tests/isolation/test_kev_exposure_has_data_live.py b/tests/isolation/test_kev_exposure_has_data_live.py
new file mode 100644
index 000000000..a302798d5
--- /dev/null
+++ b/tests/isolation/test_kev_exposure_has_data_live.py
@@ -0,0 +1,282 @@
+"""KEV exposure answers from scanner data, end to end, against real Postgres.
+
+Fix pass item 5.2. See `plans/aisoc_fix_pass_plan.plan.md`.
+
+What was wrong
+--------------
+`asset_vulnerabilities` had one writer: `POST /api/v1/assets/vulnerabilities`,
+a route a human calls by hand. The Tenable connector -- the only vulnerability
+scanner AiSOC integrates -- modelled its findings as alerts, so for any tenant
+whose vulnerability data came from a scanner the table was empty.
+
+`_tenant_has_vulnerability_data` exists precisely to tell "you are not exposed"
+apart from "nobody has told me what you run". With an empty table it returned
+the second, so KEV exposure reported **no data forever**, however many findings
+had been polled.
+
+What this file asserts
+----------------------
+The whole chain against real Postgres with every migration applied: a tenant
+starts with no vulnerability data and `check_exposure` says so; the connector's
+findings are synced; and the same call now reports the tenant exposed to the
+KEV CVE, naming the asset.
+
+The negative control is the half that makes the result mean anything: a tenant
+with data who is *not* running the vulnerable thing must come back **not
+exposed**, which is a different answer from "no data" and the whole reason the
+distinction exists.
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+import uuid
+from pathlib import Path
+
+import pytest
+import pytest_asyncio
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+
+pytestmark = [
+ pytest.mark.asyncio(loop_scope="module"),
+ pytest.mark.skipif(
+ not os.environ.get("ISOLATION_KEV_DSN", "").strip(),
+ reason="ISOLATION_KEV_DSN is not set; this suite needs a live Postgres",
+ ),
+]
+
+
+def _dsn(driver: str = "postgresql+asyncpg://") -> str:
+ value = os.environ.get("ISOLATION_KEV_DSN", "").strip()
+ if not value:
+ pytest.skip("ISOLATION_KEV_DSN is not set")
+ return value.replace("postgresql://", driver, 1) if value.startswith("postgresql://") else value
+
+
+@pytest_asyncio.fixture(scope="module", loop_scope="module")
+async def engine():
+ from sqlalchemy.ext.asyncio import create_async_engine
+
+ eng = create_async_engine(_dsn())
+ try:
+ yield eng
+ finally:
+ await eng.dispose()
+
+
+@pytest_asyncio.fixture(loop_scope="module")
+async def tenant(engine):
+ from sqlalchemy import text
+
+ tid = uuid.uuid4()
+ slug = f"kev-{tid.hex[:8]}"
+ async with engine.begin() as conn:
+ await conn.execute(
+ text("INSERT INTO tenants (id, name, slug) VALUES (:id, :n, :s)"),
+ {"id": tid, "n": slug, "s": slug},
+ )
+ try:
+ yield tid
+ finally:
+ async with engine.begin() as conn:
+ await conn.execute(text("DELETE FROM tenants WHERE id = :id"), {"id": tid})
+
+
+def _findings() -> list[dict]:
+ """The shape `TenableConnector.fetch_vulnerability_findings` returns."""
+ return [
+ {
+ "cve_id": "CVE-2021-44228",
+ "severity": "critical",
+ "hostname": "web-01.corp.example",
+ "ip_address": "198.51.100.10",
+ "title": "Log4Shell",
+ "plugin_id": 12345,
+ "source": "tenable_io",
+ },
+ {
+ # No CVE: must be skipped rather than written as an anonymous row.
+ "cve_id": "",
+ "severity": "high",
+ "hostname": "web-01.corp.example",
+ "title": "Something without a CVE",
+ "source": "tenable_io",
+ },
+ ]
+
+
+def _load_connectors_vulnerabilities():
+ """Load the connectors module by path, under its own module name.
+
+ Both services package their code as `app`, so whichever is imported first
+ wins `sys.modules["app"]` and the other's submodules resolve to
+ `ModuleNotFoundError`. This test is the one place that legitimately needs
+ both at once -- it is asserting that what the connectors service writes is
+ what the API service reads -- so the connectors half is loaded off disk
+ under a name that cannot collide.
+ """
+ import importlib.util
+
+ path = REPO_ROOT / "services" / "connectors" / "app" / "vulnerabilities.py"
+ spec = importlib.util.spec_from_file_location("aisoc_connectors_vulnerabilities", path)
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+async def _sync(engine, tenant_id):
+ sync_findings = _load_connectors_vulnerabilities().sync_findings
+ return await sync_findings(engine, tenant_id=tenant_id, findings=_findings())
+
+
+async def _exposure(engine, tenant_id, cve: str):
+ sys.path.insert(0, str(REPO_ROOT / "services" / "api"))
+ from app.services.retro_hunt.kev_exposure import check_exposure
+ from sqlalchemy.ext.asyncio import AsyncSession
+
+ async with AsyncSession(engine) as session:
+ return await check_exposure(
+ session,
+ tenant_id=tenant_id,
+ cve_id=cve,
+ feed_source="cisa-kev",
+ )
+
+
+class TestBeforeAnyScannerData:
+ async def test_the_tenant_reports_no_vulnerability_data(self, engine, tenant) -> None:
+ """Not "not exposed". The distinction is the point of the feature: a
+ tenant nobody has scanned is not a tenant that is safe."""
+ result = await _exposure(engine, tenant, "CVE-2021-44228")
+
+ assert result.checked is False, f"expected 'no data' for an unscanned tenant, got {result!r}"
+ assert "no vulnerability data" in (result.unavailable_reason or "")
+
+
+class TestAfterTheConnectorSyncs:
+ async def test_the_findings_become_rows(self, engine, tenant) -> None:
+ counts = await _sync(engine, tenant)
+
+ assert counts["findings_inserted"] == 1, counts
+ assert counts["assets_created"] == 1, counts
+ assert counts["skipped"] == 1, "the finding with no CVE should have been skipped, not written"
+
+ async def test_exposure_now_names_the_asset(self, engine, tenant) -> None:
+ await _sync(engine, tenant)
+
+ result = await _exposure(engine, tenant, "CVE-2021-44228")
+
+ assert result.checked is True, f"still reporting no data: {result!r}"
+ assert result.exposed_asset_count == 1, f"not reported exposed: {result!r}"
+ assert result.exposed_asset_names == ["web-01.corp.example"]
+
+ async def test_a_cve_the_tenant_does_not_run_is_not_exposed(self, engine, tenant) -> None:
+ """The negative control. A tenant with data who is not running the
+ vulnerable thing must come back *not exposed*, which is a different
+ answer from "no data" -- and a check that said "exposed" to everything
+ would pass the test above while being useless."""
+ await _sync(engine, tenant)
+
+ result = await _exposure(engine, tenant, "CVE-2014-0160")
+
+ assert result.checked is True, "a tenant with data must be checkable"
+ assert result.exposed_asset_count == 0, f"falsely exposed: {result!r}"
+
+ async def test_a_re_poll_touches_rather_than_duplicating(self, engine, tenant) -> None:
+ """A 5-minute schedule must not write a row every 5 minutes."""
+ from sqlalchemy import text
+
+ await _sync(engine, tenant)
+ second = await _sync(engine, tenant)
+
+ assert second["findings_inserted"] == 0
+ assert second["findings_touched"] == 1
+
+ async with engine.connect() as conn:
+ rows = (
+ await conn.execute(
+ text("SELECT count(*) FROM asset_vulnerabilities WHERE tenant_id = :t"),
+ {"t": tenant},
+ )
+ ).scalar_one()
+ assert rows == 1, f"{rows} rows after two polls of one finding"
+
+ async def test_first_found_survives_a_re_poll(self, engine, tenant) -> None:
+ """`first_found` is what an exposure window is measured against, so a
+ re-poll resetting it would silently make every finding look new."""
+ from sqlalchemy import text
+
+ await _sync(engine, tenant)
+ async with engine.connect() as conn:
+ before = (
+ await conn.execute(
+ text("SELECT first_found FROM asset_vulnerabilities WHERE tenant_id = :t"),
+ {"t": tenant},
+ )
+ ).scalar_one()
+
+ await _sync(engine, tenant)
+ async with engine.connect() as conn:
+ after = (
+ await conn.execute(
+ text("SELECT first_found FROM asset_vulnerabilities WHERE tenant_id = :t"),
+ {"t": tenant},
+ )
+ ).scalar_one()
+
+ assert before == after, "a re-poll moved first_found"
+
+ async def test_a_re_poll_cannot_touch_another_tenants_row(self, engine, tenant) -> None:
+ """The write carries its own tenant predicate.
+
+ The id handed to the UPDATE comes from a tenant-scoped SELECT, which is
+ not the same as the write being scoped: how a row was addressed is
+ irrelevant to what the statement can reach. `check_tenant_query_predicates`
+ caught this on the first version of this module, and this pins it.
+ """
+ from sqlalchemy import text
+
+ await _sync(engine, tenant)
+ async with engine.connect() as conn:
+ row_id = (await conn.execute(text("SELECT id FROM asset_vulnerabilities WHERE tenant_id = :t"), {"t": tenant})).scalar_one()
+
+ module = _load_connectors_vulnerabilities()
+ other = uuid.uuid4()
+ async with engine.begin() as conn:
+ touched = (
+ await conn.execute(
+ module._TOUCH_VULN,
+ {
+ "id": str(row_id),
+ "tenant_id": str(other),
+ "now": __import__("datetime").datetime.now(__import__("datetime").UTC),
+ "severity": "info",
+ "title": "hijacked",
+ },
+ )
+ ).rowcount
+
+ assert touched == 0, "a caller naming another tenant's id reached this row"
+
+
+class TestTenantScoping:
+ async def test_one_tenants_findings_are_invisible_to_another(self, engine, tenant) -> None:
+ from sqlalchemy import text
+
+ await _sync(engine, tenant)
+ other = uuid.uuid4()
+ async with engine.begin() as conn:
+ await conn.execute(
+ text("INSERT INTO tenants (id, name, slug) VALUES (:id, :n, :s)"),
+ {"id": other, "n": f"kev-o-{other.hex[:8]}", "s": f"kev-o-{other.hex[:8]}"},
+ )
+ try:
+ result = await _exposure(engine, other, "CVE-2021-44228")
+ assert result.checked is False, "the other tenant can see these findings"
+ finally:
+ async with engine.begin() as conn:
+ await conn.execute(text("DELETE FROM tenants WHERE id = :id"), {"id": other})
diff --git a/tests/isolation/test_retro_hunt_settings_live.py b/tests/isolation/test_retro_hunt_settings_live.py
new file mode 100644
index 000000000..565d2bfb4
--- /dev/null
+++ b/tests/isolation/test_retro_hunt_settings_live.py
@@ -0,0 +1,179 @@
+"""A tenant can opt itself into retro-hunts, against real Postgres.
+
+Fix pass item 5.1. See `plans/aisoc_fix_pass_plan.plan.md`.
+
+What was wrong
+--------------
+`retro_hunt_settings.enabled` defaults to FALSE under a comment reading "Off
+until a tenant asks", and there was nowhere to ask: no route, no console
+surface, nothing in `services/` touching the table beyond the ORM declaration.
+Opting a tenant in meant an UPDATE issued by hand.
+
+Why an offline test is not enough here
+--------------------------------------
+The write is an `INSERT ... ON CONFLICT (tenant_id) DO UPDATE`, and the thing
+that matters is the branch a plain UPDATE would have got wrong: a tenant that
+has never opted in has **no row at all**, so an UPDATE affects nothing and
+reports success. That is the exact shape of defect this fix pass exists for,
+and only a real table with a real primary key can tell the two apart.
+
+What this file asserts
+----------------------
+Real Postgres with every migration applied, driving the handlers rather than
+the SQL: a first opt-in creates the row, a second edits it rather than
+duplicating, one tenant's settings are invisible to another, the budget
+columns are not writable through this surface, and the lookback bound is
+enforced.
+"""
+
+from __future__ import annotations
+
+import os
+import uuid
+from types import SimpleNamespace
+
+import pytest
+import pytest_asyncio
+
+pytestmark = [
+ pytest.mark.asyncio(loop_scope="module"),
+ pytest.mark.skipif(
+ not os.environ.get("ISOLATION_RETRO_HUNT_DSN", "").strip(),
+ reason="ISOLATION_RETRO_HUNT_DSN is not set; this suite needs a live Postgres",
+ ),
+]
+
+
+def _dsn() -> str:
+ value = os.environ.get("ISOLATION_RETRO_HUNT_DSN", "").strip()
+ if not value:
+ pytest.skip("ISOLATION_RETRO_HUNT_DSN is not set")
+ return value
+
+
+@pytest_asyncio.fixture(scope="module", loop_scope="module")
+async def engine():
+ from sqlalchemy.ext.asyncio import create_async_engine
+
+ dsn = _dsn()
+ if dsn.startswith("postgresql://"):
+ dsn = dsn.replace("postgresql://", "postgresql+asyncpg://", 1)
+ eng = create_async_engine(dsn, poolclass=None)
+ try:
+ yield eng
+ finally:
+ await eng.dispose()
+
+
+@pytest_asyncio.fixture(loop_scope="module")
+async def two_tenants(engine):
+ """Two real tenant rows. Cleaned up by the FK cascade on delete."""
+ from sqlalchemy import text
+
+ a, b = uuid.uuid4(), uuid.uuid4()
+ async with engine.begin() as conn:
+ for tid, slug in ((a, f"retro-a-{a.hex[:8]}"), (b, f"retro-b-{b.hex[:8]}")):
+ await conn.execute(
+ text("INSERT INTO tenants (id, name, slug) VALUES (:id, :name, :slug)"),
+ {"id": tid, "name": slug, "slug": slug},
+ )
+ try:
+ yield a, b
+ finally:
+ async with engine.begin() as conn:
+ await conn.execute(text("DELETE FROM tenants WHERE id = ANY(:ids)"), {"ids": [a, b]})
+
+
+async def _get(engine, tenant_id: uuid.UUID):
+ from app.api.v1.endpoints.retro_hunts import get_retro_hunt_settings
+ from sqlalchemy.ext.asyncio import AsyncSession
+
+ async with AsyncSession(engine) as session:
+ return await get_retro_hunt_settings(db=session, user=SimpleNamespace(tenant_id=tenant_id))
+
+
+async def _put(engine, tenant_id: uuid.UUID, **fields):
+ from app.api.v1.endpoints.retro_hunts import RetroHuntSettingsIn, put_retro_hunt_settings
+ from sqlalchemy.ext.asyncio import AsyncSession
+
+ async with AsyncSession(engine) as session:
+ return await put_retro_hunt_settings(
+ body=RetroHuntSettingsIn(**fields),
+ db=session,
+ user=SimpleNamespace(tenant_id=tenant_id),
+ )
+
+
+class TestOptingIn:
+ async def test_a_tenant_with_no_row_reads_as_not_opted_in(self, engine, two_tenants) -> None:
+ """Not a 404. "You have not opted in" is a state with a correct answer,
+ and a 404 would read as "retro-hunts do not exist here"."""
+ a, _ = two_tenants
+
+ settings = await _get(engine, a)
+
+ assert settings.enabled is False
+ assert settings.lookback_days == 30
+
+ async def test_the_first_opt_in_creates_the_row(self, engine, two_tenants) -> None:
+ """The branch a plain UPDATE gets wrong: there is no row to update, so
+ an UPDATE would affect nothing and report success."""
+ a, _ = two_tenants
+
+ written = await _put(engine, a, enabled=True, lookback_days=14, include_federated=False)
+
+ assert written.enabled is True
+ assert written.lookback_days == 14
+ assert written.include_federated is False
+
+ # And it is durable, read back through a fresh session.
+ assert (await _get(engine, a)).enabled is True
+
+ async def test_a_second_write_edits_rather_than_duplicating(self, engine, two_tenants) -> None:
+ from sqlalchemy import text
+
+ a, _ = two_tenants
+ await _put(engine, a, enabled=True, lookback_days=14)
+ await _put(engine, a, enabled=False, lookback_days=90)
+
+ async with engine.connect() as conn:
+ rows = (
+ await conn.execute(
+ text("SELECT count(*) FROM retro_hunt_settings WHERE tenant_id = :t"),
+ {"t": a},
+ )
+ ).scalar_one()
+
+ assert rows == 1, f"{rows} settings rows for one tenant; the upsert duplicated instead of updating"
+ assert (await _get(engine, a)).lookback_days == 90
+
+
+class TestIsolationAndBounds:
+ async def test_one_tenants_opt_in_is_invisible_to_another(self, engine, two_tenants) -> None:
+ a, b = two_tenants
+ await _put(engine, a, enabled=True, lookback_days=7)
+
+ assert (await _get(engine, b)).enabled is False, "tenant B can see tenant A's opt-in"
+
+ async def test_the_budget_is_not_writable_through_this_surface(self, engine, two_tenants) -> None:
+ """The negative control that matters. The budget is the operator's
+ ceiling on what one tenant can cost the deployment, and a tenant that
+ could raise its own ceiling would not have one."""
+ from app.api.v1.endpoints.retro_hunts import RetroHuntSettingsIn
+
+ a, _ = two_tenants
+ await _put(engine, a, enabled=True)
+
+ assert "max_sweeps_per_hour" not in RetroHuntSettingsIn.model_fields
+ assert "max_sweeps_per_day" not in RetroHuntSettingsIn.model_fields
+ assert (await _get(engine, a)).max_sweeps_per_hour == 120
+
+ @pytest.mark.parametrize("days", [0, -1, 366, 10_000])
+ async def test_an_out_of_range_lookback_is_refused_before_postgres_sees_it(self, engine, two_tenants, days: int) -> None:
+ """The column CHECK would also catch this, as a 500. Refusing in the
+ model gives the caller a 422 naming the bound."""
+ from pydantic import ValidationError
+
+ a, _ = two_tenants
+ with pytest.raises(ValidationError):
+ await _put(engine, a, enabled=True, lookback_days=days)
diff --git a/tests/test_env_placeholder_gate.py b/tests/test_env_placeholder_gate.py
index 5fad9e959..c9ad26543 100644
--- a/tests/test_env_placeholder_gate.py
+++ b/tests/test_env_placeholder_gate.py
@@ -68,6 +68,11 @@ DELIBERATE_DEFAULTS: dict[str, str] = {
"AISOC_AGENTS_URL": "the compose hostname the console proxies agent calls to",
"AISOC_REALTIME_URL": "the compose hostname the console proxies WS/SSE to",
"AISOC_DEMO_MODE": "a boolean; false is the correct value for every deployment that is not the public demo",
+ "RETRO_HUNT_ENABLED": (
+ "a boolean, and off is the correct value for every deployment: a sweep reads back "
+ "over a tenant's history, which is a cost and a privacy decision, so it waits for "
+ "both this switch and the tenant's own opt-in"
+ ),
"AISOC_REALTIME_TICKET_TTL_SECONDS": "a duration",
"CONNECTORS_SERVICE_URL": "the compose hostname of the connectors service",
"CONNECTORS_SERVICE_TIMEOUT_SECONDS": "a duration",
diff --git a/tests/test_perf_gate_is_related_to_the_claims.py b/tests/test_perf_gate_is_related_to_the_claims.py
new file mode 100644
index 000000000..4a258dc72
--- /dev/null
+++ b/tests/test_perf_gate_is_related_to_the_claims.py
@@ -0,0 +1,147 @@
+"""The performance gate's thresholds are derived from the published figures.
+
+Fix pass item 5.8. See `plans/aisoc_fix_pass_plan.plan.md`.
+
+What was wrong
+--------------
+`perf.yml` asserted `--assert-eps-floor 5` and
+`--assert-p95-ceiling-ms 120000`. The published compose steady-state figures
+are **80.1 alerts/s** and a **1,091 ms** p95. So the floor sat 16x below the
+throughput being claimed and the ceiling 110x above the latency, and a
+regression had to be catastrophic by two orders of magnitude before the gate
+noticed -- while the job's name said it was measuring.
+
+The workflow's own comment defended this: a gate tuned close to a measurement
+flaps on a shared runner and gets disabled. That argument is right, and it
+argues for a **stated margin**, not for an arbitrary constant. `5` is a number
+that relates to nothing: when the published figure changes, it does not, and
+nobody can say what regression it would catch.
+
+`scripts/check_perf_results.py` also accepted a results directory covering one
+deployment, and had no freshness bound at all -- so a figure measured years ago
+on one of the two supported deployments would keep passing while the page
+presented it as current.
+
+What this file asserts
+----------------------
+The relationship, from the workflow and the published page as they are on
+disk: that the floor and ceiling are within a stated factor of the figures the
+docs publish, and that the gate requires both deployments and a date.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+import yaml
+
+ROOT = Path(__file__).resolve().parents[1]
+WORKFLOW = ROOT / ".github" / "workflows" / "perf.yml"
+PAGE = ROOT / "apps" / "docs" / "docs" / "operations" / "performance.md"
+
+#: The margins the repository has decided are acceptable, stated once here so
+#: the test and the workflow cannot drift apart silently. Generous on purpose:
+#: a shared GitHub runner is not the machine the figures came off, and a gate
+#: that flaps gets switched off. But bounded, so a regression of this size
+#: fails rather than passing unnoticed.
+MAX_THROUGHPUT_MARGIN = 8.0
+"""The floor may sit at most 8x below the published drain rate."""
+
+MAX_LATENCY_MARGIN = 20.0
+"""The ceiling may sit at most 20x above the published p95."""
+
+
+def _harness_args() -> str:
+ """The `run:` block that invokes the harness with its assertions.
+
+ Raises rather than falling through: a single exit keeps the return type a
+ `str` for both mypy and CodeQL's mixed-return check, and `pytest.fail()`
+ as the last statement reads as a value-returning path to both.
+ """
+ workflow = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8"))
+ for job in workflow["jobs"].values():
+ for step in job.get("steps") or []:
+ run = step.get("run") or ""
+ if "load_harness.py" in run and "--assert-eps-floor" in run:
+ return str(run)
+ raise AssertionError("perf.yml no longer runs load_harness.py with an eps floor")
+
+
+def _flag(name: str) -> float:
+ """One numeric flag out of the harness invocation.
+
+ The `re.search(...).group(1)` chain this replaces is four `union-attr`
+ findings and an unhandled `None` on the day somebody renames a flag --
+ which would surface as `AttributeError: 'NoneType'` rather than as the
+ gate saying what it could not find.
+ """
+ match = re.search(rf"--{re.escape(name)}\s+([\d.]+)", _harness_args())
+ if match is None:
+ raise AssertionError(f"perf.yml no longer passes --{name} to the harness")
+ return float(match.group(1))
+
+
+def _published(label: str) -> float:
+ """Read a figure out of the compose steady-state column of the page.
+
+ Deliberately parsed from the page rather than duplicated here: a copy would
+ agree with itself while the published number moved, which is the failure
+ this whole gate family exists to prevent.
+ """
+ text = PAGE.read_text(encoding="utf-8")
+ compose = text[text.index("## Single host, Docker Compose") :]
+ row = re.search(rf"^\|\s*{re.escape(label)}\s*\|([^|]+)\|([^|]+)\|", compose, flags=re.M)
+ if row is None:
+ raise AssertionError(f"no `{label}` row in the compose table")
+ # Column two is steady state, which the page itself calls "the row to plan
+ # against"; saturation is a backlog measurement and a floor set from it
+ # would describe the queue rather than the pipeline.
+ numbers = re.findall(r"[\d.]+", row.group(2).replace(",", ""))
+ assert numbers, f"no number in the steady-state cell for `{label}`"
+ return float(numbers[0])
+
+
+class TestTheThresholdsRelateToWhatIsPublished:
+ def test_the_throughput_floor_is_within_a_stated_factor(self) -> None:
+ published = _published("Pipeline drain rate")
+ floor = _flag("assert-eps-floor")
+
+ margin = published / floor
+ assert margin <= MAX_THROUGHPUT_MARGIN, (
+ f"the floor is {floor} against a published {published} events/s -- {margin:.0f}x below. "
+ f"A regression has to be {margin:.0f}x before this gate notices."
+ )
+
+ def test_the_latency_ceiling_is_within_a_stated_factor(self) -> None:
+ published = _published("Event-to-alert p95")
+ ceiling = _flag("assert-p95-ceiling-ms")
+
+ margin = ceiling / published
+ assert margin <= MAX_LATENCY_MARGIN, f"the ceiling is {ceiling} ms against a published {published} ms p95 -- {margin:.0f}x above."
+
+ def test_the_margins_are_still_generous(self) -> None:
+ """The negative control. Thresholds tuned to the measurement would flap
+ on a shared runner and be switched off within a week, so this asserts
+ the gate has *not* been tightened to the published figure."""
+ floor = _flag("assert-eps-floor")
+ ceiling = _flag("assert-p95-ceiling-ms")
+
+ assert floor < _published("Pipeline drain rate"), "the floor is at or above the published rate"
+ assert ceiling > _published("Event-to-alert p95"), "the ceiling is at or below the published p95"
+
+
+class TestTheResultsGateCoversBothDeploymentsAndIsTimeBound:
+ def test_it_requires_both_deployments(self) -> None:
+ """One deployment's figures passing is not the page being supported:
+ the page publishes two tables."""
+ source = (ROOT / "scripts" / "check_perf_results.py").read_text(encoding="utf-8")
+
+ assert "REQUIRED_DEPLOYMENTS" in source, "check_perf_results.py does not require a result per published deployment"
+
+ def test_it_has_a_freshness_bound(self) -> None:
+ source = (ROOT / "scripts" / "check_perf_results.py").read_text(encoding="utf-8")
+
+ assert "MAX_RESULT_AGE_DAYS" in source, (
+ "check_perf_results.py has no freshness bound, so a figure taken years ago keeps passing while the page presents it as current"
+ )
diff --git a/tests/test_release_channel_tags.py b/tests/test_release_channel_tags.py
index 39689e505..74e43dab8 100644
--- a/tests/test_release_channel_tags.py
+++ b/tests/test_release_channel_tags.py
@@ -37,7 +37,9 @@ def _tag_script() -> str:
return step["run"]
-def run_tags(*, version: str, republish: bool = False, promote_stable: bool = False, demo: bool = False) -> list[str]:
+def run_tags(
+ *, version: str, republish: bool = False, promote_stable: bool = False, demo: bool = False, stable_major: str = ""
+) -> list[str]:
"""Execute the workflow's own tag block and return the tags it emitted."""
script = _tag_script()
with tempfile.TemporaryDirectory() as tmp:
@@ -50,6 +52,7 @@ def run_tags(*, version: str, republish: bool = False, promote_stable: bool = Fa
"PROMOTE_STABLE": "true" if promote_stable else "false",
"IMAGE": IMAGE,
"IS_DEMO": "true" if demo else "false",
+ "STABLE_MAJOR": stable_major,
"GITHUB_OUTPUT": str(output),
}
done = subprocess.run(["bash", "-c", script], env=env, capture_output=True, text=True)
@@ -118,3 +121,80 @@ def test_the_promote_stable_input_is_declared_so_the_dispatch_arm_is_reachable()
"the block reads PROMOTE_STABLE but the workflow declares no such input, so the only path "
"by which `stable` can reach a major is unreachable"
)
+
+
+# ── The channel across a sequence of releases ────────────────────────────────
+#
+# Fix-pass item 5.5. Every test above asks one question of one release, and
+# the channel's whole purpose is a property of a *sequence*: `stable` must not
+# arrive at a major without an operator saying so. Asked one release at a time
+# the answer always looked right -- `v16.0.0` correctly does not move it -- and
+# `v16.1.0` then carried it across the boundary the next day, because a minor
+# is not a major and nothing in the block knew which major `stable` was on.
+#
+# That is how `stable` reached v12, v13 and v15.
+
+
+def run_ladder(versions: list[str], *, stable_major: str = "", promote_at: set[str] | None = None) -> dict[str, str | None]:
+ """Replay a release ladder, carrying the channel's major between releases.
+
+ Returns the version `stable` points at after each release, which is the
+ thing a single-release test cannot observe.
+ """
+ promote_at = promote_at or set()
+ where: str | None = None
+ for version in versions:
+ tags = run_tags(
+ version=version,
+ promote_stable=version in promote_at,
+ stable_major=stable_major,
+ )
+ if f"{IMAGE}:stable" in tags:
+ where = version
+ stable_major = version.lstrip("v").split(".")[0]
+ return {"stable": where, "major": stable_major}
+
+
+class TestStableDoesNotCrossAMajorOnItsOwn:
+ def test_the_first_minor_of_a_new_major_does_not_carry_the_channel(self) -> None:
+ """The defect, stated as a ladder.
+
+ `v15.2.0` is where `stable` sits. `v16.0.0` correctly refuses it. Then
+ `v16.1.0` arrives and -- being a minor -- takes it, so a deployment
+ pulling `stable` crosses the breaking change with nobody deciding to.
+ """
+ end = run_ladder(["v15.1.0", "v15.2.0", "v16.0.0", "v16.1.0"], stable_major="15")
+
+ assert end["stable"] == "v15.2.0", f"stable moved to {end['stable']}, crossing into v16 with no operator action"
+
+ def test_it_stays_put_for_the_whole_of_the_new_major(self) -> None:
+ """Not just the first minor. Nothing in v16 takes it."""
+ end = run_ladder(
+ ["v15.2.0", "v16.0.0", "v16.1.0", "v16.1.1", "v16.2.0", "v16.3.0"],
+ stable_major="15",
+ )
+
+ assert end["stable"] == "v15.2.0"
+
+ def test_a_deliberate_promotion_moves_it_and_the_channel_follows(self) -> None:
+ """The negative control, and the half that matters most.
+
+ A guard that simply froze `stable` forever would pass the two tests
+ above and make the channel useless. After an operator promotes
+ `v16.0.0`, the ladder must resume: v16's own minors carry it again.
+ """
+ end = run_ladder(
+ ["v15.2.0", "v16.0.0", "v16.1.0", "v16.2.0"],
+ stable_major="15",
+ promote_at={"v16.0.0"},
+ )
+
+ assert end["stable"] == "v16.2.0", "the channel did not resume inside the promoted major"
+ assert end["major"] == "16"
+
+ def test_a_first_ever_release_takes_the_channel(self) -> None:
+ """A registry with no `stable` tag yet must not be read as "a different
+ major", or a new deployment would never get one."""
+ end = run_ladder(["v1.0.0", "v1.1.0"], stable_major="")
+
+ assert end["stable"] == "v1.1.0"