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.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
fix(fusion): durable delivery, recoverable lake archival and replay-safe windowed detections (#1529)
Beenu Arora17fe377baf15
diff --git a/docs/remediation/phase-4-6-fusion-durability.md b/docs/remediation/phase-4-6-fusion-durability.mdnew file mode 100644index 000000000..236a6a338--- /dev/null+++ b/docs/remediation/phase-4-6-fusion-durability.md@@ -0,0 +1,577 @@+# Fusion durability: delivery, archival and windowed detections++Remediation phases 4, 5 and 6. All three live in `services/fusion`, which is+why they are one piece of work: they are three different answers to the same+question — *what does this service promise when the process dies between two+steps?*++Each finding below carries its status, the production path it affects, the+regression test that pins it, what changed, how it was verified, and what is+still true after the fix. Where something could not be verified it says so;+an implied pass is worth less than a stated gap.++---++## Summary of guarantees++| | Before | After |+| --- | --- | --- |+| **Fused-alert delivery** | Enqueue reported as delivery. An alert could be durable in Postgres, its offset committed, and nothing ever published. | **At-least-once.** The broker acknowledgement is awaited; an alert that still owes a notification is journalled before the message can be acknowledged, and a relay delivers it. |+| **Lake archival** | Accepted meant *buffered in memory*. A hard kill lost the buffer; capacity discarded the oldest rows after their offsets were committed. | **At-least-once with a disk spool.** Accepted means on disk. Capacity is back-pressure. A batch the store refuses is quarantined, not deleted. |+| **Windowed detections** | An observation was one *delivery*; a threshold hit was suppressed by its own retry. | **Idempotent per source event**, event-time windows, and a hit is recoverable until its alert is durable. |++None of this is exactly-once and none of it is described that way. The three+places duplicates remain possible are named in [Residual+limitations](#residual-limitations).++---++## Phase 4 — Finding 3: the fused-alert delivery future was discarded++**Status: reproduced and fixed.**++### The production path++`FusionWorker._fuse_and_persist` persists the alert row, then publishes the+fused envelope to `aisoc.alerts.fused`, which is what `services/agents`+consumes to auto-triage. The publish was:++```python+await asyncio.wait_for(producer.send(topic, value=envelope), timeout=...)+```++`AIOKafkaProducer.send` is a coroutine that appends the record to the client's+in-memory batch accumulator and returns a **future** that resolves when the+broker acknowledges it. Awaiting the call awaits the *enqueue*. The delivery+outcome — including a refusal arriving milliseconds later — was in the future+that was dropped.++The consumer commits the input offset as soon as `_handle_message` returns+true, immediately after that buffered send. A kill in that window leaves the+alert row in Postgres, the envelope in process memory, and the offset past the+source event. The alert exists and auto-triage never sees it.++The repository already knew the correct shape and explained it:+`services/fusion/app/services/dlq.py` does `future = await send(...)` then+`await future`, with a comment stating this exact hazard, and `dlq_replay.py`+uses `send_and_wait`. The hot path was the one place it was not applied.++### Why it survived a 25-case durability suite++Every existing test used `AsyncMock()` as the producer. Its `send` returns an+awaitable resolving to a `MagicMock`, so `send` and `send_and_wait` are+indistinguishable under it — both read as "awaited, no exception". The one+test that looked like it covered this,+`test_publish_failure_after_a_durable_row_is_retryable`, drives a double whose+`send` *raises*, which is an enqueue-stage failure the original code caught+correctly.++The suite's producer double now lives in+`services/fusion/tests/kafka_doubles.py`, models the two-stage contract, and+says in its docstring why `AsyncMock` must not be used for anything reaching a+publish.++### Regression tests++| Test | Proves |+| --- | --- |+| `test_publish_acknowledgement.py::test_a_broker_error_delivered_after_the_enqueue_is_observed` | A refusal arriving after a successful enqueue is reported. |+| `…::test_an_unacknowledged_record_is_not_reported_as_published` | A record still in the accumulator is not a delivery. |+| `…::test_publishing_returns_only_after_the_acknowledgement` | Positive control, and the ordering claim on the happy path. |+| `…::test_the_published_envelope_carries_a_stable_dedupe_key` | Every republication of one alert carries one key. |+| `integration/test_publish_acknowledgement_live.py` (3 tests) | The same three claims against a real broker. |++### The fix++`FusionWorker._deliver` awaits the enqueue and then the delivery future, with+one `wait_for` around both so `AISOC_KAFKA_SEND_TIMEOUT_SECONDS` is an+end-to-end delivery deadline rather than a bound on a local memory append.+A timeout cancels the wait, not the record, so a timed-out publish is reported+as **unconfirmed and re-published**, never as lost.++Records are keyed by the canonical alert id. Re-publication is designed-for —+an offset commit and a broker ack cannot be made atomic — so the key is part+of the contract: every copy of an alert lands on one partition under one key,+which is what makes a downstream de-duplicator tractable.++### Compatibility++Keying changes which partition a fused alert lands on. A consumer group reads+all partitions, so consumption is unaffected; per-key ordering improves.+`services/agents`' triage worker needs no change — `alert_row_id` was already+in the envelope, and it is the dedupe key.++---++## Phase 4 — the crash window, and the recovery mechanism++**Status: source-confirmed gap, closed.** There was no outbox and no+reconciliation sweep (`grep -r outbox services/fusion` returned nothing).++Two orderings are possible between a durable alert row and its notification,+and only one recovered:++1. **The process dies between the durable row and the publish.** The input+ offset was never committed, so Kafka re-delivers, the sink answers a+ verified `DUPLICATE`, and the publish is retried. Re-delivery is the+ recovery and it already worked.+2. **The publish fails until the retry budget runs out.** The message is then+ dead-lettered — a durable capture, so the offset *commits*, correctly. From+ that moment nothing re-delivers the record. The alert row exists, the+ offset is past the source event, and no envelope will ever be published.+ A dead letter is a triage record; nothing re-drives it.++Case 2 is permanent loss of the notification for an alert sitting in Postgres,+with every surface reporting success.++### The fix: a notification journal, not a transactional outbox++Migration `121_fusion_alert_outbox.sql` adds `fusion_alert_outbox`. A row is+written when a publish has definitively failed, and always **before** the+consumer may acknowledge the message. `NotificationRelay` runs beside the+consume loop, claims rows under a lease, publishes them through the same+awaited-ack path as the inline publish, and deletes them.++This is deliberately **not** a transactional outbox, and the reasoning is+recorded in the migration: the happy path writes nothing, because case 1 is+already closed by an offset that has not moved. Making every alert pay an+extra `INSERT` and `DELETE` to cover a window re-delivery closes for free+would buy nothing — a transactional outbox would not make delivery+exactly-once either, it would only move the duplicate.++Rows are deleted on delivery rather than flagged, so the table *is* the+backlog: `count(*)`, not a filtered scan over delivery history.++A `DUPLICATE` persist outcome clears any pending row. That is the only path on+which one can exist, so the happy path pays nothing for it.++If the journal cannot be written the alert is counted+(`notifications_unrecoverable`), logged at `critical`, and the dead-letter+reason says *the notification* was lost rather than the alert — an operator+reading "transient processing failure" alone would look for a missing alert,+find one, and conclude the pipeline is healthy.++### Acceptance criteria++| Criterion | Where it is proved |+| --- | --- |+| DB commit succeeds + Kafka delivery fails | `test_a_broker_error_delivered_after_the_enqueue_is_observed`; live `test_a_refusal_that_arrives_after_the_enqueue_is_reported` |+| Process exits after DB commit before publication | Offset is not committed, so Kafka re-delivers — `test_consumer_durability.py::test_consume_loop_does_not_commit_a_failed_message` |+| Kafka publication succeeds + input-offset commit fails | Re-delivery republishes under the same key; `test_the_published_envelope_carries_a_stable_dedupe_key` |+| Restart recovers pending notifications | `test_alert_outbox.py::test_the_relay_delivers_a_journalled_notification`; `integration/test_alert_outbox_live.py::test_the_relay_drains_the_real_table` |+| A delayed broker error is observed and reported | `integration/test_publish_acknowledgement_live.py::test_a_refusal_that_arrives_after_the_enqueue_is_reported` |+| Duplicate delivery produces no duplicate downstream effect | One key per alert plus `alert_row_id`; the sink's per-tenant dedup index (migration 120) collapses a re-persist |++---++## Phase 5 — Finding 11: "accepted" meant buffered in memory++**Status: reproduced and fixed.**++### The production path++`LakeWriter.write_event` appended to `self._buffer` — a plain `list[dict]` —+and returned `True`; its own docstring admitted True meant "accepted for+archival, not that it is already durable". `consumer.py` used that return only+to bump a counter and committed the input offset regardless. So archival rode+entirely on process memory and the fusion consumer-group offset:++* a hard kill lost the buffer whole (`stop()` was honest and counted retained+ rows as dropped, but `SIGKILL` does not run `stop()`);+* `_enforce_buffer_capacity` discarded the **oldest** rows on overflow —+ loudly, but long after their offsets were committed, so nothing could replay+ them;+* there was no spool and no lake checkpoint, so "the lake is behind" and "the+ lake has a permanent hole" were indistinguishable.++The recovery machinery already existed and nothing triggered it:+`_fallback_event_id` derives a replay-stable id from the Kafka coordinates and+the table is read with `LIMIT 1 BY event_id`, so a replay *would* deduplicate.+What was missing was a reason to replay.++ClickHouse outage handling was already good — re-prepends the batch,+distinguishes connection from data errors, reconnects with capped backoff —+and is preserved.++### The fix: the queue is a disk spool++`services/fusion/app/services/lake_spool.py`. `write_event` returns `True`+only once the row is on an append-only segment file, `start()` replays+whatever ClickHouse never took, and the consumer raises a retryable failure+when archival cannot make an event durable, so the offset is held.++**Only the spool refusing an event applies back-pressure.** A ClickHouse+outage is absorbed and costs the alert path nothing — that is the distinction+between "the archive is behind" and "the archive cannot accept anything".++**Capacity is back-pressure, never discard.** At the byte cap `write_event`+returns `False`, the offset is held, and Kafka's retention becomes the+buffer — a durable log the platform already runs, orders of magnitude larger+than any in-process cap. The regression test asserts back-pressure rather than+headroom, specifically so raising a limit cannot pass as a durability fix.++**A batch the store keeps refusing is quarantined, not deleted.** A repeated+non-connection error is a schema disagreement; retrying forever blocks+everything behind it, but deleting makes the gap permanent even after someone+fixes the schema. The rows move to `<spool>/quarantine/` and the count is+exposed.++### What the spool survives, exactly++| Failure | Survives? |+| --- | --- |+| Process crash, `SIGKILL`, container **stop** | **Yes.** The bytes are in the kernel page cache; the OS writes them out whether or not this process lives. |+| Machine power loss, kernel panic | **Only with `AISOC_LAKE_SPOOL_FSYNC=1`**, which costs a disk round trip per batch. Off by default. |+| Container **destroyed** / pod rescheduled | **Only if the spool directory is a mounted volume.** Otherwise rows whose Kafka offsets were already committed are gone. |++The third row is a real limitation and is stated rather than papered over.+`AISOC_LAKE_SPOOL_DIR` defaults to `.aisoc/lake-spool`, relative so a first run+needs no provisioning; a containerised deployment must mount it.++### Exposure++`LakeWriter.metrics()` existed and **had no caller anywhere in the service** —+the backlog it computed was unreadable. `GET /metrics` now returns it:+`spool_rows`, `spool_bytes`, `capacity_refusals`, `quarantined_rows`,+`rows_recovered`, `rows_dropped`, `spool_unreadable_lines`,+`spool_write_failures` and a `degraded` flag, alongside the notification+backlog (total, age of the oldest, and a per-tenant breakdown). Anything+unreadable reports `None`, never `0`.++`rows_dropped` is now reserved for genuine unrecoverable loss. Nothing in the+normal path increments it, so a non-zero value means events are actually gone.++### Acceptance criteria++| Criterion | Test |+| --- | --- |+| Hard termination before a flush | `test_lake_durability.py::test_a_hard_kill_before_a_flush_does_not_lose_the_archive` |+| Extended ClickHouse outage | `…::test_a_clickhouse_outage_does_not_stop_the_alert_pipeline`, `…::test_an_extended_outage_drains_when_the_store_returns` |+| Capacity exhaustion | `…::test_capacity_exhaustion_applies_back_pressure_instead_of_dropping`, `…::test_a_refused_event_stops_the_offset_committing` |+| Partial / ambiguous insert outcomes | `…::test_a_batch_the_server_keeps_rejecting_is_quarantined_not_deleted`; reading the spool is non-destructive, so a crash between insert and commit replays and collapses on `event_id` |+| Restart and recovery | `…::test_a_hard_kill_before_a_flush_does_not_lose_the_archive` |+| Duplicate replay | `…::test_a_replayed_event_keeps_one_identity` |+| Graceful shutdown | `…::test_graceful_shutdown_leaves_a_recoverable_backlog_not_a_loss` |++### Three existing tests were pinning the defect++`test_stop_counts_rows_it_could_not_flush_as_dropped`,+`test_buffer_overflow_drops_oldest_rows_explicitly` and+`test_data_errors_are_bounded_and_dropped_loudly` asserted that retained rows+are dropped at shutdown, that overflow discards the oldest rows, and that a+rejected batch is deleted. Each was a correct reading of the old design and is+now wrong; each was rewritten with a comment saying what it used to assert and+why that changed.++---++## Phase 6 — Findings 2 and 6: windowed detections were not replay-safe++**Status: both reproduced and fixed.**++### Finding 6 — observation inflation++`_observe_and_check` minted a fresh `uuid.uuid4().hex` member per call for a+threshold rule with no `distinct_by`. Delivery into this engine is+at-least-once and the consumer *deliberately* re-delivers on+`RetryableProcessingError`, so one event counted N times was N members: **N+re-deliveries of a single failed login crossed a threshold of N**, producing a+brute-force alert naming a user who did nothing.++The member is now the event's stable identity — ingest id, then Kafka+coordinates, then a content hash, the same preference order and the same+documented trade-off as `lake_writer._fallback_event_id`. `ZADD` on an+existing member updates its score rather than adding a row, so a re-delivered+event refreshes its own observation.++**The dual use of one sorted set is preserved exactly.** A `distinct_by`+rule's member is the observed value; an event-count rule's member is the+event. Both mean "one row per distinct thing" and differ only in what the+thing is. `test_a_distinct_by_rule_still_counts_distinct_values` pins that a+fix making every member the event id would turn secret enumeration into a+request-rate rule.++### Finding 2 — the retry suppressed the alert it existed to recover++The fire-once marker was written *inside* `_observe_and_check`, before+`evaluate` had built the `DetectionHit` and long before the consumer persisted+anything. `_fuse_and_persist` raises when the row is not durable, so Kafka+re-delivers — and on re-delivery `SET NX` returned falsy and no hit was+produced until the window rolled.++Firing is now a **claim**, not a flag:++1. Crossing the threshold takes `SET fired_key <token> NX EX 60`.+2. The consumer persists the alert.+3. `confirm(hit)` promotes the claim to the window-long marker; `release(hit)`+ drops it if the alert never landed.++Moving the write to *after* the database would have traded this race for a+different one — two workers both crossing the threshold before either had+written anything. Taking the claim atomically up front and resolving it+afterwards avoids both.++Both resolutions are owner-checked Lua, because an unconditional `DEL` would+free the claim of the worker that took it after yours expired, and that+worker's alert would then publish twice.++**Crash recovery** is the third outcome: a worker that dies resolves nothing+and the lease ages out, so the alert is delayed by `FIRE_CLAIM_SECONDS` (60)+rather than suppressed for the window.++### Event time, late arrival, out-of-order delivery, backfill++Scores are **event time**, with arrival as the fallback for a source that+stamps nothing. Almost every connector here polls, so arrival order is the+vendor's order; scoring by wall clock made a detection a function of the poll+cadence and made replaying a week of history look like one enormous burst+happening now.++The count is two window-length spans anchored on the event — the one ending at+it and the one starting at it — via `ZCOUNT`. The trailing span catches a+burst whose last event arrives last; the leading span catches one whose first+event arrives last.++Trimming is against the event's own time, bounded by+`REORDER_TOLERANCE_SECONDS` (300): an event that arrives late is old by+construction, and trimming it against the clock would discard the observation+it just made.++The cooldown key carries the **event-time bucket**, which is what makes a+replay idempotent rather than merely unlikely: the same events replayed at any+wall-clock time land in the same bucket and meet the same confirmed marker.++### A Redis blip no longer reads as a quiet estate++A per-rule error was caught at `logger.debug`, so a Redis outage and an estate+with nothing happening were indistinguishable. Detection stays fail-soft —+Redis must not wedge the alert pipeline — but the skip is now counted+(`WindowedDetectionEngine.rule_errors`) and logged at `warning`.++### Acceptance criteria++| Criterion | Test |+| --- | --- |+| Persistence fails immediately after a threshold is crossed | `test_windowed_replay_safety.py::test_a_hit_that_was_never_persisted_fires_again_on_re_delivery` |+| The threshold event is delivered repeatedly | `…::test_one_event_delivered_five_times_does_not_cross_a_threshold_of_five`, `…::test_a_persisted_hit_does_not_fire_twice` |+| A worker restarts during the handoff | `…::test_a_crashed_worker_does_not_suppress_the_alert_forever` |+| Multiple workers process overlapping deliveries | `…::test_two_workers_on_overlapping_deliveries_produce_one_hit`; live `integration/test_windowed_detection_live.py::test_two_concurrent_workers_take_one_claim_between_them` |+| Events arrive out of order | `…::test_out_of_order_arrival_reaches_the_same_verdict_as_in_order` |+| Historical events are backfilled | `…::test_a_historical_backfill_does_not_merge_with_live_traffic` |+| No duplicate alert or duplicate response effect | live `…::test_a_worker_cannot_release_another_workers_claim`, `…::test_a_worker_cannot_confirm_another_workers_claim` |++### Six Redis doubles became one++Five test files each carried their own in-memory Redis with a different subset+of commands; none had `eval`, some lacked `zrangebyscore`. The cost is not+duplication — it is that a command the engine newly calls raises inside the+fail-soft per-rule handler, the rule silently produces no hit, and the test+fails with "the detection did not fire" when the real answer is "the double+cannot do what Redis does". There is now one double in+`services/fusion/tests/redis_doubles.py`.++The two things a Python double cannot model — that `SET NX` is atomic between+two workers, and that the owner check and the write inside each script happen+together — are proved against a real server in+`tests/integration/test_windowed_detection_live.py`.++### One existing test had its data corrected++`test_sigma_correlation_replay.py::test_event_count_fires_at_its_threshold_and_not_one_short`+placed its first five events a second apart and the sixth **996 seconds+later**, in a 600-second window, and passed — because the engine scored by+arrival time and ignored `event_time` entirely. The data is now what the rule+describes, and the out-of-window case is asserted rather than relied on by+accident.++---++## Verification performed++Everything below was run on this branch. Commands and results are literal.++**Environment.** Python 3.11.15 in a virtualenv built from the fusion+service's own locked set (`python3 scripts/service_requirements.py fusion+--locked`); `ruff 0.16.10` and `mypy 2.4.0` in a separate virtualenv at the+pinned ranges, because a service venv holds that service's lock and nothing+else.++**Containers.** Real Postgres 16, Redis 7 and Redpanda v24.2.7 were available+and used. The live suites are gated on `AISOC_TEST_POSTGRES`,+`AISOC_TEST_REDIS` and `AISOC_TEST_KAFKA` and skip cleanly without them.++```+services/fusion$ pytest tests/ -q+1049 passed, 2 skipped, 1 warning in 20.81s # with all three containers+1035 passed, 9 skipped # without them, live suites skipped++$ ruff check services/ scripts/ tests/ tools/ → All checks passed!+$ ruff format --check . → 2605 files already formatted+$ python scripts/check_mypy_baseline.py → OK — no tree got worse (964 findings)+$ python scripts/check_tenant_query_predicates.py → OK (ratchet unchanged at 60)+$ python scripts/check_rls_policy_shape.py → OK (160 policies, 159 FORCEd)+$ python scripts/check_module_reachability.py → OK (1037 of 1065 reachable)+$ python scripts/check_raw_sql_columns.py → 566 statements parsed, no failure+$ python scripts/check_competitor_names.py → OK+$ python scripts/check_attribution.py --diff-base origin/main → OK+```++### Negative controls++Each fix was reverted in place and the suite re-run. Results are what was+actually printed.++| Control | Result |+| --- | --- |+| `await future` removed from `_deliver` | 3 failed — the two delivery-failure cases do not raise, and the happy path returns with the future pending. |+| Same, against the **real broker** | 1 failed, and Python reports the defect itself: `Future exception was never retrieved: MessageSizeTooLargeError`. |+| Journal write removed from the publish-failure path | 3 failed — `assert 0 == 1` on the pending journal row. |+| Consumer stops gating the offset on durable archival, and `write_event` ignores the spool's answer | 2 failed — capacity and offset-hold. |+| `LakeSpool.append` made a no-op (memory-only queue again) | 23 failed across both lake suites. |+| Random member per call restored | 3 failed, including the live real-Redis inflation test. |+| Cooldown written before persistence as a window-long flag | 3 failed, including both live claim/release tests. |++**One control changed a test rather than confirming it**, and it is the most+useful result here. The first version of the live broker-refusal test used+aiokafka's default `max_request_size` with a 2 MiB record; aiokafka enforces+that limit itself inside `send`, so the rejection happened at the *enqueue* —+which the original code caught correctly — and the test **passed with the fix+reverted**. Raising the client limit past the broker's moved the rejection to+delivery. A live test exercising the wrong stage is worse than no live test: it+reports coverage of exactly the thing it does not cover.++### What was not verified++* **No full-stack `make up` run.** The pipeline was exercised component by+ component against real Postgres, Redis and Redpanda, not as a 16-service+ compose stack with a connector polling a real vendor. The end-to-end+ connector → ingest → fusion → agents journey is unverified by this work.+* **No multi-replica deployment.** Two-worker behaviour is proved by two+ engine instances against one real Redis and two outbox instances against one+ real Postgres, which exercises the server-side primitives that make it safe.+ It is not the same as two containers under a rebalance.+* **No power-loss test.** The `AISOC_LAKE_SPOOL_FSYNC` path is implemented and+ unit-covered; nobody pulled a plug.+* **No throughput measurement.** The spool adds one buffered `write()` per+ archived event and the windowed engine's count went from one `ZCARD` to two+ `ZCOUNT`s. The suite's own timing is the only number taken: 18.5 s → 20.8 s+ for ~1,000 tests, of which the lake spool's initial O(backlog) line count was+ the dominant cost until it was cached. No EPS benchmark was run.++### A gate weakness found and not exploited++`scripts/check_tenant_query_predicates.py` credits a raw statement as+tenant-scoped when the token `tenant_id` appears anywhere in the SQL text,+including a `RETURNING` list. `AlertNotificationOutbox.claim` is cross-tenant+by design and is credited on that basis rather than on a predicate — confirmed+by removing `o.tenant_id` from its `RETURNING` clause, after which the gate+flags it. `backlog` is credited the same way, and it genuinely groups by+tenant.++Rather than lean on this further, `resolve` and `record_attempt_failed` were+**given real tenant predicates** using the tenant their own claim returned, so+the ratchet is unchanged at 60 entries and no ceiling was raised. The gate's+blind spot is reported here; fixing it is outside this change's scope.++---++## Residual limitations++1. **Delivery is at-least-once, not exactly-once.** The relay can publish an+ envelope an inline retry already delivered, and a broker acknowledgement+ arriving after the publisher stopped waiting is indistinguishable from one+ that never arrived. Every record is keyed by its alert id so a consumer can+ collapse duplicates; `alert_row_id` in the envelope is the same key.+2. **The journal is only as available as Postgres.** If a publish fails *and*+ the journal cannot be written, the dead-letter capture is the only record+ of the envelope. That is a durable, triageable archive of the payload but+ it is not a delivery: it is counted as `notifications_unrecoverable` and+ logged at `critical`. The consumer does not stall the partition for it,+ because the alert row itself is durable — what is lost is the notification.+3. **The spool is only as durable as its filesystem.** See the table in Phase+ 5. A container without a mounted volume loses spooled rows whose offsets+ were committed.+4. **One windowed ordering case is detected late rather than immediately.** A+ burst whose last-arriving event is strictly interior to the span is covered+ by neither anchored window; it fires on the next matching event for that+ entity. The alternative — fetching every member and sweeping in process —+ is O(backlog) per event, and the rules with the largest thresholds have the+ largest backlogs.+5. **A burst straddling an event-time bucket boundary can fire twice**, once+ per bucket. The bucket is what makes a replay idempotent, which is the more+ valuable property; the alert sink's per-tenant dedup index collapses the+ second row where the fingerprint matches.+6. **Migration 121 must be applied.** Without it the journal reports itself+ absent once at `error` and archival of undelivered notifications does not+ happen. The table is deliberately not created at runtime: a+ `CREATE TABLE IF NOT EXISTS` there would swallow a permissions failure into+ a log line and leave the service reporting a healthy journal holding+ nothing.++---++## Operator recovery procedure++### An alert exists in Postgres but auto-triage never saw it++```bash+curl -s localhost:8003/metrics | jq '.notifications'+# {"pending": 12, "oldest_seconds": 480.3, "by_tenant": {"<uuid>": 12}}+```++`pending` is the number of alerts that still owe a notification; `by_tenant`+says whose. The relay sweeps every `AISOC_OUTBOX_RELAY_INTERVAL_SECONDS`+(default 15) and only touches rows older than+`AISOC_OUTBOX_RELAY_GRACE_SECONDS` (default 120), which is the head start the+consumer's own inline retries get.++* **Pending falling** — it is draining; nothing to do.+* **Pending flat with `oldest_seconds` rising** — the broker is unreachable to+ this replica, or the relay is not running. Check `fusion.relay_publish_failed`+ and `/readyz`'s `kafka` key, which probes the broker rather than the loop.+* **`notifications_unrecoverable` non-zero** — the journal itself could not be+ written. The envelope is in the dead-letter store; search for+ `notification was neither published nor journalled`.+* **`pending: null`** — the backlog could not be read. That is *unknown*, not+ empty: check `fusion.outbox_schema_missing` (migration 121 not applied) and+ the alert sink's pool.++### The lake is missing events++```bash+curl -s localhost:8003/metrics | jq '.lake'+```++* **`spool_rows` rising, `degraded: false`** — ClickHouse is behind or down.+ The rows are on disk and will be replayed; the alert path is unaffected.+* **`capacity_refusals` non-zero** — the spool is full, so the consumer is+ holding its Kafka offset. Ingest has stopped advancing by design. Restore+ ClickHouse, or raise `AISOC_LAKE_MAX_SPOOL_BYTES` *as headroom while the+ backlog drains*, not as a fix.+* **`quarantined_rows` non-zero** — ClickHouse refused these rows repeatedly+ as data. They are in `<AISOC_LAKE_SPOOL_DIR>/quarantine/*.jsonl`, one JSON+ row per line, and are **not** in the lake. Fix the schema disagreement, then+ replay them by moving the files back into the spool directory and restarting+ the service, which replays on start.+* **`rows_dropped` non-zero** — a genuine unrecoverable gap. Nothing in the+ normal path increments it.+* **`degraded: true`** — the spool directory is unusable (missing, read-only,+ full). Archival is refusing events and the consumer is holding offsets.++After a restart, `lake_writer.spool_recovery_started` and+`lake_writer.spool_recovery_finished` report what was carried over and what is+still pending. Replayed rows carry the same deterministic `event_id`, so+`LIMIT 1 BY event_id` collapses them; a hunt, a usage figure or an aggregate+over the lake is not inflated by a recovery.++### A windowed detection did not fire when it should have++* `windowed_detection.rule_error` at `warning`, or a rising `rule_errors`,+ means Redis was unreachable and rules were skipped. The detections are not+ queued — those events are gone from the window.+* A hit that was claimed and never confirmed holds its slot for+ `FIRE_CLAIM_SECONDS` (60) and then becomes claimable again. If a worker was+ killed mid-handoff, the alert reappears within that window on the next+ matching event.+* A replay of the same events produces no second alert: the cooldown key is+ bucketed on event time, so the replay lands in the same bucket.diff --git a/services/api/migrations/121_fusion_alert_outbox.sql b/services/api/migrations/121_fusion_alert_outbox.sqlnew file mode 100644index 000000000..f8903a91d--- /dev/null+++ b/services/api/migrations/121_fusion_alert_outbox.sql@@ -0,0 +1,103 @@+-- Remediation phase 4 — a recovery record for a fused alert that was made+-- durable in Postgres but never reached `aisoc.alerts.fused`.+--+-- The window+-- ----------+-- `services/fusion` persists the alert row first and publishes second, so a+-- downstream consumer never sees a row id that does not exist. The publish+-- and the input-offset commit cannot be made atomic, which leaves two+-- orderings:+--+-- * The process dies between the durable row and the publish. The input+-- offset was never committed, Kafka re-delivers, the sink answers a+-- verified DUPLICATE, and the publish is retried. Re-delivery is the+-- recovery and it works.+--+-- * The publish fails until the consumer's retry budget is gone. The+-- message is then dead-lettered and the offset *is* committed, which is+-- correct — a dead letter is a durable capture. But the alert row+-- exists, the offset has moved past the source event, and nothing will+-- ever publish the envelope: a dead letter is a triage record, and+-- nothing re-drives it. That alert sits in Postgres invisible to+-- auto-triage for as long as the row lives.+--+-- This table is the record for the second case. A row is written only once a+-- publish has definitively failed, and always before the consumer is allowed+-- to acknowledge the message.+--+-- Why not a transactional outbox+-- ------------------------------+-- Because the first ordering is already covered by an offset that has not+-- moved. Writing a row for every alert on the happy path — an extra INSERT+-- inside the alert insert's transaction and a DELETE after the ack — would+-- make every alert pay for a window that re-delivery closes for free. The+-- guarantee is stated as at-least-once either way; a transactional outbox+-- would not make it exactly-once, it would only move the duplicate.+--+-- Rows are deleted on delivery rather than flagged, so the table *is* the+-- set of alerts still owing a notification: the backlog is count(*), not a+-- filtered scan over delivery history.++CREATE TABLE IF NOT EXISTS fusion_alert_outbox (+ id BIGSERIAL PRIMARY KEY,+ -- Carried so the table can be tenant-scoped by the same policy shape as+ -- everything else, and so a per-tenant backlog is answerable.+ tenant_id UUID NOT NULL,+ -- The durable alerts row this notification is for. Not a foreign key:+ -- retention may purge the alert before a relay that has been down for+ -- days gets to it, and a cascade would silently delete the evidence that+ -- the notification was owed.+ alert_id UUID NOT NULL,+ topic TEXT NOT NULL,+ -- The Kafka message key: the canonical alert id, so every republication+ -- lands on one partition and a consumer can collapse duplicates.+ dedupe_key TEXT NOT NULL,+ -- The fused envelope as it would have been published. Stored whole+ -- rather than rebuilt from the alerts row, because rebuilding it would+ -- re-derive fusion's verdict from a row that no longer carries the+ -- inputs, and a notification that differs from the one that failed is a+ -- different message under the same id.+ payload JSONB NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ -- Lease, not a lock. A relay that dies mid-publish must not strand the+ -- row behind a connection that is gone; the next replica may claim it+ -- once this passes.+ claimed_until TIMESTAMPTZ,+ attempts INTEGER NOT NULL DEFAULT 0,+ last_attempt_at TIMESTAMPTZ,+ last_error TEXT+);++-- One pending notification per alert. A second failure for the same alert+-- bumps `attempts` instead of adding a row, so a long broker outage cannot+-- turn a bounded backlog into an unbounded one.+CREATE UNIQUE INDEX IF NOT EXISTS fusion_alert_outbox_alert_uniq ON fusion_alert_outbox (tenant_id, alert_id);++-- The relay's claim predicate, in the order it reads them.+CREATE INDEX IF NOT EXISTS fusion_alert_outbox_claimable ON fusion_alert_outbox (created_at) WHERE claimed_until IS NULL;++DO $$+BEGIN+ EXECUTE 'ALTER TABLE fusion_alert_outbox ENABLE ROW LEVEL SECURITY';+ EXECUTE 'ALTER TABLE fusion_alert_outbox FORCE ROW LEVEL SECURITY';+ EXECUTE 'DROP POLICY IF EXISTS tenant_isolation ON fusion_alert_outbox';+ -- The unbound-session arm is the same shape 079/081/104/114/117/118 use,+ -- and it is load-bearing here rather than inherited: the only writer and+ -- the only reader are fusion's consumer and its relay, both GUC-less+ -- worker sessions that span tenants by construction. Without it the+ -- journal could never be written under the runtime role, and the failure+ -- would look like "no alerts are undelivered".+ EXECUTE+ 'CREATE POLICY tenant_isolation ON fusion_alert_outbox '+ 'USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL) '+ 'WITH CHECK (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL)';++ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'aisoc_app') THEN+ EXECUTE 'GRANT SELECT, INSERT, UPDATE, DELETE ON fusion_alert_outbox TO aisoc_app';+ -- BIGSERIAL owns a sequence, and INSERT on the table is not INSERT on+ -- its sequence: without this the runtime role can read and delete+ -- rows it can never create.+ EXECUTE 'GRANT USAGE, SELECT ON SEQUENCE fusion_alert_outbox_id_seq TO aisoc_app';+ END IF;+END+$$;diff --git a/services/fusion/app/api/router.py b/services/fusion/app/api/router.pyindex 6c6929490..973d345e9 100644--- a/services/fusion/app/api/router.py+++ b/services/fusion/app/api/router.py@@ -38,9 +38,28 @@ async def health():@router.get("/metrics")async def metrics():+ """Consumer counters, plus the two durability backlogs.++ ``LakeWriter.metrics()`` existed and nothing read it, so the archive+ backlog, the capacity pressure and the quarantined rows were computed on+ every call to a method with no caller. A gap nobody can see is the same+ as a gap nobody reported, which is the shape this service has shipped+ before.++ ``None`` in either section means "could not be read", never zero: an+ unreadable backlog rendered as an empty one is how a stuck relay and a+ stalled archive both look healthy.+ """if _worker_ref is None:return {"status": "worker not started"}- return {"status": "ok", "metrics": FusionWorker.get_metrics()}+ body: dict = {"status": "ok", "metrics": _worker_ref.get_metrics()}++ lake = _worker_ref.lake+ body["lake"] = lake.metrics() | {"degraded": lake.archive_degraded} if lake is not None else None++ pending, oldest_seconds, by_tenant = await _worker_ref.pending_notifications()+ body["notifications"] = {"pending": pending, "oldest_seconds": oldest_seconds, "by_tenant": by_tenant}+ return body@router.get("/scale-hint")diff --git a/services/fusion/app/core/config.py b/services/fusion/app/core/config.pyindex e5fff6ac0..790fc8598 100644--- a/services/fusion/app/core/config.py+++ b/services/fusion/app/core/config.py@@ -47,7 +47,19 @@ class Settings(BaseSettings):consumer_retry_base_seconds: float = Field(default=0.5, alias="AISOC_CONSUMER_RETRY_BASE_SECONDS")consumer_retry_max_seconds: float = Field(default=30.0, alias="AISOC_CONSUMER_RETRY_MAX_SECONDS")consumer_recovery_retry_seconds: float = Field(default=10.0, alias="AISOC_CONSUMER_RECOVERY_RETRY_SECONDS")+ # End-to-end deadline for one fused-alert delivery: the enqueue *and* the+ # broker acknowledgement. It used to bound the enqueue alone, which is a+ # local memory append and effectively never times out.kafka_send_timeout_seconds: float = Field(default=30.0, alias="AISOC_KAFKA_SEND_TIMEOUT_SECONDS")+ # Recovery journal for an alert that is durable in Postgres but whose+ # notification never reached the broker (app/services/alert_outbox.py).+ # The grace period is the head start the consumer's own inline retries+ # get: set it above the retry budget or the relay competes with a retry+ # that is still running and publishes avoidable duplicates.+ alert_outbox_enabled: bool = Field(default=True, alias="AISOC_ALERT_OUTBOX_ENABLED")+ outbox_relay_interval_seconds: float = Field(default=15.0, alias="AISOC_OUTBOX_RELAY_INTERVAL_SECONDS")+ outbox_relay_batch_size: int = Field(default=50, alias="AISOC_OUTBOX_RELAY_BATCH_SIZE")+ outbox_relay_grace_seconds: float = Field(default=120.0, alias="AISOC_OUTBOX_RELAY_GRACE_SECONDS")# How long stop() waits for the in-flight message before closing clients.# Work that does not finish is left uncommitted, so it is re-delivered.shutdown_grace_seconds: float = Field(default=15.0, alias="AISOC_SHUTDOWN_GRACE_SECONDS")@@ -68,6 +80,30 @@ class Settings(BaseSettings):# bound that retention: when the cap is reached the oldest rows are# discarded with an explicit counter/log, never silently.lake_max_buffer_rows: int = Field(default=10000, alias="AISOC_LAKE_MAX_BUFFER_ROWS")+ # Archival's own durable boundary (app/services/lake_spool.py). A row is+ # on this spool before `write_event` returns True, so the consumer's+ # offset commit no longer rides on an in-memory list.+ #+ # Relative by default so a first run needs no provisioning, but it is+ # only as durable as the filesystem under it: in a container, mount a+ # volume here or a destroyed container loses rows whose Kafka offsets+ # were already committed.+ lake_spool_dir: str = Field(default=".aisoc/lake-spool", alias="AISOC_LAKE_SPOOL_DIR")+ # Back-pressure threshold, not a discard threshold. At the cap the writer+ # refuses events and the consumer holds its Kafka offset, so Kafka's+ # retention becomes the buffer. Raising it is not a durability fix.+ lake_max_spool_bytes: int = Field(default=512 * 1024 * 1024, alias="AISOC_LAKE_MAX_SPOOL_BYTES")+ # Off by default: an un-synced append already survives a process kill,+ # SIGKILL and a container stop, because the bytes are in the kernel page+ # cache. Turn it on to also survive a power loss, at a disk round trip+ # per batch.+ lake_spool_fsync: bool = Field(default=False, alias="AISOC_LAKE_SPOOL_FSYNC")+ # Whether an event that could not be spooled holds the Kafka offset.+ # On (the default) an unusable or full spool applies back-pressure+ # instead of losing the archive silently. Turning it off restores+ # best-effort archival, where a refused event is counted as a reported+ # gap and the alert pipeline keeps moving.+ lake_archive_required: bool = Field(default=True, alias="AISOC_LAKE_ARCHIVE_REQUIRED")lake_reconnect_base_seconds: float = Field(default=0.5, alias="AISOC_LAKE_RECONNECT_BASE_SECONDS")lake_reconnect_max_seconds: float = Field(default=30.0, alias="AISOC_LAKE_RECONNECT_MAX_SECONDS")# A server-side/data error is retried this many times, then the batch isdiff --git a/services/fusion/app/main.py b/services/fusion/app/main.pyindex 6be90a8d2..b07c0d85e 100644--- a/services/fusion/app/main.py+++ b/services/fusion/app/main.py@@ -14,6 +14,7 @@ from app.memory.provider import MemoryPriorProviderfrom app.services import ioc_matchfrom app.services.ai_asset_recorder import AiAssetRecorderfrom app.services.alert_enricher import AlertEnricher+from app.services.alert_outbox import AlertNotificationOutboxfrom app.services.alert_sink import AlertSinkfrom app.services.attack_chain_grouper import AttackChainGrouperfrom app.services.baselines import BaselineStore@@ -172,6 +173,18 @@ async def lifespan(app: FastAPI):# every sighting for the life of the process.ai_assets = AiAssetRecorder(lambda: sink._pool) if sink is not None else None+ # Remediation phase 4 — the recovery record for a fused alert that is+ # durable in Postgres but whose Kafka notification never landed. Shares+ # the sink's pool, and is passed as a callable for the same reason the+ # two above are: `sink.start()` opens it during `worker.start()`, after+ # this point. Without a sink there is no pool and no alert row either,+ # so there is nothing for the journal to be about.+ outbox = (+ AlertNotificationOutbox(lambda: sink._pool, ensure_pool=sink.ensure_pool)+ if sink is not None and settings.alert_outbox_enabled+ else None+ )+if sink is None:# Explicit, not inferred: this mode writes no alert rows and has no# durable DLQ. The consumer still retries and holds, but its committed@@ -206,6 +219,7 @@ async def lifespan(app: FastAPI):sessions=SessionStore(_fusion_pool()) if settings.alert_sink_enabled else None,ueba_cache=ueba_cache,ai_assets=ai_assets,+ outbox=outbox,)set_worker(worker)diff --git a/services/fusion/app/services/alert_outbox.py b/services/fusion/app/services/alert_outbox.pynew file mode 100644index 000000000..56b1099d0--- /dev/null+++ b/services/fusion/app/services/alert_outbox.py@@ -0,0 +1,440 @@+"""Durable record of a fused alert that still owes its Kafka notification.++The window this closes+----------------------+``_fuse_and_persist`` persists the alert row first and publishes second, so a+downstream consumer never sees a row id that does not exist. Publication and+the input-offset commit cannot be made atomic, so two orderings have to be+accounted for, and only one of them was:++* **The process dies between the durable row and the publish.** The input+ offset was never committed, so Kafka re-delivers the record, the sink+ answers ``DUPLICATE`` (verified against the row that survived), and the+ publish is retried. Re-delivery is the recovery mechanism and it works.++* **The publish fails until the retry budget is gone.** The consumer then+ dead-letters the message and *commits the offset* — correctly, because the+ dead letter is a durable capture. But the alert row exists, the offset has+ moved past the source event, and nothing will ever publish the envelope.+ A dead letter is a triage record, not a delivery queue: nothing re-drives+ it. That alert is in Postgres and invisible to auto-triage forever.++This module is the recovery record for the second case. It is deliberately+**not** a transactional outbox: nothing is written on the happy path, because+the first case is already covered by an offset that has not moved, and making+every alert pay for an extra INSERT and DELETE to cover a window re-delivery+already covers would be a cost with no reader. A row is written only once a+publish has definitively failed, and it is written *before* the consumer is+allowed to acknowledge the message — which is the property that matters: an+acknowledged message never leaves an unpublished alert without a record of it.++What it guarantees, stated plainly+----------------------------------+Delivery of a fused alert is **at-least-once**, and this is what makes the+"at least" true rather than aspirational. It is not exactly-once and must not+be described as such: the relay can publish an envelope that an inline retry+had already delivered, and a broker acknowledgement that arrives after the+publisher stopped waiting is indistinguishable from one that never arrived.+Every published record is keyed by its canonical alert id so a consumer can+collapse the duplicates.++Rows are *deleted* when they are delivered rather than flagged, so the table+is exactly the set of alerts that still owe a notification and the backlog is+``COUNT(*)`` rather than a filtered scan over history.+"""++from __future__ import annotations++import asyncio+import contextlib+import json+from collections.abc import Awaitable, Callable+from dataclasses import dataclass+from typing import Any++import structlog++logger = structlog.get_logger()++#: One pending notification per alert. A second failure for the same alert+#: updates the attempt counter instead of adding a row, so a long outage+#: cannot turn a bounded backlog into an unbounded one.+_RECORD_SQL = """+INSERT INTO fusion_alert_outbox (tenant_id, alert_id, topic, dedupe_key, payload, attempts, last_error)+VALUES ($1::uuid, $2::uuid, $3, $4, $5::jsonb, 1, $6)+ON CONFLICT (tenant_id, alert_id) DO UPDATE+SET attempts = fusion_alert_outbox.attempts + 1,+ last_error = EXCLUDED.last_error,+ payload = EXCLUDED.payload+"""++_CLEAR_SQL = "DELETE FROM fusion_alert_outbox WHERE tenant_id = $1::uuid AND alert_id = $2::uuid"+++@dataclass(frozen=True)+class PendingNotification:+ """One fused alert whose envelope has not reached the broker."""++ id: int+ tenant_id: str+ alert_id: str+ topic: str+ key: str+ payload: dict[str, Any]+ attempts: int+++class AlertNotificationOutbox:+ """Postgres-backed journal of undelivered fused-alert notifications.++ Shares the alert sink's connection pool, for the reason the dead-letter+ queue and the AI-asset recorder share it: one pool per service, opened by+ ``sink.start()`` during ``worker.start()``. The pool therefore arrives as+ a callable, because capturing it eagerly captures ``None``.++ Every method is fail-soft and says so in its return type. A journal that+ raises into the consumer would turn a Kafka blip into a stalled partition,+ which is worse than the gap it is recording. ``record`` returning ``False``+ is the one answer a caller must act on: it means the notification is *not*+ recoverable, so the message must not be acknowledged.+ """++ def __init__(self, pool_factory: Callable[[], Any], *, ensure_pool: Callable[[], Any] | None = None) -> None:+ self._pool_factory = pool_factory+ self._ensure_pool = ensure_pool+ #: Latched after the first "relation does not exist", so a deployment+ #: that has not run the migration logs once rather than per alert.+ #: Not auto-created: a CREATE TABLE here would swallow a permissions+ #: failure into a log line and leave the service reporting healthy+ #: with no journal at all.+ self._schema_missing = False++ @property+ def available(self) -> bool:+ """Whether the journal can record. False once the table is known absent."""+ return not self._schema_missing++ async def _pool(self) -> Any | None:+ pool = self._pool_factory()+ if pool is None and self._ensure_pool is not None:+ pool = await self._ensure_pool()+ return pool++ @staticmethod+ def _is_missing_schema(exc: BaseException) -> bool:+ # asyncpg raises UndefinedTableError; matching the SQLSTATE rather+ # than the class keeps this working if the driver is swapped.+ return getattr(exc, "sqlstate", None) == "42P01"++ def _note_missing_schema(self) -> None:+ if self._schema_missing:+ return+ self._schema_missing = True+ logger.error(+ "fusion.outbox_schema_missing",+ table="fusion_alert_outbox",+ detail=(+ "migration 121 has not been applied; an alert whose publish fails until the retry "+ "budget is exhausted has no recovery record and will not be delivered"+ ),+ )++ async def record(self, *, tenant_id: str, alert_id: str, topic: str, key: str, payload: dict[str, Any], error: str) -> bool:+ """Journal one undelivered notification. False means it was not recorded.++ The caller must treat ``False`` as "this alert is not recoverable" and+ keep the Kafka offset uncommitted, because committing it is what makes+ the gap permanent.+ """+ if self._schema_missing:+ return False+ pool = await self._pool()+ if pool is None:+ return False+ try:+ async with pool.acquire() as conn:+ await conn.execute(_RECORD_SQL, tenant_id, alert_id, topic, key, json.dumps(payload, default=str), error[:2000])+ return True+ except Exception as exc: # noqa: BLE001 — never raise into the consumer+ if self._is_missing_schema(exc):+ self._note_missing_schema()+ else:+ logger.error("fusion.outbox_record_failed", alert_id=alert_id, error=str(exc))+ return False++ async def clear(self, *, tenant_id: str, alert_id: str) -> None:+ """Drop a journal row once the alert has been published inline.++ Called only when the sink answered ``DUPLICATE``, which is the one+ outcome that says "this alert already existed", and therefore the only+ path on which a journal row from an earlier attempt can be pending. On+ the ``INSERTED`` path the row is new and nothing can have journalled+ it, so the happy path pays nothing.+ """+ if self._schema_missing:+ return+ pool = await self._pool()+ if pool is None:+ return+ try:+ async with pool.acquire() as conn:+ await conn.execute(_CLEAR_SQL, tenant_id, alert_id)+ except Exception as exc: # noqa: BLE001+ if self._is_missing_schema(exc):+ self._note_missing_schema()+ else:+ # A stale row republishes later. That is a duplicate, which+ # the delivery contract already allows, so this is a warning+ # and not a failure the caller has to handle.+ logger.warning("fusion.outbox_clear_failed", alert_id=alert_id, error=str(exc))++ async def claim(self, *, limit: int, lease_seconds: float, grace_seconds: float) -> list[PendingNotification]:+ """Lease up to ``limit`` pending notifications for this replica."""+ if self._schema_missing:+ return []+ pool = await self._pool()+ if pool is None:+ return []+ # Claim with a lease, in one statement. ``FOR UPDATE SKIP LOCKED`` is what+ # makes two replicas safe to run: the second one's sub-select steps over the+ # rows the first has locked instead of blocking on them. The lease (rather+ # than a lock held for the duration of the publish) is what makes a relay+ # that dies mid-publish recoverable — the rows become claimable again when+ # it expires, instead of being stranded behind a connection that is gone.+ #+ # ``created_at < now() - grace`` gives the consumer's own inline retry budget+ # first refusal. Without it the relay would race the retry that is already+ # in progress and publish a duplicate for every transient broker blip.+ claim_sql = """+UPDATE fusion_alert_outbox AS o+SET claimed_until = now() + make_interval(secs => $1::double precision),+ last_attempt_at = now()+WHERE o.id IN (+ SELECT c.id FROM fusion_alert_outbox AS c+ WHERE (c.claimed_until IS NULL OR c.claimed_until < now())+ AND c.created_at < now() - make_interval(secs => $2::double precision)+ ORDER BY c.created_at+ FOR UPDATE SKIP LOCKED+ LIMIT $3::int+)+RETURNING o.id, o.tenant_id, o.alert_id, o.topic, o.dedupe_key, o.payload, o.attempts+"""+ try:+ async with pool.acquire() as conn:+ rows = await conn.fetch(claim_sql, float(lease_seconds), float(grace_seconds), int(limit))+ except Exception as exc: # noqa: BLE001+ if self._is_missing_schema(exc):+ self._note_missing_schema()+ else:+ logger.warning("fusion.outbox_claim_failed", error=str(exc))+ return []+ claimed: list[PendingNotification] = []+ for row in rows:+ payload = row["payload"]+ if isinstance(payload, str): # asyncpg returns jsonb as text without a codec+ try:+ payload = json.loads(payload)+ except ValueError:+ logger.error("fusion.outbox_payload_unreadable", outbox_id=row["id"])+ continue+ claimed.append(+ PendingNotification(+ id=int(row["id"]),+ tenant_id=str(row["tenant_id"]),+ alert_id=str(row["alert_id"]),+ topic=str(row["topic"]),+ key=str(row["dedupe_key"]),+ payload=payload,+ attempts=int(row["attempts"]),+ )+ )+ return claimed++ async def resolve(self, delivered: list[PendingNotification]) -> None:+ """Delete the rows this replica has now delivered.++ Takes the claims rather than bare ids so the delete carries a tenant+ predicate. The relay spans tenants by construction -- it drains+ whatever is owed -- but that is a reason for the *claim* to be+ unscoped, not for every statement after it: a delete keyed on an id+ alone would reach any row in the table if the id were ever wrong,+ and the pairing costs nothing because the claim already returned it.+ """+ if self._schema_missing or not delivered:+ return+ pool = await self._pool()+ if pool is None:+ return+ resolve_sql = """+DELETE FROM fusion_alert_outbox+WHERE (tenant_id, id) IN (SELECT * FROM unnest($1::uuid[], $2::bigint[]))+"""+ try:+ async with pool.acquire() as conn:+ await conn.execute(resolve_sql, [item.tenant_id for item in delivered], [item.id for item in delivered])+ except Exception as exc: # noqa: BLE001+ # The lease expires and the row is re-claimed, so the cost of+ # this failing is a duplicate publication, not a lost alert.+ logger.warning("fusion.outbox_resolve_failed", count=len(delivered), error=str(exc))++ async def record_attempt_failed(self, pending: PendingNotification, error: str) -> None:+ """Release the lease early so a transient failure retries sooner.++ Scoped on the tenant the claim returned, for the reason+ :meth:`resolve` is.+ """+ if self._schema_missing:+ return+ pool = await self._pool()+ if pool is None:+ return+ fail_sql = """+UPDATE fusion_alert_outbox+SET attempts = attempts + 1, last_error = $3, claimed_until = NULL+WHERE id = $1::bigint AND tenant_id = $2::uuid+"""+ try:+ async with pool.acquire() as conn:+ await conn.execute(fail_sql, pending.id, pending.tenant_id, error[:2000])+ except Exception as exc: # noqa: BLE001+ logger.warning("fusion.outbox_attempt_update_failed", outbox_id=pending.id, error=str(exc))++ async def backlog(self) -> tuple[int | None, float | None, dict[str, int]]:+ """``(pending rows, age of the oldest in seconds, per-tenant counts)``.++ ``None`` for either number means it could not be read, which is+ deliberately not zero: an unreadable backlog reported as no backlog+ is how a stuck relay looks healthy. The age rides along because a+ count alone cannot tell a backlog that is draining from one that is+ stuck -- ten rows ten seconds old and ten three days old read+ identically.++ Grouped by tenant rather than summed in SQL. On a deployment serving+ several tenants the useful question is *whose* notifications are+ stuck, and a single number cannot answer it; the totals the metrics+ route renders are folded from these rows.+ """+ if self._schema_missing:+ return None, None, {}+ pool = await self._pool()+ if pool is None:+ return None, None, {}+ backlog_sql = """+SELECT tenant_id, count(*) AS n, extract(epoch FROM now() - min(created_at)) AS age+FROM fusion_alert_outbox+GROUP BY tenant_id+"""+ try:+ async with pool.acquire() as conn:+ rows = await conn.fetch(backlog_sql)+ except Exception as exc: # noqa: BLE001+ if self._is_missing_schema(exc):+ self._note_missing_schema()+ else:+ logger.warning("fusion.outbox_backlog_unreadable", error=str(exc))+ return None, None, {}+ per_tenant = {str(row["tenant_id"]): int(row["n"]) for row in rows}+ oldest = max((float(row["age"]) for row in rows if row["age"] is not None), default=None)+ return sum(per_tenant.values()), oldest, per_tenant+++class NotificationRelay:+ """Drains the journal: claims pending notifications and publishes them.++ Runs as a background task beside the consume loop rather than as its own+ service, because it needs exactly the two things the worker already holds+ — the Kafka producer and the alert sink's pool — and a separate process+ would be a component CORE does not start, which is the deployment most+ likely to be running without one.++ ``publish`` is injected rather than the producer, so the relay delivers+ through the same awaited-acknowledgement path as the inline publish. A+ relay with its own send would be a second definition of "delivered", and+ the one that drifts is always the one with no traffic on it.+ """++ def __init__(+ self,+ outbox: AlertNotificationOutbox,+ publish: Callable[[dict[str, Any], str], Awaitable[None]],+ *,+ interval_seconds: float = 15.0,+ batch_size: int = 50,+ lease_seconds: float = 60.0,+ grace_seconds: float = 120.0,+ ) -> None:+ self._outbox = outbox+ self._publish = publish+ self._interval = max(1.0, interval_seconds)+ self._batch = max(1, batch_size)+ self._lease = max(1.0, lease_seconds)+ #: Head start for the consumer's own inline retries. Set above the+ #: retry budget (8 attempts, 30 s cap) so the relay is the recovery+ #: for a message that has been acknowledged, never a competitor to a+ #: retry that is still running.+ self._grace = max(0.0, grace_seconds)+ self._task: asyncio.Task | None = None+ self._stop = asyncio.Event()+ self.recovered = 0+ self.failures = 0++ def start(self) -> None:+ if self._task is not None: # pragma: no cover — start() is called once+ return+ self._stop.clear()+ self._task = asyncio.create_task(self._run())++ async def stop(self) -> None:+ self._stop.set()+ if self._task is not None:+ self._task.cancel()+ with contextlib.suppress(asyncio.CancelledError):+ await self._task+ self._task = None++ async def _run(self) -> None:+ try:+ while not self._stop.is_set():+ with contextlib.suppress(TimeoutError):+ await asyncio.wait_for(self._stop.wait(), timeout=self._interval)+ if self._stop.is_set():+ return+ try:+ await self.drain_once()+ except asyncio.CancelledError:+ raise+ except Exception as exc: # noqa: BLE001 — a relay must not die on one sweep+ logger.error("fusion.relay_sweep_failed", error=str(exc), exc_info=True)+ except asyncio.CancelledError: # pragma: no cover — shutdown path+ pass++ async def drain_once(self) -> int:+ """Publish one batch of pending notifications. Returns how many landed."""+ pending = await self._outbox.claim(limit=self._batch, lease_seconds=self._lease, grace_seconds=self._grace)+ if not pending:+ return 0+ delivered: list[PendingNotification] = []+ for item in pending:+ try:+ await self._publish(item.payload, item.key)+ except asyncio.CancelledError:+ raise+ except Exception as exc: # noqa: BLE001+ self.failures += 1+ logger.warning(+ "fusion.relay_publish_failed",+ alert_id=item.alert_id,+ attempts=item.attempts,+ error=str(exc),+ )+ await self._outbox.record_attempt_failed(item, str(exc))+ # Stop the sweep rather than walking the rest of the batch+ # into the same unreachable broker. The remaining rows keep+ # their lease and are re-claimed once it expires.+ break+ delivered.append(item)+ if delivered:+ self.recovered += len(delivered)+ await self._outbox.resolve(delivered)+ logger.info("fusion.notifications_recovered", count=len(delivered))+ return len(delivered)diff --git a/services/fusion/app/services/lake_spool.py b/services/fusion/app/services/lake_spool.pynew file mode 100644index 000000000..cd1b2b88f--- /dev/null+++ b/services/fusion/app/services/lake_spool.py@@ -0,0 +1,385 @@+"""On-disk spool for lake rows that ClickHouse has not accepted yet.++Why this exists+---------------+``LakeWriter`` buffered rows in a Python list and returned ``True`` from+``write_event`` to mean "accepted for archival". The fusion consumer then+committed the input Kafka offset. So the offset -- the only record of what+has been archived -- advanced on the strength of process memory: a hard kill+lost the buffer whole, and the capacity guard discarded the *oldest* rows,+whose offsets had been committed minutes earlier. Nothing could replay them,+because nothing knew they were missing.++The spool gives archival a recovery boundary that does not depend on the+alert pipeline's offsets. A row is on disk before ``write_event`` returns,+and a restart replays whatever ClickHouse never took.++Durability, stated exactly+--------------------------+Segments are appended with ``write()`` and are **not** ``fsync``ed per row by+default. That is a deliberate boundary, not an oversight:++* A process crash, SIGKILL, container stop or `docker kill` loses nothing:+ the bytes are in the kernel page cache and the OS writes them out whether+ or not this process is alive. That is the failure this module is for.+* A machine power loss or a kernel panic can lose the tail. Set+ ``AISOC_LAKE_SPOOL_FSYNC=1`` to flush every append if that matters; it+ costs a disk round trip per batch.+* The spool is only as durable as its filesystem. On Kubernetes with an+ ``emptyDir``, a rescheduled pod starts with an empty spool, and rows whose+ offsets were already committed are gone. Mount a volume. This is documented+ rather than papered over, because the alternative -- claiming durability+ the deployment does not have -- is the thing being fixed.++Capacity is back-pressure, never discard+----------------------------------------+At ``max_bytes`` the spool refuses the append and says so. The caller turns+that into a retryable failure, the consumer holds the Kafka offset, and+Kafka's retention becomes the buffer -- which is the durable log the platform+already runs, orders of magnitude larger than any in-process cap. Raising a+memory limit was never a durability fix, and neither is raising this one.++Format+------+Line-delimited JSON, one row per line, in rotating segments. A truncated+final line (the power-loss case above) is skipped on read with a counter, so+one torn write cannot make the rest of a segment unreadable.+"""++from __future__ import annotations++import json+import os+import time+import uuid+from collections.abc import Iterator+from datetime import UTC, datetime+from pathlib import Path+from typing import Any++import structlog++logger = structlog.get_logger()++_SEGMENT_SUFFIX = ".jsonl"+_QUARANTINE_DIR = "quarantine"+++def _encode(row: dict[str, Any]) -> str:+ """One row as a JSON line.++ ``event_time`` is a ``datetime`` by the time it reaches here (the driver+ binds DateTime64 from an object, not a string), so it round-trips through+ an explicit ISO conversion rather than ``default=str``: reading it back+ has to produce the same value the first attempt would have inserted, or a+ recovered row is a different row.+ """+ out = dict(row)+ when = out.get("event_time")+ if isinstance(when, datetime):+ out["event_time"] = when.replace(tzinfo=UTC).isoformat() if when.tzinfo is None else when.isoformat()+ return json.dumps(out, default=str, separators=(",", ":"))+++def _decode(line: str) -> dict[str, Any] | None:+ try:+ row = json.loads(line)+ except ValueError:+ return None+ if not isinstance(row, dict):+ return None+ when = row.get("event_time")+ if isinstance(when, str):+ try:+ parsed = datetime.fromisoformat(when)+ row["event_time"] = parsed.astimezone(UTC).replace(tzinfo=None) if parsed.tzinfo else parsed+ except ValueError:+ row["event_time"] = datetime.now(UTC).replace(tzinfo=None)+ return row+++class LakeSpool:+ """Append-only disk spool with rotating segments and a byte cap."""++ def __init__(+ self,+ directory: str | Path,+ *,+ max_bytes: int = 512 * 1024 * 1024,+ segment_bytes: int = 32 * 1024 * 1024,+ fsync: bool = False,+ ) -> None:+ self._dir = Path(directory)+ self._quarantine = self._dir / _QUARANTINE_DIR+ self._max_bytes = max(1, int(max_bytes))+ self._segment_bytes = max(1, int(segment_bytes))+ self._fsync = fsync+ self._handle: Any = None+ #: Lazily scanned, then maintained by append and invalidated by+ #: anything that rewrites a segment. None means "rescan".+ self._rows_cache: int | None = None+ self._bytes_cache: int | None = None+ self._segment: Path | None = None+ self._segment_bytes_written = 0+ self.rows_spooled = 0+ self.rows_recovered = 0+ self.rows_quarantined = 0+ self.capacity_refusals = 0+ self.unreadable_lines = 0+ self.write_failures = 0+ #: False once the directory proves unusable, so a deployment with a+ #: read-only or missing volume refuses events loudly instead of+ #: pretending to spool them.+ self._usable = True++ @property+ def usable(self) -> bool:+ return self._usable++ @property+ def directory(self) -> Path:+ return self._dir++ def open(self) -> bool:+ """Create the spool directory. False means archival has no disk home."""+ try:+ self._dir.mkdir(parents=True, exist_ok=True)+ self._quarantine.mkdir(parents=True, exist_ok=True)+ except OSError as exc:+ self._usable = False+ logger.error(+ "lake_spool.unusable",+ directory=str(self._dir),+ error=str(exc),+ detail="lake rows cannot be made durable; archival will apply back-pressure rather than accept them",+ )+ return False+ # Seeded from the directory, not carried over: the count that+ # matters is the one a restarted process reads, and whatever the+ # previous process had in memory is gone with it.+ self._invalidate()+ return True++ def bytes_on_disk(self) -> int:+ if self._bytes_cache is None:+ self._bytes_cache = self._scan_bytes()+ return self._bytes_cache++ def rows_on_disk(self) -> int:+ """Pending rows.++ Cached, and the cache is seeded by a real scan of the directory at+ :meth:`open` — which is the case that matters, because the number is+ read right after the restart this module exists for, when a running+ total from the previous process would be meaningless. From then on+ it is maintained by the two operations that can change it (append+ and commit), because counting lines in every segment on every+ accepted event is an O(backlog) cost on the hot path: with the+ scan in place the fusion suite went from 18 s to 30 s.+ """+ if self._rows_cache is None:+ self._rows_cache = self._scan_rows()+ return self._rows_cache++ def _scan_bytes(self) -> int:+ total = 0+ for segment in self._segments():+ try:+ total += segment.stat().st_size+ except OSError: # pragma: no cover — a segment removed mid-scan+ continue+ return total++ def _scan_rows(self) -> int:+ pending = 0+ for segment in self._segments():+ try:+ with segment.open("r", encoding="utf-8") as handle:+ pending += sum(1 for line in handle if line.strip())+ except OSError: # pragma: no cover+ continue+ return pending++ def _invalidate(self) -> None:+ """Drop the cached counts so the next read rescans.++ Used after a commit or a quarantine, where the change is a rewrite+ rather than a known delta and guessing at one is how a counter+ drifts away from the directory it claims to describe.+ """+ self._rows_cache = None+ self._bytes_cache = None++ def _segments(self) -> list[Path]:+ if not self._dir.exists():+ return []+ return sorted(p for p in self._dir.glob(f"*{_SEGMENT_SUFFIX}") if p.is_file())++ def append(self, rows: list[dict[str, Any]]) -> bool:+ """Spool rows. False means the cap was hit or the disk refused them.++ A False answer must reach the Kafka offset: it is the whole point of+ the back-pressure contract.+ """+ if not rows:+ return True+ if not self._usable:+ return False+ payload = "".join(_encode(row) + "\n" for row in rows)+ encoded = payload.encode("utf-8")+ if self.bytes_on_disk() + len(encoded) > self._max_bytes:+ self.capacity_refusals += 1+ logger.error(+ "lake_spool.at_capacity",+ cap_bytes=self._max_bytes,+ on_disk_bytes=self.bytes_on_disk(),+ detail=("the archive spool is full; the consumer will hold its Kafka offset rather than discard events"),+ )+ return False+ try:+ handle = self._ensure_segment()+ handle.write(payload)+ handle.flush()+ if self._fsync:+ os.fsync(handle.fileno())+ except OSError as exc:+ self.write_failures += 1+ self._close_segment()+ self._invalidate()+ logger.error("lake_spool.append_failed", error=str(exc), rows=len(rows))+ return False+ self._segment_bytes_written += len(encoded)+ self.rows_spooled += len(rows)+ if self._rows_cache is not None:+ self._rows_cache += len(rows)+ if self._bytes_cache is not None:+ self._bytes_cache += len(encoded)+ if self._segment_bytes_written >= self._segment_bytes:+ self._close_segment()+ return True++ def _ensure_segment(self) -> Any:+ if self._handle is not None:+ return self._handle+ self._dir.mkdir(parents=True, exist_ok=True)+ # Monotonic-ish name so `sorted()` replays oldest first, with a short+ # random tail because two replicas may share a volume.+ name = f"{time.time_ns():020d}-{uuid.uuid4().hex[:8]}{_SEGMENT_SUFFIX}"+ self._segment = self._dir / name+ self._handle = self._segment.open("a", encoding="utf-8")+ self._segment_bytes_written = 0+ return self._handle++ def _close_segment(self) -> None:+ if self._handle is not None:+ try:+ self._handle.close()+ except OSError: # pragma: no cover+ pass+ self._handle = None+ self._segment = None+ self._segment_bytes_written = 0++ def read_batches(self, batch_size: int) -> Iterator[tuple[list[dict[str, Any]], Path, int]]:+ """Yield ``(rows, segment, lines consumed)`` oldest segment first.++ The caller drives this: it inserts a batch and then calls+ :meth:`commit_segment` once ClickHouse has taken it. A batch that is+ never committed stays on disk, which is the recovery property --+ reading must not be destructive.+ """+ self._close_segment() # so the current segment is complete on disk+ for segment in self._segments():+ rows: list[dict[str, Any]] = []+ consumed = 0+ try:+ with segment.open("r", encoding="utf-8") as handle:+ for line in handle:+ if not line.strip():+ consumed += 1+ continue+ row = _decode(line)+ consumed += 1+ if row is None:+ # A torn final line from a power loss, or a line+ # another process was mid-write on. Skipped with+ # a counter rather than failing the segment.+ self.unreadable_lines += 1+ continue+ rows.append(row)+ if len(rows) >= batch_size:+ yield rows, segment, consumed+ rows, consumed = [], 0+ except OSError as exc: # pragma: no cover — a segment removed mid-read+ logger.warning("lake_spool.segment_unreadable", segment=segment.name, error=str(exc))+ continue+ if rows:+ yield rows, segment, consumed++ def commit_segment(self, segment: Path, consumed: int) -> None:+ """Drop ``consumed`` leading lines from ``segment``, deleting it when empty.++ Rewrites the remainder rather than tracking an offset in a sidecar,+ because a sidecar is a second thing that can be lost independently of+ the data it describes. Segments are bounded by ``segment_bytes``, so+ the rewrite is bounded too.+ """+ try:+ if not segment.exists():+ return+ with segment.open("r", encoding="utf-8") as handle:+ remaining = handle.readlines()[consumed:]+ if not any(line.strip() for line in remaining):+ segment.unlink(missing_ok=True)+ return+ tmp = segment.with_suffix(".tmp")+ with tmp.open("w", encoding="utf-8") as handle:+ handle.writelines(remaining)+ tmp.replace(segment)+ except OSError as exc: # pragma: no cover+ logger.warning("lake_spool.commit_failed", segment=segment.name, error=str(exc))+ finally:+ self._invalidate()++ def quarantine(self, rows: list[dict[str, Any]], *, reason: str) -> None:+ """Move rows ClickHouse keeps refusing somewhere replayable.++ A repeatedly-rejected batch is a schema disagreement, not a transport+ fault, so retrying it forever blocks everything behind it. Deleting+ it makes the gap permanent even after someone fixes the schema. It+ goes to a file an operator can replay and the count is exposed.+ """+ if not rows:+ return+ try:+ self._quarantine.mkdir(parents=True, exist_ok=True)+ target = self._quarantine / f"{time.time_ns():020d}-{uuid.uuid4().hex[:8]}{_SEGMENT_SUFFIX}"+ with target.open("w", encoding="utf-8") as handle:+ handle.write("".join(_encode(row) + "\n" for row in rows))+ except OSError as exc:+ logger.error("lake_spool.quarantine_failed", error=str(exc), rows=len(rows))+ return+ self.rows_quarantined += len(rows)+ self._invalidate()+ logger.error(+ "lake_spool.quarantined",+ rows=len(rows),+ reason=reason,+ path=str(self._quarantine),+ detail="ClickHouse refused these rows repeatedly; they are retained for replay and are NOT in the lake",+ )++ def quarantined_rows_on_disk(self) -> int:+ if not self._quarantine.exists():+ return 0+ total = 0+ for path in self._quarantine.glob(f"*{_SEGMENT_SUFFIX}"):+ try:+ with path.open("r", encoding="utf-8") as handle:+ total += sum(1 for line in handle if line.strip())+ except OSError: # pragma: no cover+ continue+ return total++ def close(self) -> None:+ self._close_segment()diff --git a/services/fusion/app/services/lake_writer.py b/services/fusion/app/services/lake_writer.pyindex 089c1583b..e251c96d5 100644--- a/services/fusion/app/services/lake_writer.py+++ b/services/fusion/app/services/lake_writer.py@@ -16,13 +16,12 @@ Design constraints (mirroring ``AlertSink``):* **Fail-soft.** A ClickHouse outage must degrade to "events still flow throughKafka/fusion, lake archival resumes when the store returns" — never crash the- consumer. A failed connection flush retains the batch (bounded by- ``max_buffer_rows``) and reconnects with capped backoff; rows are only- discarded on explicit overflow or repeated non-connection errors, and both- increments a counter so the archive gap is visible.-* **Batched.** ClickHouse is happiest with bulk inserts, so events are buffered- and flushed by size (``batch_size``) or age (``batch_max_age_seconds``); the- consumer calls :meth:`flush_if_stale` each loop and :meth:`flush` on stop.+ consumer. A failed flush leaves the rows on the spool and reconnects with+ capped backoff.+* **Batched.** ClickHouse is happiest with bulk inserts, so events are drained+ from the spool in batches by size (``batch_size``) or age+ (``batch_max_age_seconds``); the consumer calls :meth:`flush_if_stale` each+ loop and :meth:`flush` on stop.* **At-least-once with a deterministic ``event_id``.** MergeTree does notdeduplicate, so a Kafka replay can produce a duplicate lake row. Each rowcarries a stable identity so downstream queries can ``argMax``/``LIMIT 1 BY@@ -33,6 +32,28 @@ Design constraints (mirroring ``AlertSink``):memory was not, so a replay after a crash could not be collapsed. The PhaseA1 gate asserts *queryability* (``count >= 1``), not exact-once.+Durability: the queue is on disk+--------------------------------+This used to buffer rows in a Python list and return ``True`` from+:meth:`write_event` to mean "accepted for archival". The fusion consumer then+committed the input Kafka offset, so the only record of what had been archived+advanced on the strength of process memory. A hard kill lost the buffer whole,+and the capacity guard discarded the *oldest* rows — whose offsets had been+committed minutes earlier, so nothing could replay them and nothing knew they+were missing.++The queue is now :class:`app.services.lake_spool.LakeSpool`, an append-only+disk spool. ``write_event`` returns ``True`` only once the row is on it, and+:meth:`start` replays whatever ClickHouse never took. The byte cap is+**back-pressure, not discard**: at the cap ``write_event`` returns ``False``,+the consumer holds the Kafka offset, and Kafka's retention — the durable log+this platform already runs — becomes the buffer. Raising a memory limit was+never a durability fix and neither is raising this one.++``lake_spool`` documents exactly what the spool survives (a process kill, yes;+a power loss only with ``AISOC_LAKE_SPOOL_FSYNC``; a destroyed container only+if the directory is a mounted volume).+``clickhouse-driver`` is synchronous, so every insert is dispatched to a workerthread via :func:`asyncio.to_thread` to keep the fusion event loop responsive.If the driver is not installed (some dev images), the writer disables itself at@@ -426,14 +447,18 @@ def _is_connection_lake_error(exc: BaseException) -> bool:class LakeWriter:- """Batched, fail-soft ClickHouse writer for the ``aisoc.raw_events`` lake.-- A failed batch is **retained and retried**, not dropped. Retention is- bounded by ``max_buffer_rows``; overflow discards the oldest rows and- increments ``rows_dropped`` with an error log, because unbounded memory is- a worse failure than an explicitly reported archive gap. A connection- failure triggers a capped exponential reconnect, so an outage that ends- does not require a fusion restart.+ """Spool-backed, fail-soft ClickHouse writer for the ``aisoc.raw_events`` lake.++ A failed batch is **retained on disk and retried**, not dropped. A+ connection failure triggers a capped exponential reconnect, so an outage+ that ends does not require a fusion restart. Capacity is enforced on the+ spool as back-pressure: nothing is ever discarded to make room.++ The one path that does give up is a batch ClickHouse refuses repeatedly+ as *data* (a schema disagreement, not a transport fault). Retrying it+ forever would block everything behind it, so after ``max_data_failures``+ it is moved to the spool's quarantine directory — retained for replay,+ counted, and logged — rather than deleted."""def __init__(@@ -451,6 +476,9 @@ class LakeWriter:reconnect_max_seconds: float | None = None,max_data_failures: int | None = None,client_factory: Any | None = None,+ spool_dir: str | None = None,+ max_spool_bytes: int | None = None,+ spool_fsync: bool | None = None,) -> None:# Imported here, not at module scope, and this is load-bearing rather# than style: `tests/isolation/test_retro_hunt_live.py` and@@ -462,6 +490,7 @@ class LakeWriter:# `pydantic_settings` — and takes the whole offline isolation suite# down at collection time. Keep every settings read inside a function.from app.core.config import settings # noqa: PLC0415+ from app.services.lake_spool import LakeSpool # noqa: PLC0415 — same reason as the settings import aboveself._host = hostself._port = port@@ -477,8 +506,15 @@ class LakeWriter:self._max_data_failures = max(1, int(max_data_failures or settings.lake_max_data_failures))self._client_factory = client_factoryself._client: Any | None = None- self._buffer: list[dict[str, Any]] = []- self._buffer_started_at: float = 0.0+ #: The queue is the spool, not a list. ``write_event`` returns True+ #: only once the row is on it, which is the property the consumer's+ #: offset commit now depends on.+ self._spool = LakeSpool(+ spool_dir or settings.lake_spool_dir,+ max_bytes=int(max_spool_bytes or settings.lake_max_spool_bytes),+ fsync=settings.lake_spool_fsync if spool_fsync is None else spool_fsync,+ )+ self._oldest_pending_at: float = 0.0# ImportError is the only permanent disable: without the driver there# is no code that can ever connect. A missing server is recoverable.self._disabled = False@@ -494,9 +530,31 @@ class LakeWriter:async def start(self) -> None:if self._disabled:return+ spool_ready = self._spool.open()self._client = self._make_client()if self._client is not None:- logger.info("lake_writer.started", host=self._host, database=self._database)+ logger.info("lake_writer.started", host=self._host, database=self._database, spool=str(self._spool.directory))+ if not spool_ready:+ return+ # Replay whatever the previous process accepted and never archived.+ # This is the half that was missing: `_fallback_event_id` has always+ # produced a replay-stable id and the table is read with+ # `LIMIT 1 BY event_id`, so a replay would deduplicate correctly --+ # there was simply nothing that ever replayed.+ carried = self._spool.rows_on_disk()+ if carried:+ logger.warning(+ "lake_writer.spool_recovery_started",+ rows=carried,+ detail="lake rows accepted by a previous process were never archived; replaying them now",+ )+ self._oldest_pending_at = time.monotonic()+ recovered_before = self._spool.rows_recovered+ await self.flush()+ self._spool.rows_recovered = recovered_before + (carried - self._spool.rows_on_disk())+ logger.info(+ "lake_writer.spool_recovery_finished", recovered=self._spool.rows_recovered, still_pending=self._spool.rows_on_disk()+ )def _make_client(self) -> Any | None:try:@@ -554,17 +612,19 @@ class LakeWriter:async def stop(self) -> None:await self.flush()- if self._buffer:- # The process is going away and the store did not accept these- # rows. They are lost, so they belong in `rows_dropped`: a log line- # alone would leave the metric claiming nothing was discarded.- dropped = len(self._buffer)- self.rows_dropped += dropped- logger.error(- "lake_writer.shutdown_retained_rows",- rows=dropped,- detail="ClickHouse did not accept the buffered batch before shutdown; rows are not durable",+ pending = self._spool.rows_on_disk()+ if pending:+ # Not `rows_dropped` any more, and the distinction is the whole+ # point of the spool: these rows are on disk and the next start+ # replays them. Counting them as dropped would report a loss+ # that has not happened and hide the one that has.+ logger.warning(+ "lake_writer.shutdown_pending_rows",+ rows=pending,+ spool=str(self._spool.directory),+ detail="ClickHouse did not accept these rows before shutdown; they are spooled and will be replayed on restart",)+ self._spool.close()if self._client is not None:try:await asyncio.to_thread(self._client.disconnect)@@ -580,11 +640,19 @@ class LakeWriter:partition: int | None = None,offset: int | None = None,) -> bool:- """Buffer one normalized event for the lake. Returns True if buffered.+ """Spool one normalized event for the lake. Returns True if durable.- Flushes automatically when the buffer reaches ``batch_size``. A failed- flush leaves the batch buffered (bounded), so True still means the- event was accepted for archival, not that it is already durable.+ ``True`` means the row is **on disk** and will reach ClickHouse even+ if this process is killed now. That is a stronger claim than the one+ this method used to make — it returned True for an append to a list,+ and the consumer committed the Kafka offset on the strength of it.++ ``False`` means the row is *not* recoverable: the spool is at its+ byte cap or its directory is unusable. The caller must not let the+ input offset commit, which is what turns a full disk into+ back-pressure rather than silent archive loss.++ Flushes automatically once ``batch_size`` rows are pending.``topic``/``partition``/``offset`` are the Kafka coordinates of therecord being archived. They are the fallback identity for an envelope@@ -604,12 +672,13 @@ class LakeWriter:# partially-sent batch keeps the same id and `LIMIT 1 BY event_id`# still works.row["event_id"] = self._fallback_event_id(row, topic=topic, partition=partition, offset=offset)- if not self._buffer:- self._buffer_started_at = time.monotonic()- self._buffer.append(row)- if len(self._buffer) >= self._batch_size:+ pending_before = self._spool.rows_on_disk()+ if not self._spool.append([row]):+ return False+ if pending_before == 0:+ self._oldest_pending_at = time.monotonic()+ if pending_before + 1 >= self._batch_size:await self.flush()- self._enforce_buffer_capacity()return True@staticmethod@@ -644,20 +713,31 @@ class LakeWriter:return str(uuid.uuid5(_EVENT_ID_NAMESPACE, f"content:{material}"))async def flush_if_stale(self) -> None:- if self._buffer and (time.monotonic() - self._buffer_started_at) >= self._batch_max_age:+ if self._oldest_pending_at and (time.monotonic() - self._oldest_pending_at) >= self._batch_max_age:await self.flush()async def flush(self) -> None:- if self._disabled or not self._buffer:+ """Drain the spool into ClickHouse, oldest batch first.++ Reading the spool is non-destructive: a batch's lines are committed+ only once ClickHouse has taken them, so a crash anywhere in here+ leaves the rows for the next attempt. The cost is that a crash+ *between* the insert and the commit replays those rows, which the+ deterministic ``event_id`` and ``LIMIT 1 BY event_id`` collapse.+ """+ if self._disabled:returnclient = self._ensure_client()if client is None:return- batch = self._buffer- batch_started_at = self._buffer_started_at- self._buffer = []- self._buffer_started_at = 0.0+ for batch, segment, consumed in self._spool.read_batches(self._batch_size):+ if not await self._insert_batch(client, batch, segment, consumed):+ return+ self._oldest_pending_at = time.monotonic() if self._spool.rows_on_disk() else 0.0++ async def _insert_batch(self, client: Any, batch: list[dict[str, Any]], segment: Any, consumed: int) -> bool:+ """Insert one batch. False means stop draining (the store is unhappy)."""def _insert() -> None:# clickhouse-driver executes INSERT ... VALUES with a list of dicts.@@ -675,28 +755,16 @@ class LakeWriter:try:await asyncio.to_thread(_insert)- self.rows_written += len(batch)- self._data_failures = 0except asyncio.CancelledError:- # Cancellation (shutdown, task teardown) is a BaseException, so the- # handler below never sees it. The batch was already popped from- # the buffer; putting it back keeps cancellation from being a- # silent row-loss path. The task still unwinds.- self._buffer = batch + self._buffer- self._buffer_started_at = batch_started_at- self._enforce_buffer_capacity()+ # Cancellation (shutdown, task teardown) is a BaseException, so+ # the handler below never sees it. Nothing is committed, so the+ # rows stay spooled and the next start replays them.raiseexcept Exception as exc: # noqa: BLE001 — never raise into the consumerself.flush_failures += 1connection_error = _is_connection_lake_error(exc)self._data_failures = 0 if connection_error else self._data_failures + 1- # Retain, oldest-first. `self._buffer` may have grown while the- # insert ran, so the failed batch goes in front of it.- self._buffer = batch + self._buffer- self._buffer_started_at = batch_started_at- overflow = self._enforce_buffer_capacity()-# Force a fresh client on the next attempt: a broken driver# connection otherwise fails every subsequent flush, which is the# permanent-disable failure in slower motion.@@ -704,48 +772,66 @@ class LakeWriter:self._schedule_reconnect()if not connection_error and self._data_failures >= self._max_data_failures:- dropped = len(self._buffer)- self._buffer = []- self._buffer_started_at = 0.0+ # A batch the server keeps refusing is a schema disagreement,+ # not a transport fault. Retrying forever blocks everything+ # behind it; deleting it makes the gap permanent even after+ # someone fixes the schema. Quarantine keeps both doors open.+ self._spool.quarantine(batch, reason=str(exc))+ self._spool.commit_segment(segment, consumed)self._data_failures = 0- self.rows_dropped += dropped- logger.error(- "lake_writer.batch_dropped_after_data_errors",- dropped=dropped,- failures=self._max_data_failures,- error=str(exc),- )- return+ return Falselogger.error("lake_writer.flush_failed",error=str(exc),- retained=len(self._buffer),- dropped_on_overflow=overflow,+ pending=self._spool.rows_on_disk(),retryable=connection_error,retry_in_seconds=round(max(0.0, self._next_reconnect_at - time.monotonic()), 1),)+ return False- def _enforce_buffer_capacity(self) -> int:- overflow = max(0, len(self._buffer) - self._max_buffer_rows)- if overflow:- del self._buffer[:overflow]- self.rows_dropped += overflow- self._buffer_started_at = time.monotonic()- logger.error(- "lake_writer.buffer_overflow_dropped",- dropped=overflow,- cap=self._max_buffer_rows,- detail="oldest buffered lake rows discarded; archive coverage has a gap",- )- return overflow+ self.rows_written += len(batch)+ self._data_failures = 0+ self._spool.commit_segment(segment, consumed)+ return Truedef metrics(self) -> dict[str, int]:+ pending = self._spool.rows_on_disk()return {"rows_written": self.rows_written,"flush_failures": self.flush_failures,- "buffered": len(self._buffer),+ # Kept under its original name because dashboards and the health+ # route read it, but it now counts rows pending **on disk** rather+ # than in memory. The number means something much stronger: a+ # backlog that survives this process.+ "buffered": pending,+ "spool_rows": pending,+ "spool_bytes": self._spool.bytes_on_disk(),+ # Reserved for a genuine, unrecoverable loss. Nothing in the+ # normal path increments it any more: capacity is back-pressure+ # and a refused batch is quarantined, so a non-zero value here+ # means events are actually gone."rows_dropped": self.rows_dropped,+ "rows_recovered": self._spool.rows_recovered,+ "quarantined_rows": self._spool.quarantined_rows_on_disk(),+ "capacity_refusals": self._spool.capacity_refusals,+ "spool_unreadable_lines": self._spool.unreadable_lines,+ "spool_write_failures": self._spool.write_failures,"connect_failures": self.connect_failures,"reconnects": self.reconnects,}++ @property+ def spooled_rows(self) -> int:+ """Rows accepted for archival that ClickHouse has not taken yet."""+ return self._spool.rows_on_disk()++ @property+ def archive_degraded(self) -> bool:+ """Whether archival cannot currently make an event durable.++ Exposed because "the lake is behind" and "the lake is refusing+ events" are different operational states and a backlog count alone+ cannot distinguish them.+ """+ return self._disabled or not self._spool.usablediff --git a/services/fusion/app/services/windowed_detection.py b/services/fusion/app/services/windowed_detection.pyindex 1111dfb23..b79a448ff 100644--- a/services/fusion/app/services/windowed_detection.py+++ b/services/fusion/app/services/windowed_detection.py@@ -7,18 +7,77 @@ scans, data-staging bursts. This engine adds sliding-window threshold detection:count events matching a rule, grouped by an entity, and fire once when the countcrosses a threshold inside the window.-State lives in Redis sorted sets (member = event id, score = epoch seconds) so-the window is a cheap ``ZREMRANGEBYSCORE`` + ``ZCARD``, and a short-lived-"fired" marker suppresses duplicate alerts for the same window. Everything is-fail-soft: a Redis outage degrades to "windowed detections are skipped for the-outage", never crashing the fusion pipeline.+State lives in Redis sorted sets (member = event identity, score = **event+time**) so the window is a cheap range count, and a claim marker coordinates+firing once per window. Everything is fail-soft: a Redis outage degrades to+"windowed detections are skipped for the outage", never crashing the fusion+pipeline — but the skip is now counted (:attr:`WindowedDetectionEngine.rule_errors`)+rather than logged at debug, because a Redis blip and a quiet estate used to+be indistinguishable.Only security-relevant bursts fire — a benign event that doesn't match a rule's``match_when`` never even touches Redis.++Replay safety+-------------+Kafka delivery into this engine is at-least-once and the fusion consumer+*deliberately* re-delivers a message whose alert did not become durable. Two+things follow, and before the remediation pass neither held.++**An observation must be idempotent.** The member for an event-count rule was+a fresh ``uuid4`` per call, so one event delivered N times was N members and N+re-deliveries of a single failed login crossed a threshold of N. The member is+now the event's stable identity — its ingest id, or the Kafka coordinates, or+a content hash in that order of preference. ZADD on an existing member updates+its score instead of adding a row, so a re-delivered event refreshes its own+observation and counts once.++That is the same mechanism the ``distinct_by`` rules already relied on, and+the dual use of one sorted set is preserved exactly: a *distinct* rule's+member is the observed value, an *event-count* rule's member is the event+identity. Both mean "one row per distinct thing"; they differ only in what+the thing is.++**A hit must be recoverable until it is durable.** The fire-once marker used+to be written inside the counting step, before the hit existed and long+before the consumer persisted anything — so a persistence failure, which is+exactly what the retry exists for, guaranteed the re-delivery produced+nothing until the window rolled.++Firing is now a claim, not a flag. Crossing the threshold takes a short+lease; the caller persists; :meth:`WindowedDetectionEngine.confirm` promotes+the claim to a window-long marker and :meth:`release` drops it if the alert+never landed. Simply moving the write after the database would have swapped+one race for another — two workers both crossing the threshold before either+had written anything — so the claim is taken atomically up front and only its+*resolution* waits for the database. A worker that dies mid-handoff releases+nothing, and the lease ages out: the alert is delayed by the lease rather+than suppressed for the window.++Event time, late arrival and backfill+-------------------------------------+Scores are event time, with arrival time as the fallback for a source that+stamps nothing. Almost every connector here polls, so arrival order is the+vendor's order and scoring by wall clock would make a detection a function of+the poll cadence — and would make replaying a week of history look like one+enormous burst happening now.++The count is therefore "the largest number of observations in any+``window_seconds``-long span near this event", which is independent of+arrival order: the same events in any order reach the same verdict. Trimming+is done against the event's own time (an event that arrives late is old by+construction, and trimming it against the clock would discard the observation+it just made), bounded by :data:`REORDER_TOLERANCE_SECONDS`.++The cooldown key carries the event-time bucket for the same reason, which is+what makes a replay idempotent rather than merely unlikely: the same events+replayed at any wall-clock time land in the same bucket and meet the same+confirmed marker."""from __future__ import annotations+import hashlibimport jsonimport timeimport uuid@@ -122,6 +181,46 @@ class SequenceRule:#: something that does not exist.SEQUENCE_REORDER_TOLERANCE_SECONDS = 300+#: The same bound for threshold rules. One name per rule family rather than+#: one shared constant, because the two could reasonably diverge and a single+#: number silently governing both is how a tuning change to one detection+#: family lands on the other.+REORDER_TOLERANCE_SECONDS = SEQUENCE_REORDER_TOLERANCE_SECONDS++#: How long a worker owns a threshold fire before the claim ages out. Long+#: enough to cover a persist plus the consumer's publish, short enough that a+#: worker killed mid-handoff delays the alert rather than suppressing it for+#: the window. The failure it bounds is a crash, so it must not be derived+#: from ``window_seconds``: a ten-minute window would mean a ten-minute hole.+FIRE_CLAIM_SECONDS = 60++#: Value of a cooldown key whose alert is durable. Distinguished from a claim+#: token so a second worker can tell "someone is persisting this right now"+#: from "this already fired" -- both suppress, but only the second survives+#: the claim's lease.+FIRED_CONFIRMED = "1"++#: Promote this worker's claim to the window-long marker, and only this+#: worker's. A plain SET would overwrite a claim another worker took after+#: ours expired, confirming an alert that worker has not persisted yet.+_CONFIRM_IF_OWNER = """+if redis.call('get', KEYS[1]) == ARGV[1] then+ return redis.call('set', KEYS[1], ARGV[2], 'EX', ARGV[3])+end+return 0+"""++#: Drop this worker's claim so a re-delivery can fire again. Owner-checked+#: for the same reason: an unconditional DEL would clear a claim that another+#: worker is mid-persist on, and that worker's alert would then be published+#: twice.+_RELEASE_IF_OWNER = """+if redis.call('get', KEYS[1]) == ARGV[1] then+ return redis.call('del', KEYS[1])+end+return 0+"""+# Built-in windowed rules. Intentionally small + high-signal; the corpus can grow# via the same JSON export path as the stateless engine later.@@ -298,6 +397,28 @@ def load_sequence_rules(path: Path | None = None) -> tuple[SequenceRule, ...]:return tuple(loaded)+@dataclass(frozen=True)+class WindowedHit(DetectionHit):+ """A :class:`DetectionHit` that still owes a decision about its claim.++ Subclasses rather than wrapping so every existing caller keeps working:+ ``hit.rule_id``, ``build_alert(message, hit)`` and the consumer's loop+ are unchanged, and the stateless engine's hits simply carry no claim.++ The claim is the engine's half of a two-phase handoff. ``evaluate``+ returns the hit holding a short lease on the fire slot; the caller+ persists the alert and then calls :meth:`WindowedDetectionEngine.confirm`+ or :meth:`WindowedDetectionEngine.release`. Neither being called -- a+ worker that dies -- is a third outcome the lease expiry covers.+ """++ #: Redis key holding the claim. Empty for a hit that took none.+ claim_key: str = ""+ #: This worker's token for that key, checked before confirm or release so+ #: one worker cannot resolve another's claim.+ claim_token: str = ""++def _unordered_set_exists(observations: list[list[tuple[float, str]]], window_seconds: int) -> bool:"""Is there one *distinct* event per stage inside one window, any order?@@ -382,6 +503,11 @@ class WindowedDetectionEngine:clauses: list[dict[str, Any]] = [{"match_when": rule.match_when} for rule in self._rules]clauses += [{"match_when": stage} for rule in self._sequences for stage in rule.sequence]self._derived_wanted: set[str] = requested_derived_fields(clauses)+ #: Rules skipped because Redis (or the rule itself) raised. Counted+ #: rather than only logged: at debug a Redis blip meant the rule+ #: silently did not fire, which is indistinguishable from a quiet+ #: estate, and nothing anywhere reported the difference.+ self.rule_errors = 0@propertydef rule_count(self) -> int:@@ -425,8 +551,31 @@ class WindowedDetectionEngine:return mergedreturn fields- async def evaluate(self, message: dict[str, Any], overlay: Any | None = None) -> list[DetectionHit]:- """Count this event into any matching window; return threshold-crossing hits."""+ async def evaluate(+ self,+ message: dict[str, Any],+ overlay: Any | None = None,+ *,+ event_id: str | None = None,+ topic: str | None = None,+ partition: int | None = None,+ offset: int | None = None,+ ) -> list[DetectionHit]:+ """Count this event into any matching window; return threshold-crossing hits.++ ``event_id`` (or the Kafka coordinates) is the event's stable+ identity and is what makes an observation idempotent under the+ consumer's at-least-once re-delivery. Without one the identity falls+ back to a hash of the event body -- stable across deliveries, which+ a random member was not, at the cost of collapsing two+ byte-identical events. The consumer always supplies coordinates, so+ production does not take that branch; the same trade-off and the+ same reasoning as ``lake_writer._fallback_event_id``.++ A returned :class:`WindowedHit` holds a short claim on its fire+ slot. The caller must call :meth:`confirm` once the alert is durable+ or :meth:`release` if it is not, or the claim ages out.+ """ocsf = message.get("ocsf_event")if not isinstance(ocsf, dict):return []@@ -456,6 +605,8 @@ class WindowedDetectionEngine:if privileged:fields = {**fields, **privileged}now = time.time()+ identity = self._event_identity(message, event_id=event_id, topic=topic, partition=partition, offset=offset)+ when = self._event_seconds(fields, now)hits: list[DetectionHit] = []for rule in self._rules:try:@@ -474,18 +625,27 @@ class WindowedDetectionEngine:# different, louder detection wearing this one's id.continuemember = str(value)- if await self._observe_and_check(rule, tenant, observed, now, member=member):+ claim = await self._observe_and_check(rule, tenant, observed, when, member=member, identity=identity)+ if claim is not None:hits.append(- DetectionHit(+ WindowedHit(rule_id=rule.id,name=rule.name,severity=rule.severity,category=rule.category,mitre=list(rule.mitre),+ claim_key=claim[0],+ claim_token=claim[1],))except Exception as exc: # noqa: BLE001 — one rule/Redis error must not wedge detection- logger.debug("windowed_detection.rule_error", rule=rule.id, error=str(exc))+ # Counted, not just logged. At debug this was invisible: a+ # Redis blip meant the rule silently did not fire, which+ # reads exactly like a quiet estate. Detection stays+ # fail-soft -- Redis must not wedge the alert pipeline --+ # but the degradation has to be countable.+ self.rule_errors += 1+ logger.warning("windowed_detection.rule_error", rule=rule.id, error=str(exc))if self._sequences:# One token per event, shared by every stage it matches, so two@@ -499,9 +659,38 @@ class WindowedDetectionEngine:if hit is not None:hits.append(hit)except Exception as exc: # noqa: BLE001 — same fail-soft contract- logger.debug("windowed_detection.sequence_error", rule=sequence.id, error=str(exc))+ self.rule_errors += 1+ logger.warning("windowed_detection.sequence_error", rule=sequence.id, error=str(exc))return hits+ @staticmethod+ def _event_identity(+ message: dict[str, Any],+ *,+ event_id: str | None,+ topic: str | None,+ partition: int | None,+ offset: int | None,+ ) -> str:+ """A member that is the same on every delivery of one event.++ Preference order mirrors ``lake_writer``: the ingest id first, so a+ record produced to Kafka twice still counts once; the Kafka+ coordinates next, which distinguish two events with identical+ bodies; and a content hash last, which is stable across deliveries+ but collapses byte-identical events. A random member -- what this+ used to be -- is stable across nothing, which is the defect.+ """+ if event_id:+ return f"e:{event_id}"+ ingest_id = message.get("id") or message.get("event_id")+ if ingest_id:+ return f"e:{ingest_id}"+ if topic is not None and partition is not None and offset is not None:+ return f"k:{topic}:{partition}:{offset}"+ digest = hashlib.sha256(json.dumps(message, sort_keys=True, default=str).encode("utf-8")).hexdigest()+ return f"c:{digest[:32]}"+@staticmethoddef _event_seconds(fields: dict[str, Any], now: float) -> float:"""When the event happened, falling back to when we heard about it.@@ -578,28 +767,128 @@ class WindowedDetectionEngine:rule: WindowRule,tenant: str,entity: str,- now: float,+ when: float,*,member: str | None = None,- ) -> bool:+ identity: str,+ ) -> tuple[str, str] | None:+ """Record this observation and, on a threshold crossing, claim the fire.++ Returns ``(claim_key, claim_token)`` for the worker that owns the+ fire, or ``None``. Owning the claim is a promise to call+ :meth:`confirm` or :meth:`release`.+ """key = f"{self._prefix}:{tenant}:{rule.id}:{entity}"- # A random member counts events; the observed value counts distinct- # ones, because ZADD on an existing member updates its score instead- # of adding a row. So the same sorted set serves both, and a repeated- # value refreshes its recency rather than inflating the count.- member = member if member is not None else uuid.uuid4().hex- await self._redis.zadd(key, {member: now})- await self._redis.zremrangebyscore(key, 0, now - rule.window_seconds)+ # One sorted set serves both rule families, and that duality is+ # deliberate: ZADD on an existing member updates its score instead+ # of adding a row, so a member is "one distinct thing". For a+ # distinct rule the thing is the observed value; for an event-count+ # rule it is the event. The event member used to be a fresh uuid4,+ # which made it "one delivery" rather than "one event", so the+ # consumer's at-least-once re-delivery inflated the count.+ member = member if member is not None else identity+ await self._redis.zadd(key, {member: when})+ # Trimmed against this event's own time, not the wall clock: an+ # event that arrives late is old by construction, and trimming it+ # against now would discard the observation it just made. Same+ # reasoning as the sequence path.+ retain = rule.window_seconds + REORDER_TOLERANCE_SECONDS+ await self._redis.zremrangebyscore(key, 0, when - retain)# Expire the key a window after the last event so idle entities are reaped.- await self._redis.expire(key, rule.window_seconds + 60)- count = await self._redis.zcard(key)- if count < rule.threshold:- return False- # Fire once per window: a short-lived marker suppresses re-firing on every- # subsequent event until the window rolls.- fired_key = f"{key}:fired"- already = await self._redis.set(fired_key, "1", nx=True, ex=rule.window_seconds)- return bool(already)+ await self._redis.expire(key, retain + 60)++ # Two window-length spans anchored on this event: the one ending at+ # it and the one starting at it. ``ZCOUNT`` answers each in+ # O(log N) server-side, which matters -- fetching the members and+ # sweeping them in Python is O(backlog) per event, and the rules+ # with the largest thresholds are exactly the ones with the largest+ # backlogs (a 5,000-threshold scan rule would ship 5,000 members+ # across the wire for every packet).+ #+ # Both spans, not just the trailing one, because arrival order is+ # not event order here: a polled connector delivers the vendor's+ # order, so the event that *starts* a burst routinely arrives after+ # the one that ends it. The trailing span catches a burst whose last+ # event arrives last; the leading span catches one whose first event+ # arrives last. The residual is an event arriving last from strictly+ # inside the span, which neither anchored span fully covers -- that+ # burst is detected on the next matching event for the entity rather+ # than immediately, and `window_seconds` is the delay bound.+ trailing = await self._redis.zcount(key, when - rule.window_seconds, when)+ leading = await self._redis.zcount(key, when, when + rule.window_seconds)+ if max(int(trailing or 0), int(leading or 0)) < rule.threshold:+ return None++ # Fire once per window. The key carries the event-time bucket rather+ # than relying on a wall-clock TTL alone, which is what makes a+ # replay idempotent: the same events replayed at any later time land+ # in the same bucket and meet the same marker.+ bucket = int(when // rule.window_seconds)+ fired_key = f"{key}:fired:{bucket}"+ token = uuid.uuid4().hex+ # A claim, not a flag. The old code wrote the full-window marker+ # here -- before the hit existed and long before anything was+ # persisted -- so a persistence failure, which is exactly what the+ # consumer's retry exists for, guaranteed the re-delivery produced+ # nothing. Taking the claim atomically up front is also what stops+ # two workers both firing; moving the write after the database would+ # have traded this race for that one.+ claimed = await self._redis.set(fired_key, token, nx=True, ex=FIRE_CLAIM_SECONDS)+ if not claimed:+ return None+ return fired_key, token++ async def confirm(self, hit: DetectionHit) -> None:+ """Promote a claim to the window-long cooldown: the alert is durable.++ Fail-soft: if Redis is unreachable the claim simply expires and a+ later delivery may re-fire, which is a duplicate alert rather than a+ missing one. That is the right direction for a detection engine to+ fail in, and the alert sink's per-tenant dedup guard collapses most+ of it anyway.+ """+ claim = self._claim_of(hit)+ if claim is None:+ return+ key, token = claim+ try:+ await self._redis.eval(_CONFIRM_IF_OWNER, 1, key, token, FIRED_CONFIRMED, str(self._cooldown_for(hit)))+ except Exception as exc: # noqa: BLE001 — a cooldown write must not wedge the pipeline+ self.rule_errors += 1+ logger.warning("windowed_detection.confirm_failed", rule=hit.rule_id, error=str(exc))++ async def release(self, hit: DetectionHit) -> None:+ """Drop a claim whose alert never became durable, so a retry re-fires.++ Owner-checked, so a worker cannot release a claim another worker is+ mid-persist on and cause that alert to be published twice.+ """+ claim = self._claim_of(hit)+ if claim is None:+ return+ key, token = claim+ try:+ await self._redis.eval(_RELEASE_IF_OWNER, 1, key, token)+ except Exception as exc: # noqa: BLE001+ # The claim expires on its own, so the cost of this failing is+ # the alert being delayed by the lease rather than lost.+ self.rule_errors += 1+ logger.warning("windowed_detection.release_failed", rule=hit.rule_id, error=str(exc))++ @staticmethod+ def _claim_of(hit: DetectionHit) -> tuple[str, str] | None:+ key = getattr(hit, "claim_key", "")+ token = getattr(hit, "claim_token", "")+ return (key, token) if key and token else None++ def _cooldown_for(self, hit: DetectionHit) -> int:+ for rule in self._rules:+ if rule.id == hit.rule_id:+ return rule.window_seconds+ for sequence in self._sequences:+ if sequence.id == hit.rule_id:+ return sequence.window_seconds+ return FIRE_CLAIM_SECONDSdef build_alert(self, message: dict[str, Any], hit: DetectionHit) -> RawAlert | None:ocsf = message.get("ocsf_event") or {}diff --git a/services/fusion/app/workers/consumer.py b/services/fusion/app/workers/consumer.pyindex 2c0c658a1..db10cf302 100644--- a/services/fusion/app/workers/consumer.py+++ b/services/fusion/app/workers/consumer.py@@ -18,6 +18,7 @@ from app.core.config import settingsfrom app.core.kafka_security import kafka_client_kwargsfrom app.models.alert import FusionDecision, RawAlertfrom app.services.ai_asset_recorder import AiAssetRecorder+from app.services.alert_outbox import AlertNotificationOutbox, NotificationRelayfrom app.services.alert_sink import AlertSink, PersistOutcome, PersistResultfrom app.services.detection_engine import DetectionEnginefrom app.services.dlq import DeadLetter, DeadLetterQueue, LoggingDLQ, safe_record@@ -45,6 +46,10 @@ _METRICS = {"persist_failed": 0,"persist_retryable": 0,"laked": 0,+ # Events archival could not make durable. Non-zero means the spool is+ # full or unusable: with AISOC_LAKE_ARCHIVE_REQUIRED on these hold the+ # Kafka offset, and with it off each one is a gap in the lake.+ "lake_refused": 0,# Events recorded against a session (depth plan 2.4). Counted separately# from `laked` so a deployment can see that the session store is working# rather than inferring it from alerts that happen to carry an id.@@ -62,6 +67,13 @@ _METRICS = {"retry_exhausted": 0,"recovery_holds": 0,"publish_failed": 0,+ # Notifications for an alert that is durable in Postgres but did not+ # reach the broker. `journalled` are recoverable (the relay will+ # publish them); `unrecoverable` could not even be recorded, and+ # `recovered` is how many the relay has since delivered.+ "notifications_journalled": 0,+ "notifications_unrecoverable": 0,+ "notifications_recovered": 0,# 1 when the configured DLQ is durable storage, 0 in the explicit# persistence-free mode (LoggingDLQ). A committed offset is evidence of# durable capture only in the first case.@@ -140,9 +152,21 @@ class FusionWorker:overlays: OverlayCache | None = None,sessions: SessionStore | None = None,ai_assets: AiAssetRecorder | None = None,+ outbox: AlertNotificationOutbox | None = None,) -> None:self._engine = engineself._sink = sink+ #: Recovery record for an alert that is durable in Postgres but whose+ #: notification never reached the broker. Optional in the same sense+ #: the lake writer is: a deployment that passes nothing keeps the+ #: previous behaviour, which is that such an alert is lost once the+ #: retry budget runs out. See app/services/alert_outbox.py.+ self._outbox = outbox+ self._relay: NotificationRelay | None = None+ #: Set when a notification could neither be published nor journalled,+ #: so the dead-letter reason can say so instead of reading like an+ #: ordinary transient failure.+ self._notification_at_risk = Falseself._lake = lakeself._detector = detectorself._windowed = windowed_detector@@ -190,6 +214,17 @@ class FusionWorker:def engine(self) -> FusionEngine:return self._engine+ @property+ def lake(self) -> LakeWriter | None:+ """The archival writer, so its backlog can be reported.++ Exposed because ``LakeWriter.metrics()`` had no caller anywhere in+ the service: the archive backlog, the capacity pressure and the+ quarantined rows were all computed on demand by a method nothing+ demanded.+ """+ return self._lake+@propertydef attached(self) -> bool:"""Whether the consume loop is currently iterating the subscription.@@ -270,6 +305,11 @@ class FusionWorker:self._producer = AIOKafkaProducer(bootstrap_servers=settings.kafka_bootstrap_servers,value_serializer=lambda v: json.dumps(v).encode("utf-8"),+ # Fused alerts are keyed by their canonical alert id so every+ # re-publication of one alert lands on the same partition and a+ # downstream consumer can collapse duplicates. Without a+ # serializer aiokafka requires the key to be bytes already.+ key_serializer=lambda k: None if k is None else str(k).encode("utf-8"),**kafka_client_kwargs(),)await self._consumer.start()@@ -290,6 +330,18 @@ class FusionWorker:# forever and "what else did this sitting do" would accumulate# months of unrelated activity under one id.self._flush_task = asyncio.create_task(self._periodic_flush())+ # Started after the producer, because its first sweep publishes. A+ # relay that is not started is the same defect as a journal nothing+ # reads: the rows accumulate and the alerts stay undelivered.+ if self._outbox is not None:+ self._relay = NotificationRelay(+ self._outbox,+ self._publish_recovered,+ interval_seconds=settings.outbox_relay_interval_seconds,+ batch_size=settings.outbox_relay_batch_size,+ grace_seconds=settings.outbox_relay_grace_seconds,+ )+ self._relay.start()self._running = Trueif not self._durable_capture:logger.warning(@@ -347,6 +399,12 @@ class FusionWorker:with contextlib.suppress(asyncio.CancelledError):_ = await self._flush_task # await the cancellation to settleself._flush_task = None+ if self._relay is not None:+ # Stopped before the producer is closed. A sweep publishing+ # through a torn-down producer would mark nothing delivered and+ # bump every claimed row's attempt count for no reason.+ await self._relay.stop()+ self._relay = None# Let an in-flight message finish (and, if it succeeded, commit)# before tearing the clients down. Closing Kafka underneath the loop@@ -492,6 +550,9 @@ class FusionWorker:attempt = 0max_retries = max(0, settings.consumer_max_retries)+ # Per message, not per worker: the flag describes this record's+ # notifications, and leaving it set would mislabel the next one.+ self._notification_at_risk = Falsewhile True:if not self._running or self._stop_event.is_set():return False@@ -533,10 +594,19 @@ class FusionWorker:offset=msg.offset,error=str(exc),)+ reason = f"transient processing failure after {attempt} attempts: {exc}"+ if self._notification_at_risk:+ # Say which kind of loss this is. The alert row is+ # durable; what is gone is the notification, and the+ # dead-letter payload is now the only copy of the+ # envelope. An operator reading "transient processing+ # failure" alone would look for a missing alert and+ # find one, and conclude the pipeline is fine.+ reason += " (fused alert is durable but its notification was neither published nor journalled)"captured = await self._dead_letter_or_hold(topic=msg.topic,payload=msg.value,- reason=f"transient processing failure after {attempt} attempts: {exc}",+ reason=reason,partition=msg.partition,offset=msg.offset,)@@ -722,8 +792,38 @@ class FusionWorker:# Phase A1 — archive EVERY normalized event into the ClickHouse lake# first, independent of the promotion decision below. A non-promoted# Medium event still has to be queryable via /lake/sql.- if self._lake is not None and await self._lake.write_event(payload, topic=resolved_topic, partition=partition, offset=offset):- _METRICS["laked"] += 1+ #+ # The return value is now load-bearing rather than a counter+ # input. It used to mean "appended to a list", and this offset+ # committed regardless — so archival rode entirely on an+ # in-memory buffer that a kill erased. True now means the row is+ # on the archival spool and survives this process; False means it+ # is not recoverable, and committing the offset would be the+ # silent archive loss the spool exists to prevent.+ #+ # Only the spool refusing an event holds the offset. A ClickHouse+ # outage is absorbed by the spool and costs the alert path+ # nothing, which is the distinction between "the archive is+ # behind" and "the archive cannot accept anything".+ if self._lake is not None:+ if await self._lake.write_event(payload, topic=resolved_topic, partition=partition, offset=offset):+ _METRICS["laked"] += 1+ else:+ _METRICS["lake_refused"] += 1+ if settings.lake_archive_required:+ raise RetryableProcessingError(+ "lake archival could not make this event durable; holding the offset rather than losing the archive"+ )+ logger.error(+ "fusion.lake_gap",+ topic=resolved_topic,+ partition=partition,+ offset=offset,+ detail=(+ "AISOC_LAKE_ARCHIVE_REQUIRED is off, so this event is not archived and the offset will commit; "+ "the lake has a gap at this offset"+ ),+ )# Depth 6.1 — the observed AI estate is built here rather than by# a separate worker reading the lake, for one reason: this is the@@ -768,11 +868,45 @@ class FusionWorker:# Wave 2 — stateful/windowed detections (brute force, spray, scans)# count this event into its sliding window and fire once on threshold.if self._windowed is not None:- for hit in await self._windowed.evaluate(payload, overlay):+ # The event identity is threaded in so an observation is+ # idempotent: this loop re-runs on every re-delivery, and+ # with a random member per call one event counted N times+ # crossed a threshold of N. Same preference order as the+ # lake writer -- ingest id, then Kafka coordinates.+ windowed_hits = await self._windowed.evaluate(+ payload,+ overlay,+ event_id=validation.source_event_id,+ topic=resolved_topic,+ partition=partition,+ offset=offset,+ )+ for hit in windowed_hits:win_alert = self._windowed.build_alert(payload, hit)- if win_alert is not None:- _METRICS["detected"] += 1+ if win_alert is None:+ # Nothing will be persisted, so the claim has to go+ # back or this window stays suppressed for a hit+ # that never became an alert.+ await self._windowed.release(hit)+ continue+ _METRICS["detected"] += 1+ # A threshold hit is claimed, not fired, until its alert+ # is durable. Confirming after persistence is what lets+ # a re-delivery recover an alert the database refused;+ # the claim itself (taken atomically inside `evaluate`)+ # is what stops two workers firing the same window.+ try:await self._fuse_and_persist(win_alert, source_event_id=validation.source_event_id, session=session)+ except BaseException:+ # Best-effort: under cancellation this await may not+ # complete, which is why the claim also carries a+ # lease. A released claim re-fires on the next+ # delivery; an unreleased one re-fires when the+ # lease expires. Neither suppresses the window.+ with contextlib.suppress(Exception):+ await self._windowed.release(hit)+ raise+ await self._windowed.confirm(hit)# Ingest-normalized OCSF event — run the deterministic promotion# policy (see app/services/promoter.py). Non-promoted events are@@ -870,12 +1004,10 @@ class FusionWorker:producer = self._producerif producer is None: # pragma: no cover — assigned by start()raise RuntimeError("fusion produced a fused alert before the Kafka producer started")+ key = str(fused.id)try:await asyncio.wait_for(- producer.send(- settings.kafka_topic_alerts_fused,- value=envelope,- ),+ self._deliver(producer, envelope, key=key),timeout=max(0.1, settings.kafka_send_timeout_seconds),)except asyncio.CancelledError:@@ -884,9 +1016,135 @@ class FusionWorker:# The row is durable but the notification is not. Retrying the# message republishes it; the sink's duplicate reconciliation# makes that a no-op at the database.+ #+ # Journal it before raising. The retry budget is finite: once it+ # runs out the message is dead-lettered and the offset *is*+ # committed, and from then on nothing re-delivers this record.+ # The journal is the only thing that can still publish the alert+ # after that point, so it has to be written now rather than at+ # the moment of giving up._METRICS["publish_failed"] += 1+ await self._journal_notification(fused, envelope, key=key, error=str(exc))raise RetryableProcessingError(f"fused alert publish failed: {exc}") from exc+ if result.outcome is PersistOutcome.DUPLICATE:+ # DUPLICATE is the one outcome meaning "this alert already+ # existed", so it is the only path on which an earlier attempt+ # can have left a journal row pending. Clearing it here is what+ # stops the relay republishing an alert an inline retry already+ # delivered. An INSERTED alert is new and cannot have been+ # journalled, so the happy path pays nothing for this.+ await self._clear_journalled_notification(fused)++ async def _journal_notification(self, fused: Any, envelope: dict, *, key: str, error: str) -> None:+ """Record an undelivered notification, and say so loudly if we cannot.++ A failure here is not fatal to the message — the alert row is durable+ and the offset is still uncommitted — but it does mean that if the+ retry budget runs out, the dead-letter capture will be the only+ record of this alert's envelope. That is a real archive of the+ payload rather than silent loss, but it is not a delivery, so it gets+ its own counter and a critical log rather than being folded into the+ publish-failure count.+ """+ if self._outbox is None:+ return+ recorded = await self._outbox.record(+ tenant_id=str(fused.tenant_id),+ alert_id=str(fused.id),+ topic=settings.kafka_topic_alerts_fused,+ key=key,+ payload=envelope,+ error=error,+ )+ if recorded:+ _METRICS["notifications_journalled"] += 1+ return+ _METRICS["notifications_unrecoverable"] += 1+ self._notification_at_risk = True+ logger.critical(+ "fusion.notification_unrecoverable",+ alert_id=str(fused.id),+ tenant_id=str(fused.tenant_id),+ error=error,+ detail=(+ "the alert row is durable but its notification could not be published or journalled; "+ "if the retry budget runs out the dead-letter capture is the only record of the envelope"+ ),+ )++ async def _clear_journalled_notification(self, fused: Any) -> None:+ if self._outbox is None:+ return+ await self._outbox.clear(tenant_id=str(fused.tenant_id), alert_id=str(fused.id))++ async def _publish_recovered(self, envelope: dict, key: str) -> None:+ """Deliver a journalled envelope through the same awaited-ack path.++ Injected into the relay rather than giving it its own producer call,+ so there is exactly one definition of "delivered" in this service.+ """+ producer = self._producer+ if producer is None:+ raise RuntimeError("the notification relay ran before the Kafka producer started")+ await asyncio.wait_for(+ self._deliver(producer, envelope, key=key),+ timeout=max(0.1, settings.kafka_send_timeout_seconds),+ )+ # Counted here rather than at shutdown so the figure is live: a+ # recovery an operator cannot see until the process stops is not an+ # observable recovery.+ _METRICS["notifications_recovered"] += 1++ async def pending_notifications(self) -> tuple[int | None, float | None, dict[str, int]]:+ """``(undelivered notifications, age of the oldest, per-tenant counts)``.++ ``(None, None, {})`` when there is no journal configured or it cannot+ be read — never ``(0, None, {})``, because an unreadable backlog+ reported as an empty one is how a stuck relay looks healthy.+ """+ if self._outbox is None:+ return None, None, {}+ return await self._outbox.backlog()++ @staticmethod+ async def _deliver(producer: Any, envelope: dict, *, key: str) -> None:+ """Publish one envelope and wait for the broker to acknowledge it.++ ``AIOKafkaProducer.send`` is a coroutine that appends the record to+ the client's batch accumulator and returns a *future* resolving when+ the broker acks. Awaiting the call alone awaits the **enqueue**: the+ record is in this process's memory and nowhere else, and the delivery+ outcome -- including a refusal that arrives milliseconds later -- is+ in the future that was discarded. The consumer commits the input+ offset straight afterwards, so that window loses the notification+ while keeping the alert row and advancing past the source event.++ Written as the ``send`` + ``await future`` pair rather than+ ``send_and_wait`` to match ``dlq.KafkaDLQ.record``, which carries the+ same reasoning, and because it keeps the worker compatible with+ producers that expose only ``send``.++ The caller wraps this in one ``wait_for``, so the configured timeout+ is an end-to-end *delivery* deadline rather than a bound on the+ enqueue. A timeout cancels the wait, not the record: aiokafka may+ still deliver it, so a timed-out publish is reported as unconfirmed+ and re-published, never as lost.++ ``key`` puts every copy of one alert on a single partition and gives+ a downstream consumer something stable to collapse duplicates on.+ Re-publication is designed-for here -- an offset commit and a broker+ ack cannot be made atomic -- so the key is part of the contract, not+ a tuning detail.+ """+ future = await producer.send(settings.kafka_topic_alerts_fused, value=envelope, key=key)+ acknowledged = await future+ # Referenced rather than discarded for the reason `KafkaDLQ.record`+ # records: a bare `await <name>` reads to CodeQL as an ineffectual+ # statement. The ack's payload is not part of this contract -- the+ # absence of an exception is what makes the offset commit safe.+ logger.debug("fusion.publish_acknowledged", key=key, acknowledged=acknowledged is not None)+@staticmethoddef get_metrics() -> dict:return dict(_METRICS)diff --git a/services/fusion/tests/conftest.py b/services/fusion/tests/conftest.pyindex 203f9adb2..4f95f3376 100644--- a/services/fusion/tests/conftest.py+++ b/services/fusion/tests/conftest.py@@ -4,11 +4,28 @@ Pytest config for the fusion service test suite.Sets ``asyncio_mode = auto`` so the ``@pytest.mark.asyncio`` decorators in``test_entity_risk.py`` resolve without per-test event-loop boilerplate. Theexisting ``test_alert_model.py`` is sync and unaffected.++The canonical Kafka producer double lives in ``tests/kafka_doubles.py``:+anything reaching a publish must use it rather than ``AsyncMock()``, which+cannot tell an enqueue from a delivery."""from __future__ import annotationsimport pytest+from app.core.config import settings++[email protected](autouse=True)+def _isolated_lake_spool(tmp_path, monkeypatch):+ """Point lake archival at a per-test directory.++ The lake writer spools to disk before reporting an event durable, so+ without this every test that touches it would append to one shared+ directory: tests would see each other's backlog, and a suite run would+ leave rows behind on a contributor's machine.+ """+ monkeypatch.setattr(settings, "lake_spool_dir", str(tmp_path / "lake-spool"))def pytest_collection_modifyitems(items):diff --git a/services/fusion/tests/integration/test_alert_outbox_live.py b/services/fusion/tests/integration/test_alert_outbox_live.pynew file mode 100644index 000000000..3a13598bd--- /dev/null+++ b/services/fusion/tests/integration/test_alert_outbox_live.py@@ -0,0 +1,192 @@+"""The notification journal, against a real Postgres and the real migration.++``tests/test_alert_outbox.py`` drives the worker and the relay over an+in-memory journal, which proves the *decisions*. It cannot prove the SQL:+``FOR UPDATE SKIP LOCKED``, the lease, the ``ON CONFLICT`` upsert and the+``jsonb`` round trip are all properties of the database, and a double that+implements them in Python is exactly the kind of test that passes while the+statement it stands for has never run.++So this applies ``services/api/migrations/121_fusion_alert_outbox.sql`` to a+real server and exercises the claim path from two connections at once.++Skips cleanly when no server is reachable, and says so rather than passing+quietly -- a skipped integration test that reads like a pass is how a+never-executed gate stays green.++ docker run -d --name aisoc-outbox-pg -e POSTGRES_PASSWORD=aisoc_secret \\+ -e POSTGRES_USER=aisoc -e POSTGRES_DB=aisoc -p 55432:5432 \\+ postgres:16-alpine++ AISOC_TEST_POSTGRES=postgresql://aisoc:[email protected]:55432/aisoc \\+ pytest tests/integration/test_alert_outbox_live.py+"""++from __future__ import annotations++import os+import pathlib+import uuid++import pytest+import pytest_asyncio+from app.services.alert_outbox import AlertNotificationOutbox, NotificationRelay++DSN = os.getenv("AISOC_TEST_POSTGRES", "").strip()+pytestmark = pytest.mark.skipif(not DSN, reason="set AISOC_TEST_POSTGRES=postgresql://... to run the live journal proof")++_REPO = pathlib.Path(__file__).resolve().parents[4]+_MIGRATION = _REPO / "services" / "api" / "migrations" / "121_fusion_alert_outbox.sql"++#: `current_tenant_id()` lives in migration 002. Only the function is needed+#: here -- the policy this migration installs reads it, and CREATE POLICY+#: fails outright without it.+_TENANT_GUC_FN = """+CREATE OR REPLACE FUNCTION current_tenant_id() RETURNS UUID+LANGUAGE plpgsql STABLE AS $$+BEGIN+ RETURN NULLIF(current_setting('app.current_tenant_id', TRUE), '')::uuid;+EXCEPTION WHEN OTHERS THEN RETURN NULL;+END;+$$;+"""+++@pytest_asyncio.fixture+async def pool(): # noqa: ANN201+ asyncpg = pytest.importorskip("asyncpg")+ created = await asyncpg.create_pool(DSN, min_size=1, max_size=4)+ async with created.acquire() as conn:+ await conn.execute("DROP TABLE IF EXISTS fusion_alert_outbox")+ await conn.execute(_TENANT_GUC_FN)+ await conn.execute(_MIGRATION.read_text(encoding="utf-8"))+ yield created+ await created.close()+++def _envelope(alert_id: str) -> dict:+ return {"id": alert_id, "alert_row_id": alert_id, "persist_outcome": "inserted", "alert": {"title": "LSASS access"}}+++async def test_the_migration_applies_and_a_record_round_trips(pool): # noqa: ANN001+ outbox = AlertNotificationOutbox(lambda: pool)+ tenant, alert_id = str(uuid.uuid4()), str(uuid.uuid4())++ assert await outbox.record(+ tenant_id=tenant, alert_id=alert_id, topic="aisoc.alerts.fused", key=alert_id, payload=_envelope(alert_id), error="broker down"+ )++ count, oldest, by_tenant = await outbox.backlog()+ assert count == 1+ assert oldest is not None and oldest >= 0.0+ assert by_tenant == {tenant: 1}, "an operator needs to know whose notifications are stuck, not just how many"++ claimed = await outbox.claim(limit=10, lease_seconds=30.0, grace_seconds=0.0)+ assert len(claimed) == 1+ # The jsonb round trip is the half a Python double cannot vouch for.+ assert claimed[0].payload == _envelope(alert_id)+ assert claimed[0].key == alert_id+ assert claimed[0].attempts == 1++ await outbox.resolve(claimed)+ assert (await outbox.backlog())[0] == 0+++async def test_repeated_failures_for_one_alert_do_not_grow_the_backlog(pool): # noqa: ANN001+ """A long broker outage must not turn a bounded backlog into an unbounded one."""+ outbox = AlertNotificationOutbox(lambda: pool)+ tenant, alert_id = str(uuid.uuid4()), str(uuid.uuid4())++ for n in range(5):+ assert await outbox.record(+ tenant_id=tenant, alert_id=alert_id, topic="t", key=alert_id, payload=_envelope(alert_id), error=f"attempt {n}"+ )++ assert (await outbox.backlog())[0] == 1+ claimed = await outbox.claim(limit=10, lease_seconds=30.0, grace_seconds=0.0)+ assert claimed[0].attempts == 5, "the attempt count is the record of how long this has been owed"+++async def test_a_leased_row_is_not_handed_to_a_second_replica(pool): # noqa: ANN001+ """Two relays, one row. Exactly one may publish it.++ This is the property ``FOR UPDATE SKIP LOCKED`` plus the lease exists+ for, and it cannot be tested without a real server: the second claim has+ to observe the first one's committed lease.+ """+ first = AlertNotificationOutbox(lambda: pool)+ second = AlertNotificationOutbox(lambda: pool)+ tenant = str(uuid.uuid4())+ for _ in range(3):+ alert_id = str(uuid.uuid4())+ await first.record(tenant_id=tenant, alert_id=alert_id, topic="t", key=alert_id, payload=_envelope(alert_id), error="down")++ claimed_a = await first.claim(limit=10, lease_seconds=60.0, grace_seconds=0.0)+ claimed_b = await second.claim(limit=10, lease_seconds=60.0, grace_seconds=0.0)++ assert len(claimed_a) == 3+ assert claimed_b == [], "a leased notification must not be published twice"+++async def test_an_expired_lease_is_reclaimable(pool): # noqa: ANN001+ """A relay that dies mid-publish must not strand the row forever."""+ outbox = AlertNotificationOutbox(lambda: pool)+ tenant, alert_id = str(uuid.uuid4()), str(uuid.uuid4())+ await outbox.record(tenant_id=tenant, alert_id=alert_id, topic="t", key=alert_id, payload=_envelope(alert_id), error="down")++ # A lease that has already expired stands in for the replica that died.+ assert len(await outbox.claim(limit=10, lease_seconds=-1.0, grace_seconds=0.0)) == 1+ assert len(await outbox.claim(limit=10, lease_seconds=60.0, grace_seconds=0.0)) == 1, "an expired lease must be re-claimable"+++async def test_the_grace_period_keeps_the_relay_off_an_in_flight_retry(pool): # noqa: ANN001+ """Fresh rows belong to the consumer's inline retry, not to the relay."""+ outbox = AlertNotificationOutbox(lambda: pool)+ tenant, alert_id = str(uuid.uuid4()), str(uuid.uuid4())+ await outbox.record(tenant_id=tenant, alert_id=alert_id, topic="t", key=alert_id, payload=_envelope(alert_id), error="down")++ assert await outbox.claim(limit=10, lease_seconds=30.0, grace_seconds=300.0) == []+ assert len(await outbox.claim(limit=10, lease_seconds=30.0, grace_seconds=0.0)) == 1+++async def test_the_relay_drains_the_real_table(pool): # noqa: ANN001+ """End to end over the real store: claim, publish, delete."""+ outbox = AlertNotificationOutbox(lambda: pool)+ tenant = str(uuid.uuid4())+ ids = [str(uuid.uuid4()) for _ in range(3)]+ for alert_id in ids:+ await outbox.record(tenant_id=tenant, alert_id=alert_id, topic="t", key=alert_id, payload=_envelope(alert_id), error="down")++ published: list[tuple[dict, str]] = []++ async def publish(payload, key): # noqa: ANN001, ANN202+ published.append((payload, key))++ relay = NotificationRelay(outbox, publish, grace_seconds=0.0)+ assert await relay.drain_once() == 3+ assert sorted(key for _, key in published) == sorted(ids)+ assert (await outbox.backlog())[0] == 0+++async def test_a_missing_table_is_reported_rather_than_silently_absorbed(pool): # noqa: ANN001+ """A deployment that has not run the migration must say so.++ ``record`` returning False is what tells the consumer the alert is not+ recoverable. Returning True here -- or auto-creating the table, which+ would swallow a permissions failure into a log line -- would leave the+ service reporting a healthy journal that holds nothing.+ """+ async with pool.acquire() as conn:+ await conn.execute("DROP TABLE fusion_alert_outbox")+ outbox = AlertNotificationOutbox(lambda: pool)++ assert await outbox.record(tenant_id=str(uuid.uuid4()), alert_id=str(uuid.uuid4()), topic="t", key="k", payload={}, error="x") is False+ assert outbox.available is False+ assert await outbox.backlog() == (None, None, {}), "an unreadable backlog is not an empty one"diff --git a/services/fusion/tests/integration/test_publish_acknowledgement_live.py b/services/fusion/tests/integration/test_publish_acknowledgement_live.pynew file mode 100644index 000000000..0c682cf2c--- /dev/null+++ b/services/fusion/tests/integration/test_publish_acknowledgement_live.py@@ -0,0 +1,164 @@+"""Fused-alert delivery, against a real broker.++``tests/test_publish_acknowledgement.py`` proves the worker waits for the+future its double hands back. What it cannot prove is that a *real*+``AIOKafkaProducer`` behaves the way the double models it -- that ``send``+returns before the record is delivered, and that the delivery outcome is only+in the returned future. That is the premise the whole fix rests on, so it is+worth asserting against a broker rather than against a transcription of the+documentation.++The second test is the one that matters most and the one no double can+really stand in for: a record sent to a topic the broker will refuse. The+enqueue succeeds, the refusal arrives afterwards, and only code that awaits+the future ever learns about it.++Skips cleanly when no broker is reachable, and says so rather than passing+quietly.++ docker run -d --name aisoc-p4-redpanda -p 59092:9092 \\+ docker.redpanda.com/redpandadata/redpanda:v24.2.7 \\+ redpanda start --mode dev-container --smp 1 --memory 1G \\+ --kafka-addr PLAINTEXT://0.0.0.0:9092 \\+ --advertise-kafka-addr PLAINTEXT://127.0.0.1:59092++ AISOC_TEST_KAFKA=127.0.0.1:59092 pytest tests/integration/test_publish_acknowledgement_live.py+"""++from __future__ import annotations++import asyncio+import json+import os+import uuid+from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest+import pytest_asyncio+from app.core.config import settings+from app.models.alert import AlertSeverity, FusedAlert, FusionDecision, RawAlert+from app.services.alert_sink import PersistOutcome, PersistResult+from app.workers.consumer import FusionWorker, RetryableProcessingError++BROKER = os.getenv("AISOC_TEST_KAFKA", "").strip()+pytestmark = pytest.mark.skipif(not BROKER, reason="set AISOC_TEST_KAFKA=host:port to run the live delivery proof")+++#: Bigger than a broker's default 1 MiB ``max.message.bytes``, and the whole+#: point of raising it. aiokafka checks ``max_request_size`` *itself*, inside+#: ``send``, and raises there — which is an enqueue-stage failure that the+#: original code caught perfectly well. Leaving the client limit at its+#: default produced a live test that passed against the defect: see the+#: refusal test below. Raising it past the broker's limit is what moves the+#: rejection to where the defect actually lives.+_CLIENT_REQUEST_LIMIT = 8 * 1024 * 1024+++@pytest_asyncio.fixture+async def producer(): # noqa: ANN201+ aiokafka = pytest.importorskip("aiokafka")+ client = aiokafka.AIOKafkaProducer(+ bootstrap_servers=BROKER,+ value_serializer=lambda v: json.dumps(v).encode("utf-8"),+ key_serializer=lambda k: None if k is None else str(k).encode("utf-8"),+ max_request_size=_CLIENT_REQUEST_LIMIT,+ )+ await client.start()+ yield client+ await client.stop()+++def _worker(producer, topic: str): # noqa: ANN001, ANN202+ alert = RawAlert(+ tenant_id="00000000-0000-0000-0000-000000000001",+ source="CrowdStrike Falcon",+ title="Credential dumping via LSASS access",+ severity=AlertSeverity.CRITICAL,+ src_ip="10.20.30.40",+ hostname="WIN-DC01",+ )+ alert.id = alert.deterministic_id()+ fused = FusedAlert(id=alert.id, tenant_id=alert.tenant_id, fusion_decision=FusionDecision.NEW_ALERT, alert=alert)+ worker = FusionWorker(engine=SimpleNamespace(process=AsyncMock(return_value=fused)), sink=AsyncMock()) # type: ignore[arg-type]+ worker._sink.persist = AsyncMock(return_value=PersistResult(PersistOutcome.INSERTED, str(fused.id))) # type: ignore[method-assign, union-attr] # noqa: SLF001+ worker._producer = producer # noqa: SLF001+ return worker, alert+++async def test_a_real_producer_returns_before_the_record_is_delivered(producer, monkeypatch): # noqa: ANN001+ """The premise, measured rather than quoted.++ If ``send`` resolved only once the broker had the record, the original+ code would have been correct and there would be nothing to fix. It does+ not: the coroutine returns as soon as the record is in the accumulator,+ and the delivery result is in the future it hands back.+ """+ topic = f"aisoc-p4-live-{uuid.uuid4().hex[:8]}"+ monkeypatch.setattr(settings, "kafka_topic_alerts_fused", topic)++ future = await producer.send(topic, value={"probe": True}, key="k")+ enqueued_but_undelivered = not future.done()+ metadata = await future++ assert enqueued_but_undelivered, "send resolved only after delivery; the two-stage premise would not hold"+ assert metadata.topic == topic+++async def test_a_fused_alert_reaches_the_broker_under_its_alert_id(producer, monkeypatch): # noqa: ANN001+ """The happy path end to end: published, acknowledged, and keyed."""+ aiokafka = pytest.importorskip("aiokafka")+ topic = f"aisoc-p4-live-{uuid.uuid4().hex[:8]}"+ monkeypatch.setattr(settings, "kafka_topic_alerts_fused", topic)+ monkeypatch.setattr(settings, "kafka_send_timeout_seconds", 20.0)+ worker, alert = _worker(producer, topic)++ await worker._fuse_and_persist(alert) # noqa: SLF001++ consumer = aiokafka.AIOKafkaConsumer(topic, bootstrap_servers=BROKER, auto_offset_reset="earliest", group_id=None)+ await consumer.start()+ try:+ record = await asyncio.wait_for(consumer.getone(), timeout=20.0)+ finally:+ await consumer.stop()++ assert record.key.decode() == str(alert.id), "every copy of one alert must carry one key"+ body = json.loads(record.value.decode())+ assert body["alert_row_id"] == str(alert.id)+ assert body["persist_outcome"] == "inserted"+++async def test_a_refusal_that_arrives_after_the_enqueue_is_reported(producer, monkeypatch): # noqa: ANN001+ """The defect, reproduced against a real broker.++ A record between the client's request limit and the broker's message+ limit is accepted into the accumulator and refused on delivery. Code+ that awaits only the enqueue returns cleanly here, the consumer commits+ the input offset, and the alert row sits in Postgres with nothing ever+ published for it.++ The first version of this test used the *default* ``max_request_size``+ and a 2 MiB record, and it passed against the defect. aiokafka enforces+ that limit itself, inside ``send``, so the rejection happened at the+ enqueue -- which the original code caught, correctly, because an+ enqueue-stage exception was the one failure it could see. A live test+ exercising the wrong stage is worse than no live test, so the client+ limit is raised past the broker's and the negative control is what+ established that it now discriminates.+ """+ topic = f"aisoc-p4-live-{uuid.uuid4().hex[:8]}"+ monkeypatch.setattr(settings, "kafka_topic_alerts_fused", topic)+ monkeypatch.setattr(settings, "kafka_send_timeout_seconds", 20.0)+ worker, alert = _worker(producer, topic)+ # Comfortably inside the 8 MiB client limit and comfortably past the+ # broker's 1 MiB one, so the enqueue succeeds and the broker refuses.+ alert.description = "A" * (3 * 1024 * 1024)++ before = worker.get_metrics()["publish_failed"]+ with pytest.raises(RetryableProcessingError):+ await worker._fuse_and_persist(alert) # noqa: SLF001++ assert worker.get_metrics()["publish_failed"] == before + 1diff --git a/services/fusion/tests/integration/test_windowed_detection_live.py b/services/fusion/tests/integration/test_windowed_detection_live.pynew file mode 100644index 000000000..86f27c725--- /dev/null+++ b/services/fusion/tests/integration/test_windowed_detection_live.py@@ -0,0 +1,190 @@+"""The windowed engine's claim protocol, against a real Redis.++``tests/test_windowed_replay_safety.py`` drives the engine over an in-memory+double, which proves the *decisions*. It cannot prove the two things the+protocol actually rests on, because both are properties of the server:++* ``SET key token NX EX`` is atomic, so exactly one of two concurrent+ workers takes the claim;+* the owner check and the write inside ``_CONFIRM_IF_OWNER`` /+ ``_RELEASE_IF_OWNER`` happen together, so a worker cannot resolve a claim+ that expired and was retaken by somebody else in between.++A Python double implements both by construction — it is single-threaded —+so it would pass whether or not the scripts are correct. That is exactly+the more-capable-than-reality shape this repository keeps finding, which is+why these run against the server.++Skips cleanly when no server is reachable, and says so rather than passing+quietly.++ docker run -d --name aisoc-wd-redis -p 56379:6379 redis:7-alpine+ AISOC_TEST_REDIS=redis://127.0.0.1:56379/0 pytest tests/integration/test_windowed_detection_live.py+"""++from __future__ import annotations++import json+import os+import uuid++import pytest+import pytest_asyncio+from app.services.windowed_detection import (+ FIRE_CLAIM_SECONDS,+ FIRED_CONFIRMED,+ WindowedDetectionEngine,+ WindowRule,+)++URL = os.getenv("AISOC_TEST_REDIS", "").strip()+pytestmark = pytest.mark.skipif(not URL, reason="set AISOC_TEST_REDIS=redis://host:port/db to run the live claim proof")++_RULE = WindowRule(+ id="wd-bruteforce-auth",+ name="Brute-force: repeated authentication failures",+ severity="high",+ category="identity",+ mitre=["T1110"],+ match_when={"event_type": "authentication", "outcome": "failure"},+ group_by="user",+ threshold=5,+ window_seconds=600,+)+++@pytest_asyncio.fixture+async def redis(): # noqa: ANN201+ aioredis = pytest.importorskip("redis.asyncio")+ client = aioredis.from_url(URL, decode_responses=True)+ await client.flushdb()+ yield client+ await client.aclose()+++def _auth_fail(tenant: str, when: str, user: str = "alice") -> dict:+ return {+ "tenant_id": tenant,+ "ocsf_event": {+ "tenant_uid": tenant,+ "raw_data": json.dumps({"event_type": "authentication", "outcome": "failure", "user": user, "timestamp": when}),+ },+ }+++async def _drive_to_threshold(engine, tenant, *, start=0, count=4): # noqa: ANN001, ANN202+ hits = []+ for n in range(start, start + count):+ hits += await engine.evaluate(_auth_fail(tenant, f"2026-10-27T12:00:{n:02d}Z"), event_id=f"evt-{n}")+ return hits+++async def test_a_real_threshold_crossing_claims_exactly_once(redis): # noqa: ANN001+ engine = WindowedDetectionEngine(redis, rules=(_RULE,))+ tenant = str(uuid.uuid4())+ assert await _drive_to_threshold(engine, tenant) == []++ hits = await engine.evaluate(_auth_fail(tenant, "2026-10-27T12:00:04Z"), event_id="evt-4")+ assert len(hits) == 1++ # The claim is a token with a short lease, not the window-long marker.+ key, token = hits[0].claim_key, hits[0].claim_token+ assert await redis.get(key) == token+ ttl = await redis.ttl(key)+ assert 0 < ttl <= FIRE_CLAIM_SECONDS, "a claim must age out well inside the window"+++async def test_two_concurrent_workers_take_one_claim_between_them(redis): # noqa: ANN001+ """SET NX is the mutual exclusion, and only a real server settles it."""+ worker_a = WindowedDetectionEngine(redis, rules=(_RULE,))+ worker_b = WindowedDetectionEngine(redis, rules=(_RULE,))+ tenant = str(uuid.uuid4())+ await _drive_to_threshold(worker_a, tenant)++ hits_a = await worker_a.evaluate(_auth_fail(tenant, "2026-10-27T12:00:04Z"), event_id="evt-4")+ hits_b = await worker_b.evaluate(_auth_fail(tenant, "2026-10-27T12:00:05Z"), event_id="evt-5")++ assert len(hits_a) + len(hits_b) == 1+++async def test_confirm_promotes_the_claim_to_the_window_cooldown(redis): # noqa: ANN001+ engine = WindowedDetectionEngine(redis, rules=(_RULE,))+ tenant = str(uuid.uuid4())+ await _drive_to_threshold(engine, tenant)+ hit = (await engine.evaluate(_auth_fail(tenant, "2026-10-27T12:00:04Z"), event_id="evt-4"))[0]++ await engine.confirm(hit)++ assert await redis.get(hit.claim_key) == FIRED_CONFIRMED+ assert await redis.ttl(hit.claim_key) > FIRE_CLAIM_SECONDS, "a durable hit holds the slot for the window, not the lease"+ assert await engine.evaluate(_auth_fail(tenant, "2026-10-27T12:00:06Z"), event_id="evt-6") == []+++async def test_release_frees_the_slot_so_a_retry_can_fire(redis): # noqa: ANN001+ engine = WindowedDetectionEngine(redis, rules=(_RULE,))+ tenant = str(uuid.uuid4())+ await _drive_to_threshold(engine, tenant)+ hit = (await engine.evaluate(_auth_fail(tenant, "2026-10-27T12:00:04Z"), event_id="evt-4"))[0]++ await engine.release(hit)++ assert await redis.get(hit.claim_key) is None+ again = await engine.evaluate(_auth_fail(tenant, "2026-10-27T12:00:04Z"), event_id="evt-4")+ assert len(again) == 1, "a hit that reached no database must be re-claimable"+++async def test_a_worker_cannot_release_another_workers_claim(redis): # noqa: ANN001+ """The owner check is the whole reason these are scripts and not a DEL.++ Without it, a worker whose lease expired would delete the claim of the+ worker that took it next -- and that second worker's alert would then be+ published twice.+ """+ engine = WindowedDetectionEngine(redis, rules=(_RULE,))+ tenant = str(uuid.uuid4())+ await _drive_to_threshold(engine, tenant)+ hit = (await engine.evaluate(_auth_fail(tenant, "2026-10-27T12:00:04Z"), event_id="evt-4"))[0]++ # A second worker's claim lands on the same key after the first expired.+ await redis.set(hit.claim_key, "another-workers-token", ex=FIRE_CLAIM_SECONDS)+ await engine.release(hit)++ assert await redis.get(hit.claim_key) == "another-workers-token", "a stale worker must not free a live claim"+++async def test_a_worker_cannot_confirm_another_workers_claim(redis): # noqa: ANN001+ """The mirror image: confirming someone else's claim would mark an alert+ durable that the other worker has not persisted yet."""+ engine = WindowedDetectionEngine(redis, rules=(_RULE,))+ tenant = str(uuid.uuid4())+ await _drive_to_threshold(engine, tenant)+ hit = (await engine.evaluate(_auth_fail(tenant, "2026-10-27T12:00:04Z"), event_id="evt-4"))[0]++ await redis.set(hit.claim_key, "another-workers-token", ex=FIRE_CLAIM_SECONDS)+ await engine.confirm(hit)++ assert await redis.get(hit.claim_key) == "another-workers-token"+++async def test_re_delivery_does_not_inflate_the_count_on_a_real_server(redis): # noqa: ANN001+ """ZADD on an existing member updates its score instead of adding a row.++ The whole idempotence argument rests on that, so it is worth asserting+ against the server rather than against a dict.+ """+ engine = WindowedDetectionEngine(redis, rules=(_RULE,))+ tenant = str(uuid.uuid4())++ for _ in range(10):+ assert await engine.evaluate(_auth_fail(tenant, "2026-10-27T12:00:00Z"), event_id="the-same-event") == []++ keys = [k for k in await redis.keys(f"aisoc:wd:{tenant}:*") if not k.endswith(tuple(f":fired:{n}" for n in range(100)))]+ assert keys, "the observation should have been recorded"+ assert await redis.zcard(keys[0]) == 1, "ten deliveries of one event are one member"diff --git a/services/fusion/tests/kafka_doubles.py b/services/fusion/tests/kafka_doubles.pynew file mode 100644index 000000000..dc02da2a3--- /dev/null+++ b/services/fusion/tests/kafka_doubles.py@@ -0,0 +1,66 @@+"""Kafka client doubles shared across the fusion suite.++:class:`TwoStageProducer` is the canonical producer double. It lives in its+own module rather than in one test file because reaching for ``AsyncMock()``+instead is a silent loss of coverage -- see the class docstring.+"""++from __future__ import annotations++import asyncio+from types import SimpleNamespace+++class TwoStageProducer:+ """A producer double with aiokafka's real enqueue/acknowledge split.++ ``AIOKafkaProducer.send`` is a coroutine that appends a record to the+ client's in-memory batch accumulator and returns a **future** that+ resolves when the broker acknowledges it. Those are two outcomes, and+ only the second one means the record left the process.++ ``AsyncMock()`` collapses them. Its ``send`` returns an awaitable+ resolving to a ``MagicMock``, so ``send`` and ``send_and_wait`` are+ indistinguishable under it -- both read as "awaited, no exception" --+ and a publish that only enqueues passes every assertion. That is why the+ fused-alert path shipped awaiting the enqueue and discarding the delivery+ future. Use this double for anything that reaches a publish.++ ``send`` here resolves as soon as the record is accepted into the batch+ and hands back a future, which can resolve with metadata (delivered),+ resolve with an exception (the broker refused it *after* the enqueue+ returned), or never resolve at all (still in the accumulator).+ """++ def __init__(self, *, ack_after: float = 0.0, ack_error: Exception | None = None, never_ack: bool = False) -> None:+ self.enqueued: list[dict] = []+ self.futures: list[asyncio.Future] = []+ self._ack_after = ack_after+ self._ack_error = ack_error+ self._never_ack = never_ack+ self._tasks: list[asyncio.Task] = []++ async def send(self, topic, value=None, key=None): # noqa: ANN001, ANN201+ loop = asyncio.get_running_loop()+ future: asyncio.Future = loop.create_future()+ self.enqueued.append({"topic": topic, "value": value, "key": key})+ self.futures.append(future)+ if not self._never_ack:+ self._tasks.append(loop.create_task(self._settle(future)))+ return future++ async def _settle(self, future: asyncio.Future) -> None:+ if self._ack_after:+ await asyncio.sleep(self._ack_after)+ if future.done(): # pragma: no cover — the caller cancelled it+ return+ if self._ack_error is not None:+ future.set_exception(self._ack_error)+ else:+ future.set_result(SimpleNamespace(topic="t", partition=0, offset=len(self.enqueued)))++ async def drain(self) -> None:+ """Settle the pending ack tasks so a test leaves no stray task behind."""+ for task in self._tasks:+ task.cancel()+ await asyncio.gather(*self._tasks, return_exceptions=True)diff --git a/services/fusion/tests/redis_doubles.py b/services/fusion/tests/redis_doubles.pynew file mode 100644index 000000000..5af7ab5d2--- /dev/null+++ b/services/fusion/tests/redis_doubles.py@@ -0,0 +1,97 @@+"""One in-memory Redis stand-in for the windowed detection engine.++Six copies of this used to live in six test files, each implementing a+different subset of the commands: some had ``zrangebyscore`` and some did+not, none had ``eval``. The cost is not duplication, it is that a change to+the engine breaks a test for a reason that has nothing to do with the+behaviour under test -- a missing method raises inside the engine's+fail-soft per-rule handler, the rule silently produces no hit, and the test+fails with "the detection did not fire" when the real answer is "the double+cannot do what Redis does".++So there is one double, it implements everything the engine calls, and+adding a command to the engine means adding it here once.++``eval`` dispatches on the exact scripts :mod:`app.services.windowed_detection`+defines rather than interpreting Lua. Their real semantics -- in particular+that the owner check and the write are atomic -- are pinned against a live+server in ``tests/integration/test_windowed_detection_live.py``; a double+that guessed at atomicity would be the more-capable-than-reality kind this+repository keeps finding.+"""++from __future__ import annotations++from typing import Any+++class FakeRedis:+ """Sorted sets, string keys with NX/EX, and the engine's two Lua scripts."""++ def __init__(self) -> None:+ self.zsets: dict[str, dict[str, float]] = {}+ self.strings: dict[str, str] = {}+ #: Set to make every command raise, for the fail-soft paths.+ self.failing = False++ def _check(self) -> None:+ if self.failing:+ raise ConnectionError("redis down")++ async def zadd(self, key: str, mapping: dict[str, float]) -> None:+ self._check()+ self.zsets.setdefault(key, {}).update(mapping)++ async def zremrangebyscore(self, key: str, min_s: float, max_s: float) -> None:+ self._check()+ members = self.zsets.get(key, {})+ for member in [m for m, score in list(members.items()) if min_s <= score <= max_s]:+ del members[member]++ async def zrangebyscore(self, key: str, min_s: float, max_s: float, withscores: bool = False) -> list[Any]: # noqa: FBT001, FBT002+ self._check()+ ordered = sorted((score, member) for member, score in self.zsets.get(key, {}).items() if min_s <= score <= max_s)+ return [(member, score) for score, member in ordered] if withscores else [member for _, member in ordered]++ async def zcard(self, key: str) -> int:+ self._check()+ return len(self.zsets.get(key, {}))++ async def zcount(self, key: str, min_s: float, max_s: float) -> int:+ self._check()+ return sum(1 for score in self.zsets.get(key, {}).values() if min_s <= score <= max_s)++ async def expire(self, key: str, ttl: int) -> None:+ self._check()++ async def set(self, key: str, value: str, nx: bool = False, ex: int | None = None) -> Any: # noqa: FBT001, FBT002+ self._check()+ if nx and key in self.strings:+ return None+ self.strings[key] = value+ return True++ async def get(self, key: str) -> Any:+ self._check()+ return self.strings.get(key)++ async def delete(self, key: str) -> int:+ self._check()+ return 1 if self.strings.pop(key, None) is not None else 0++ async def eval(self, script: str, numkeys: int, *args: Any) -> int: # noqa: ARG002+ self._check()+ from app.services import windowed_detection as wd # noqa: PLC0415 — avoids an import cycle at module load++ key, token = args[0], args[1]+ if script == wd._RELEASE_IF_OWNER: # noqa: SLF001+ if self.strings.get(key) == token:+ del self.strings[key]+ return 1+ return 0+ if script == wd._CONFIRM_IF_OWNER: # noqa: SLF001+ if self.strings.get(key) == token:+ self.strings[key] = args[2]+ return 1+ return 0+ raise AssertionError(f"the double does not implement this script: {script[:60]!r}")diff --git a/services/fusion/tests/test_aitm_session_rules.py b/services/fusion/tests/test_aitm_session_rules.pyindex ef6786d51..1122a5712 100644--- a/services/fusion/tests/test_aitm_session_rules.py+++ b/services/fusion/tests/test_aitm_session_rules.py@@ -44,6 +44,8 @@ from app.services.windowed_detection import (load_window_rules,)+from tests.redis_doubles import FakeRedis+#: Transcribed from what the connector emits. A transcription rather than a#: reimplementation: the connector's own test asserts this exact mapping#: against the real class, so a connector change that drops a field reds that@@ -116,47 +118,9 @@ AITM_RULE_IDS = ()-class _FakeRedis:- """The sorted-set and marker calls the engine makes, faithfully.-- A fake store, not a fake engine: every matching, grouping, windowing and- ordering decision below is made by the real ``WindowedDetectionEngine``.- Redis here is storage, which is why the alert-reduction gate could drive- the real correlator without a container either.- """-- def __init__(self) -> None:- self.zsets: dict[str, dict[str, float]] = {}- self.strings: dict[str, str] = {}-- async def zadd(self, key: str, mapping: dict[str, float]) -> None:- self.zsets.setdefault(key, {}).update(mapping)-- async def zremrangebyscore(self, key: str, min_s: float, max_s: float) -> None:- members = self.zsets.get(key, {})- for member in [m for m, score in list(members.items()) if min_s <= score <= max_s]:- del members[member]-- async def zcard(self, key: str) -> int:- return len(self.zsets.get(key, {}))-- async def zrangebyscore(self, key: str, min_s: float, max_s: float, withscores: bool = False) -> list[Any]:- items = sorted(((m, s) for m, s in self.zsets.get(key, {}).items() if min_s <= s <= max_s), key=lambda kv: (kv[1], kv[0]))- return items if withscores else [m for m, _ in items]-- async def expire(self, key: str, ttl: int) -> None:- return None-- async def set(self, key: str, value: str, nx: bool = False, ex: int | None = None) -> Any:- if nx and key in self.strings:- return None- self.strings[key] = value- return True--def _shipped_engine() -> WindowedDetectionEngine:"""The engine, loaded with what the product ships."""- return WindowedDetectionEngine(_FakeRedis(), rules=load_window_rules(), sequences=load_sequence_rules())+ return WindowedDetectionEngine(FakeRedis(), rules=load_window_rules(), sequences=load_sequence_rules())def _message(tenant: str, event: dict[str, Any], when: float) -> dict[str, Any]:diff --git a/services/fusion/tests/test_alert_outbox.py b/services/fusion/tests/test_alert_outbox.pynew file mode 100644index 000000000..9a29d26fd--- /dev/null+++ b/services/fusion/tests/test_alert_outbox.py@@ -0,0 +1,296 @@+"""An acknowledged message must never leave an alert row without a notification.++The gap these pin+-----------------+``_fuse_and_persist`` persists first and publishes second, and the consumer+commits the input offset only after the message is handled. Two orderings+follow, and before this change only one of them recovered:++* Crash between the durable row and the publish -- the offset never moved, so+ Kafka re-delivers and the publish is retried. Covered already.+* The publish fails until the retry budget runs out -- the message is then+ dead-lettered, which is a durable capture, so the **offset commits**. The+ alert row exists, the offset is past the source event, and nothing will ever+ publish the envelope. A dead letter is a triage record; nothing re-drives it.++The second case is permanent loss of the notification for an alert that is+sitting in Postgres, which is how an alert becomes invisible to auto-triage+with every surface reporting success.++The SQL itself is covered against a real Postgres in+``tests/integration/test_alert_outbox_live.py``. These drive the worker and+the relay over an in-memory journal that implements the same contract, so the+*decisions* -- journal before acknowledging, clear on a duplicate, recover on+restart -- are pinned without a container.+"""++from __future__ import annotations++from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest+from app.core.config import settings+from app.models.alert import AlertSeverity, FusedAlert, FusionDecision, RawAlert+from app.services.alert_outbox import NotificationRelay, PendingNotification+from app.services.alert_sink import PersistOutcome, PersistResult+from app.services.dlq import InMemoryDLQ+from app.workers.consumer import FusionWorker++from tests.kafka_doubles import TwoStageProducer++TENANT = "00000000-0000-0000-0000-000000000001"+++class InMemoryOutbox:+ """The journal contract, in memory.++ Deliberately not a mock: ``record`` returning False is a decision the+ worker must act on, and a mock that answers True to everything would make+ the unrecoverable case untestable.+ """++ def __init__(self, *, writable: bool = True) -> None:+ self.rows: dict[tuple[str, str], PendingNotification] = {}+ self.writable = writable+ self.cleared: list[tuple[str, str]] = []+ self._next_id = 1++ @property+ def available(self) -> bool:+ return self.writable++ async def record(self, *, tenant_id, alert_id, topic, key, payload, error) -> bool: # noqa: ANN001+ if not self.writable:+ return False+ existing = self.rows.get((tenant_id, alert_id))+ attempts = existing.attempts + 1 if existing else 1+ self.rows[(tenant_id, alert_id)] = PendingNotification(+ id=existing.id if existing else self._next_id,+ tenant_id=tenant_id,+ alert_id=alert_id,+ topic=topic,+ key=key,+ payload=payload,+ attempts=attempts,+ )+ if existing is None:+ self._next_id += 1+ return True++ async def clear(self, *, tenant_id, alert_id) -> None: # noqa: ANN001+ self.cleared.append((tenant_id, alert_id))+ self.rows.pop((tenant_id, alert_id), None)++ async def claim(self, *, limit, lease_seconds, grace_seconds) -> list[PendingNotification]: # noqa: ANN001, ARG002+ return list(self.rows.values())[:limit]++ async def resolve(self, delivered) -> None: # noqa: ANN001+ done = {(item.tenant_id, item.alert_id) for item in delivered}+ for key in list(self.rows):+ if key in done:+ del self.rows[key]++ async def record_attempt_failed(self, pending, error) -> None: # noqa: ANN001, ARG002+ return None++ async def backlog(self) -> tuple[int | None, float | None, dict[str, int]]:+ return len(self.rows), (0.0 if self.rows else None), {t: 1 for t, _ in self.rows}+++def _alert() -> RawAlert:+ return RawAlert(+ tenant_id=TENANT,+ source="CrowdStrike Falcon",+ title="Credential dumping via LSASS access",+ severity=AlertSeverity.CRITICAL,+ src_ip="10.20.30.40",+ hostname="WIN-DC01",+ )+++def _worker(producer, outbox, *, outcome=PersistOutcome.INSERTED): # noqa: ANN001, ANN201+ alert = _alert()+ alert.id = alert.deterministic_id()+ fused = FusedAlert(id=alert.id, tenant_id=alert.tenant_id, fusion_decision=FusionDecision.NEW_ALERT, alert=alert)+ worker = FusionWorker(+ engine=SimpleNamespace(process=AsyncMock(return_value=fused)),+ sink=AsyncMock(),+ dlq=InMemoryDLQ(),+ outbox=outbox,+ )+ worker._sink.persist = AsyncMock(return_value=PersistResult(outcome, str(fused.id))) # noqa: SLF001+ worker._producer = producer # noqa: SLF001+ worker._running = True # noqa: SLF001+ worker._stop_event.clear() # noqa: SLF001+ return worker, alert+++def _msg(offset: int = 0) -> SimpleNamespace:+ """A record that genuinely reaches the publish.++ The whole point is the ordering between a durable row and its+ notification, so the message has to travel the real promotion path+ rather than being short-circuited into ``_fuse_and_persist``.+ """+ return SimpleNamespace(+ value={+ "tenant_id": TENANT,+ "ocsf_event": {+ "class_uid": 2001,+ "category_uid": 2,+ "severity_id": 5,+ "message": "Credential dumping",+ "metadata": {"uid": "ev-1", "product": {"name": "Falcon", "vendor_name": "CrowdStrike"}},+ },+ },+ topic=settings.kafka_topic_raw_events,+ partition=0,+ offset=offset,+ )+++async def test_an_undelivered_notification_is_recoverable_once_the_offset_commits(monkeypatch):+ """The acceptance case. Retries exhaust, the message is acknowledged, and+ the alert must still be deliverable afterwards.++ ``_handle_message`` returning True is what lets the consume loop commit+ the offset. After that point Kafka will never hand this record over+ again, so if the journal is empty here the alert's notification is gone+ for good while the alert row sits in Postgres looking fine.+ """+ monkeypatch.setattr(settings, "consumer_max_retries", 1)+ monkeypatch.setattr(settings, "consumer_retry_base_seconds", 0.0)+ monkeypatch.setattr(settings, "consumer_retry_max_seconds", 0.0)+ monkeypatch.setattr(settings, "kafka_send_timeout_seconds", 1.0)++ outbox = InMemoryOutbox()+ producer = TwoStageProducer(ack_error=RuntimeError("broker refused the record"))+ worker, alert = _worker(producer, outbox)++ acknowledged = await worker._handle_message(_msg()) # noqa: SLF001++ assert acknowledged is True, "a dead-lettered message is acknowledged; that is the existing contract"+ assert len(outbox.rows) == 1, "the offset is about to commit and nothing can re-deliver this alert"+ pending = next(iter(outbox.rows.values()))+ assert pending.alert_id == str(alert.id)+ assert pending.key == str(alert.id)+ assert pending.payload["alert_row_id"] == str(alert.id)+ await producer.drain()+++async def test_the_dead_letter_says_the_notification_is_the_thing_that_was_lost(monkeypatch):+ """A journal that cannot be written must not read as an ordinary retry.++ The alert row is durable, so an operator looking for a missing alert+ finds one and concludes the pipeline is healthy. The reason has to name+ the notification.+ """+ monkeypatch.setattr(settings, "consumer_max_retries", 0)+ monkeypatch.setattr(settings, "consumer_retry_base_seconds", 0.0)+ monkeypatch.setattr(settings, "kafka_send_timeout_seconds", 1.0)++ outbox = InMemoryOutbox(writable=False)+ producer = TwoStageProducer(ack_error=RuntimeError("broker refused the record"))+ worker, _ = _worker(producer, outbox)++ before = worker.get_metrics()["notifications_unrecoverable"]+ assert await worker._handle_message(_msg()) is True # noqa: SLF001++ assert worker.get_metrics()["notifications_unrecoverable"] == before + 1+ captured = worker._dlq.records # noqa: SLF001+ assert len(captured) == 1+ assert "notification was neither published nor journalled" in captured[0].reason+ await producer.drain()+++async def test_the_relay_delivers_a_journalled_notification(monkeypatch):+ """Restart recovery: a pending row becomes a real published record."""+ monkeypatch.setattr(settings, "kafka_send_timeout_seconds", 1.0)+ outbox = InMemoryOutbox()+ failing = TwoStageProducer(ack_error=RuntimeError("broker down"))+ worker, alert = _worker(failing, outbox)+ monkeypatch.setattr(settings, "consumer_max_retries", 0)+ monkeypatch.setattr(settings, "consumer_retry_base_seconds", 0.0)+ await worker._handle_message(_msg()) # noqa: SLF001+ await failing.drain()+ assert len(outbox.rows) == 1++ # The broker comes back. A new producer stands in for the restart.+ healthy = TwoStageProducer()+ worker._producer = healthy # noqa: SLF001+ relay = NotificationRelay(outbox, worker._publish_recovered, grace_seconds=0.0) # noqa: SLF001++ delivered = await relay.drain_once()++ assert delivered == 1+ assert outbox.rows == {}, "a delivered notification must leave the journal"+ assert len(healthy.enqueued) == 1+ assert healthy.enqueued[0]["key"] == str(alert.id)+ assert healthy.futures[0].done(), "the relay must wait for the broker like the inline path does"+ assert worker.get_metrics()["notifications_recovered"] >= 1+ await healthy.drain()+++async def test_the_relay_leaves_the_row_pending_when_the_broker_is_still_down(monkeypatch):+ """A failed recovery attempt must not look like a delivery."""+ monkeypatch.setattr(settings, "kafka_send_timeout_seconds", 1.0)+ outbox = InMemoryOutbox()+ await outbox.record(+ tenant_id=TENANT, alert_id=str(_alert().deterministic_id()), topic="t", key="k", payload={"id": "x"}, error="first failure"+ )+ producer = TwoStageProducer(ack_error=RuntimeError("still down"))+ worker, _ = _worker(producer, outbox)+ relay = NotificationRelay(outbox, worker._publish_recovered, grace_seconds=0.0) # noqa: SLF001++ delivered = await relay.drain_once()++ assert delivered == 0+ assert len(outbox.rows) == 1, "an undelivered notification must stay pending"+ assert relay.failures == 1+ await producer.drain()+++async def test_a_duplicate_clears_a_journal_row_an_inline_retry_already_delivered(monkeypatch):+ """The relay must not republish what a retry has already published.++ DUPLICATE is the one persist outcome meaning the alert already existed,+ so it is the only path where an earlier attempt can have journalled it.+ """+ monkeypatch.setattr(settings, "kafka_send_timeout_seconds", 1.0)+ outbox = InMemoryOutbox()+ producer = TwoStageProducer()+ worker, alert = _worker(producer, outbox, outcome=PersistOutcome.DUPLICATE)+ await outbox.record(+ tenant_id=TENANT, alert_id=str(alert.id), topic="t", key=str(alert.id), payload={"id": "x"}, error="earlier failure"+ )++ await worker._fuse_and_persist(alert) # noqa: SLF001++ assert outbox.rows == {}, "the retry delivered it; the relay must not send it again"+ assert (TENANT, str(alert.id)) in outbox.cleared+ await producer.drain()+++async def test_an_inserted_alert_does_not_touch_the_journal(monkeypatch):+ """The happy path pays nothing.++ A new alert cannot have a pending journal row, so clearing one would be+ a round trip per alert for an outcome that is impossible.+ """+ monkeypatch.setattr(settings, "kafka_send_timeout_seconds", 1.0)+ outbox = InMemoryOutbox()+ producer = TwoStageProducer()+ worker, alert = _worker(producer, outbox, outcome=PersistOutcome.INSERTED)++ await worker._fuse_and_persist(alert) # noqa: SLF001++ assert outbox.cleared == []+ assert outbox.rows == {}+ await producer.drain()diff --git a/services/fusion/tests/test_consumer_dlq.py b/services/fusion/tests/test_consumer_dlq.pyindex 99b72d7b2..f67a1b82b 100644--- a/services/fusion/tests/test_consumer_dlq.py+++ b/services/fusion/tests/test_consumer_dlq.py@@ -18,6 +18,8 @@ from app.models.alert import FusionDecisionfrom app.services.dlq import InMemoryDLQfrom app.workers.consumer import FusionWorker, PermanentProcessingError+from tests.kafka_doubles import TwoStageProducer+pytestmark = pytest.mark.asyncioTENANT = "00000000-0000-0000-0000-000000000001"@@ -50,7 +52,10 @@ def _worker_with_dlq() -> tuple[FusionWorker, InMemoryDLQ]:))worker = FusionWorker(engine=engine, sink=None, dlq=dlq)- worker._producer = AsyncMock() # noqa: SLF001 — test drives the internals+ # Not an AsyncMock: its `send` cannot distinguish an enqueue from a+ # delivery, so a publish that never leaves the process passes. See+ # tests.kafka_doubles.TwoStageProducer.+ worker._producer = TwoStageProducer() # noqa: SLF001 — test drives the internalsreturn worker, dlq@@ -59,7 +64,9 @@ async def test_valid_event_is_processed_and_not_dead_lettered():await worker._process_message(_valid_raw_event(), topic=RAW_EVENTS) # noqa: SLF001assert dlq.records == []worker._engine.process.assert_awaited_once() # noqa: SLF001- worker._producer.send.assert_awaited_once() # noqa: SLF001+ assert len(worker._producer.enqueued) == 1 # noqa: SLF001+ assert worker._producer.futures[0].done(), "published without waiting for the broker" # noqa: SLF001+ await worker._producer.drain() # noqa: SLF001async def test_missing_ocsf_event_is_dead_lettered_not_dropped():diff --git a/services/fusion/tests/test_lake_durability.py b/services/fusion/tests/test_lake_durability.pynew file mode 100644index 000000000..ff1f047f3--- /dev/null+++ b/services/fusion/tests/test_lake_durability.py@@ -0,0 +1,341 @@+"""Lake archival must have a recovery boundary of its own.++The defect these pin+--------------------+``LakeWriter.write_event`` appends to ``self._buffer`` -- a plain list -- and+returns ``True``. Its own docstring admits that True means "accepted for+archival, not that it is already durable". The consumer uses that return only+to bump a counter and commits the input Kafka offset regardless, so the offset+advances on the strength of an in-memory list.++Three consequences, all of them silent:++* A hard kill loses the whole buffer. ``stop()`` is honest and counts retained+ rows as dropped, but SIGKILL does not run ``stop()``.+* ``_enforce_buffer_capacity`` discards the **oldest** rows on overflow. It+ says so loudly, but their offsets were committed long before, so nothing+ can replay them.+* Archival rides entirely on the fusion consumer-group offset. There is no+ lake checkpoint and no spool, so "the lake is behind" and "the lake has a+ permanent hole" are indistinguishable.++The machinery for recovery already exists and nothing triggers it:+``_fallback_event_id`` derives a replay-stable id from the Kafka coordinates+and the table is read with ``LIMIT 1 BY event_id``, so a replay *would*+deduplicate. The missing half is a reason to replay.++Raising ``max_buffer_rows`` is not a fix and these tests are written so that+it cannot pass as one: the capacity case asserts back-pressure, not headroom.+"""++from __future__ import annotations++import json+import uuid++import pytest+from app.services.lake_writer import LakeWriter++TENANT = "00000000-0000-0000-0000-000000000001"+++def _event(uid: str = "ev-1") -> dict:+ return {+ "tenant_id": TENANT,+ "id": uid,+ "ocsf_event": {+ "tenant_uid": TENANT,+ "class_uid": 4001,+ "category_uid": 4,+ "severity_id": 2,+ "time": "2026-10-27T00:00:00Z",+ "metadata": {"uid": uid, "product": {"name": "Falcon"}},+ },+ }+++class _DownClickHouse:+ """A server that is unreachable, the way the driver reports it."""++ def __init__(self) -> None:+ self.inserted: list[dict] = []++ def execute(self, sql, rows=None, **kwargs): # noqa: ANN001, ANN201, ARG002+ raise ConnectionError("connection refused")++ def disconnect(self) -> None:+ return None+++class _UpClickHouse:+ def __init__(self) -> None:+ self.inserted: list[dict] = []++ def execute(self, sql, rows=None, **kwargs): # noqa: ANN001, ANN201, ARG002+ self.inserted.extend(rows or [])+ return []++ def disconnect(self) -> None:+ return None+++def _writer(tmp_path, client, **kwargs): # noqa: ANN001, ANN201+ return LakeWriter(+ host="localhost",+ batch_size=kwargs.pop("batch_size", 2),+ client_factory=lambda: client,+ spool_dir=str(tmp_path / "spool"),+ **kwargs,+ )+++async def test_an_accepted_event_is_on_disk_before_the_offset_can_commit(tmp_path):+ """``write_event`` returning True must mean "survives this process".++ The consumer commits the input offset after this returns. If True only+ means "appended to a list", the offset has moved for an event that exists+ nowhere but RAM.+ """+ writer = _writer(tmp_path, _DownClickHouse(), batch_size=50)+ await writer.start()++ assert await writer.write_event(_event("ev-1"), topic="aisoc.raw_events", partition=0, offset=7) is True++ assert writer.spooled_rows == 1, "the event must be recorded somewhere that outlives the process"+ assert writer.metrics()["spool_rows"] == 1+++async def test_a_hard_kill_before_a_flush_does_not_lose_the_archive(tmp_path):+ """SIGKILL: no ``stop()``, no graceful flush, nothing in Python's hands.++ Modelled by abandoning the writer object entirely and building a new one+ over the same spool directory, which is what a restarted process sees.+ """+ down = _DownClickHouse()+ writer = _writer(tmp_path, down, batch_size=50)+ await writer.start()+ for n in range(5):+ await writer.write_event(_event(f"ev-{n}"), topic="aisoc.raw_events", partition=0, offset=n)+ del writer # the process is gone; nothing ran++ up = _UpClickHouse()+ restarted = _writer(tmp_path, up, batch_size=50)+ await restarted.start()+ await restarted.flush()++ assert len(up.inserted) == 5, "every event accepted before the kill must reach the lake on restart"+ assert restarted.metrics()["rows_recovered"] == 5+++async def test_a_replayed_event_keeps_one_identity(tmp_path):+ """Recovery must not inflate hunts, usage figures or aggregations.++ The spool can hand the same event to ClickHouse twice (it is replayed+ after a crash whose offset commit may or may not have landed), so the+ identity has to be a function of the event, not of the attempt.+ """+ up = _UpClickHouse()+ writer = _writer(tmp_path, up, batch_size=50)+ await writer.start()+ await writer.write_event(_event("ev-1"), topic="aisoc.raw_events", partition=0, offset=3)+ await writer.flush()+ first = up.inserted[0]["event_id"]++ replayed = _writer(tmp_path, up, batch_size=50)+ await replayed.start()+ await replayed.write_event(_event("ev-1"), topic="aisoc.raw_events", partition=0, offset=3)+ await replayed.flush()++ assert len(up.inserted) == 2+ assert up.inserted[1]["event_id"] == first, "a replayed event must collapse under LIMIT 1 BY event_id"+++async def test_capacity_exhaustion_applies_back_pressure_instead_of_dropping(tmp_path):+ """The explicit non-fix: more memory is not durability.++ At capacity the writer must refuse the event so the consumer holds the+ Kafka offset -- Kafka's retention is the back-pressure buffer, and it is+ orders of magnitude more durable than any in-process cap. Discarding the+ oldest rows, which is what the buffer did, loses events whose offsets+ were committed minutes earlier.+ """+ writer = _writer(tmp_path, _DownClickHouse(), batch_size=50, max_spool_bytes=600)+ await writer.start()++ accepted = 0+ for n in range(200):+ if await writer.write_event(_event(f"ev-{n}"), topic="aisoc.raw_events", partition=0, offset=n):+ accepted += 1+ else:+ break++ assert accepted < 200, "capacity must be reachable, or the test proves nothing"+ assert writer.metrics()["capacity_refusals"] >= 1+ assert writer.metrics()["rows_dropped"] == 0, "back-pressure, not discard: nothing may be lost at the cap"+++async def test_a_refused_event_stops_the_offset_committing(tmp_path):+ """The consumer half of the contract.++ Archival having its own durable boundary is only worth anything if the+ consumer reads it. A refused event must raise so the message is retried+ with its offset uncommitted.+ """+ from types import SimpleNamespace+ from unittest.mock import AsyncMock++ from app.workers.consumer import FusionWorker, RetryableProcessingError++ writer = _writer(tmp_path, _DownClickHouse(), batch_size=50, max_spool_bytes=1)+ await writer.start()+ worker = FusionWorker(engine=SimpleNamespace(process=AsyncMock()), lake=writer)++ with pytest.raises(RetryableProcessingError):+ await worker._process_message( # noqa: SLF001+ _event("ev-1"), topic="aisoc.raw_events", partition=0, offset=11+ )+++async def test_a_clickhouse_outage_does_not_stop_the_alert_pipeline(tmp_path):+ """The other half: an archive fault must not cost the alert path.++ A ClickHouse outage is absorbed by the spool. Only a spool that cannot+ accept the event is allowed to apply back-pressure.+ """+ writer = _writer(tmp_path, _DownClickHouse(), batch_size=1)+ await writer.start()++ for n in range(20):+ assert await writer.write_event(_event(f"ev-{n}"), topic="aisoc.raw_events", partition=0, offset=n) is True++ assert writer.metrics()["spool_rows"] == 20+ assert writer.metrics()["rows_dropped"] == 0+++async def test_an_extended_outage_drains_when_the_store_returns(tmp_path):+ down, up = _DownClickHouse(), _UpClickHouse()+ client = {"current": down}+ writer = LakeWriter(+ host="localhost",+ batch_size=5,+ reconnect_base_seconds=0.0,+ reconnect_max_seconds=0.0,+ client_factory=lambda: client["current"],+ spool_dir=str(tmp_path / "spool"),+ )+ await writer.start()+ for n in range(12):+ await writer.write_event(_event(f"ev-{n}"), topic="aisoc.raw_events", partition=0, offset=n)+ assert writer.metrics()["spool_rows"] == 12++ client["current"] = up+ writer._client = None # noqa: SLF001 — the reconnect the backoff would do+ await writer.flush()++ assert len(up.inserted) == 12+ assert writer.metrics()["spool_rows"] == 0, "a drained backlog must leave the spool"+++async def test_a_batch_the_server_keeps_rejecting_is_quarantined_not_deleted(tmp_path):+ """Unrecoverable is a place, not a deletion.++ A schema mismatch is not a transport fault and must not be retried+ forever, but discarding the rows makes the gap unrecoverable even once+ someone fixes the schema. They go somewhere an operator can replay them+ from, and the count is exposed.+ """++ class _RejectingClickHouse:+ def execute(self, sql, rows=None, **kwargs): # noqa: ANN001, ANN201, ARG002+ raise ValueError("Unknown column nonsense_column")++ def disconnect(self) -> None:+ return None++ writer = _writer(+ tmp_path,+ _RejectingClickHouse(),+ batch_size=1,+ max_data_failures=2,+ # Without this the reconnect backoff skips the second and third+ # flushes, the failure counter never reaches its bound, and the test+ # would pass for having proved nothing.+ reconnect_base_seconds=0,+ reconnect_max_seconds=0,+ )+ await writer.start()+ for n in range(3):+ await writer.write_event(_event(f"ev-{n}"), topic="aisoc.raw_events", partition=0, offset=n)+ await writer.flush()++ metrics = writer.metrics()+ assert metrics["quarantined_rows"] >= 1+ quarantined = list((tmp_path / "spool" / "quarantine").glob("*.jsonl"))+ assert quarantined, "a rejected batch must be readable again after the schema is fixed"+ recovered = [json.loads(line) for line in quarantined[0].read_text(encoding="utf-8").splitlines() if line.strip()]+ assert recovered and uuid.UUID(recovered[0]["event_id"])+++async def test_the_backlog_is_actually_reachable_from_the_metrics_route(tmp_path):+ """A gap nobody can see is a gap nobody reported.++ ``LakeWriter.metrics()`` existed and had no caller anywhere in the+ service, so every one of these figures was computed on demand by a+ method nothing demanded. The requirement is to *expose* backlog,+ capacity pressure and quarantined rows, which means a route has to+ return them.+ """+ from types import SimpleNamespace+ from unittest.mock import AsyncMock++ from app.api import router as router_module+ from app.workers.consumer import FusionWorker++ writer = _writer(tmp_path, _DownClickHouse(), batch_size=50)+ await writer.start()+ for n in range(3):+ await writer.write_event(_event(f"ev-{n}"), topic="aisoc.raw_events", partition=0, offset=n)++ worker = FusionWorker(engine=SimpleNamespace(process=AsyncMock()), lake=writer)+ router_module.set_worker(worker)+ try:+ body = await router_module.metrics()+ finally:+ router_module.set_worker(None) # type: ignore[arg-type]++ assert body["lake"]["spool_rows"] == 3+ assert body["lake"]["spool_bytes"] > 0+ assert body["lake"]["quarantined_rows"] == 0+ assert body["lake"]["capacity_refusals"] == 0+ assert body["lake"]["degraded"] is False+ # No journal configured, so the honest answer is "unknown", not zero.+ assert body["notifications"] == {"pending": None, "oldest_seconds": None, "by_tenant": {}}+++async def test_graceful_shutdown_leaves_a_recoverable_backlog_not_a_loss(tmp_path):+ """``stop()`` used to count retained rows as dropped. They are not dropped+ any more -- they are on disk, and the next start replays them."""+ down = _DownClickHouse()+ writer = _writer(tmp_path, down, batch_size=50)+ await writer.start()+ for n in range(4):+ await writer.write_event(_event(f"ev-{n}"), topic="aisoc.raw_events", partition=0, offset=n)+ await writer.stop()++ assert writer.metrics()["rows_dropped"] == 0, "a spooled row is a backlog, not a loss"++ up = _UpClickHouse()+ restarted = _writer(tmp_path, up, batch_size=50)+ await restarted.start()+ await restarted.flush()+ assert len(up.inserted) == 4diff --git a/services/fusion/tests/test_lake_writer.py b/services/fusion/tests/test_lake_writer.pyindex 485b0c013..bd95f93a0 100644--- a/services/fusion/tests/test_lake_writer.py+++ b/services/fusion/tests/test_lake_writer.py@@ -144,17 +144,21 @@ async def test_stop_flushes_remaining():assert len(fake.inserted) == 1-async def test_stop_counts_rows_it_could_not_flush_as_dropped():- """A row still buffered when the process exits is not durable.-- Logging it without incrementing `rows_dropped` leaves the metric claiming- the archive gap did not happen.+async def test_stop_leaves_an_unflushed_row_recoverable_rather_than_dropped():+ """This assertion used to be the opposite, and it was pinning the defect.++ A row the store had not taken by shutdown really was lost, because the+ queue was a list in memory, so counting it as dropped was the honest+ reading. The queue is now the disk spool: the row is still there, the+ next start replays it, and reporting it as dropped would claim a loss+ that has not happened — while making a real one indistinguishable."""w, fake = _writer_with_fake(batch_size=100, reconnect_base_seconds=0, reconnect_max_seconds=0)fake.fail = Trueawait w.write_event(_message())await w.stop()- assert w.metrics()["rows_dropped"] == 1+ assert w.metrics()["rows_dropped"] == 0+ assert w.metrics()["spool_rows"] == 1, "the row must still be queued for the next process"async def test_flush_if_stale_flushes_old_buffer():@@ -202,7 +206,11 @@ async def test_a_generated_event_id_is_stable_across_a_retry():msg["id"] = "not-a-uuid"fake.fail = Trueawait w.write_event(msg)- generated = w._buffer[0]["event_id"] # noqa: SLF001 — the retained row+ # Read back off the spool rather than an in-memory buffer: the row is on+ # disk now, which is what makes the identity survive the restart the+ # sibling test covers.+ retained = next(iter(w._spool.read_batches(10)))[0] # noqa: SLF001 — the retained row+ generated = retained[0]["event_id"]assert generatedfake.fail = False@@ -282,23 +290,31 @@ async def test_flush_failure_retains_batch_and_never_raises():assert w.metrics()["buffered"] == 0-async def test_buffer_overflow_drops_oldest_rows_explicitly():- """Retention is bounded; overflow is counted rather than silent."""- w, fake = _writer_with_fake(batch_size=1, max_buffer_rows=2, reconnect_base_seconds=0, reconnect_max_seconds=0)+async def test_capacity_refuses_the_newest_row_rather_than_discarding_the_oldest():+ """The other assertion that used to pin the defect.++ The old guard discarded the *oldest* buffered rows on overflow — rows+ whose Kafka offsets had been committed minutes earlier, so nothing could+ ever replay them and nothing knew they were missing. Capacity now+ refuses the incoming event instead, which the consumer turns into a held+ offset: Kafka's retention becomes the buffer and nothing is lost.+ """+ w, fake = _writer_with_fake(batch_size=1, max_spool_bytes=1, reconnect_base_seconds=0, reconnect_max_seconds=0)fake.fail = True- for _ in range(3):- await w.write_event(_message()) # each write attempts a flush, all fail+ assert await w.write_event(_message()) is False, "a full spool must refuse, so the offset is held"metrics = w.metrics()- assert metrics["buffered"] == 2- assert metrics["rows_dropped"] == 1+ assert metrics["capacity_refusals"] >= 1+ assert metrics["rows_dropped"] == 0-async def test_data_errors_are_bounded_and_dropped_loudly():- """A batch the server keeps rejecting must not grow forever.+async def test_data_errors_are_bounded_and_quarantined_loudly():+ """A batch the server keeps rejecting must not block everything behind it.Connection errors are retained (the store is down, the rows may be fine);- non-connection errors are retried a bounded number of times and then- dropped with `rows_dropped` incremented.+ non-connection errors are retried a bounded number of times and then set+ aside. They used to be deleted, which made the gap permanent even after+ someone fixed the schema — so they are now quarantined on disk, counted,+ and replayable."""w, fake = _writer_with_fake(batch_size=2,@@ -313,8 +329,9 @@ async def test_data_errors_are_bounded_and_dropped_loudly():w._client = fake # noqa: SLF001 — retry without waiting for reconnectawait w.flush() # second data failure reaches the boundassert w.flush_failures == 2- assert w.metrics()["buffered"] == 0- assert w.metrics()["rows_dropped"] == 2+ assert w.metrics()["spool_rows"] == 0, "the rejected batch must stop blocking the queue"+ assert w.metrics()["quarantined_rows"] == 2+ assert w.metrics()["rows_dropped"] == 0, "set aside for replay is not the same as lost"async def test_connect_failure_is_retried_instead_of_permanently_disabling():diff --git a/services/fusion/tests/test_publish_acknowledgement.py b/services/fusion/tests/test_publish_acknowledgement.pynew file mode 100644index 000000000..86f5fee63--- /dev/null+++ b/services/fusion/tests/test_publish_acknowledgement.py@@ -0,0 +1,163 @@+"""The fused-alert publish must wait for the broker, not for the accumulator.++``AIOKafkaProducer.send`` is a coroutine that appends a record to the client's+in-memory batch accumulator and returns a **future** that resolves when the+broker acknowledges it. Awaiting the call therefore awaits the *enqueue*; the+delivery result is in the returned future, and a caller that drops the future+has learned nothing about whether the record was ever delivered.++The consumer commits the input offset as soon as the message is handled. So an+enqueue-only publish means the offset advances while the envelope is still in+process memory: a kill in that window leaves the alert row in Postgres, the+offset past it, and nothing on ``aisoc.alerts.fused`` for auto-triage to read.++The repository already applies the right pattern two files away --+``dlq.KafkaDLQ.record`` does ``future = await send(...)`` then ``await future``+and says why, and ``dlq_replay`` uses ``send_and_wait``. The fused-alert hot+path was the one place it was not applied.++Why the double here is shaped the way it is+-------------------------------------------+``AsyncMock()`` cannot test this. Its ``send`` returns an awaitable resolving+to a ``MagicMock``, so ``send`` and ``send_and_wait`` are indistinguishable:+both read as "awaited, no exception". Every assertion built on one would pass+against the defect. ``tests.kafka_doubles.TwoStageProducer`` models the real contract --+the enqueue and the acknowledgement are separate awaitables with separate+outcomes -- which is the only way a test can tell the two apart.+"""++from __future__ import annotations++from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest+from app.core.config import settings+from app.models.alert import AlertSeverity, FusedAlert, FusionDecision, RawAlert+from app.services.alert_sink import PersistOutcome, PersistResult+from app.workers.consumer import FusionWorker, RetryableProcessingError++from tests.kafka_doubles import TwoStageProducer+++def _alert() -> RawAlert:+ return RawAlert(+ tenant_id="00000000-0000-0000-0000-000000000001",+ source="CrowdStrike Falcon",+ title="Credential dumping via LSASS access",+ severity=AlertSeverity.CRITICAL,+ src_ip="10.20.30.40",+ hostname="WIN-DC01",+ )+++def _fused(alert: RawAlert) -> FusedAlert:+ alert.id = alert.deterministic_id()+ return FusedAlert(id=alert.id, tenant_id=alert.tenant_id, fusion_decision=FusionDecision.NEW_ALERT, alert=alert)+++def _worker(producer) -> tuple[FusionWorker, RawAlert]: # noqa: ANN001+ """A worker whose alert is always durable, so the test is about the publish.++ The three ignores match the sibling durability suite: the worker only+ ever awaits ``engine.process`` and ``sink.persist``, so a namespace and+ a mock are the whole contract these tests need. Targeted rather than a+ widened config, which is what ``check_mypy_baseline`` asks for.+ """+ alert = _alert()+ fused = _fused(alert)+ worker = FusionWorker(engine=SimpleNamespace(process=AsyncMock(return_value=fused)), sink=AsyncMock()) # type: ignore[arg-type]+ worker._sink.persist = AsyncMock( # type: ignore[method-assign, union-attr] # noqa: SLF001+ return_value=PersistResult(PersistOutcome.INSERTED, str(fused.id))+ )+ worker._producer = producer # noqa: SLF001+ return worker, alert+++async def test_a_broker_error_delivered_after_the_enqueue_is_observed(monkeypatch):+ """The acceptance case: a *delayed* delivery failure must be reported.++ The enqueue succeeds -- there is no exception to catch at that point --+ and the broker refuses the record a moment later. Code that awaits only+ the enqueue returns cleanly here and lets the offset commit, so the alert+ row exists in Postgres with nothing ever published for it.+ """+ monkeypatch.setattr(settings, "kafka_send_timeout_seconds", 2.0)+ producer = TwoStageProducer(ack_after=0.02, ack_error=RuntimeError("NotLeaderForPartitionError"))+ worker, alert = _worker(producer)++ before = worker.get_metrics()["publish_failed"]+ with pytest.raises(RetryableProcessingError):+ await worker._fuse_and_persist(alert) # noqa: SLF001++ assert producer.enqueued, "the record should still have been enqueued"+ assert worker.get_metrics()["publish_failed"] == before + 1+ await producer.drain()+++async def test_an_unacknowledged_record_is_not_reported_as_published(monkeypatch):+ """A record still in the accumulator is not a delivery.++ This is the crash window stated directly: the broker never acknowledges,+ so the only honest outcome is "not delivered". Awaiting the enqueue alone+ returns immediately and reports success for an envelope that exists+ nowhere but this process's memory.+ """+ monkeypatch.setattr(settings, "kafka_send_timeout_seconds", 0.2)+ producer = TwoStageProducer(never_ack=True)+ worker, alert = _worker(producer)++ with pytest.raises(RetryableProcessingError):+ await worker._fuse_and_persist(alert) # noqa: SLF001+ assert worker.get_metrics()["publish_failed"] >= 1+ await producer.drain()+++async def test_publishing_returns_only_after_the_acknowledgement(monkeypatch):+ """The positive control, and the ordering claim stated directly.++ A successful delivery must still be a success -- without this the fix+ could be "always raise", which passes every failure test and breaks the+ pipeline. The second assertion is the one that distinguishes the two+ implementations on the *happy* path: when ``_fuse_and_persist`` returns,+ the acknowledgement must already have arrived. An enqueue-only publish+ returns with the future still pending.+ """+ monkeypatch.setattr(settings, "kafka_send_timeout_seconds", 2.0)+ producer = TwoStageProducer(ack_after=0.01)+ worker, alert = _worker(producer)++ await worker._fuse_and_persist(alert) # noqa: SLF001++ assert len(producer.enqueued) == 1+ assert producer.futures[0].done(), "returned before the broker acknowledged the record"+ assert producer.futures[0].exception() is None+ await producer.drain()+++async def test_the_published_envelope_carries_a_stable_dedupe_key(monkeypatch):+ """Duplicate publication is designed-for, so it needs a key to collapse on.++ Re-delivery republishes by design (the offset commit and the broker ack+ cannot be made atomic), so the contract downstream needs is a key that is+ identical across every republication of one alert and different between+ alerts. Keying the Kafka record also puts every copy of an alert on one+ partition, which is what makes a downstream de-duplicator tractable.+ """+ monkeypatch.setattr(settings, "kafka_send_timeout_seconds", 2.0)+ producer = TwoStageProducer(ack_after=0.0)+ worker, alert = _worker(producer)++ await worker._fuse_and_persist(alert) # noqa: SLF001+ await worker._fuse_and_persist(alert) # noqa: SLF001 — the re-delivery++ keys = [record["key"] for record in producer.enqueued]+ assert len(keys) == 2+ assert keys[0] is not None, "a fused alert must be keyed so duplicates can be collapsed"+ assert keys[0] == keys[1], "the same alert must republish under the same key"+ assert keys[0] == str(alert.id)+ await producer.drain()diff --git a/services/fusion/tests/test_sigma_correlation_replay.py b/services/fusion/tests/test_sigma_correlation_replay.pyindex 25c5f7bcb..4351ebe27 100644--- a/services/fusion/tests/test_sigma_correlation_replay.py+++ b/services/fusion/tests/test_sigma_correlation_replay.py@@ -18,6 +18,7 @@ that works.from __future__ import annotations+import itertoolsimport jsonimport refrom pathlib import Path@@ -27,37 +28,9 @@ from uuid import uuid4import pytestfrom app.services.windowed_detection import WindowedDetectionEngine, load_sequence_rules, load_window_rules-RULESET = Path(__file__).resolve().parents[1] / "app" / "data" / "windowed_ruleset.json"---class _FakeRedis:- def __init__(self) -> None:- self.zsets: dict[str, dict[str, float]] = {}- self.strings: dict[str, str] = {}-- async def zadd(self, key: str, mapping: dict[str, float]) -> None:- self.zsets.setdefault(key, {}).update(mapping)-- async def zremrangebyscore(self, key: str, min_s: float, max_s: float) -> None:- members = self.zsets.get(key, {})- for member in [m for m, score in list(members.items()) if min_s <= score <= max_s]:- del members[member]+from tests.redis_doubles import FakeRedis- async def zcard(self, key: str) -> int:- return len(self.zsets.get(key, {}))-- async def zrangebyscore(self, key: str, min_s: float, max_s: float, withscores: bool = False) -> list[Any]:- items = sorted(((m, s) for m, s in self.zsets.get(key, {}).items() if min_s <= s <= max_s), key=lambda kv: (kv[1], kv[0]))- return items if withscores else [m for m, _ in items]-- async def expire(self, key: str, ttl: int) -> None:- return None-- async def set(self, key: str, value: str, nx: bool = False, ex: int | None = None) -> Any:- if nx and key in self.strings:- return None- self.strings[key] = value- return True+RULESET = Path(__file__).resolve().parents[1] / "app" / "data" / "windowed_ruleset.json"def _correlations() -> list[dict[str, Any]]:@@ -87,20 +60,29 @@ def _satisfying(key: str, value: Any) -> tuple[str, Any]:return key, value+_EVENT_SEQ = itertools.count()++def _event(rule: dict[str, Any], tenant: str, clause: dict[str, Any], entity: str, when: float, distinct: str = "") -> dict[str, Any]:raw = dict(_satisfying(key, value) for key, value in clause.items())raw[rule["group_by"]] = entityraw["event_time"] = whenif rule.get("distinct_by"):raw[rule["distinct_by"]] = distinct- return {"tenant_id": tenant, "ocsf_event": {"tenant_uid": tenant, "raw_data": json.dumps(raw)}}+ # A distinct ingest id per call, as above: the engine counts one+ # observation per event identity.+ return {+ "tenant_id": tenant,+ "id": f"evt-{next(_EVENT_SEQ)}",+ "ocsf_event": {"tenant_uid": tenant, "raw_data": json.dumps(raw)},+ }def _engine_for(rule: dict[str, Any]) -> WindowedDetectionEngine:counting = tuple(r for r in load_window_rules() if r.id == rule["id"])staged = tuple(r for r in load_sequence_rules() if r.id == rule["id"])assert counting or staged, f"{rule['id']} is in the committed JSON but neither loader accepted it"- return WindowedDetectionEngine(_FakeRedis(), rules=counting, sequences=staged)+ return WindowedDetectionEngine(FakeRedis(), rules=counting, sequences=staged)def test_all_four_correlation_types_are_covered() -> None:@@ -110,14 +92,33 @@ def test_all_four_correlation_types_are_covered() -> None:@pytest.mark.asyncioasync def test_event_count_fires_at_its_threshold_and_not_one_short() -> None:+ """The threshold event has to be *inside* the window, which it was not.++ This used to place the first five events a second apart and the sixth+ 996 seconds later, in a 600-second window, and it passed -- because the+ engine scored observations by arrival time and ignored ``event_time``+ entirely. Under event-time windowing those six events are correctly not+ a burst, so the data is now what the rule actually describes and the+ out-of-window case is asserted rather than relied on by accident.+ """rule = BY_TYPE["event_count"]- engine = _engine_for(rule)tenant = str(uuid4())+ entity = "arn:aws:iam::1:user/a"++ engine = _engine_for(rule)for index in range(rule["threshold"] - 1):- assert not await engine.evaluate(_event(rule, tenant, rule["match_when"], "arn:aws:iam::1:user/a", 1000.0 + index))- hits = await engine.evaluate(_event(rule, tenant, rule["match_when"], "arn:aws:iam::1:user/a", 2000.0))+ assert not await engine.evaluate(_event(rule, tenant, rule["match_when"], entity, 1000.0 + index))+ hits = await engine.evaluate(_event(rule, tenant, rule["match_when"], entity, 1000.0 + rule["threshold"]))assert [h.rule_id for h in hits] == [rule["id"]]+ spread = _engine_for(rule)+ for index in range(rule["threshold"] - 1):+ assert not await spread.evaluate(_event(rule, tenant, rule["match_when"], entity, 1000.0 + index))+ outside = 1000.0 + rule["window_seconds"] + 1+ assert not await spread.evaluate(_event(rule, tenant, rule["match_when"], entity, outside)), (+ "an event past the window must not complete a burst it was never part of"+ )+@pytest.mark.asyncioasync def test_value_count_needs_distinct_values() -> None:diff --git a/services/fusion/tests/test_windowed_detection.py b/services/fusion/tests/test_windowed_detection.pyindex c1c2db263..47e303281 100644--- a/services/fusion/tests/test_windowed_detection.py+++ b/services/fusion/tests/test_windowed_detection.py@@ -3,39 +3,16 @@ sliding window, and only once per window."""from __future__ import annotations+import itertoolsimport jsonfrom uuid import uuid4import pytestfrom app.services.windowed_detection import WindowedDetectionEngine, WindowRule+from tests.redis_doubles import FakeRedis-class _FakeRedis:- """Minimal in-memory Redis for the sorted-set window + fired marker."""-- def __init__(self) -> None:- self.zsets: dict[str, dict[str, float]] = {}- self.strings: dict[str, str] = {}-- async def zadd(self, key: str, mapping: dict[str, float]) -> None:- self.zsets.setdefault(key, {}).update(mapping)-- async def zremrangebyscore(self, key: str, min_s: float, max_s: float) -> None:- z = self.zsets.get(key, {})- for m in [m for m, s in list(z.items()) if min_s <= s <= max_s]:- del z[m]-- async def expire(self, key: str, ttl: int) -> None:- return None-- async def zcard(self, key: str) -> int:- return len(self.zsets.get(key, {}))-- async def set(self, key: str, value: str, nx: bool = False, ex: int | None = None):- if nx and key in self.strings:- return None- self.strings[key] = value- return True+_EVENT_SEQ = itertools.count()def _auth_fail_event(tenant: str, user: str = "alice", src: str = "1.2.3.4") -> dict:@@ -45,12 +22,18 @@ def _auth_fail_event(tenant: str, user: str = "alice", src: str = "1.2.3.4") ->"tenant_uid": tenant,"raw_data": json.dumps({"event_type": "authentication", "outcome": "failure", "user": user, "src_ip": src}),},+ # Each call is a distinct event and carries the id ingest would have+ # stamped on it. The engine counts one observation per event+ # identity, which is what makes a re-delivery idempotent, so a+ # builder returning byte-identical events would be simulating one+ # event arriving repeatedly -- a different scenario entirely.+ "id": f"evt-{next(_EVENT_SEQ)}",}@pytest.mark.asyncioasync def test_bruteforce_fires_at_threshold_once():- eng = WindowedDetectionEngine(_FakeRedis())+ eng = WindowedDetectionEngine(FakeRedis())tenant = str(uuid4())# First 4 failures: below the threshold of 5 -> no brute-force hit.@@ -69,7 +52,7 @@ async def test_bruteforce_fires_at_threshold_once():@pytest.mark.asyncioasync def test_group_by_isolates_entities():- eng = WindowedDetectionEngine(_FakeRedis())+ eng = WindowedDetectionEngine(FakeRedis())tenant = str(uuid4())# 4 failures for alice + 4 for bob: neither user reaches the per-user threshold.for _ in range(4):@@ -81,7 +64,7 @@ async def test_group_by_isolates_entities():@pytest.mark.asyncioasync def test_non_matching_event_never_fires():- eng = WindowedDetectionEngine(_FakeRedis())+ eng = WindowedDetectionEngine(FakeRedis())tenant = str(uuid4())benign = {"tenant_id": tenant, "ocsf_event": {"raw_data": json.dumps({"event_type": "process", "user": "alice"})}}for _ in range(20):@@ -91,7 +74,7 @@ async def test_non_matching_event_never_fires():@pytest.mark.asyncioasync def test_build_alert_from_hit():- eng = WindowedDetectionEngine(_FakeRedis())+ eng = WindowedDetectionEngine(FakeRedis())tenant = str(uuid4())hit = Nonefor _ in range(5):@@ -143,14 +126,14 @@ DISTINCT_RULE = WindowRule(async def test_repeating_one_value_never_crosses_a_distinct_threshold():"""The regression this exists for: a script reading the same secret in aloop is not enumeration, and must not be reported as it."""- engine = WindowedDetectionEngine(_FakeRedis(), rules=(DISTINCT_RULE,))+ engine = WindowedDetectionEngine(FakeRedis(), rules=(DISTINCT_RULE,))for _ in range(20):assert await engine.evaluate(_secret_event("alice", "db-password")) == []@pytest.mark.asyncioasync def test_distinct_values_cross_the_threshold():- engine = WindowedDetectionEngine(_FakeRedis(), rules=(DISTINCT_RULE,))+ engine = WindowedDetectionEngine(FakeRedis(), rules=(DISTINCT_RULE,))assert await engine.evaluate(_secret_event("alice", "s1")) == []assert await engine.evaluate(_secret_event("alice", "s2")) == []hits = await engine.evaluate(_secret_event("alice", "s3"))@@ -159,7 +142,7 @@ async def test_distinct_values_cross_the_threshold():@pytest.mark.asyncioasync def test_distinct_counts_are_per_entity():- engine = WindowedDetectionEngine(_FakeRedis(), rules=(DISTINCT_RULE,))+ engine = WindowedDetectionEngine(FakeRedis(), rules=(DISTINCT_RULE,))for secret in ("s1", "s2"):await engine.evaluate(_secret_event("alice", secret))# Bob's two are his own; neither principal has reached three.@@ -171,7 +154,7 @@ async def test_distinct_counts_are_per_entity():async def test_an_event_missing_the_distinct_field_is_skipped_not_counted():"""Falling back to counting events would be a different, louder detectionwearing this one's id."""- engine = WindowedDetectionEngine(_FakeRedis(), rules=(DISTINCT_RULE,))+ engine = WindowedDetectionEngine(FakeRedis(), rules=(DISTINCT_RULE,))bare = {"tenant_id": _TENANT, "ocsf_event": {"raw_event": {"event_type": "secret_access", "user": "alice"}}}for _ in range(10):assert await engine.evaluate(bare) == []diff --git a/services/fusion/tests/test_windowed_replay_safety.py b/services/fusion/tests/test_windowed_replay_safety.pynew file mode 100644index 000000000..3e9138e5b--- /dev/null+++ b/services/fusion/tests/test_windowed_replay_safety.py@@ -0,0 +1,356 @@+"""Windowed detections must survive the re-delivery the consumer relies on.++Two defects, and they pull in opposite directions, which is why they have to+be fixed together.++**Observation inflation.** ``_observe_and_check`` mints a fresh+``uuid.uuid4().hex`` member per call for a threshold rule with no+``distinct_by``. Kafka delivery here is at-least-once and the consumer+deliberately re-delivers on ``RetryableProcessingError``, so one event+counted N times is N members in the sorted set: N re-deliveries of a single+event cross a threshold of N. A brute-force alert fires for one failed login+that the database happened to be slow about.++**Threshold suppression.** The fire-once marker is written *inside*+``_observe_and_check`` — before ``evaluate`` has built the ``DetectionHit``,+and long before the consumer persists anything. ``_fuse_and_persist`` raises+``RetryableProcessingError`` when the row is not durable, so Kafka+re-delivers; on re-delivery ``SET NX`` returns falsy and no hit is produced+until the window rolls. **The retry path that exists specifically to recover+the alert is the thing guaranteed to suppress it.**++The dual-use of one sorted set at the heart of ``_observe_and_check`` is+deliberate and must keep working: a random member counts *events*, an+observed value counts *distinct values*, because ZADD on an existing member+updates its score instead of adding a row. The fix has to preserve both+meanings while making the event counter idempotent, which means the member+for an event-count rule becomes the event's stable identity rather than a+random one.+"""++from __future__ import annotations++import json+import time+from uuid import uuid4++import pytest+from app.services.windowed_detection import WindowedDetectionEngine, WindowRule++from tests.redis_doubles import FakeRedis+++def _auth_fail(tenant: str, user: str = "alice", when: str | None = None) -> dict:+ payload = {"event_type": "authentication", "outcome": "failure", "user": user}+ if when is not None:+ payload["timestamp"] = when+ return {"tenant_id": tenant, "ocsf_event": {"tenant_uid": tenant, "raw_data": json.dumps(payload)}}+++def _engine(redis, rules=None): # noqa: ANN001, ANN201+ return WindowedDetectionEngine(redis, rules=rules if rules is not None else _BRUTE_FORCE)+++_BRUTE_FORCE = (+ WindowRule(+ id="wd-bruteforce-auth",+ name="Brute-force: repeated authentication failures",+ severity="high",+ category="identity",+ mitre=["T1110"],+ match_when={"event_type": "authentication", "outcome": "failure"},+ group_by="user",+ threshold=5,+ window_seconds=600,+ ),+)+++async def test_one_event_delivered_five_times_does_not_cross_a_threshold_of_five():+ """The inflation case, stated as bluntly as it happens in production.++ At-least-once delivery plus a random member per call means a single+ failed login that the database was slow about becomes a brute-force+ alert naming a user who did nothing.+ """+ redis = FakeRedis()+ engine = _engine(redis)+ event = _auth_fail(str(uuid4()))++ hits = []+ for _ in range(5):+ hits += await engine.evaluate(event, event_id="ingest-evt-1")++ assert hits == [], "five deliveries of one event are one observation"+++async def test_five_distinct_events_still_cross_the_threshold():+ """The positive control. Deduplicating must not break the detection."""+ redis = FakeRedis()+ engine = _engine(redis)+ tenant = str(uuid4())++ hits = []+ for n in range(5):+ hits += await engine.evaluate(_auth_fail(tenant), event_id=f"ingest-evt-{n}")++ assert [h.rule_id for h in hits] == ["wd-bruteforce-auth"]+++async def test_a_distinct_by_rule_still_counts_distinct_values():+ """The dual use of one sorted set is deliberate and must survive.++ "Fifty requests from one source" and "fifty *different* secrets read by+ one principal" are different detections. A fix that made every member+ the event id would turn the second into the first.+ """+ rule = WindowRule(+ id="wd-secret-enumeration",+ name="Secret enumeration",+ severity="high",+ category="identity",+ mitre=["T1552"],+ match_when={"event_type": "secret_read"},+ group_by="user",+ threshold=3,+ window_seconds=600,+ distinct_by="secret_name",+ )+ redis = FakeRedis()+ engine = _engine(redis, rules=(rule,))+ tenant = str(uuid4())++ def event(secret: str) -> dict:+ return {+ "tenant_id": tenant,+ "ocsf_event": {+ "tenant_uid": tenant,+ "raw_data": json.dumps({"event_type": "secret_read", "user": "svc", "secret_name": secret}),+ },+ }++ # The same secret read ten times by ten *different* events is one value.+ hits = []+ for n in range(10):+ hits += await engine.evaluate(event("db-password"), event_id=f"evt-{n}")+ assert hits == [], "re-reading one secret is not enumeration"++ hits += await engine.evaluate(event("api-key"), event_id="evt-a")+ hits += await engine.evaluate(event("signing-key"), event_id="evt-b")+ assert [h.rule_id for h in hits] == ["wd-secret-enumeration"]+++async def test_a_hit_that_was_never_persisted_fires_again_on_re_delivery():+ """The suppression case: the retry must be able to recover the alert.++ The cooldown was written before the hit even existed, so a persistence+ failure -- the exact condition the retry exists for -- guaranteed the+ re-delivery produced nothing.+ """+ redis = FakeRedis()+ engine = _engine(redis)+ tenant = str(uuid4())+ for n in range(4):+ await engine.evaluate(_auth_fail(tenant), event_id=f"evt-{n}")++ first = await engine.evaluate(_auth_fail(tenant), event_id="evt-threshold")+ assert len(first) == 1++ # Persistence failed. The consumer releases the claim and Kafka+ # re-delivers the very same record.+ await engine.release(first[0])+ again = await engine.evaluate(_auth_fail(tenant), event_id="evt-threshold")++ assert len(again) == 1, "a hit that reached no database must fire again"+++async def test_a_persisted_hit_does_not_fire_twice():+ """The other half: once it is durable, re-delivery must stay quiet."""+ redis = FakeRedis()+ engine = _engine(redis)+ tenant = str(uuid4())+ for n in range(4):+ await engine.evaluate(_auth_fail(tenant), event_id=f"evt-{n}")++ first = await engine.evaluate(_auth_fail(tenant), event_id="evt-threshold")+ assert len(first) == 1+ await engine.confirm(first[0])++ again = await engine.evaluate(_auth_fail(tenant), event_id="evt-threshold")+ assert again == [], "a durable hit must not produce a second alert"+++async def test_two_workers_on_overlapping_deliveries_produce_one_hit():+ """Concurrency: the claim is what stops a duplicate alert.++ Moving the cooldown write to *after* persistence would create exactly+ this race instead of fixing it -- two workers both crossing the+ threshold before either has written anything.+ """+ redis = FakeRedis()+ worker_a = _engine(redis)+ worker_b = _engine(redis)+ tenant = str(uuid4())+ for n in range(4):+ await worker_a.evaluate(_auth_fail(tenant), event_id=f"evt-{n}")++ hits_a = await worker_a.evaluate(_auth_fail(tenant), event_id="evt-5")+ hits_b = await worker_b.evaluate(_auth_fail(tenant), event_id="evt-6")++ assert len(hits_a) + len(hits_b) == 1, "exactly one worker may own the fire"+++async def test_a_crashed_worker_does_not_suppress_the_alert_forever():+ """Crash recovery: a claim nobody confirmed must expire, not persist.++ A worker that dies between the hit and the database never releases its+ claim. If the claim were the full window the alert would be suppressed+ for ten minutes by a process that no longer exists.+ """+ redis = FakeRedis()+ engine = _engine(redis)+ tenant = str(uuid4())+ for n in range(4):+ await engine.evaluate(_auth_fail(tenant), event_id=f"evt-{n}")++ claimed = await engine.evaluate(_auth_fail(tenant), event_id="evt-5")+ assert len(claimed) == 1+ # The worker is gone. Nothing released the claim; the lease simply ages+ # out, which the double models by dropping the key the way an EX would.+ redis.strings.clear()++ recovered = await engine.evaluate(_auth_fail(tenant), event_id="evt-6")+ assert len(recovered) == 1, "an unconfirmed claim must not outlive the worker that took it"+++async def test_out_of_order_arrival_reaches_the_same_verdict_as_in_order():+ """Arrival order is not evidence of event order.++ Almost every connector here polls, so a batch arrives in the vendor's+ order. Scoring the window by wall clock makes the detection a function+ of the poll cadence; two deliveries of one burst must agree.+ """+ tenant = str(uuid4())+ stamps = [f"2026-10-27T12:00:0{n}Z" for n in range(5)]++ in_order = FakeRedis()+ engine_a = _engine(in_order)+ forward = []+ for n, stamp in enumerate(stamps):+ forward += await engine_a.evaluate(_auth_fail(tenant, when=stamp), event_id=f"evt-{n}")++ reversed_order = FakeRedis()+ engine_b = _engine(reversed_order)+ backward = []+ for n, stamp in reversed(list(enumerate(stamps))):+ backward += await engine_b.evaluate(_auth_fail(tenant, when=stamp), event_id=f"evt-{n}")++ assert len(forward) == 1+ assert len(backward) == 1, "the same five events in the other order must reach the same verdict"+++async def test_a_historical_backfill_does_not_merge_with_live_traffic():+ """Backfill must be counted in its own window, not piled onto today's.++ Scoring by arrival time means replaying a week of history looks like one+ enormous burst happening right now.+ """+ redis = FakeRedis()+ engine = _engine(redis)+ tenant = str(uuid4())++ # Four failures last week, and one now. Nothing should fire: neither+ # window holds five.+ hits = []+ for n in range(4):+ hits += await engine.evaluate(_auth_fail(tenant, when=f"2026-10-20T03:00:0{n}Z"), event_id=f"old-{n}")+ hits += await engine.evaluate(_auth_fail(tenant, when="2026-10-27T12:00:00Z"), event_id="new-0")++ assert hits == [], "four old failures and one new one are not a burst"+++async def test_a_redis_failure_is_reported_rather_than_swallowed():+ """A blip meant the rule silently did not fire.++ The per-rule handler logged at debug, so a Redis outage and a quiet+ estate were indistinguishable. Detection stays fail-soft -- Redis must+ not wedge the alert pipeline -- but the degradation has to be countable.+ """+ redis = FakeRedis()+ engine = _engine(redis)+ redis.failing = True++ hits = await engine.evaluate(_auth_fail(str(uuid4())), event_id="evt-1")++ assert hits == []+ assert engine.rule_errors >= 1, "a skipped rule must be visible, not inferred from an absence of alerts"+++async def test_an_event_with_no_identity_still_counts_exactly_once():+ """No ingest id and no Kafka coordinates: the fallback must still be stable.++ Falling back to a random member here would reintroduce the whole defect+ for any producer that does not set an id.+ """+ redis = FakeRedis()+ engine = _engine(redis)+ tenant = str(uuid4())+ event = _auth_fail(tenant, when="2026-10-27T12:00:00Z")++ for _ in range(5):+ hits = await engine.evaluate(event)++ assert hits == [], "an identity derived from the event content must be stable across deliveries"+++async def test_the_window_is_measured_in_event_time_not_arrival_time():+ """Five failures spread over an hour are not a ten-minute burst."""+ redis = FakeRedis()+ engine = _engine(redis)+ tenant = str(uuid4())++ hits = []+ for n in range(5):+ # One every fifteen minutes, all arriving now.+ hits += await engine.evaluate(_auth_fail(tenant, when=f"2026-10-27T{12 + n:02d}:00:00Z"), event_id=f"evt-{n}")++ assert hits == [], "arrival time would make this a burst; event time does not"+++async def test_a_confirmed_hit_survives_a_second_evaluation_pass_over_the_window():+ """Replaying the whole window must not produce a second alert.++ The cooldown is keyed on the event-time bucket, so a replay lands in the+ same bucket and finds the confirmed marker rather than a cooldown that+ happens to have aged out in wall-clock terms.+ """+ redis = FakeRedis()+ engine = _engine(redis)+ tenant = str(uuid4())+ stamps = [f"2026-10-27T12:00:0{n}Z" for n in range(5)]++ hits = []+ for n, stamp in enumerate(stamps):+ hits += await engine.evaluate(_auth_fail(tenant, when=stamp), event_id=f"evt-{n}")+ assert len(hits) == 1+ await engine.confirm(hits[0])++ replay = []+ for n, stamp in enumerate(stamps):+ replay += await engine.evaluate(_auth_fail(tenant, when=stamp), event_id=f"evt-{n}")++ assert replay == [], "replaying the window must be idempotent"+ assert time.time() > 0 # the verdict must not depend on the wall clockdiff --git a/services/fusion/tests/test_windowed_sequences.py b/services/fusion/tests/test_windowed_sequences.pyindex c3f7247b5..d54c43508 100644--- a/services/fusion/tests/test_windowed_sequences.py+++ b/services/fusion/tests/test_windowed_sequences.py@@ -29,39 +29,7 @@ from uuid import uuid4import pytestfrom app.services.windowed_detection import SequenceRule, WindowedDetectionEngine--class _FakeRedis:- """The sorted-set, hash and marker calls the engine makes, faithfully."""-- def __init__(self) -> None:- self.zsets: dict[str, dict[str, float]] = {}-- self.strings: dict[str, str] = {}-- async def zadd(self, key: str, mapping: dict[str, float]) -> None:- self.zsets.setdefault(key, {}).update(mapping)-- async def zremrangebyscore(self, key: str, min_s: float, max_s: float) -> None:- members = self.zsets.get(key, {})- for member in [m for m, score in list(members.items()) if min_s <= score <= max_s]:- del members[member]-- async def zcard(self, key: str) -> int:- return len(self.zsets.get(key, {}))-- async def zrangebyscore(self, key: str, min_s: float, max_s: float, withscores: bool = False) -> list[Any]:- items = sorted(((m, s) for m, s in self.zsets.get(key, {}).items() if min_s <= s <= max_s), key=lambda kv: (kv[1], kv[0]))- return items if withscores else [m for m, _ in items]-- async def expire(self, key: str, ttl: int) -> None:- return None-- async def set(self, key: str, value: str, nx: bool = False, ex: int | None = None) -> Any:- if nx and key in self.strings:- return None- self.strings[key] = value- return True-+from tests.redis_doubles import FakeRedisSPRAY_THEN_SUCCESS = SequenceRule(id="wd-seq-test-spray-then-success",@@ -89,7 +57,7 @@ def _event(tenant: str, outcome: str, when: float, user: str = "alice") -> dict[def _engine() -> WindowedDetectionEngine:- return WindowedDetectionEngine(_FakeRedis(), rules=(), sequences=(SPRAY_THEN_SUCCESS,))+ return WindowedDetectionEngine(FakeRedis(), rules=(), sequences=(SPRAY_THEN_SUCCESS,))@pytest.mark.asyncio@@ -163,7 +131,7 @@ async def test_one_event_cannot_advance_two_stages() -> None:group_by="user",window_seconds=600,)- engine = WindowedDetectionEngine(_FakeRedis(), rules=(), sequences=(overlapping,))+ engine = WindowedDetectionEngine(FakeRedis(), rules=(), sequences=(overlapping,))tenant = str(uuid4())assert not await engine.evaluate(_event(tenant, "failure", 1000.0))hits = await engine.evaluate(_event(tenant, "failure", 1001.0))@@ -195,7 +163,7 @@ async def test_a_three_stage_sequence_needs_all_three_in_order() -> None:group_by="user",window_seconds=600,)- engine = WindowedDetectionEngine(_FakeRedis(), rules=(), sequences=(three,))+ engine = WindowedDetectionEngine(FakeRedis(), rules=(), sequences=(three,))tenant = str(uuid4())assert not await engine.evaluate(_event(tenant, "failure", 1000.0))assert not await engine.evaluate(_event(tenant, "mfa_reset", 1010.0))diff --git a/services/fusion/tests/test_windowed_translation_replay.py b/services/fusion/tests/test_windowed_translation_replay.pyindex 82521cc26..ba66f22d0 100644--- a/services/fusion/tests/test_windowed_translation_replay.py+++ b/services/fusion/tests/test_windowed_translation_replay.py@@ -28,6 +28,7 @@ to cross its threshold. It is not a claim that the rule detects an attack.from __future__ import annotations+import itertoolsimport jsonfrom pathlib import Pathfrom typing import Any@@ -36,40 +37,9 @@ from uuid import uuid4import pytestfrom app.services.windowed_detection import WindowedDetectionEngine, WindowRule, load_window_rules-RULESET = Path(__file__).resolve().parents[1] / "app" / "data" / "windowed_ruleset.json"---class _FakeRedis:- """In-memory stand-in for the sorted-set window and the fired marker.-- Deliberately a faithful implementation of the five calls the engine makes- rather than a mock that answers whatever is asked: a double that returns- a crossing count for any key would make every assertion below vacuous.- """-- def __init__(self) -> None:- self.zsets: dict[str, dict[str, float]] = {}- self.strings: dict[str, str] = {}+from tests.redis_doubles import FakeRedis- async def zadd(self, key: str, mapping: dict[str, float]) -> None:- self.zsets.setdefault(key, {}).update(mapping)-- async def zremrangebyscore(self, key: str, min_s: float, max_s: float) -> None:- members = self.zsets.get(key, {})- for member in [m for m, score in list(members.items()) if min_s <= score <= max_s]:- del members[member]-- async def expire(self, key: str, ttl: int) -> None:- return None-- async def zcard(self, key: str) -> int:- return len(self.zsets.get(key, {}))-- async def set(self, key: str, value: str, nx: bool = False, ex: int | None = None) -> Any:- if nx and key in self.strings:- return None- self.strings[key] = value- return True+RULESET = Path(__file__).resolve().parents[1] / "app" / "data" / "windowed_ruleset.json"def _translated() -> list[dict[str, Any]]:@@ -112,6 +82,10 @@ def _satisfying_value(key: str, value: Any) -> tuple[str, Any] | None:return key, value+#: Distinct ingest ids for distinct events; see `_event_for`.+_EVENT_SEQ = itertools.count()++def _event_for(rule: dict[str, Any], tenant: str, entity: str, distinct: str) -> dict[str, Any]:"""A flat connector-shaped event that this rule's selector accepts."""raw: dict[str, Any] = {}@@ -123,14 +97,23 @@ def _event_for(rule: dict[str, Any], tenant: str, entity: str, distinct: str) ->raw[rule["group_by"]] = entityif rule.get("distinct_by"):raw[rule["distinct_by"]] = distinct- return {"tenant_id": tenant, "ocsf_event": {"tenant_uid": tenant, "raw_data": json.dumps(raw)}}---def _engine(rule: dict[str, Any]) -> tuple[WindowedDetectionEngine, _FakeRedis]:+ # Every call is a distinct event, so each gets the id ingest would have+ # stamped on it. The engine counts one observation per event identity --+ # that is what makes a re-delivery idempotent -- so a builder that+ # returned byte-identical events would be simulating one event arriving+ # repeatedly, which is a different scenario and a different verdict.+ return {+ "tenant_id": tenant,+ "id": f"evt-{next(_EVENT_SEQ)}",+ "ocsf_event": {"tenant_uid": tenant, "raw_data": json.dumps(raw)},+ }+++def _engine(rule: dict[str, Any]) -> tuple[WindowedDetectionEngine, FakeRedis]:"""An engine holding exactly one rule, so a hit can only be that rule's."""loaded = {r.id: r for r in load_window_rules()}assert rule["id"] in loaded, f"{rule['id']} is in the committed JSON but the engine did not load it"- redis = _FakeRedis()+ redis = FakeRedis()return WindowedDetectionEngine(redis, rules=(loaded[rule["id"]],)), redis@@ -240,20 +223,24 @@ async def test_a_translated_rule_reads_a_tenant_allowlist_boolean() -> None:return {}loaded = {r.id: r for r in load_window_rules()}- engine = WindowedDetectionEngine(_FakeRedis(), rules=(loaded[rule["id"]],))+ engine = WindowedDetectionEngine(FakeRedis(), rules=(loaded[rule["id"]],))tenant = str(uuid4())def event() -> dict[str, Any]:raw = {k: v for k, v in rule["match_when"].items() if k != clause}raw[rule["group_by"]] = "entity-a"- return {"tenant_id": tenant, "ocsf_event": {"tenant_uid": tenant, "raw_data": json.dumps(raw)}}+ return {+ "tenant_id": tenant,+ "id": f"evt-{next(_EVENT_SEQ)}",+ "ocsf_event": {"tenant_uid": tenant, "raw_data": json.dumps(raw)},+ }# Without the overlay the allowlist clause is unresolvable, so the rule# must stay silent rather than treat "unknown" as "not allowlisted".for _ in range(rule["threshold"] + 2):assert not await engine.evaluate(event())- engine_with_overlay = WindowedDetectionEngine(_FakeRedis(), rules=(loaded[rule["id"]],))+ engine_with_overlay = WindowedDetectionEngine(FakeRedis(), rules=(loaded[rule["id"]],))hits: list[Any] = []for _ in range(rule["threshold"]):hits = await engine_with_overlay.evaluate(event(), _Overlay())@@ -279,12 +266,17 @@ async def test_enrichment_runs_before_the_window_counts() -> None:threshold=2,window_seconds=60,)- engine = WindowedDetectionEngine(_FakeRedis(), rules=(rule,))+ engine = WindowedDetectionEngine(FakeRedis(), rules=(rule,))tenant = str(uuid4())- same = {"tenant_id": tenant, "ocsf_event": {"tenant_uid": tenant, "raw_data": json.dumps({"actor": "u1", "target": "u1"})}}- different = {"tenant_id": tenant, "ocsf_event": {"tenant_uid": tenant, "raw_data": json.dumps({"actor": "u1", "target": "u2"})}}- assert not await engine.evaluate(different)- assert not await engine.evaluate(different)- assert not await engine.evaluate(same)- assert [h.rule_id for h in await engine.evaluate(same)] == ["wd-test-derived"]+ def build(actor: str, target: str) -> dict[str, Any]:+ return {+ "tenant_id": tenant,+ "id": f"evt-{next(_EVENT_SEQ)}",+ "ocsf_event": {"tenant_uid": tenant, "raw_data": json.dumps({"actor": actor, "target": target})},+ }++ assert not await engine.evaluate(build("u1", "u2"))+ assert not await engine.evaluate(build("u1", "u2"))+ assert not await engine.evaluate(build("u1", "u1"))+ assert [h.rule_id for h in await engine.evaluate(build("u1", "u1"))] == ["wd-test-derived"]