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(autonomy): demote a drifted grant without waiting for a page load (#1196)

Beenu Arora9da6c6b3622a
diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml
index a8d00367e..1416acfb9 100644
--- a/.github/workflows/integration.yml
+++ b/.github/workflows/integration.yml
@@ -868,6 +868,28 @@ jobs:
AUTONOMY_PROMOTION_LIVE_REQUIRED: '1'
run: python -m pytest ../../tests/isolation/test_autonomy_promotion_live.py -v --tb=short
+ # Fix pass 3.7. The dispatch half of the same control, and it needs its
+ # own step because it needs a different `app`: `services/api` and
+ # `services/actions` both package their code as top-level `app`, so one
+ # process holds one of them.
+ #
+ # `services/actions` resolved unattended execution from `state =
+ # 'granted'` alone, and the only thing that ever moved a grant out of
+ # that column was `reconcile_grants` — called by the autonomy page and
+ # nothing else. A fake connection cannot settle whether the aggregate
+ # and the evaluator agree about real rows, and the arity defect this
+ # code shipped with proves it: seven parameters into a statement that
+ # binds six failed closed, so every grant on every deployment was
+ # withheld, and no double would have refused the parameter count.
+ #
+ # AUTONOMY_DRIFT_LIVE_REQUIRED turns an unreachable database into a
+ # failure rather than a skip, for the same reason as the jobs above.
+ - name: Dispatch re-checks a grant's evidence (live Postgres)
+ working-directory: services/actions
+ env:
+ AUTONOMY_DRIFT_LIVE_REQUIRED: '1'
+ run: python -m pytest ../../tests/isolation/test_autonomy_drift_at_dispatch_live.py -v --tb=short
+
# Gap-closure Phase 6.3. A replay freezes the knowledge base with a
# predicate in SQL rather than with a captured set, so every offline
# test of that freeze proves the reader *asks* for a cutoff and none of
diff --git a/FIX_PASS_PROGRESS.md b/FIX_PASS_PROGRESS.md
index 087fc8581..17b4b8953 100644
--- a/FIX_PASS_PROGRESS.md
+++ b/FIX_PASS_PROGRESS.md
@@ -86,14 +86,14 @@ conditional `numpy` pins collide into an unresolvable install. Parse with
## Wave 3: Replay, shadow mode and evaluation measure the real thing
-- [ ] **3.1** Frozen context, not empty context
+- [x] **3.1** Frozen context, not empty context
- [x] **3.2** No side effects from a replay
-- [ ] **3.3** Input shapes: per-source adapters for Elastic and Defender
+- [x] **3.3** Input shapes: per-source adapters for Elastic and Defender
- [x] **3.4** Model attribution: `model_used` is set from the call that answered
- [x] **3.5** Non-degenerate acceptance for the reproducibility test
- [x] **3.6** Tool calls recorded from the ledger, not hard-coded to 0
-- [ ] **3.7** Demotion without a page load
-- [ ] **3.8** Skills: activation evidence, LLM-path-only disclosure, console retraction
+- [x] **3.7** Demotion without a page load
+- [x] **3.8** Skills: activation evidence, LLM-path-only disclosure, console retraction
- [~] **3.9** The weekly live evaluation installs from the lockfile and fails loudly; it still cannot *run* without a funded key (M2)
- [x] **3.10** The 9.3% flip rate is qualified or removed
- [x] **3.11** CI runs the live tests
@@ -539,12 +539,11 @@ left implied.
## Wave 3 (partial): what is done and what is not
-**Done, each with a reproduction and a negative control:** 3.2, 3.4, 3.5, 3.6,
-3.10, 3.11, 3.12, and the actionable half of 3.9.
+**Done, each with a reproduction and a negative control:** 3.1, 3.2, 3.3,
+3.4, 3.5, 3.6, 3.7, 3.8, 3.10, 3.11, 3.12, and the actionable half of 3.9.
-**Not started:** 3.1 (frozen context), 3.3 (per-source input adapters),
-3.7 (demotion without a page load),
-3.8 (skills activation evidence and the console retraction).
+**Wave 3 is closed.** Every item carries its reproduction and its negative
+control; 3.9's remaining half is maintainer-blocked on a funded key (M2).
### 3.2 A replay has no side effects
@@ -572,6 +571,44 @@ default was the only branch that ever ran. `tool_calls` was a literal under a
comment promising it would move. `_classify_pivots` counted a raised call as a
pivot, so four timeouts looked like four pivots.
+### 3.7 Demotion without a page load
+
+Reproduced against a real Postgres before anything was written. A tenant
+earns `auto_execute` on `isolate_host` from a 240-decision record, 30
+disagreements are injected -- window agreement 88.9%, trailing slice 40%, both
+under the floors -- and then, with no read of the API: the grant row still
+says `granted`, and `services/actions` still reports
+`earned_autonomy_for('isolate_host') == 'earned'`. That second one is the
+sharp end. It means the dispatch path would have auto-isolated a production
+host on a track record the product itself no longer accepted.
+
+Two callers now, where there was one. `app.workers.autonomy_drift` sweeps
+every tenant holding a grant on a timer from the API lifespan and writes the
+demotion with its audit row; `tenant_policy` re-runs the same evaluator before
+handing a verb to dispatch and **withholds** one that no longer holds,
+without writing anything -- issuing and revoking stay with the service that
+owns the hash chain.
+
+The sweep is on by default, unlike `shadow_reconcile` beside it, and the
+difference is what each reaches: that one polls a customer's SIEM, this one
+aggregates rows this deployment already wrote. A safety control that has to be
+switched on is off wherever nobody knew to switch it on.
+
+**A defect in the fix, caught by its own positive control.** The two shared
+aggregates bind different parameter counts -- the trailing slice takes `$7`
+for its `LIMIT`, the window aggregate stops at `$6` -- and passing seven to
+both made asyncpg refuse. The refusal was caught and an unreadable record is
+treated as no record, so *every* grant on *every* deployment was withheld
+while the log called the evidence unreadable. It passed the demotion test
+perfectly. Only the test asserting a healthy tenant **keeps** its verb found
+it. A safety control stuck on reads like working caution, which is why
+nothing about the symptom says "broken", and the arity is now derived from
+the statement so an edit to the shared module cannot put it back.
+
+`scripts/check_module_reachability.py` went the way an allowlist is supposed
+to: `autonomy_evidence_rules.py` was listed as a permanent entry reached only
+by tooling, the dispatch re-check gave it a production caller, and the gate
+refused the stale entry.
### 3.5 Non-degenerate acceptance
Measured before touching anything: all six decisions in the test window came
diff --git a/apps/docs/docs/operations/shadow-mode.md b/apps/docs/docs/operations/shadow-mode.md
index 7af0694fe..721ae89fd 100644
--- a/apps/docs/docs/operations/shadow-mode.md
+++ b/apps/docs/docs/operations/shadow-mode.md
@@ -310,11 +310,23 @@ frustration rather than on the merits.
### Demotion is automatic
-Standing grants are re-checked whenever they are read and whenever the
-dispatch path refreshes. A grant is demoted when agreement falls below 90%,
-malicious recall below 80%, the abstention rate rises above the cap, or the
-trailing slice of recent decisions has slipped below those floors even though
-the window average has not.
+A grant is demoted when agreement falls below 90%, malicious recall below 80%,
+the abstention rate rises above the cap, or the trailing slice of recent
+decisions has slipped below those floors even though the window average has
+not.
+
+Three things apply the floors, and none of them is a person:
+
+| | Cadence | What it does |
+|---|---|---|
+| The drift sweep | Every `AUTONOMY_DRIFT_INTERVAL_SECONDS`, 10 minutes by default | Re-checks every tenant holding a standing grant and writes the demotion with its audit row. On by default; it reads only this deployment's own database. |
+| The dispatch path | Whenever `services/actions` refreshes its 30-second policy cache | Re-runs the same evaluator before handing back a verb, and **withholds** one whose evidence no longer holds. It does not write the transition — issuing and revoking belong to the API, which owns the audit chain — so the withholding closes the window between sweeps rather than replacing them. |
+| Reading the autonomy page | On request | Reconciles and demotes on the way out, so the page you are looking at is not describing a state the product has already left. |
+
+Until v17.1 only the third of those existed, which meant a grant whose
+evidence had collapsed kept auto-executing until somebody opened the page.
+Setting `AUTONOMY_DRIFT_ENABLED=false` returns a deployment to that behaviour
+for the durable half; the dispatch-time re-check cannot be switched off.
The demotion floors sit below the promotion thresholds on purpose. Equal values
would flip a grant on every decision that moved the rate across the line, and
diff --git a/scripts/check_module_reachability.py b/scripts/check_module_reachability.py
index dff31ac08..fbc785567 100644
--- a/scripts/check_module_reachability.py
+++ b/scripts/check_module_reachability.py
@@ -107,17 +107,12 @@ ALLOWED_UNREACHABLE: dict[str, str] = {
"shows: deleting its sibling below broke two gates that read it "
"without importing it."
),
- "services/actions/app/services/autonomy_evidence_rules.py": (
- "Reached by tooling rather than by import, which is why it appears "
- "here and why the entry used to be wrong. It is the source of "
- "truth for what counts as a graded disposition, and two gates read "
- "it: `check_replay_contract_parity.py` compares its "
- "GRADED_DISPOSITIONS, ABSTENTION_VERDICTS and MALICIOUS spellings "
- "against the benchmark's, and `sync_vendored_autonomy_evidence.py "
- "--check` byte-compares the API's vendored copy, because a safety "
- "control defined twice is off in whichever copy is more generous. "
- "An import-graph checker cannot see either. Permanent entry."
- ),
+ # `services/actions/app/services/autonomy_evidence_rules.py` was here,
+ # described as a permanent entry reached only by tooling. Fix pass 3.7
+ # gave it a production caller: `tenant_policy` runs its two aggregates
+ # and its demotion evaluator before handing a verb to dispatch. The entry
+ # went the way an allowlist entry is supposed to go — a module stopped
+ # being unreachable and the gate said so.
# ── Vendor clients reached only through a capability executor ─────────
# These are constructed by name at dispatch time, not imported. The
# import graph cannot see that, and inventing a dynamic-loader entry for
diff --git a/services/actions/app/services/tenant_policy.py b/services/actions/app/services/tenant_policy.py
index a0b2b7970..034d7865f 100644
--- a/services/actions/app/services/tenant_policy.py
+++ b/services/actions/app/services/tenant_policy.py
@@ -29,14 +29,26 @@ Safety posture when the policy cannot be read:
from __future__ import annotations
import os
+import re
import time
from dataclasses import dataclass, field
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta
from typing import Any
from uuid import UUID
import structlog
+from app.services.autonomy_evidence_rules import (
+ ABSTENTION_VERDICTS,
+ AGREEMENT_COUNTS_SQL,
+ GRADED_DISPOSITIONS,
+ MALICIOUS,
+ RECENT_COUNTS_SQL,
+ PromotionThresholds,
+ evaluate_demotion,
+ scoped_sql,
+ window_from_counts,
+)
from app.services.maturity import MaturityTier
logger = structlog.get_logger(__name__)
@@ -205,6 +217,84 @@ async def _load_from_store(tenant_id: str, dsn: str) -> TenantPolicy | None:
)
+#: A numbered placeholder in one of the shared aggregate statements.
+_PLACEHOLDER = re.compile(r"\$(\d+)")
+
+
+def _bound(statement: str, params: tuple[Any, ...]) -> tuple[Any, ...]:
+ """The statement and only the parameters it actually carries.
+
+ The two aggregates do not bind the same number: the trailing slice takes
+ ``$7`` for its ``LIMIT`` and the window aggregate stops at ``$6``. asyncpg
+ refuses a mismatch outright, and because an unreadable record fails closed
+ here, passing seven to both withheld *every* grant on *every* deployment
+ while logging it as unreadable evidence — a safety control stuck on, which
+ reads like working caution and is a product that has stopped acting.
+
+ Deriving the arity from the statement rather than slicing at a literal
+ means an edit to the shared module cannot put it back.
+ """
+ highest = max((int(index) for index in _PLACEHOLDER.findall(statement)), default=0)
+ return (scoped_sql(statement), *params[:highest])
+
+
+async def _evidence_still_holds(conn: Any, tenant_id: str) -> tuple[bool, list[str]]:
+ """Re-run the demotion evaluator here, against the evidence as it stands now.
+
+ Fix pass 3.7. ``state = 'granted'`` is a cached verdict. The only thing
+ that moved a grant out of that state was ``reconcile_grants``, and its one
+ production caller was the handler behind ``GET /autonomy-policy/grants``
+ — so on a deployment nobody opens that page on, a grant whose agreement
+ had collapsed kept auto-executing containment indefinitely. The API sweep
+ added alongside this closes the durable half; this closes the window
+ between its ticks, on the one path where being wrong executes something at
+ a customer's vendor.
+
+ It is the *same* evaluator, not a second opinion. ``evaluate_demotion``
+ and both aggregate statements live in ``autonomy_evidence_rules``, which
+ ``services/api`` carries byte-identical and a gate keeps that way, for the
+ reason this function is an instance of: a safety control two services
+ define differently is off in whichever one is more generous. The numbered
+ placeholders in those statements were written for an asyncpg caller; this
+ is it.
+
+ Every ``action_verb`` grant is judged on the tenant-wide window, which is
+ the scope ``reconcile_grants`` uses for anything that is not an alert
+ class, so one pair of aggregates answers for all of them.
+
+ Returns ``(holds, refusals)``. A read failure answers ``False``: this
+ service enforces grants and never issues them, so withholding one costs a
+ human approval and granting one that is no longer earned costs a
+ containment nobody authorised.
+ """
+ thresholds = PromotionThresholds()
+ window_end = datetime.now(UTC)
+ window_start = window_end - timedelta(days=thresholds.window_days)
+ params = (
+ UUID(tenant_id),
+ list(GRADED_DISPOSITIONS),
+ sorted(ABSTENTION_VERDICTS),
+ MALICIOUS,
+ window_start,
+ window_end,
+ thresholds.drift_sample,
+ )
+
+ try:
+ window_row = await conn.fetchrow(*_bound(AGREEMENT_COUNTS_SQL, params))
+ recent_row = await conn.fetchrow(*_bound(RECENT_COUNTS_SQL, params))
+ except Exception as exc: # noqa: BLE001 - an unreadable record is not a track record
+ logger.warning("tenant_policy.evidence_unreadable", tenant_id=tenant_id, error=str(exc)[:300])
+ return False, ["evidence_unreadable"]
+
+ verdict = evaluate_demotion(
+ window=window_from_counts(dict(window_row or {})),
+ recent=window_from_counts(dict(recent_row or {})),
+ thresholds=thresholds,
+ )
+ return verdict.allowed, list(verdict.refusal_values)
+
+
async def _load_earned_verbs(conn: Any, tenant_id: str) -> dict[str, str]:
"""Which response verbs this tenant has earned the right to run unattended.
@@ -212,6 +302,14 @@ async def _load_earned_verbs(conn: Any, tenant_id: str) -> dict[str, str]:
grant keeps its row so the history survives, and reading it as current is
exactly the mistake that would let a revoked capability keep executing.
+ Fix pass 3.7: the state alone is not enough, so the evidence behind it is
+ re-checked here before any verb is handed back. See
+ :func:`_evidence_still_holds`. The withholding is not persisted — the
+ demotion row and its audit entry belong to ``services/api``, which owns
+ the tenant session and the hash chain, and writing a transition from the
+ dispatch path would be the second way to become autonomous this module's
+ docstring exists to refuse.
+
A read failure returns nothing rather than raising. That is the safe
direction here and it is the opposite of the choice made for the tier: an
unreadable *tier* falls back to a conservative floor because the tier
@@ -234,6 +332,24 @@ async def _load_earned_verbs(conn: Any, tenant_id: str) -> dict[str, str]:
except Exception as exc: # noqa: BLE001 - no grant is the safe answer
logger.warning("tenant_policy.grants_unreadable", tenant_id=tenant_id, error=str(exc)[:300])
return {}
+
+ if not rows:
+ # No grant, nothing to re-check, and no reason to run two aggregates
+ # over a month of decisions on the hot path for every tenant that has
+ # never asked for unattended execution.
+ return {}
+
+ holds, refusals = await _evidence_still_holds(conn, tenant_id)
+ if not holds:
+ logger.warning(
+ "tenant_policy.grants_withheld",
+ tenant_id=tenant_id,
+ verbs=sorted(str(row["scope_key"]) for row in rows),
+ refusals=refusals,
+ reason="the evidence behind these grants no longer meets the demotion floors",
+ )
+ return {}
+
return {str(row["scope_key"]): str(row["source"]) for row in rows}
diff --git a/services/actions/tests/test_tenant_policy_drift.py b/services/actions/tests/test_tenant_policy_drift.py
new file mode 100644
index 000000000..44caae3d5
--- /dev/null
+++ b/services/actions/tests/test_tenant_policy_drift.py
@@ -0,0 +1,101 @@
+"""Dispatch re-checks the evidence behind a grant, using the shared evaluator.
+
+Fix pass item 3.7. See ``plans/aisoc_fix_pass_plan.plan.md``.
+
+``state = 'granted'`` is a cached verdict, and the only thing that moved a
+grant out of it was ``reconcile_grants`` in ``services/api`` — whose single
+production caller was the handler behind ``GET /autonomy-policy/grants``. So a
+tenant whose agreement had collapsed kept auto-executing containment until
+somebody opened a page, which on an unattended deployment is never.
+
+The behaviour lives in ``tests/isolation/test_autonomy_drift_at_dispatch_live.py``,
+against a real Postgres, because the thing worth proving is that the aggregate
+and the evaluator agree about real rows. What is here is what does not need a
+database: that the parameters match the statements, and that the decision is
+the shared evaluator's rather than a second opinion written locally.
+"""
+
+from __future__ import annotations
+
+import ast
+import re
+from pathlib import Path
+
+from app.services.autonomy_evidence_rules import (
+ AGREEMENT_COUNTS_SQL,
+ RECENT_COUNTS_SQL,
+)
+from app.services.tenant_policy import _bound
+
+_MODULE = Path(__file__).resolve().parents[1] / "app" / "services" / "tenant_policy.py"
+
+
+def _placeholders(statement: str) -> int:
+ return max((int(index) for index in re.findall(r"\$(\d+)", statement)), default=0)
+
+
+class TestTheParametersMatchTheStatements:
+ """The defect this class exists for failed closed, which is why it hid.
+
+ The two aggregates bind different numbers of parameters — the trailing
+ slice takes ``$7`` for its ``LIMIT`` and the window aggregate stops at
+ ``$6``. Passing seven to both made asyncpg refuse, the refusal was caught,
+ and an unreadable record is treated as no record: every grant on every
+ deployment was withheld while the log said the evidence could not be read.
+ A safety control stuck on reads like working caution, so nothing about the
+ symptom says "broken".
+ """
+
+ def test_the_window_aggregate_gets_exactly_what_it_binds(self) -> None:
+ params = tuple(range(1, 20))
+ statement, *bound = _bound(AGREEMENT_COUNTS_SQL, params)
+
+ assert statement.strip().startswith("SELECT")
+ assert len(bound) == _placeholders(AGREEMENT_COUNTS_SQL)
+
+ def test_the_trailing_slice_gets_its_limit(self) -> None:
+ params = tuple(range(1, 20))
+ bound = _bound(RECENT_COUNTS_SQL, params)[1:]
+
+ assert len(bound) == _placeholders(RECENT_COUNTS_SQL)
+
+ def test_the_two_statements_really_do_differ(self) -> None:
+ """Otherwise the derivation above is untested by construction."""
+ assert _placeholders(RECENT_COUNTS_SQL) > _placeholders(AGREEMENT_COUNTS_SQL)
+
+
+class TestTheDecisionIsTheSharedEvaluators:
+ def test_the_dispatch_path_calls_evaluate_demotion(self) -> None:
+ """Not a locally written threshold comparison.
+
+ A safety control two services define differently is off in whichever
+ one is more generous, which is the whole reason
+ ``autonomy_evidence_rules`` is vendored byte-identical into both. A
+ dispatch-side re-check that compared its own numbers would reintroduce
+ exactly the divergence the vendoring exists to prevent.
+ """
+ tree = ast.parse(_MODULE.read_text(encoding="utf-8"))
+
+ imported = {
+ alias.name
+ for node in ast.walk(tree)
+ if isinstance(node, ast.ImportFrom) and node.module == "app.services.autonomy_evidence_rules"
+ for alias in node.names
+ }
+ assert "evaluate_demotion" in imported, "tenant_policy no longer imports the shared demotion evaluator"
+
+ called = {node.func.id for node in ast.walk(tree) if isinstance(node, ast.Call) and isinstance(node.func, ast.Name)}
+ assert "evaluate_demotion" in called, "the evaluator is imported but never called, which is the shape this item exists to remove"
+
+ def test_dispatch_writes_no_grant_transition(self) -> None:
+ """Enforcing is this service's job; issuing and revoking are not.
+
+ ``services/api`` owns the tenant session and the hash-chained audit
+ log, so a demotion written from here would be a state change with
+ nobody's name on it and no entry explaining it. Withholding is the
+ whole of the dispatch-side remedy.
+ """
+ source = _MODULE.read_text(encoding="utf-8")
+
+ assert "UPDATE aisoc_autonomy_grants" not in source
+ assert "INSERT INTO aisoc_autonomy_grants" not in source
diff --git a/services/api/app/core/config.py b/services/api/app/core/config.py
index 1cf55f84f..9b1c740f5 100644
--- a/services/api/app/core/config.py
+++ b/services/api/app/core/config.py
@@ -515,6 +515,20 @@ class Settings(BaseSettings):
SHADOW_RECONCILE_MAX_WINDOW_HOURS: int = 24
SHADOW_RECONCILE_LIMIT: int = 1000
+ # Fix pass 3.7. Re-checks every standing autonomy grant against the
+ # demotion floors on a timer. Default **on**, unlike the sweep above, and
+ # the difference is what each one reaches: that one polls a customer's
+ # SIEM, this one aggregates rows this deployment already wrote and makes
+ # no outbound call. The thing it catches is a grant that has stopped being
+ # earned, which nobody is watching for by definition, so shipping it off
+ # would leave it off wherever it matters.
+ AUTONOMY_DRIFT_ENABLED: bool = Field(
+ default=True,
+ validation_alias=AliasChoices("AUTONOMY_DRIFT_ENABLED", "AISOC_AUTONOMY_DRIFT_ENABLED"),
+ )
+ AUTONOMY_DRIFT_INTERVAL_SECONDS: int = 600 # 10m
+ AUTONOMY_DRIFT_MAX_TENANTS_PER_TICK: int = 100
+
# Database
# The default points at the bundled compose Postgres with its dev password.
# In docker-compose.yml and .env.example the password is parameterised via
diff --git a/services/api/app/main.py b/services/api/app/main.py
index 906eb471a..e6a2a04d3 100644
--- a/services/api/app/main.py
+++ b/services/api/app/main.py
@@ -37,6 +37,7 @@ from app.services.plugin_manager import get_plugin_manager
from app.services.scim.resources import SCIM_CONTENT_TYPE
from app.services.scim.resources import error_response as scim_error_response
from app.workers.approval_expiry import run_forever as run_approval_expiry
+from app.workers.autonomy_drift import run_forever as run_autonomy_drift
from app.workers.hunt_scheduler import run_forever as run_hunt_scheduler
from app.workers.oauth_refresh import run_forever as run_oauth_refresh
from app.workers.outbound_webhook_delivery import run_forever as run_outbound_webhook_delivery
@@ -79,6 +80,13 @@ _REPORT_SCHEDULER_LOCK_TTL_SECONDS = 600
# search load for no extra evidence.
_SHADOW_RECONCILE_LOCK_TTL_SECONDS = 1800
+# A drift pass runs two bounded aggregates per tenant holding a grant, against
+# this deployment's own database and nothing else. Same shape and same TTL as
+# the approval sweep: short, because a lock still held after a replica crashed
+# would leave grants un-demoted for far longer than the work takes, and a
+# capability nobody has earned staying live is the condition this closes.
+_AUTONOMY_DRIFT_LOCK_TTL_SECONDS = 300
+
async def _run_guarded_scheduler_worker(
*,
@@ -516,6 +524,57 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
"Set APPROVAL_EXPIRY_ENABLED=true to sweep them"
)
+ # Fix pass 3.7. `reconcile_grants` shipped with one caller, the handler
+ # behind `GET /autonomy-policy/grants`, so a grant whose agreement had
+ # collapsed stayed `granted` -- and kept auto-executing -- until somebody
+ # opened the autonomy page. This is the caller that needs no human.
+ autonomy_drift_task: asyncio.Task | None = None
+ if settings.AUTONOMY_DRIFT_ENABLED:
+ try:
+ autonomy_drift_task = asyncio.create_task(
+ _run_guarded_scheduler_worker(
+ job_name="autonomy_drift",
+ ttl_seconds=_AUTONOMY_DRIFT_LOCK_TTL_SECONDS,
+ worker=run_autonomy_drift,
+ ),
+ name="autonomy_drift_worker",
+ )
+ logger.info("autonomy_drift worker started")
+ except Exception as exc:
+ logger.warning("autonomy_drift worker failed to start", error=str(exc))
+ else:
+ # Said out loud. With this off a grant is only re-checked when the
+ # autonomy page is read or when the dispatch path refreshes its
+ # policy cache, and the first of those is a human nobody scheduled.
+ logger.info(
+ "autonomy_drift worker disabled; a standing grant whose evidence has slipped will keep its "
+ "'granted' state until somebody opens the autonomy page. Set AUTONOMY_DRIFT_ENABLED=true to sweep them"
+ )
+
+ # Gap-closure Phase 8.1. The consumer for the `NEW_IOC` events
+ # `services/threatintel` has always emitted and nothing has ever read.
+ #
+ # Default off, and deliberately not guarded by the scheduler lock the
+ # three workers above use: this is a Kafka consumer group, so the broker
+ # already assigns partitions across replicas, and adding a lock on top
+ # would leave every replica but one subscribed to nothing.
+ retro_hunt_task: asyncio.Task | None = None
+ if settings.RETRO_HUNT_ENABLED:
+ try:
+ retro_hunt_task = asyncio.create_task(
+ run_retro_hunt_consumer(),
+ name="retro_hunt_consumer",
+ )
+ logger.info("retro_hunt consumer started")
+ except Exception as exc:
+ logger.warning("retro_hunt consumer failed to start", error=str(exc))
+
+ # Phase 2.6 — flip /readyz to 200. All lifespan-managed
+ # dependencies have been touched at this point (DB, Redis,
+ # Neo4j, schedulers); the load balancer can route traffic
+ # to this pod safely now.
+ app.state.mark_ready()
+
# Depth 5.2. The reader `report_templates.cron_schedule` never had.
# Guarded by the same scheduler lock the three workers above use, so
# two replicas do not both generate a tenant's weekly report.
@@ -552,24 +611,6 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
except Exception as exc:
logger.warning("outbound_webhook worker failed to start", error=str(exc))
- # Gap-closure Phase 8.1. The consumer for the `NEW_IOC` events
- # `services/threatintel` has always emitted and nothing has ever read.
- #
- # Default off, and deliberately not guarded by the scheduler lock the
- # three workers above use: this is a Kafka consumer group, so the broker
- # already assigns partitions across replicas, and adding a lock on top
- # would leave every replica but one subscribed to nothing.
- retro_hunt_task: asyncio.Task | None = None
- if settings.RETRO_HUNT_ENABLED:
- try:
- retro_hunt_task = asyncio.create_task(
- run_retro_hunt_consumer(),
- name="retro_hunt_consumer",
- )
- logger.info("retro_hunt consumer started")
- except Exception as exc:
- logger.warning("retro_hunt consumer failed to start", error=str(exc))
-
# Phase 2.6 — flip /readyz to 200. All lifespan-managed
# dependencies have been touched at this point (DB, Redis,
# Neo4j, schedulers); the load balancer can route traffic
@@ -620,6 +661,15 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
except Exception as exc:
logger.warning("approval_expiry worker shutdown error", error=type(exc).__name__)
+ if autonomy_drift_task is not None and not autonomy_drift_task.done():
+ autonomy_drift_task.cancel()
+ try:
+ await autonomy_drift_task
+ except asyncio.CancelledError:
+ logger.debug("autonomy_drift worker cancelled during shutdown")
+ except Exception as exc:
+ logger.warning("autonomy_drift worker shutdown error", error=type(exc).__name__)
+
if retention_purge_task is not None and not retention_purge_task.done():
retention_purge_task.cancel()
try:
diff --git a/services/api/app/services/autonomy_grants.py b/services/api/app/services/autonomy_grants.py
index 2577de048..f36b6d9cd 100644
--- a/services/api/app/services/autonomy_grants.py
+++ b/services/api/app/services/autonomy_grants.py
@@ -430,10 +430,15 @@ async def reconcile_grants(
) -> list[GrantTransition]:
"""Re-check every standing grant and demote the ones that no longer hold.
- Demotion is automatic in the sense that nobody has to ask for it: this
- runs whenever the grants are read and whenever the dispatch path refreshes
- its view, so a grant cannot outlive its evidence by more than the interval
- between those.
+ Demotion is automatic in the sense that nobody has to ask for it. For most
+ of this function's life that sentence was false: its only production
+ caller was the handler behind ``GET /autonomy-policy/grants``, so a grant
+ outlived its evidence until somebody opened a page, which on an unattended
+ deployment is never. ``app.workers.autonomy_drift`` is the caller that
+ needs no human, and ``services/actions`` re-runs the same evaluator before
+ handing a verb to dispatch, so the longest a grant can outlive its
+ evidence is now one sweep interval and the dispatch path refuses it even
+ inside that.
An override is re-checked too, and demoted on the same floors. An operator
overruling a refusal is saying "I accept this today", not "stop measuring";
diff --git a/services/api/app/workers/autonomy_drift.py b/services/api/app/workers/autonomy_drift.py
new file mode 100644
index 000000000..843e8aa2a
--- /dev/null
+++ b/services/api/app/workers/autonomy_drift.py
@@ -0,0 +1,201 @@
+"""Take autonomy back when the evidence stops holding, without waiting to be read.
+
+Fix pass item 3.7. See ``plans/aisoc_fix_pass_plan.plan.md``.
+
+``reconcile_grants`` re-checks every standing grant against the demotion
+floors and writes the transition with its audit row. It shipped with exactly
+one production caller: ``GET /api/v1/autonomy-policy/grants``. So a grant
+whose agreement had collapsed stayed ``granted`` — and kept auto-executing at
+dispatch — until somebody happened to open the autonomy page. On a deployment
+nobody opens that page on, which is every deployment running unattended, the
+demotion floors were decoration.
+
+This is the caller that does not need a human. It runs in ``services/api``
+because that is where the evaluator's write half lives: the tenant session,
+the hash-chained audit log, and the one module allowed to move a grant
+between states.
+
+Reads only this deployment's database
+=====================================
+
+Unlike ``shadow_reconcile``, which is default-off because it polls a
+customer's SIEM on a timer, this sweep makes no outbound call at all. It
+aggregates rows this platform already wrote and, when the floors are crossed,
+demotes. So it is **default on**: a safety control that has to be switched on
+is one that is off wherever nobody knew to switch it on, and the condition it
+exists to catch is precisely the one nobody is watching for.
+
+Closures first
+==============
+
+Each tenant's own closures are reconciled before the grants are judged, in
+that order and for the same reason the endpoint does it: an analyst who has
+just worked a queue should be judged on those decisions rather than on the
+state before them. Running the demotion first would score a window that is
+knowably out of date by the length of one tick.
+
+What it does not do
+===================
+
+It does not promote. Nothing here can widen a tenant's autonomy, in either
+direction of the evidence — a tenant whose numbers recover asks for the
+capability again through the gate, with an actor and an audit row, because a
+grant that reappeared on its own would have nobody's name on it.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import uuid
+from dataclasses import dataclass, field
+from datetime import UTC, datetime
+from typing import Any
+
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.core.config import settings
+from app.db.cross_tenant import assert_cross_tenant_session
+from app.db.database import AsyncSessionLocal
+from app.services.autonomy_grants import reconcile_grants
+from app.services.shadow_agreement import reconcile_local_closures
+from app.workers._tick_failures import TickFailures
+
+logger = logging.getLogger("aisoc.autonomy_drift")
+
+__all__ = [
+ "SweepRun",
+ "run_forever",
+ "run_once",
+]
+
+#: Tenants holding at least one standing grant. A tenant with none has nothing
+#: that could drift, and sweeping every tenant on the deployment to discover
+#: that would scale with the customer list rather than with the feature.
+_TENANTS_WITH_GRANTS_SQL = """
+SELECT DISTINCT tenant_id
+FROM aisoc_autonomy_grants
+WHERE state = 'granted'
+ORDER BY tenant_id
+"""
+
+
+@dataclass
+class SweepRun:
+ """One pass, in the terms an operator reading the log needs.
+
+ ``tenants`` and ``demoted`` are both reported. Zero tenants means nobody
+ on this deployment holds autonomy, which is a different fact from a sweep
+ that looked at twenty and found nothing wrong, and the two are otherwise
+ indistinguishable from the outside.
+ """
+
+ started_at: datetime
+ tenants: int = 0
+ reconciled_closures: int = 0
+ demoted: list[dict[str, Any]] = field(default_factory=list)
+ failed: list[str] = field(default_factory=list)
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "started_at": self.started_at.isoformat(),
+ "tenants": self.tenants,
+ "reconciled_closures": self.reconciled_closures,
+ "demoted": len(self.demoted),
+ "failed": len(self.failed),
+ }
+
+
+def _interval() -> int:
+ """Tick cadence, floored so a misconfigured value cannot become a scan storm."""
+ return max(int(getattr(settings, "AUTONOMY_DRIFT_INTERVAL_SECONDS", 600)), 60)
+
+
+def _max_tenants() -> int:
+ return max(int(getattr(settings, "AUTONOMY_DRIFT_MAX_TENANTS_PER_TICK", 100)), 1)
+
+
+def _safe(value: object, cap: int = 300) -> str:
+ return str(value).replace("\r", "").replace("\n", " ")[:cap]
+
+
+async def run_once(*, db: AsyncSession | None = None, now: datetime | None = None) -> SweepRun:
+ """Re-check every standing grant on the deployment and demote what no longer holds."""
+ started = now or datetime.now(UTC)
+ own_session = db is None
+ if db is None:
+ db = AsyncSessionLocal()
+ run = SweepRun(started_at=started)
+
+ try:
+ await assert_cross_tenant_session(db, "autonomy drift sweep")
+ tenants: list[uuid.UUID] = list((await db.execute(text(_TENANTS_WITH_GRANTS_SQL))).scalars().all())
+ run.tenants = len(tenants)
+
+ for tenant_id in tenants[: _max_tenants()]:
+ try:
+ run.reconciled_closures += await reconcile_local_closures(db, tenant_id)
+ transitions = await reconcile_grants(db, tenant_id, now=now)
+ await db.commit()
+ except Exception as exc: # noqa: BLE001 - one tenant must not end the pass
+ await db.rollback()
+ run.failed.append(str(tenant_id))
+ logger.warning(
+ "autonomy_drift.tenant_failed tenant=%s err=%s detail=%s",
+ _safe(tenant_id, 64),
+ type(exc).__name__,
+ _safe(exc),
+ )
+ continue
+
+ for transition in transitions:
+ record = transition.as_dict()
+ run.demoted.append({"tenant_id": str(tenant_id), **record})
+ # Warning, not info. A capability was taken away from a tenant
+ # who is not looking at the page that would have told them.
+ logger.warning(
+ "autonomy_drift.demoted tenant=%s reasons=%s",
+ _safe(tenant_id, 64),
+ _safe(",".join(transition.refusal_values)),
+ )
+ finally:
+ if own_session:
+ await db.close()
+
+ _log_pass(run)
+ return run
+
+
+def _log_pass(run: SweepRun) -> None:
+ if run.tenants == 0:
+ logger.info("autonomy_drift idle: no tenant holds a standing grant, so nothing can have drifted")
+ return
+ logger.info(
+ "autonomy_drift pass tenants=%d closures_reconciled=%d demoted=%d failed=%d",
+ run.tenants,
+ run.reconciled_closures,
+ len(run.demoted),
+ len(run.failed),
+ )
+
+
+async def run_forever() -> None:
+ """Tick until cancelled. Owned by the API ``lifespan``, like the other workers."""
+ interval = _interval()
+ logger.info("autonomy_drift started interval=%ds max-tenants-per-tick=%d", interval, _max_tenants())
+ failures = TickFailures("autonomy_drift", logger)
+ try:
+ while True:
+ try:
+ await run_once()
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc: # pragma: no cover - defensive
+ failures.record_failure(exc)
+ else:
+ failures.record_success()
+ await asyncio.sleep(interval)
+ except asyncio.CancelledError:
+ logger.info("autonomy_drift stopped")
+ raise
diff --git a/services/api/tests/test_autonomy_drift_sweep.py b/services/api/tests/test_autonomy_drift_sweep.py
new file mode 100644
index 000000000..6e82f903f
--- /dev/null
+++ b/services/api/tests/test_autonomy_drift_sweep.py
@@ -0,0 +1,124 @@
+"""The drift sweep exists, is started, and is on by default.
+
+Fix pass item 3.7. See ``plans/aisoc_fix_pass_plan.plan.md``.
+
+``reconcile_grants`` shipped with one production caller, the handler behind
+``GET /api/v1/autonomy-policy/grants``, so a grant whose evidence had
+collapsed stayed ``granted`` until somebody opened that page. The sweep is the
+caller that needs no human.
+
+What it demotes, and what it leaves alone, is proven against a real Postgres
+in ``tests/isolation/test_autonomy_promotion_live.py``: the aggregate and the
+evaluator agree by convention and a convention is what drifts, so only real
+rows settle it. What is here is the half a database cannot answer — whether
+anything starts the sweep. A worker nobody calls is this repository's most
+frequently rediscovered defect, and it is the defect the sweep itself exists
+to repair one layer down.
+"""
+
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+
+_MAIN = Path(__file__).resolve().parents[1] / "app" / "main.py"
+
+
+def test_the_lifespan_starts_the_sweep() -> None:
+ """Read with ``ast`` rather than imported.
+
+ Importing ``app.main`` pulls in the service's whole startup graph, and a
+ registration test that has to boot the service gets deleted the first time
+ it is slow. Same approach, and the same three checks, as the shadow
+ reconciliation sweep's: the module is imported, a task is created for it,
+ and the task's ``worker=`` is this sweep rather than something that merely
+ mentions it.
+ """
+ tree = ast.parse(_MAIN.read_text(encoding="utf-8"))
+
+ imported = {
+ alias.asname or alias.name
+ for node in ast.walk(tree)
+ if isinstance(node, ast.ImportFrom) and node.module == "app.workers.autonomy_drift"
+ for alias in node.names
+ }
+ assert imported, "app/main.py no longer imports the autonomy drift sweep"
+
+ guarded = [
+ call
+ for call in ast.walk(tree)
+ if isinstance(call, ast.Call) and isinstance(call.func, ast.Name) and call.func.id == "_run_guarded_scheduler_worker"
+ ]
+ assert guarded, "app/main.py no longer registers guarded scheduler workers; this test is stale"
+
+ registered = [
+ call
+ for call in guarded
+ for kw in call.keywords
+ if kw.arg == "worker" and isinstance(kw.value, ast.Name) and kw.value.id in imported
+ ]
+ assert registered, (
+ "the drift sweep is imported by app/main.py but never passed to _run_guarded_scheduler_worker, "
+ "so nothing would call it on a schedule — which is the defect it was written to repair"
+ )
+
+ job_names = {
+ kw.value.value for call in registered for kw in call.keywords if kw.arg == "job_name" and isinstance(kw.value, ast.Constant)
+ }
+ assert "autonomy_drift" in job_names, (
+ f"the sweep is registered under {job_names or 'no job name'}; the Redis scheduler lease is keyed on the "
+ f"job name, so two names means two replicas can demote the same tenant at once"
+ )
+
+
+def test_the_shutdown_path_cancels_it() -> None:
+ """A worker the lifespan starts and never cancels leaks a task per reload."""
+ assert "autonomy_drift_task.cancel()" in _MAIN.read_text(encoding="utf-8")
+
+
+def test_the_sweep_is_on_by_default_and_the_disabled_case_is_announced() -> None:
+ """Unlike the shadow sweep, and the difference is what each one reaches.
+
+ That one polls a customer's SIEM on a timer, so the plan's rule applies
+ and it ships off. This one aggregates rows the deployment already wrote
+ and makes no outbound call; the condition it catches is a grant that has
+ stopped being earned, which by definition nobody is watching for, so
+ shipping it off would leave it off exactly where it matters.
+ """
+ from app.core.config import Settings # noqa: PLC0415
+
+ assert Settings.model_fields["AUTONOMY_DRIFT_ENABLED"].default is True
+
+ # Still announced when switched off, because "no demotions" and "no sweep"
+ # look identical from outside.
+ assert "autonomy_drift worker disabled" in _MAIN.read_text(encoding="utf-8")
+
+
+def test_the_tick_cadence_has_a_floor() -> None:
+ """A misconfigured interval must not become a scan storm over every tenant."""
+ from app.workers import autonomy_drift # noqa: PLC0415
+
+ class _Settings:
+ AUTONOMY_DRIFT_INTERVAL_SECONDS = 0
+ AUTONOMY_DRIFT_MAX_TENANTS_PER_TICK = 0
+
+ original = autonomy_drift.settings
+ autonomy_drift.settings = _Settings() # type: ignore[assignment]
+ try:
+ assert autonomy_drift._interval() >= 60
+ assert autonomy_drift._max_tenants() >= 1
+ finally:
+ autonomy_drift.settings = original
+
+
+def test_the_sweep_cannot_promote() -> None:
+ """It can only take autonomy away.
+
+ A grant that reappeared on its own would have nobody's name on it. A
+ tenant whose numbers recover asks again through the gate, with an actor
+ and an audit row.
+ """
+ source = (Path(__file__).resolve().parents[1] / "app" / "workers" / "autonomy_drift.py").read_text(encoding="utf-8")
+
+ assert "request_promotion" not in source
+ assert "reconcile_grants" in source
diff --git a/tests/isolation/test_autonomy_drift_at_dispatch_live.py b/tests/isolation/test_autonomy_drift_at_dispatch_live.py
new file mode 100644
index 000000000..89f69251b
--- /dev/null
+++ b/tests/isolation/test_autonomy_drift_at_dispatch_live.py
@@ -0,0 +1,260 @@
+"""Dispatch re-checks a standing grant's evidence, against a real database.
+
+Fix pass item 3.7. See ``plans/aisoc_fix_pass_plan.plan.md``.
+
+``services/actions`` resolved unattended execution from ``state = 'granted'``
+alone. That column is a cached verdict: the only thing that ever moved a grant
+out of it was ``reconcile_grants``, whose single production caller was the
+handler behind ``GET /api/v1/autonomy-policy/grants``. So on a deployment
+nobody opens that page on, a tenant whose agreement had collapsed kept
+auto-executing containment at a customer's vendor indefinitely.
+
+Why this file is separate from ``test_autonomy_promotion_live.py``
+------------------------------------------------------------------
+
+``services/api`` and ``services/actions`` both package their code as top-level
+``app``, so one process holds one of them. That suite runs with the API on the
+path; this one runs with the actions service on it, and
+``integration.yml`` gives it its own step with ``working-directory:
+services/actions`` for exactly that reason.
+
+Why it needs a real database rather than a fake connection
+-----------------------------------------------------------
+
+The thing being proven is that two independently-written halves agree: a
+Postgres aggregate written in the shared rules module, and a pure evaluator
+written beside it. A fake connection would answer whatever shape the test
+handed it, which is the assertion agreeing with itself. The arity defect this
+code shipped with makes the point — passing seven parameters to a statement
+that binds six failed closed, so every grant on every deployment was withheld
+while the log called it unreadable evidence, and no offline double would have
+noticed because no offline double refuses a parameter count.
+
+Skipping
+--------
+
+Skips when no Postgres answers, and refuses to skip when
+``AUTONOMY_DRIFT_LIVE_REQUIRED`` is set, following its sibling suite. A suite
+that can silently skip where it is supposed to run reports green for a gate
+nobody executed.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import uuid
+from contextlib import asynccontextmanager
+from datetime import UTC, datetime, timedelta
+
+import pytest
+
+DSN = os.environ.get("DATABASE_URL", "")
+REQUIRED = os.environ.get("AUTONOMY_DRIFT_LIVE_REQUIRED", "").strip().lower() in {"1", "true", "yes", "on"}
+
+pytestmark = [
+ pytest.mark.asyncio,
+ pytest.mark.skipif(
+ "postgres" not in DSN and not REQUIRED,
+ reason="no Postgres DATABASE_URL; set AUTONOMY_DRIFT_LIVE_REQUIRED=1 to make this a failure",
+ ),
+]
+
+CLASS = "identity"
+RULE = "det-identity-004"
+SOURCE = "okta"
+MODEL = "ollama_chat/llama3.2:3b"
+
+#: A HIGH blast-radius verb, deliberately. The cost of reading a stale
+#: ``granted`` is whatever the verb does, and this is the one that takes a
+#: production host off the network.
+VERB = "isolate_host"
+
+MALICIOUS = "true_positive"
+FALSE_POSITIVE = "false_positive"
+
+#: L3. High enough that the tier is not what withholds the verb, so a failure
+#: here is about the evidence and not about the ladder.
+TIER = 3
+
+
+def _asyncpg_dsn(url: str) -> str:
+ """Whatever spelling the environment holds, as a plain asyncpg DSN."""
+ return re.sub(r"^postgres(ql)?\+asyncpg://", "postgresql://", url)
+
+
+@asynccontextmanager
+async def probe():
+ """A tenant at L3 measuring one class, and a connection. Cleans up after itself."""
+ asyncpg = pytest.importorskip("asyncpg")
+
+ conn = await asyncpg.connect(_asyncpg_dsn(DSN), timeout=10.0)
+ try:
+ try:
+ await conn.execute("SELECT 1 FROM aisoc_autonomy_grants LIMIT 0")
+ except Exception as exc: # noqa: BLE001
+ if REQUIRED:
+ pytest.fail(f"migration 067 has not been applied: {exc}")
+ pytest.skip(f"aisoc_autonomy_grants is absent: {exc}")
+
+ tenant_id = uuid.uuid4()
+ slug = f"drift-{tenant_id.hex[:10]}"
+ await conn.execute("INSERT INTO tenants (id, name, slug) VALUES ($1, $2, $3)", tenant_id, "Drift probe", slug)
+ await conn.execute(
+ "INSERT INTO aisoc_shadow_mode (tenant_id, alert_class, enabled, enabled_at) VALUES ($1, $2, TRUE, now())",
+ tenant_id,
+ CLASS,
+ )
+ await conn.execute("INSERT INTO remediation_maturity (tenant_id, maturity_tier) VALUES ($1, $2)", tenant_id, TIER)
+ try:
+ yield conn, tenant_id
+ finally:
+ for table in ("aisoc_autonomy_grants", "aisoc_shadow_decisions", "aisoc_shadow_mode", "remediation_maturity"):
+ await conn.execute(f"DELETE FROM {table} WHERE tenant_id = $1", tenant_id) # noqa: S608 - fixed table list
+ finally:
+ await conn.close()
+
+
+async def _record(conn, tenant_id, *, count: int, verdict: str, disposition: str, resolved_at: datetime) -> None:
+ """``count`` decisions that said ``verdict`` and were closed ``disposition``."""
+ for index in range(count):
+ await conn.execute(
+ """
+ INSERT INTO aisoc_shadow_decisions
+ (tenant_id, alert_id, alert_class, rule_id, source, model, verdict,
+ confidence, decided_at, analyst_disposition, resolution_source, resolved_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, 0.91, $8, $9, 'aisoc', $8)
+ """,
+ tenant_id,
+ uuid.uuid4(),
+ CLASS,
+ RULE,
+ SOURCE,
+ MODEL,
+ verdict,
+ resolved_at + timedelta(seconds=index * 60),
+ disposition,
+ )
+
+
+async def _grant(conn, tenant_id) -> None:
+ """A standing ``action_verb`` grant, written directly.
+
+ Not earned through ``request_promotion``: that lives in ``services/api``
+ and cannot be imported here. Writing the row states the precondition this
+ suite is about — a grant whose *state* says granted — without making the
+ dispatch assertion depend on the promotion gate agreeing first.
+ """
+ await conn.execute(
+ """
+ INSERT INTO aisoc_autonomy_grants
+ (tenant_id, scope_kind, scope_key, capability, state, source, evidence, granted_at)
+ VALUES ($1, 'action_verb', $2, 'auto_execute', 'granted', 'earned', '{}'::jsonb, now())
+ """,
+ tenant_id,
+ VERB,
+ )
+
+
+async def _strong_record(conn, tenant_id) -> None:
+ base = datetime.now(UTC) - timedelta(days=20)
+ await _record(conn, tenant_id, count=200, verdict=FALSE_POSITIVE, disposition=FALSE_POSITIVE, resolved_at=base)
+ await _record(conn, tenant_id, count=40, verdict=MALICIOUS, disposition=MALICIOUS, resolved_at=base + timedelta(days=1))
+
+
+async def _resolve(tenant_id):
+ from app.services.tenant_policy import clear_cache, resolve_tenant_policy
+
+ # The resolver caches for 30s and these tests change the evidence under
+ # one tenant several times, which is not something production does.
+ clear_cache()
+ return await resolve_tenant_policy(str(tenant_id))
+
+
+class TestDispatchReadsTheEvidenceAndNotJustTheState:
+ async def test_a_grant_whose_evidence_has_drifted_is_withheld(self):
+ """The reproduction. The row still says ``granted``; the verb is refused.
+
+ Deliberately without running the API's sweep first, because the point
+ is the window between its ticks: in that window the stored state is
+ stale and this is the only thing standing between it and a vendor.
+ """
+ async with probe() as (conn, tenant_id):
+ await _strong_record(conn, tenant_id)
+ await _grant(conn, tenant_id)
+ await _record(
+ conn,
+ tenant_id,
+ count=30,
+ verdict=FALSE_POSITIVE,
+ disposition=MALICIOUS,
+ resolved_at=datetime.now(UTC) - timedelta(minutes=30),
+ )
+
+ state = await conn.fetchval("SELECT state FROM aisoc_autonomy_grants WHERE tenant_id = $1", tenant_id)
+ assert state == "granted", "the stored state must still be stale, or this proves nothing"
+
+ policy = await _resolve(tenant_id)
+
+ assert policy.from_store is True, f"the tenant's stored policy was not read: source={policy.source}"
+ assert policy.earned_autonomy_for(VERB) is None
+ assert policy.earned_verbs == {}
+
+ async def test_a_grant_whose_record_still_holds_is_honoured(self):
+ """The control. A re-check that always refuses is not a re-check.
+
+ It would pass the test above, and it would silently disable earned
+ autonomy on every deployment — a product that has stopped acting,
+ wearing the appearance of caution.
+ """
+ async with probe() as (conn, tenant_id):
+ await _strong_record(conn, tenant_id)
+ await _grant(conn, tenant_id)
+ await _record(
+ conn,
+ tenant_id,
+ count=30,
+ verdict=FALSE_POSITIVE,
+ disposition=FALSE_POSITIVE,
+ resolved_at=datetime.now(UTC) - timedelta(minutes=30),
+ )
+
+ policy = await _resolve(tenant_id)
+
+ assert policy.earned_autonomy_for(VERB) == "earned"
+
+ async def test_a_demoted_row_is_refused_without_reaching_the_aggregate(self):
+ """The pre-existing state check still stands in front of the new one."""
+ async with probe() as (conn, tenant_id):
+ await _strong_record(conn, tenant_id)
+ await _grant(conn, tenant_id)
+ await conn.execute(
+ "UPDATE aisoc_autonomy_grants SET state = 'demoted', demoted_at = now() WHERE tenant_id = $1",
+ tenant_id,
+ )
+
+ policy = await _resolve(tenant_id)
+
+ assert policy.earned_autonomy_for(VERB) is None
+
+ async def test_an_empty_window_keeps_the_grant_as_the_shared_evaluator_says(self):
+ """Dispatch must not be stricter than the evaluator, only no laxer.
+
+ ``evaluate_demotion`` deliberately ignores an unmeasured rate: a week
+ in which no malicious alert arrived is not evidence the agent got
+ worse, and revoking over an empty denominator would make quiet weeks
+ dangerous. The grant was earned on evidence at promotion time and an
+ empty window since does not retract it.
+
+ This is asserted rather than assumed because the obvious instinct
+ writing a dispatch-side re-check is to refuse what it cannot measure,
+ and a re-check that invented that rule would be a *second* definition
+ of the floors — the divergence the shared module exists to prevent,
+ reintroduced by the fix for it.
+ """
+ async with probe() as (conn, tenant_id):
+ await _grant(conn, tenant_id)
+
+ policy = await _resolve(tenant_id)
+
+ assert policy.earned_autonomy_for(VERB) == "earned"
diff --git a/tests/isolation/test_autonomy_promotion_live.py b/tests/isolation/test_autonomy_promotion_live.py
index 0b929dba9..353101fb9 100644
--- a/tests/isolation/test_autonomy_promotion_live.py
+++ b/tests/isolation/test_autonomy_promotion_live.py
@@ -646,3 +646,109 @@ class TestTheTransitionsAreInTheHashChainedLog:
assert valid, f"chain broken at row {index}: {reason}"
# The second row chains onto the first rather than starting a new one.
assert rows[1]["prev_hash"] == rows[0]["entry_hash"]
+
+
+class TestDemotionDoesNotWaitForAPageLoad:
+ """Fix pass 3.7. Every test here reaches the grants through the sweep.
+
+ ``reconcile_grants`` had one production caller: the handler behind ``GET
+ /api/v1/autonomy-policy/grants``. The class above proves the evaluator
+ demotes correctly; it proves it by calling ``reconcile_grants`` directly,
+ which is also what the endpoint does, so between them they say nothing
+ about whether a demotion ever happens on a deployment nobody is clicking
+ around in. On an unattended one — which is every deployment running the
+ product as intended — the floors were decoration.
+
+ So nothing below touches the router, the endpoint or an HTTP client. The
+ sweep is handed a session and asked what it did.
+ """
+
+ async def test_the_sweep_demotes_a_drifted_grant_with_no_read_of_the_api(self):
+ async with probe() as (session, tenant_id, user_id):
+ from app.workers.autonomy_drift import run_once
+ from sqlalchemy import text
+
+ base = datetime.now(UTC) - timedelta(days=20)
+ await _record(session, tenant_id, count=200, verdict=FALSE_POSITIVE, disposition=FALSE_POSITIVE, resolved_at=base)
+ await _record(session, tenant_id, count=40, verdict=MALICIOUS, disposition=MALICIOUS, resolved_at=base + timedelta(days=1))
+ assert (await _promote(session, tenant_id, user_id)).granted is True
+
+ await _record(
+ session,
+ tenant_id,
+ count=30,
+ verdict=FALSE_POSITIVE,
+ disposition=MALICIOUS,
+ resolved_at=datetime.now(UTC) - timedelta(minutes=30),
+ )
+
+ run = await run_once(db=session)
+
+ mine = [row for row in run.demoted if row["tenant_id"] == str(tenant_id)]
+ assert len(mine) == 1, f"the sweep did not demote this tenant: {run.as_dict()}"
+ assert "recent_drift" in mine[0]["refusals"]
+
+ state = (
+ await session.execute(
+ text("SELECT state FROM aisoc_autonomy_grants WHERE tenant_id = :t"),
+ {"t": tenant_id},
+ )
+ ).scalar_one()
+ assert state == "demoted"
+ assert await _audit_actions(session, tenant_id) == ["autonomy:granted", "autonomy:demoted"]
+
+ async def test_the_sweep_leaves_a_grant_whose_record_still_holds(self):
+ """The control that matters more than the demotion.
+
+ A sweep that demoted everything would pass the test above and would
+ be worse than no sweep: it would take every tenant's autonomy away on
+ the first tick, and the symptom — a product that has quietly stopped
+ acting — reads as caution rather than as a fault.
+ """
+ async with probe() as (session, tenant_id, user_id):
+ from app.workers.autonomy_drift import run_once
+ from sqlalchemy import text
+
+ base = datetime.now(UTC) - timedelta(days=20)
+ await _record(session, tenant_id, count=200, verdict=FALSE_POSITIVE, disposition=FALSE_POSITIVE, resolved_at=base)
+ await _record(session, tenant_id, count=40, verdict=MALICIOUS, disposition=MALICIOUS, resolved_at=base + timedelta(days=1))
+ assert (await _promote(session, tenant_id, user_id)).granted is True
+
+ # Thirty more decisions, all agreed. Nothing has drifted.
+ await _record(
+ session,
+ tenant_id,
+ count=30,
+ verdict=FALSE_POSITIVE,
+ disposition=FALSE_POSITIVE,
+ resolved_at=datetime.now(UTC) - timedelta(minutes=30),
+ )
+
+ run = await run_once(db=session)
+
+ assert [row for row in run.demoted if row["tenant_id"] == str(tenant_id)] == []
+ state = (
+ await session.execute(
+ text("SELECT state FROM aisoc_autonomy_grants WHERE tenant_id = :t"),
+ {"t": tenant_id},
+ )
+ ).scalar_one()
+ assert state == "granted"
+ assert await _audit_actions(session, tenant_id) == ["autonomy:granted"]
+
+ async def test_a_tenant_with_no_grant_is_not_swept(self):
+ """The sweep's candidate list is grants, not the customer list.
+
+ Enumerating every tenant to discover that almost none of them holds
+ autonomy would make the cost of this feature scale with how many
+ customers a deployment has rather than with how many use it.
+ """
+ async with probe() as (session, tenant_id, _user_id):
+ from app.workers.autonomy_drift import run_once
+
+ base = datetime.now(UTC) - timedelta(days=20)
+ await _record(session, tenant_id, count=50, verdict=FALSE_POSITIVE, disposition=MALICIOUS, resolved_at=base)
+
+ run = await run_once(db=session)
+
+ assert [row for row in run.demoted if row["tenant_id"] == str(tenant_id)] == []