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): make alert delivery durable and enforce tenant dedup uniqueness (#1491)
Beenu Arora9f815c796f5f
diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.ymlindex ac381005d..dc9bcbbee 100644--- a/.github/workflows/integration.yml+++ b/.github/workflows/integration.yml@@ -537,15 +537,16 @@ jobs:docker compose up -d fusionpython3 scripts/integration/spine_test.py --await-alert --title "${TITLE}" --timeout 180- # ── Chaos: Postgres outage — graceful degradation + self-heal ────────- # Kill Postgres mid-stream. The fusion AlertSink must degrade to- # "fused alerts still flow over Kafka/WS, persistence is dropped for the- # outage window" WITHOUT crashing the consumer, and must self-heal once- # Postgres returns. Distinct event titles side-step fusion's in-memory- # dedup so the post-restart event is a fresh persist, not a duplicate.- # (The during-outage event's row is intentionally not recovered — a hard- # DB outage is a degradation window, not corruption; the healed event- # proves persistence resumes.)+ # ── Chaos: Postgres outage — hold, recover, no silent loss ───────────+ # Kill Postgres mid-stream. Fusion must stay alive, keep the Kafka+ # offset uncommitted, and retry the alert with bounded backoff instead+ # of committing past a failed insert. When Postgres returns, the+ # during-outage event must become an alert row — the dedup fingerprint+ # was registered in Redis before the failed insert, so this also+ # exercises duplicate reconciliation (fusion says DUPLICATE, the sink+ # verifies the surviving row, finds none, and repairs it).+ # The post-recovery event then proves the sink's stale pool was replaced+ # without restarting fusion.- name: Chaos — Postgres outage (graceful degradation + self-heal)run: |set -euo pipefail@@ -576,8 +577,13 @@ jobs:sleep 1done- # A fresh event after restart must persist — proving the sink and the- # API both self-heal their Postgres pools with no restart.+ # The event produced while the DB was down must be recovered, not+ # abandoned. This is the assertion the old version deliberately+ # omitted; accepting the loss is what let the retry defect ship.+ python3 scripts/integration/spine_test.py --await-alert --title "${OUT}" --timeout 180++ # A fresh event after restart must also persist — proving the sink+ # and the API both self-heal their Postgres pools with no restart.python3 scripts/integration/spine_test.py --post-event --title "${HEAL}"python3 scripts/integration/spine_test.py --await-alert --title "${HEAL}" --timeout 180diff --git a/scripts/chaos/fusion_restart.py b/scripts/chaos/fusion_restart.pyindex 48f0355fc..777c2edde 100644--- a/scripts/chaos/fusion_restart.py+++ b/scripts/chaos/fusion_restart.py@@ -182,6 +182,57 @@ def count_marked(target: Target, run_id: str) -> int:return int(raw or 0)+def _is_compose(target_name: str) -> bool:+ """Whether a target name is the compose adapter's.++ The CLI spells its choice ``compose`` and ``load_harness.compose_target``+ names the adapter ``docker-compose``. Reading only the CLI spelling made+ the self-test pass while ``main`` refused a single-replica stack: the guard+ is handed ``Target.name``, which is the adapter's spelling.+ """+ return target_name in ("compose", "docker-compose")+++def minimum_replicas(target_name: str) -> int:+ """How many fusion replicas the harness needs before it can prove anything.++ Compose in CI runs one replica. Deleting it does not reduce capacity for a+ survivor to absorb — the container is restarted and Kafka re-delivers from+ the last committed offset — so a single-replica restart is a valid test of+ the durability property. Kubernetes keeps the two-replica requirement: the+ interesting claim there is takeover, not restart latency.+ """+ return 1 if _is_compose(target_name) else 2+++def wait_for_replacement(+ target: Target,+ namespace: str,+ *,+ victim: str,+ replicas_before: list[str],+ timeout_seconds: float,+) -> list[str]:+ """Poll until the killed replica is running again (or the timeout expires).++ Compose restarts the same container name; Kubernetes creates a new pod.+ Both count as replacement. Returning the last observation lets the caller+ report what it actually saw rather than assuming recovery from ``docker+ kill`` returning 0.+ """+ deadline = time.time() + max(1.0, timeout_seconds)+ after = fusion_victims(target, namespace)+ while time.time() < deadline:+ after = fusion_victims(target, namespace)+ if _is_compose(target.name):+ if after and len(after) >= len(replicas_before):+ return after+ elif victim not in after and len(after) >= len(replicas_before):+ return after+ time.sleep(2)+ return after++def main(argv: list[str] | None = None) -> int:parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)parser.add_argument("--target", choices=("compose", "kubernetes"), default="kubernetes")@@ -199,6 +250,7 @@ def main(argv: list[str] | None = None) -> int:parser.add_argument("--kafka-ref", default="statefulset/aisoc-kafka")parser.add_argument("--producer-bin", default=os.environ.get("AISOC_PRODUCER_BIN", ""))parser.add_argument("--drain-timeout", type=int, default=420)+ parser.add_argument("--restart-timeout", type=int, default=180)parser.add_argument("--out", type=Path)args = parser.parse_args(argv)@@ -221,11 +273,16 @@ def main(argv: list[str] | None = None) -> int:)before = fusion_victims(target, args.namespace)- if len(before) < 2:+ required = minimum_replicas(target.name)+ if len(before) < required:+ detail = (+ "compose restarts the same container, so the offset/loss property is still testable"+ if _is_compose(target.name)+ else "the surviving replica must take over while the killed pod is absent"+ )print(f"fusion_restart: found {len(before)} running fusion replica(s): {before or 'none'}. "- "This test needs at least two, because with one there is nothing for the surviving "- "consumer to take over and the result would only measure restart time.",+ f"This target needs at least {required}: {detail}.",file=sys.stderr,)return 2@@ -272,6 +329,18 @@ def main(argv: list[str] | None = None) -> int:time.sleep(1)if proc.poll() is not None:break+ if proc.poll() is not None:+ # The producer finished before the kill landed. Killing a replica now+ # would measure restart time against an already-drained stream: the+ # verdict would pass without ever testing an in-flight event. That is a+ # vacuous PASS, so refuse to grade it.+ print(+ "chaos: the producer finished before the kill landed, so no event was in flight. "+ "That tests nothing; raise --events, lower --target-eps, or lower --kill-at.",+ file=sys.stderr,+ )+ return 2+in_flight = count_marked(target, run_id)victim = before[0]killed_ok, detail = kill_fusion(target, args.namespace, victim)@@ -320,8 +389,17 @@ def main(argv: list[str] | None = None) -> int:seq_counts[row.seq] = seq_counts.get(row.seq, 0) + 1verdict = grade(accepted, seq_counts)- after = fusion_victims(target, args.namespace)- replaced = args.target == "compose" or (victim not in after and len(after) >= len(before))+ after = wait_for_replacement(+ target,+ args.namespace,+ victim=victim,+ replicas_before=before,+ timeout_seconds=args.restart_timeout,+ )+ if _is_compose(args.target):+ replaced = bool(after) and len(after) >= len(before)+ else:+ replaced = victim not in after and len(after) >= len(before)report = {"schema": "aisoc.chaos_fusion_restart/v1",@@ -363,6 +441,9 @@ def main(argv: list[str] | None = None) -> int:def _self_test() -> int:"""Prove the verdict fails in both directions it is supposed to catch."""+ # The adapter's name, not the CLI's spelling: `main` reads `Target.name`,+ # and those two disagreed once already.+ compose_name = compose_target(Path("."), ["docker-compose.yml"], "").namechecks = [("a clean run passes",@@ -384,6 +465,18 @@ def _self_test() -> int:"a run where nothing was accepted is not a pass",not grade(0, {}).ok,),+ (+ "a single-replica compose stack is runnable (CI boots one fusion container)",+ minimum_replicas(compose_name) == 1,+ ),+ (+ "a single-replica kubernetes stack is still refused",+ minimum_replicas("kubernetes") == 2,+ ),+ (+ "the compose branch is chosen for the adapter's target name, not the CLI's spelling",+ _is_compose(compose_name) and not _is_compose("kubernetes"),+ ),]ok = Truefor description, passed in checks:diff --git a/services/api/migrations/120_alerts_tenant_dedup_unique.sql b/services/api/migrations/120_alerts_tenant_dedup_unique.sqlnew file mode 100644index 000000000..53e4dc2c3--- /dev/null+++ b/services/api/migrations/120_alerts_tenant_dedup_unique.sql@@ -0,0 +1,154 @@+-- 120_alerts_tenant_dedup_unique.sql+--+-- Make the database enforce what the Fusion alert sink already intends:+-- one visible alert per (tenant_id, dedup_hash).+--+-- Why this exists+-- ───────────────+-- ``alert_sink._INSERT_SQL`` deduplicates with+--+-- WHERE NOT EXISTS (+-- SELECT 1 FROM alerts WHERE tenant_id = $2 AND dedup_hash = $11+-- )+--+-- That check and the INSERT are two statements. Under READ COMMITTED two+-- workers can both run the check before either inserts, both see no row, and+-- both insert. They only avoided that for the canonical Fusion path because+-- ``RawAlert.deterministic_id()`` gives both writers the same primary key, so+-- the second INSERT hits ``ON CONFLICT (id) DO NOTHING``. The sink's contract+-- is not "callers must supply a deterministic id": any writer that supplies a+-- different id for the same tenant and fingerprint — a replay after an id+-- algorithm change, a future batch producer, a direct write — can persist a+-- second visible alert.+--+-- The non-unique ``idx_alerts_dedup`` from 001_init.sql cannot prevent that.+-- This partial unique index is the authoritative guarantee, scoped per tenant+-- exactly like the lookup it backs. Rows with a NULL dedup_hash (manual+-- alerts, connector paths that do not use the fingerprint) are outside the+-- predicate and keep their current behaviour.+--+-- The sink handles the resulting conflict explicitly: migration 120 makes the+-- loser of the race raise ``UniqueViolationError`` on constraint+-- ``uq_alerts_tenant_dedup``, and ``AlertSink._persist_on_conn`` resolves it+-- to the winner's row instead of writing a second alert.+--+-- Precondition: no existing duplicate pairs+-- ──────────────────────────────────────────+-- ``CREATE UNIQUE INDEX`` fails if the table already contains duplicates.+-- This migration checks first and raises a diagnostic naming the offending+-- pairs. It deliberately does not delete, merge, or rewrite any alert: which+-- of two analyst-visible rows survives is an operator decision, and a+-- migration that silently picks one would destroy evidence.+--+-- Find the blockers before deploying with:+--+-- SELECT tenant_id, dedup_hash, count(*) AS rows,+-- min(created_at) AS first_seen, max(created_at) AS last_seen+-- FROM alerts+-- WHERE dedup_hash IS NOT NULL+-- GROUP BY tenant_id, dedup_hash+-- HAVING count(*) > 1+-- ORDER BY count(*) DESC;+--+-- Resolve them deliberately, then re-run the migration chain. Until this file+-- succeeds it is not recorded in ``aisoc_schema_migrations`` and the old+-- non-unique behaviour remains, so a failed run is safe but incomplete.+--+-- Rollout notes+-- ─────────────+-- The index is built inside this file's transaction. PostgreSQL takes a+-- SHARE lock on ``alerts`` while it builds, which blocks writes but not reads;+-- on a large table schedule the deploy accordingly. An operator who cannot+-- take that lock can build the index out of band with+-- ``CREATE UNIQUE INDEX CONCURRENTLY uq_alerts_tenant_dedup ...`` first; the+-- ``IF NOT EXISTS`` below then treats it as already done. Do not use+-- CONCURRENTLY inside this file: the runner sends the whole script as one+-- simple-query batch, and a failed concurrent build would leave an invalid+-- index that ``IF NOT EXISTS`` would later mistake for a valid one.+--+-- Runner behaviour (operational requirement)+-- ──────────────────────────────────────────+-- ``run_migrations.py`` logs a failed migration, rolls it back, continues with+-- the remaining files, and exits 0 unless ``AISOC_MIGRATIONS_STRICT=1`` (also+-- accepted: true/yes/on). A non-strict run therefore looks successful while+-- this index is absent and the sink's cross-writer race is still open.+--+-- Set ``AISOC_MIGRATIONS_STRICT=1`` for this deploy. The failure is never+-- recorded in ``aisoc_schema_migrations`` either way, so the file is retried+-- on the next run; strict mode is what stops the release from proceeding with+-- the guarantee missing.+--+-- Deploy ordering+-- ───────────────+-- The index can be applied before the Fusion sink change, but an old sink+-- treats the resulting UniqueViolationError as a permanent constraint failure+-- and dead-letters the losing event. The alert itself is not lost (the winner+-- row exists), but the DLQ entry is spurious. Deploy the sink change first, or+-- both together, to avoid that window.+--+-- Rollback: DROP INDEX IF EXISTS uq_alerts_tenant_dedup;+-- The non-unique ``idx_alerts_dedup`` from 001_init.sql is unaffected.++BEGIN;++DO $$+DECLARE+ duplicate_pairs bigint;+ sample text;+ index_is_invalid boolean;+BEGIN+ -- A failed CREATE INDEX CONCURRENTLY leaves an invalid index behind, and+ -- ``IF NOT EXISTS`` below would then treat it as a valid guarantee. Fail+ -- loudly instead: the operator must drop the invalid index and re-run.+ SELECT NOT i.indisvalid+ INTO index_is_invalid+ FROM pg_index i+ JOIN pg_class c ON c.oid = i.indexrelid+ WHERE i.indrelid = 'alerts'::regclass+ AND c.relname = 'uq_alerts_tenant_dedup';++ IF index_is_invalid THEN+ RAISE EXCEPTION+ 'index uq_alerts_tenant_dedup exists but is invalid (a failed CREATE INDEX CONCURRENTLY leaves this state). DROP INDEX uq_alerts_tenant_dedup and re-run. No rows were changed.';+ END IF;++ SELECT count(*)+ INTO duplicate_pairs+ FROM (+ SELECT 1+ FROM alerts+ WHERE dedup_hash IS NOT NULL+ GROUP BY tenant_id, dedup_hash+ HAVING count(*) > 1+ ) AS duplicates;++ IF duplicate_pairs > 0 THEN+ SELECT string_agg(+ format('%s / %s (%s rows)', tenant_id, dedup_hash, row_count),+ '; '+ ORDER BY row_count DESC+ )+ INTO sample+ FROM (+ SELECT tenant_id, dedup_hash, count(*) AS row_count+ FROM alerts+ WHERE dedup_hash IS NOT NULL+ GROUP BY tenant_id, dedup_hash+ HAVING count(*) > 1+ ORDER BY count(*) DESC+ LIMIT 5+ ) AS duplicates;++ RAISE EXCEPTION+ 'alerts has % duplicate (tenant_id, dedup_hash) pair(s); refusing to create uq_alerts_tenant_dedup. Sample: %. Resolve the duplicates deliberately (merge or delete) and re-run. No rows were changed.',+ duplicate_pairs,+ sample;+ END IF;+END+$$;++CREATE UNIQUE INDEX IF NOT EXISTS uq_alerts_tenant_dedup+ ON alerts (tenant_id, dedup_hash)+ WHERE dedup_hash IS NOT NULL;++COMMIT;diff --git a/services/fusion/app/core/config.py b/services/fusion/app/core/config.pyindex 4d3c436d0..e5fff6ac0 100644--- a/services/fusion/app/core/config.py+++ b/services/fusion/app/core/config.py@@ -27,7 +27,30 @@ class Settings(BaseSettings):event_promotion_enabled: bool = Field(default=True, alias="AISOC_EVENT_PROMOTION_ENABLED")# Phase 3.1 spine bridge — persist fused (non-duplicate) alerts to the# Postgres alert store (app/services/alert_sink.py). Fail-soft by design.+ #+ # Disabling this also disables the durable DLQ (main.py wires PostgresDLQ+ # only when the sink exists) and the session store. The worker then runs+ # in an explicitly persistence-free mode: alerts stream over Kafka but no+ # row is written, and a refused event is only logged. Do not read a+ # committed Kafka offset in that mode as proof of durable capture.alert_sink_enabled: bool = Field(default=True, alias="AISOC_ALERT_SINK_ENABLED")+ # Bounded time for one insert/duplicate-verification. A hung connection+ # must surface as a retryable outcome, not stall the partition forever.+ alert_sink_operation_timeout_seconds: float = Field(default=10.0, alias="AISOC_ALERT_SINK_OPERATION_TIMEOUT_SECONDS")++ # Consumer durability. Transient persistence/publish failures are retried+ # with exponential backoff + jitter and the Kafka offset is not committed+ # until the message is durable (or captured by the DLQ). The recovery+ # interval is the long, capped delay used when the primary store *and*+ # the DLQ are both unreachable: the message is held, not dropped.+ consumer_max_retries: int = Field(default=8, alias="AISOC_CONSUMER_MAX_RETRIES")+ 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")+ kafka_send_timeout_seconds: float = Field(default=30.0, alias="AISOC_KAFKA_SEND_TIMEOUT_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")# Phase A1 — archive every normalized OCSF event into the ClickHouse event# lake (app/services/lake_writer.py). Independent of promotion: an event@@ -41,6 +64,16 @@ class Settings(BaseSettings):clickhouse_password: str = Field(default="", alias="CLICKHOUSE_PASSWORD")lake_batch_size: int = Field(default=100, alias="AISOC_LAKE_BATCH_SIZE")lake_batch_max_age_seconds: float = Field(default=2.0, alias="AISOC_LAKE_BATCH_MAX_AGE_SECONDS")+ # A failed ClickHouse batch is retained and retried, not dropped. These+ # 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")+ 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 is+ # dropped explicitly. Connection errors keep the batch (bounded above)+ # because the store being down is not evidence that the rows are bad.+ lake_max_data_failures: int = Field(default=5, alias="AISOC_LAKE_MAX_DATA_FAILURES")# Phase A2 — evaluate the executable native detection corpus against the# live event stream (app/services/detection_engine.py). Each firing rule@@ -62,8 +95,12 @@ class Settings(BaseSettings):attack_chain_grouping_enabled: bool = Field(default=True, alias="AISOC_ATTACK_CHAIN_GROUPING_ENABLED")attack_chain_window_seconds: int = Field(default=3600, alias="AISOC_ATTACK_CHAIN_WINDOW_SECONDS")- # Redis+ # Redis. Dedup/correlation are hints, not the source of truth (Postgres is),+ # so a Redis outage must degrade rather than raise. Short socket timeouts+ # keep a black-holed Redis from stalling the alert path.redis_url: str = Field(default="redis://localhost:6379/2", alias="REDIS_URL")+ redis_socket_timeout_seconds: float = Field(default=5.0, alias="AISOC_REDIS_SOCKET_TIMEOUT_SECONDS")+ redis_connect_timeout_seconds: float = Field(default=5.0, alias="AISOC_REDIS_CONNECT_TIMEOUT_SECONDS")dedup_window_seconds: int = Field(default=300, alias="DEDUP_WINDOW_SECONDS")correlation_window_seconds: int = Field(default=3600, alias="CORRELATION_WINDOW_SECONDS")diff --git a/services/fusion/app/main.py b/services/fusion/app/main.pyindex d1ecf9aa0..b38721c08 100644--- a/services/fusion/app/main.py+++ b/services/fusion/app/main.py@@ -56,7 +56,16 @@ async def lifespan(app: FastAPI):configure_logging()logger.info("Starting AiSOC Alert Fusion Service", port=settings.http_port)- redis_client = aioredis.from_url(settings.redis_url, decode_responses=False)+ # Short socket timeouts are part of the Redis fallback: a black-holed+ # connection must fail open into Postgres-backed dedup, not stall the+ # alert path waiting for a TCP read that never arrives.+ redis_client = aioredis.from_url(+ settings.redis_url,+ decode_responses=False,+ socket_connect_timeout=settings.redis_connect_timeout_seconds,+ socket_timeout=settings.redis_socket_timeout_seconds,+ health_check_interval=30,+ )dedup = Deduplicator(redis_client)correlator = Correlator(redis_client)@@ -141,7 +150,19 @@ async def lifespan(app: FastAPI):# The pool is passed as a callable because `sink.start()` opens it# during `worker.start()`, after this point; capturing it eagerly would# capture None and drop every dead letter.- dlq = PostgresDLQ(lambda: sink._pool) if sink is not None else None+ # `ensure_pool`/`invalidate_pool` matter here: the DLQ shares the sink's+ # pool, and while the consumer is holding a message neither the alert path+ # nor anything else reconnects. Without them a Postgres outage that+ # invalidated the pool would turn the hold into a permanent stall.+ dlq = (+ PostgresDLQ(+ lambda: sink._pool,+ ensure_pool=sink.ensure_pool,+ invalidate_pool=sink.invalidate_pool,+ )+ if sink is not None+ else None+ )# Depth 6.1 — the observed AI estate. Shares the alert sink's pool for# the same reason the dead-letter queue does: one Postgres connection@@ -151,6 +172,19 @@ 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+ 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+ # offsets are not evidence that an alert survived. Development-only.+ logger.warning(+ "fusion.alert_persistence_disabled",+ setting="AISOC_ALERT_SINK_ENABLED=false",+ detail=(+ "alerts are not persisted to Postgres and dead letters are log-only; "+ "Kafka offsets commit after processing, not after durable capture"+ ),+ )+worker = FusionWorker(engine,sink=sink,diff --git a/services/fusion/app/services/alert_sink.py b/services/fusion/app/services/alert_sink.pyindex a6b260d28..e78ecc6c7 100644--- a/services/fusion/app/services/alert_sink.py+++ b/services/fusion/app/services/alert_sink.py@@ -20,6 +20,7 @@ Design constraints:from __future__ import annotations+import asyncioimport jsonfrom collections.abc import Sequencefrom dataclasses import dataclass@@ -29,6 +30,7 @@ from typing import Anyimport asyncpgimport structlog+from app.core.config import settingsfrom app.models.alert import FusedAlert, FusionDecisionlogger = structlog.get_logger()@@ -50,10 +52,24 @@ class PersistOutcome(str, Enum):@dataclass(frozen=True)class PersistResult:- """Outcome of :meth:`AlertSink.persist` plus the canonical alert id."""+ """Outcome of :meth:`AlertSink.persist` plus the canonical alert id.++ ``retryable`` distinguishes an outage from a bad row. The outcome alone+ cannot: a connection reset and a foreign-key violation both used to be+ ``FAILED``, and the consumer treated both the same way — either committing+ the offset (loss) or retrying a permanently bad alert forever.++ ``verified`` says the caller may trust the outcome as durable evidence.+ A ``DUPLICATE`` verdict with an unreachable database is a correct *fusion*+ verdict but not a verified store state: the surviving row might itself+ never have been written. The consumer must not commit until it is verified+ or repaired.+ """outcome: PersistOutcomealert_id: str | None = None+ retryable: bool = False+ verified: bool = True@propertydef persisted(self) -> bool:@@ -61,8 +77,13 @@ class PersistResult:@propertydef durable(self) -> bool:- """True when the alert is known to exist in the store (new or dup)."""- return self.outcome in (PersistOutcome.INSERTED, PersistOutcome.DUPLICATE)+ """True when the alert is known to exist in the store (new or dup).++ Unverified duplicates are deliberately *not* durable. That distinction+ is the difference between "fusion remembers seeing this" (a Redis hint+ that may predate a crash) and "the row is in Postgres".+ """+ return self.verified and self.outcome in (PersistOutcome.INSERTED, PersistOutcome.DUPLICATE)_INSERT_SQL = """@@ -97,6 +118,23 @@ RETURNING id# placeholders to make a list read nicely is how a confidence score ends up# in a narrative column.+#: The reconciliation read for a fusion ``DUPLICATE`` verdict.+#:+#: Fusion registers a dedup fingerprint in Redis *before* the row is durable.+#: If the process dies (or Postgres rejects the insert) in that window, the+#: re-delivered message is still classified ``DUPLICATE`` and the old sink+#: returned without writing anything: the event was permanently lost while the+#: consumer committed its offset. The dedup hint is therefore treated as a+#: claim to verify, not a fact. If no row carries this ``(tenant, dedup_hash)``+#: pair, the redelivered alert is inserted under its deterministic id.+_SURVIVING_ALERT_SQL = """+SELECT id+ FROM alerts+ WHERE tenant_id = $1+ AND dedup_hash = $2::text+ LIMIT 1+"""+#: Record a raw event that deduplicated onto an alert that already exists.#:#: Issue #1244. `source_event_ids` is "the raw events that produced this@@ -170,22 +208,77 @@ def writeback_vendor(connector_type: str | None) -> str | None:return _WRITEBACK_VENDOR_BY_CONNECTOR.get(connector_type.strip().lower())-# Two idempotency guards, complementary (issue #568):+# Three layers of idempotency, complementary (issue #568):# * WHERE NOT EXISTS (tenant_id, dedup_hash) — content dedup; also protects# legacy rows written before ids were deterministic (random id, same hash).# * ON CONFLICT (id) DO NOTHING — exact-replay idempotency on the canonical# deterministic UUID (RawAlert.deterministic_id()).+# * uq_alerts_tenant_dedup (migration 120) — the database-level guarantee for+# two concurrent writers that supply different ids but the same fingerprint.+# Under READ COMMITTED both can pass WHERE NOT EXISTS; the partial unique+# index makes the second INSERT raise UniqueViolationError instead of+# writing a second visible alert. `_persist_on_conn` resolves that+# violation to the winner's row (see `_DEDUP_UNIQUE_INDEX`).# NB: $11 (dedup_hash) is cast ::text in BOTH the INSERT target and the WHERE.# `dedup_hash` is VARCHAR(64); a varchar/text mismatch makes asyncpg's prepare# fail to unify parameter $11 ("inconsistent types deduced"), silently dropping# every write. Pinning both uses to ::text makes the deduction unambiguous.+#: The partial unique index created by+#: ``services/api/migrations/120_alerts_tenant_dedup_unique.sql``. A unique+#: violation carrying this constraint name is the concurrent-dedup race, not a+#: malformed row: the loser must resolve the winner's row rather than fail (or+#: insert a second alert).+_DEDUP_UNIQUE_INDEX = "uq_alerts_tenant_dedup"+def _asyncpg_dsn(url: str) -> str:"""Strip the SQLAlchemy driver suffix — asyncpg wants plain postgresql://."""return url.replace("postgresql+asyncpg://", "postgresql://", 1)+def _is_retryable_db_error(exc: BaseException) -> bool:+ """Whether re-running the statement could plausibly succeed.++ Transient: the connection was lost, the server was shutting down, a+ statement was cancelled by a timeout, or the pool was exhausted. Permanent:+ a constraint violation, an unknown tenant, invalid SQL. The two classes+ need different handling at the consumer: retry (and do not commit) versus+ dead-letter and move on.+ """+ if isinstance(+ exc,+ (+ asyncpg.PostgresConnectionError,+ asyncpg.InterfaceError,+ asyncpg.QueryCanceledError,+ asyncpg.DeadlockDetectedError,+ asyncpg.TooManyConnectionsError,+ TimeoutError,+ OSError,+ ),+ ):+ return True+ text = str(exc).lower()+ return any(+ marker in text+ for marker in (+ "connection",+ "connect",+ "server closed",+ "connection reset",+ "connection refused",+ "timed out",+ "timeout",+ "pool",+ "too many clients",+ "starting up",+ "shutting down",+ "not yet accepting",+ )+ )++def _iocs(fused: FusedAlert) -> list[dict[str, str]]:alert = fused.alertout: list[dict[str, str]] = []@@ -286,20 +379,45 @@ class AlertSink:self._pool_size = pool_sizeself._pool: asyncpg.Pool | None = Noneself._connect_failed_logged = False+ self._operation_timeout = float(getattr(settings, "alert_sink_operation_timeout_seconds", 10.0))+ self._start_lock = asyncio.Lock()async def start(self) -> None:"""Open the pool. Failure is logged, not raised (fail-soft)."""- try:- self._pool = await asyncpg.create_pool(self._dsn, min_size=1, max_size=self._pool_size, timeout=10)- logger.info("alert_sink.started")- except Exception as exc: # noqa: BLE001 — degrade, never crash the worker- self._pool = None- logger.error("alert_sink.connect_failed", error=str(exc))+ async with self._start_lock:+ if self._pool is not None:+ return+ try:+ self._pool = await asyncpg.create_pool(+ self._dsn,+ min_size=1,+ max_size=self._pool_size,+ timeout=10,+ command_timeout=self._operation_timeout,+ )+ logger.info("alert_sink.started")+ except Exception as exc: # noqa: BLE001 — degrade, never crash the worker+ self._pool = None+ logger.error("alert_sink.connect_failed", error=str(exc))async def stop(self) -> None:- if self._pool is not None:- await self._pool.close()- self._pool = None+ await self._invalidate_pool()++ async def _invalidate_pool(self) -> None:+ """Forget a pool that just proved unusable.++ ``_ensure_pool`` used to reconnect only when ``_pool is None``. A pool+ whose server went away stayed non-None, so every later persist raised+ from ``acquire()`` and returned ``FAILED`` forever even after Postgres+ came back: recovery required a fusion restart. Dropping the handle on a+ connection-level failure lets the next attempt rebuild it.+ """+ pool, self._pool = self._pool, None+ if pool is not None:+ try:+ await pool.close()+ except Exception as exc: # noqa: BLE001 — the pool is already broken+ logger.debug("alert_sink.pool_close_failed", error=str(exc))async def _ensure_pool(self) -> asyncpg.Pool | None:if self._pool is None:@@ -308,54 +426,194 @@ class AlertSink:await self.start()return self._pool+ async def ensure_pool(self) -> asyncpg.Pool | None:+ """Rebuild the pool if it was invalidated.++ Public because the dead-letter queue shares this pool: during a+ recovery hold no alert is being persisted, so nothing else would+ reconnect and the hold would never end after Postgres returns.+ """+ return await self._ensure_pool()++ async def invalidate_pool(self) -> None:+ """Drop a pool that just proved unusable, so the next call reconnects."""+ await self._invalidate_pool()+async def persist(self, fused: FusedAlert) -> PersistResult:"""Insert one fused alert, returning a structured :class:`PersistResult`.The canonical alert id is ``fused.id`` (deterministic — issue #568), soeven a duplicate / outage carries the id the row resolves to once theDB is reachable.++ A fusion ``DUPLICATE`` is *reconciled* rather than trusted: the dedup+ fingerprint lives in Redis and is written before the row, so it can+ outlive a crash that prevented the insert. When no row carries the+ fingerprint, the redelivered alert is persisted, repairing the loss+ instead of confirming it."""canonical_id = str(fused.id)- alert = fused.alert- if fused.fusion_decision == FusionDecision.DUPLICATE:- # Fusion has already decided: there is no row to write, and a- # database outage cannot change that verdict. The folded-away- # event is still part of the surviving alert's provenance, so- # record it when there is a pool — best-effort, never a reconnect- # attempt, and never a different outcome.- if self._pool is not None:- try:- async with self._pool.acquire() as conn:- await self._record_deduplicated_event(conn, alert)- except Exception as exc: # noqa: BLE001 — provenance is not worth the verdict- logger.warning("alert_sink.dedup_provenance_failed", error=str(exc))- return PersistResult(PersistOutcome.DUPLICATE, canonical_id)-+ is_duplicate = fused.fusion_decision == FusionDecision.DUPLICATE+ try:+ result = await asyncio.wait_for(self._persist_once(fused), timeout=self._operation_timeout)+ except TimeoutError as exc:+ await self._invalidate_pool()+ logger.error("alert_sink.persist_timeout", error=str(exc), duplicate=is_duplicate)+ return PersistResult(+ PersistOutcome.DUPLICATE if is_duplicate else PersistOutcome.UNAVAILABLE,+ canonical_id,+ retryable=True,+ verified=False,+ )+ except asyncpg.ForeignKeyViolationError:+ # Unknown tenant — a mis-provisioned connector, not a pipeline bug.+ # Distinct from a duplicate so it is observable, not silently masked.+ logger.warning("alert_sink.unknown_tenant", tenant_id=str(fused.alert.tenant_id))+ return PersistResult(PersistOutcome.FAILED, None)+ except Exception as exc: # noqa: BLE001 — one bad row must not wedge the consumer+ retryable = _is_retryable_db_error(exc)+ if retryable:+ await self._invalidate_pool()+ logger.error("alert_sink.persist_failed", error=str(exc), retryable=retryable, duplicate=is_duplicate)+ if retryable and is_duplicate:+ # Fusion's verdict stands, but the surviving row is unverified.+ return PersistResult(PersistOutcome.DUPLICATE, canonical_id, retryable=True, verified=False)+ return PersistResult(PersistOutcome.FAILED, None, retryable=retryable)++ if result.outcome is PersistOutcome.INSERTED and result.alert_id:+ await self._link_source_finding_safely(fused, alert_id=result.alert_id)+ return result++ async def _persist_once(self, fused: FusedAlert) -> PersistResult:pool = await self._ensure_pool()if pool is None:if not self._connect_failed_logged:logger.error("alert_sink.unavailable_dropping_persistence")self._connect_failed_logged = True- return PersistResult(PersistOutcome.UNAVAILABLE, canonical_id)+ if fused.fusion_decision == FusionDecision.DUPLICATE:+ # Cannot verify; the consumer must retry rather than commit a+ # duplicate whose surviving row may never have been written.+ return PersistResult(PersistOutcome.DUPLICATE, str(fused.id), retryable=True, verified=False)+ return PersistResult(PersistOutcome.UNAVAILABLE, str(fused.id), retryable=True)self._connect_failed_logged = False+ async with pool.acquire() as conn:+ return await self._persist_on_conn(conn, fused)++ async def _persist_on_conn(self, conn: Any, fused: FusedAlert) -> PersistResult:+ """Persist one alert over an already-acquired connection.++ Shared by the single and batch paths so the duplicate-reconciliation+ rule cannot drift between them.+ """+ canonical_id = str(fused.id)+ alert = fused.alert+ is_duplicate = fused.fusion_decision == FusionDecision.DUPLICATE++ if is_duplicate:+ existing_id = await self._surviving_alert_id(conn, alert)+ if existing_id is not None:+ await self._record_deduplicated_event(conn, alert)+ return PersistResult(PersistOutcome.DUPLICATE, str(existing_id))try:- async with pool.acquire() as conn:- row = await conn.fetchrow(_INSERT_SQL, *_insert_args(fused))- if row is None:- logger.debug("alert_sink.dedup_skip", fingerprint=alert.fingerprint())- await self._record_deduplicated_event(conn, alert)- return PersistResult(PersistOutcome.DUPLICATE, canonical_id)- await self._link_source_finding(pool, alert, alert_id=row["id"])- return PersistResult(PersistOutcome.INSERTED, str(row["id"]))- except asyncpg.ForeignKeyViolationError:- # Unknown tenant — a mis-provisioned connector, not a pipeline bug.- # Distinct from a duplicate so it is observable, not silently masked.- logger.warning("alert_sink.unknown_tenant", tenant_id=str(alert.tenant_id))- return PersistResult(PersistOutcome.FAILED, None)- except Exception as exc: # noqa: BLE001 — one bad row must not wedge the consumer- logger.error("alert_sink.persist_failed", error=str(exc))- return PersistResult(PersistOutcome.FAILED, None)+ row = await conn.fetchrow(_INSERT_SQL, *_insert_args(fused))+ except asyncpg.UniqueViolationError as exc:+ # Two writers with different ids can both pass the WHERE NOT EXISTS+ # guard under READ COMMITTED. The partial unique index from+ # migration 120 is the authority that stops the second row; this+ # writer lost the race and must resolve the winner's row rather+ # than report a failure (which would dead-letter an alert that is+ # already durable) or retry blindly (which would do the same).+ #+ # Both call sites (``persist`` and ``persist_many``) run each+ # statement in autocommit, so the failed INSERT does not leave a+ # transaction aborted and the reconciliation read below is valid.+ # Nothing in services/fusion opens a transaction around persist;+ # asyncpg's pool release also resets (ROLLBACKs) a leaked one. If a+ # caller ever wraps this in a transaction, run the INSERT inside a+ # nested ``conn.transaction()`` (a savepoint) so the error is+ # rolled back before this read, or it will fail with "current+ # transaction is aborted".+ #+ # Only this index is handled here. Any other *named* unique+ # violation is a schema/code disagreement and falls through to the+ # caller's existing failure path, so a database error is never+ # converted into a duplicate verdict. A driver that does not name+ # the index (constraint_name is None) still falls through to the+ # surviving-row read: if a row with this tenant and hash exists,+ # the alert is durable regardless of which constraint reported it.+ constraint = getattr(exc, "constraint_name", None)+ if constraint is not None and constraint != _DEDUP_UNIQUE_INDEX:+ raise+ existing_id = await self._surviving_alert_id(conn, alert)+ if existing_id is not None:+ logger.info(+ "alert_sink.concurrent_dedup_resolved",+ tenant_id=str(alert.tenant_id),+ fingerprint=alert.fingerprint(),+ )+ await self._record_deduplicated_event(conn, alert)+ return PersistResult(PersistOutcome.DUPLICATE, str(existing_id))+ # The winner's row is not visible: it was rolled back, deleted, or+ # the read is looking at a different snapshot. Do not claim+ # durability; the consumer retries.+ logger.error(+ "alert_sink.dedup_conflict_unverified",+ tenant_id=str(alert.tenant_id),+ fingerprint=alert.fingerprint(),+ )+ return PersistResult(PersistOutcome.FAILED, canonical_id, retryable=True, verified=False)++ if row is None:+ # The `WHERE NOT EXISTS` guard filtered the insert. Resolve the row+ # that filtered it, so the returned id is the durable one (which+ # may predate deterministic ids).+ existing_id = await self._surviving_alert_id(conn, alert)+ if existing_id is not None:+ logger.debug("alert_sink.dedup_skip", fingerprint=alert.fingerprint())+ await self._record_deduplicated_event(conn, alert)+ return PersistResult(PersistOutcome.DUPLICATE, str(existing_id))+ if is_duplicate:+ # The hint said duplicate, but neither row nor insert exists.+ # Do not report durability: a retry can settle the race.+ logger.error(+ "alert_sink.duplicate_unverified",+ tenant_id=str(alert.tenant_id),+ fingerprint=alert.fingerprint(),+ )+ return PersistResult(PersistOutcome.FAILED, canonical_id, retryable=True, verified=False)+ # A concurrent writer may have inserted the same id between the+ # two statements; retrying the message will re-read it.+ logger.warning("alert_sink.insert_filtered", alert_id=canonical_id)+ return PersistResult(PersistOutcome.FAILED, None, retryable=True)++ return PersistResult(PersistOutcome.INSERTED, str(row["id"]))++ async def _surviving_alert_id(self, conn: Any, alert: Any) -> Any | None:+ row = await conn.fetchrow(_SURVIVING_ALERT_SQL, alert.tenant_id, alert.fingerprint())+ return row["id"] if row is not None else None++ async def _link_source_finding_safely(self, fused: FusedAlert, *, alert_id: Any) -> None:+ # getattr rather than direct access: the batch-path tests construct the+ # sink with __new__ and replace this method, so there is no pool yet.+ pool = getattr(self, "_pool", None)+ if pool is not None:+ await self._link_source_finding(pool, fused.alert, alert_id=alert_id)++ @staticmethod+ def _unavailable_result(fused: FusedAlert) -> PersistResult:+ """A non-durable result that preserves the fusion verdict.++ A duplicate stays a duplicate (observable), but ``verified=False``+ tells the consumer it cannot commit yet.+ """+ duplicate = fused.fusion_decision == FusionDecision.DUPLICATE+ return PersistResult(+ PersistOutcome.DUPLICATE if duplicate else PersistOutcome.UNAVAILABLE,+ str(fused.id),+ retryable=True,+ verified=False,+ )async def persist_many(self, fused_batch: Sequence[FusedAlert]) -> list[PersistResult]:"""Insert a batch of fused alerts over one connection.@@ -395,39 +653,55 @@ class AlertSink:if not self._connect_failed_logged:logger.error("alert_sink.unavailable_dropping_persistence")self._connect_failed_logged = True- return [PersistResult(PersistOutcome.UNAVAILABLE, str(f.id)) for f in fused_batch]+ return [self._unavailable_result(f) for f in fused_batch]self._connect_failed_logged = False- async with pool.acquire() as conn:- for fused in fused_batch:- canonical_id = str(fused.id)- if fused.fusion_decision == FusionDecision.DUPLICATE:- await self._record_deduplicated_event(conn, fused.alert)- results.append(PersistResult(PersistOutcome.DUPLICATE, canonical_id))- continue- try:- row = await conn.fetchrow(_INSERT_SQL, *_insert_args(fused))- except asyncpg.ForeignKeyViolationError:- logger.warning("alert_sink.unknown_tenant", tenant_id=str(fused.alert.tenant_id))- results.append(PersistResult(PersistOutcome.FAILED, None))- continue- except Exception as exc: # noqa: BLE001 — one bad row must not wedge the batch- logger.error("alert_sink.persist_failed", error=str(exc))- results.append(PersistResult(PersistOutcome.FAILED, None))- continue-- if row is None:- await self._record_deduplicated_event(conn, fused.alert)- results.append(PersistResult(PersistOutcome.DUPLICATE, canonical_id))- continue- results.append(PersistResult(PersistOutcome.INSERTED, str(row["id"])))+ connection_lost = False+ try:+ async with pool.acquire() as conn:+ for fused in fused_batch:+ if connection_lost:+ results.append(self._unavailable_result(fused))+ continue+ try:+ results.append(await self._persist_on_conn(conn, fused))+ except asyncpg.ForeignKeyViolationError:+ logger.warning("alert_sink.unknown_tenant", tenant_id=str(fused.alert.tenant_id))+ results.append(PersistResult(PersistOutcome.FAILED, None))+ except Exception as exc: # noqa: BLE001 — one bad row must not wedge the batch+ retryable = _is_retryable_db_error(exc)+ logger.error("alert_sink.persist_failed", error=str(exc), retryable=retryable)+ if retryable:+ # The connection is no longer trustworthy. Stop+ # using it for the rest of the batch, but keep the+ # results already obtained: those rows are durable.+ connection_lost = True+ duplicate = fused.fusion_decision == FusionDecision.DUPLICATE+ results.append(+ PersistResult(+ PersistOutcome.DUPLICATE if duplicate else PersistOutcome.FAILED,+ str(fused.id) if duplicate else None,+ retryable=retryable,+ verified=False,+ )+ )+ except Exception as exc: # noqa: BLE001 — acquire/context failure is not a row failure+ retryable = _is_retryable_db_error(exc)+ if retryable:+ await self._invalidate_pool()+ logger.error("alert_sink.batch_failed", error=str(exc), retryable=retryable)+ done = len(results)+ results.extend(self._unavailable_result(f) for f in fused_batch[done:])+ else:+ if connection_lost:+ await self._invalidate_pool()# Source links after the inserts, on their own connections. They# are best-effort and a slow vendor lookup must not hold the# batch's connection open.for fused, result in zip(fused_batch, results, strict=True):if result.outcome is PersistOutcome.INSERTED and result.alert_id:- await self._link_source_finding(pool, fused.alert, alert_id=result.alert_id)+ await self._link_source_finding_safely(fused, alert_id=result.alert_id)return resultsdiff --git a/services/fusion/app/services/correlator.py b/services/fusion/app/services/correlator.pyindex 236e673cc..390eca932 100644--- a/services/fusion/app/services/correlator.py+++ b/services/fusion/app/services/correlator.py@@ -8,6 +8,7 @@ from uuid import uuid4import redis.asyncio as aioredisimport structlog+from redis.exceptions import RedisErrorfrom app.core.config import settingsfrom app.models.alert import AlertSeverity, IncidentSummary, RawAlert@@ -37,6 +38,8 @@ class Correlator:self._redis = redis_clientself._window = settings.correlation_window_secondsself._max_alerts = settings.max_alerts_per_incident+ self._degraded = False+ self.fallbacks = 0async def correlate(self, alert: RawAlert) -> tuple[bool, IncidentSummary]:"""@@ -44,7 +47,24 @@ class Correlator:Returns:(is_correlated_to_existing, incident_summary)++ Redis is the correlation store, not the alert store. If it is+ unreachable the alert still has to flow: a synthetic single-alert+ incident is returned and the degradation is counted, rather than the+ ``RedisError`` escaping into the engine and costing the alert (or being+ swallowed by a caller that then commits the offset)."""+ try:+ result = await self._correlate(alert)+ except (TimeoutError, RedisError, OSError) as exc:+ self.fallbacks += 1+ self._enter_degraded(exc)+ return False, self._create_incident(alert)++ self._exit_degraded()+ return result++ async def _correlate(self, alert: RawAlert) -> tuple[bool, IncidentSummary]:corr_key = alert.correlation_key()index_key = f"{_CORRELATION_PREFIX}{corr_key}"@@ -52,8 +72,12 @@ class Correlator:incident_id_bytes = await self._redis.get(index_key)if incident_id_bytes:- incident_id = incident_id_bytes.decode()- incident = await self._load_incident(incident_id)+ try:+ incident_id = incident_id_bytes.decode()+ except (AttributeError, UnicodeDecodeError):+ # A corrupt index value is a cache miss, not an alert failure.+ incident_id = ""+ incident = await self._load_incident(incident_id) if incident_id else Noneif incident and incident.alert_count < self._max_alerts:# Update existing incidentincident = await self._merge_alert(incident, alert)@@ -79,6 +103,23 @@ class Correlator:)return False, incident+ def metrics(self) -> dict[str, int | bool]:+ return {"degraded": self._degraded, "fallbacks": self.fallbacks}++ def _enter_degraded(self, exc: BaseException) -> None:+ if not self._degraded:+ self._degraded = True+ logger.warning(+ "fusion.correlation_degraded",+ error=str(exc),+ detail="Redis unavailable; alerts continue as uncorrelated single-alert incidents",+ )++ def _exit_degraded(self) -> None:+ if self._degraded:+ self._degraded = False+ logger.info("fusion.correlation_recovered")+def _create_incident(self, alert: RawAlert) -> IncidentSummary:incident = IncidentSummary(id=uuid4(),@@ -137,4 +178,16 @@ class Correlator:data = await self._redis.get(key)if not data:return None- return IncidentSummary.model_validate_json(data)+ try:+ return IncidentSummary.model_validate_json(data)+ except ValueError as exc:+ # Redis is a cache, not the source of truth. A truncated or+ # schema-stale incident payload must read as "no existing+ # incident" and let a fresh one be created — raising here would+ # dead-letter an otherwise valid alert over a cache artifact.+ logger.warning(+ "fusion.correlation_payload_invalid",+ incident_id=incident_id,+ error=str(exc),+ )+ return Nonediff --git a/services/fusion/app/services/deduplicator.py b/services/fusion/app/services/deduplicator.pyindex 59f3536fb..bbc91a97d 100644--- a/services/fusion/app/services/deduplicator.py+++ b/services/fusion/app/services/deduplicator.py@@ -1,9 +1,25 @@"""Alert deduplication using fingerprinting and a Redis sliding-window cache.++Postgres is the source of truth for whether an alert row exists+(``alert_sink`` inserts under a per-tenant dedup-hash guard), so this Redis+window is an optimisation: it avoids re-running correlation for an alert that+was just seen. It is **not** evidence that a row is durable.++Consequently a Redis outage must fail *open*. The previous implementation let+``RedisError`` escape from :meth:`is_duplicate`, which propagated out of the+fusion engine and — before the consumer's retry loop — either wedged the+partition or (worse) was logged and its offset committed, losing the event.+With Redis down an alert is now treated as non-duplicate, correlation still+runs (degraded), and the sink's database guard suppresses the actual duplicate+row."""+from __future__ import annotations+import redis.asyncio as aioredisimport structlog+from redis.exceptions import RedisErrorfrom app.core.config import settingsfrom app.models.alert import RawAlert@@ -19,6 +35,9 @@ class Deduplicator:def __init__(self, redis_client: aioredis.Redis) -> None:self._redis = redis_clientself._window = settings.dedup_window_seconds+ self._degraded = False+ self.read_fallbacks = 0+ self.write_fallbacks = 0async def is_duplicate(self, alert: RawAlert) -> tuple[bool, str | None]:"""@@ -30,26 +49,76 @@ class Deduplicator:fingerprint = alert.fingerprint()key = f"{_DEDUP_PREFIX}{fingerprint}"- existing = await self._redis.get(key)+ try:+ existing = await self._redis.get(key)+ except (TimeoutError, RedisError, OSError) as exc:+ self.read_fallbacks += 1+ self._enter_degraded(exc)+ # Fail open: Postgres still enforces per-tenant dedup, so the+ # worst case is a duplicate decision made downstream, never a lost+ # alert. Reporting "duplicate" here would be the loss.+ return False, None++ self._exit_degraded()if existing:+ try:+ original_id = existing.decode()+ except (AttributeError, UnicodeDecodeError):+ # A corrupt cache value is a cache miss, not a duplicate. The+ # Postgres guard still suppresses a real repeat row, whereas+ # raising here would dead-letter a valid alert over cache bytes.+ logger.warning("fusion.dedup_payload_invalid", fingerprint=fingerprint)+ return False, Nonelogger.debug("Duplicate alert detected",fingerprint=fingerprint,- original_id=existing.decode(),+ original_id=original_id,alert_id=str(alert.id),)- return True, existing.decode()+ return True, original_idreturn False, Noneasync def register(self, alert: RawAlert) -> None:- """Register an alert fingerprint to suppress future duplicates."""+ """Register an alert fingerprint to suppress future duplicates.++ Best-effort. A failed write means a later replay is not suppressed by+ Redis; the database's dedup guard still prevents a second row.+ """fingerprint = alert.fingerprint()key = f"{_DEDUP_PREFIX}{fingerprint}"- await self._redis.set(key, str(alert.id), ex=self._window)+ try:+ await self._redis.set(key, str(alert.id), ex=self._window)+ except (TimeoutError, RedisError, OSError) as exc:+ self.write_fallbacks += 1+ self._enter_degraded(exc)+ return++ self._exit_degraded()logger.debug("Alert fingerprint registered",fingerprint=fingerprint,alert_id=str(alert.id),ttl_seconds=self._window,)++ def metrics(self) -> dict[str, int | bool]:+ return {+ "degraded": self._degraded,+ "read_fallbacks": self.read_fallbacks,+ "write_fallbacks": self.write_fallbacks,+ }++ def _enter_degraded(self, exc: BaseException) -> None:+ if not self._degraded:+ self._degraded = True+ logger.warning(+ "fusion.dedup_degraded_fail_open",+ error=str(exc),+ detail="Redis unavailable; dedup falls back to the Postgres uniqueness guard",+ )++ def _exit_degraded(self) -> None:+ if self._degraded:+ self._degraded = False+ logger.info("fusion.dedup_recovered")diff --git a/services/fusion/app/services/dlq.py b/services/fusion/app/services/dlq.pyindex d071f1f40..c2d12dfa7 100644--- a/services/fusion/app/services/dlq.py+++ b/services/fusion/app/services/dlq.py@@ -98,54 +98,102 @@ class DeadLetter:@runtime_checkableclass DeadLetterQueue(Protocol):- async def record(self, dead_letter: DeadLetter) -> None:- """Persist/emit a rejected message so it is never silently lost."""+ """A sink for rejected messages.++ Implementations may expose a class attribute ``durable`` saying whether a+ successful ``record`` is *storage* rather than a log line. It is not part+ of the protocol because a data member would make ``issubclass`` unusable+ for a ``runtime_checkable`` protocol; the consumer reads it with+ ``getattr(..., "durable", False)`` and defaults to the honest answer.+ """++ async def record(self, dead_letter: DeadLetter) -> bool | None:+ """Persist/emit a rejected message.++ Return ``False`` when the capture definitively failed. Any other+ result — including the historical ``None`` — is treated as success,+ so an existing sink that only raises on failure keeps working.+ """class LoggingDLQ:"""Default sink — structured warning. Alert on ``fusion.dead_letter``."""- async def record(self, dead_letter: DeadLetter) -> None:+ #: A log line is not durable storage. See the protocol attribute.+ durable = False++ async def record(self, dead_letter: DeadLetter) -> bool:logger.warning("fusion.dead_letter", **dead_letter.to_dict())+ return Trueclass InMemoryDLQ:"""Test double. Keeps records so assertions can inspect them."""+ #: Forgets on restart, so it is not a durable capture either.+ durable = False+def __init__(self) -> None:self.records: list[DeadLetter] = []- async def record(self, dead_letter: DeadLetter) -> None:+ async def record(self, dead_letter: DeadLetter) -> bool:self.records.append(dead_letter)+ return Trueclass KafkaDLQ:"""Republish to a dead-letter topic via the consumer's producer.``producer`` is the worker's ``AIOKafkaProducer`` (already started). We do- not own its lifecycle. If the send fails, :func:`safe_record` upstream- swallows it — a broken DLQ must not wedge the consumer.+ not own its lifecycle. A send failure raises; :func:`safe_record` turns it+ into ``False`` — a broken DLQ must not wedge the consumer, but it must not+ look like a successful capture either."""+ #: ``record`` returns True only after the broker acknowledges the write.+ durable = True+def __init__(self, producer: Any, topic: str = "aisoc.alerts.dlq") -> None:self._producer = producerself._topic = topic- async def record(self, dead_letter: DeadLetter) -> None:- await self._producer.send(self._topic, value=dead_letter.to_dict())+ async def record(self, dead_letter: DeadLetter) -> bool:+ # ``AIOKafkaProducer.send`` only enqueues the record: it returns a+ # future that resolves when the broker acknowledges. Awaiting the call+ # alone would report a capture that a later producer failure can still+ # lose, while the consumer commits the offset on the strength of it.+ # ``send_and_wait`` is exactly this pair; using ``send`` keeps the sink+ # compatible with producers (and test doubles) that expose only send.+ future = await self._producer.send(self._topic, value=dead_letter.to_dict())+ acknowledged = await future+ # The ack's payload — ``RecordMetadata`` in production, ``None`` from a+ # producer double — is not part of this contract: ``record`` reports on+ # the *absence of an exception*, which is what makes the offset commit+ # that follows it safe. It is referenced rather than discarded because a+ # bare ``await <name>`` reads to CodeQL as `py/ineffectual-statement`+ # (it does not model ``await`` as effectful) and binding it to an+ # unreferenced name only trades that for `py/unused-local-variable`.+ logger.debug("fusion.dlq.acknowledged", topic=self._topic, acknowledged=acknowledged is not None)+ return Trueasync def safe_record(dlq: DeadLetterQueue | None, dead_letter: DeadLetter) -> bool:"""Record to the DLQ, swallowing any sink error. Returns True on success.A DLQ that raises must never propagate — that would let one poison message- crash the consumer, the exact failure mode the DLQ exists to prevent.+ crash the consumer, the exact failure mode the DLQ exists to prevent. But+ a sink that reports ``False`` (notably :class:`PostgresDLQ` when its pool+ is down) must not be mistaken for a capture: the consumer holds the offset+ uncommitted until a later attempt succeeds.++ ``None`` is accepted as success for backwards compatibility with sinks+ written against the original ``-> None`` protocol."""if dlq is None:return Falsetry:- await dlq.record(dead_letter)- return True+ result = await dlq.record(dead_letter)+ return result is not Falseexcept Exception as exc: # noqa: BLE001 — fail-soft by contractlogger.error("fusion.dlq_sink_failed", error=str(exc), topic=dead_letter.topic, reason=dead_letter.reason)return Falsediff --git a/services/fusion/app/services/dlq_sink.py b/services/fusion/app/services/dlq_sink.pyindex 8bb6dc508..171e4ea41 100644--- a/services/fusion/app/services/dlq_sink.py+++ b/services/fusion/app/services/dlq_sink.py@@ -15,8 +15,13 @@ This persists them. Two properties matter more than the writing:**A DLQ that fails must not take the pipeline with it.** The whole pointof routing a poison message aside is to keep consuming; if recording thatdecision can raise, the DLQ becomes a second way for one bad event to stop-everything. Every failure here is logged and swallowed, which is the one-place in this codebase where swallowing is the correct behaviour.+everything. Every failure here is logged and turned into ``False`` rather+than raised, which is the one place in this codebase where swallowing is the+correct behaviour.++``False`` is not the same as "nothing to see": it tells the caller the+capture did not happen, so the consumer can hold the Kafka offset instead of+committing a message that exists nowhere durable.**The payload is truncated, never stored whole.** It is untrusted bydefinition — it is the thing the pipeline refused — and may be large or@@ -26,7 +31,7 @@ the content that was rejected.from __future__ import annotations-from collections.abc import Callable+from collections.abc import Awaitable, Callableimport asyncpgimport structlog@@ -64,27 +69,50 @@ class PostgresDLQ(DeadLetterQueue):``lambda: pool``."""- def __init__(self, pool_provider: Callable[[], asyncpg.Pool | None]) -> None:- self._pool_provider = pool_provider-- def _pool_now(self) -> asyncpg.Pool | None:- return self._pool_provider()+ #: A committed INSERT is durable storage; ``False`` from `record` is not.+ durable = True- async def record(self, letter: DeadLetter) -> None:+ def __init__(+ self,+ pool_provider: Callable[[], asyncpg.Pool | None],+ *,+ ensure_pool: Callable[[], Awaitable[asyncpg.Pool | None]] | None = None,+ invalidate_pool: Callable[[], Awaitable[None]] | None = None,+ ) -> None:+ self._pool_provider = pool_provider+ # The DLQ shares the alert sink's pool. When that pool has been+ # invalidated, nothing rebuilds it during a recovery hold — no alert is+ # being persisted, which is the only other caller of `ensure_pool`. The+ # callbacks let the hold actually end once Postgres returns instead of+ # waiting for a restart.+ self._ensure_pool = ensure_pool+ self._invalidate_pool = invalidate_pool++ async def _pool_now(self) -> asyncpg.Pool | None:+ pool = self._pool_provider()+ if pool is None and self._ensure_pool is not None:+ pool = await self._ensure_pool()+ return pool++ async def record(self, letter: DeadLetter) -> bool:excerpt = (letter.payload_excerpt or "")[:MAX_EXCERPT]tenant_id = _as_uuid(letter.tenant_id)- pool = self._pool_now()+ pool = await self._pool_now()if pool is None:# The sink never opened, so there is nowhere to write. Logged# at warning rather than silently skipped: a DLQ that records# nothing looks exactly like a pipeline dropping nothing.+ #+ # Returning False is what tells the consumer this capture did not+ # happen, so it holds the offset instead of committing a message+ # that now exists nowhere durable.logger.warning("dlq.no_pool",topic=letter.topic,reason=letter.reason,)- return+ return Falsetry:async with pool.acquire() as conn:@@ -107,13 +135,21 @@ class PostgresDLQ(DeadLetterQueue):# consumer because we could not record it is worse: one poison# message would then halt the pipeline, which is precisely the# outcome the DLQ exists to prevent.+ #+ # Drop a pool that just failed so the next attempt can rebuild it;+ # without this a stale handle makes every retry fail the same way.+ if self._invalidate_pool is not None:+ try:+ await self._invalidate_pool()+ except Exception as invalidate_exc: # noqa: BLE001+ logger.debug("dlq.pool_invalidate_failed", error=str(invalidate_exc))logger.warning("dlq.persist_failed",topic=letter.topic,reason=letter.reason,error=str(exc),)- return+ return Falselogger.info("dlq.recorded",@@ -121,6 +157,7 @@ class PostgresDLQ(DeadLetterQueue):reason=letter.reason,tenant_id=letter.tenant_id,)+ return Truedef _as_uuid(value: str | None):diff --git a/services/fusion/app/services/fusion_engine.py b/services/fusion/app/services/fusion_engine.pyindex 99d9e2eaa..a1606a9c2 100644--- a/services/fusion/app/services/fusion_engine.py+++ b/services/fusion/app/services/fusion_engine.py@@ -163,12 +163,19 @@ class FusionEngine:alert_id=str(alert.id),original_id=original_id,)+ # A decodable but non-UUID cache value must not turn a valid alert+ # into an unhandled exception: the duplicate verdict stands, only+ # the back-reference is dropped.+ try:+ duplicate_of = UUID(original_id) if original_id else None+ except (AttributeError, TypeError, ValueError):+ duplicate_of = Nonereturn FusedAlert(id=alert.id,tenant_id=alert.tenant_id,incident_id=None,fusion_decision=FusionDecision.DUPLICATE,- duplicate_of=UUID(original_id) if original_id else None,+ duplicate_of=duplicate_of,alert=alert,)diff --git a/services/fusion/app/services/lake_writer.py b/services/fusion/app/services/lake_writer.pyindex a7f81e9c4..089c1583b 100644--- a/services/fusion/app/services/lake_writer.py+++ b/services/fusion/app/services/lake_writer.py@@ -15,17 +15,23 @@ queryable in the lake.Design constraints (mirroring ``AlertSink``):* **Fail-soft.** A ClickHouse outage must degrade to "events still flow through- Kafka/fusion, lake archival is dropped for the outage window" — never crash- the consumer. A failed flush drops that batch (best-effort archival) rather- than growing an unbounded in-memory buffer.+ Kafka/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 bufferedand flushed by size (``batch_size``) or age (``batch_max_age_seconds``); theconsumer 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 row- carries the ingest event id (when it is a valid UUID) so downstream queries- can ``argMax``/``LIMIT 1 BY event_id`` if exact-once is required. The Phase A1- gate asserts *queryability* (``count >= 1``), not exact-once.+ carries a stable identity so downstream queries can ``argMax``/``LIMIT 1 BY+ event_id`` if exact-once is required. Ingest ids are used verbatim when they+ are UUIDs; a non-UUID ingest id is mapped through a fixed UUIDv5 namespace,+ and an event with no id at all is keyed by its Kafka coordinates. Both are+ stable across retries *and process restarts* — a random id generated in+ memory was not, so a replay after a crash could not be collapsed. The Phase+ A1 gate asserts *queryability* (``count >= 1``), not exact-once.``clickhouse-driver`` is synchronous, so every insert is dispatched to a workerthread via :func:`asyncio.to_thread` to keep the fusion event loop responsive.@@ -38,6 +44,7 @@ from __future__ import annotationsimport asyncioimport ipaddressimport json+import randomimport timeimport uuidfrom datetime import UTC, datetime@@ -113,6 +120,36 @@ _INSERT_SQL = f"INSERT INTO aisoc.raw_events ({', '.join(_COLUMNS)}) VALUES"# ClickHouse IPv6 columns reject empty/invalid strings; "::" is the safe null._NULL_IP = "::"+#: Fixed namespace for deterministic lake identities. Never change it: every+#: replayed event would then look new to `LIMIT 1 BY event_id`, which is the+#: property the namespace exists to provide.+_EVENT_ID_NAMESPACE = uuid.uuid5(uuid.NAMESPACE_URL, "https://aisoc.dev/fusion/lake/event-id")+++def _stable_event_id(raw_id: Any) -> str | None:+ """A deterministic UUID for an ingest id that is not one already.++ Ingest derives its ids with UUIDv5, but the raw-events topic also accepts+ envelopes from other producers (and from older versions) whose ``id`` is+ not a UUID. Generating a random one made the lake row's identity depend on+ the process that wrote it: replaying the same Kafka message after a restart+ produced a second id for the same event.++ A UUIDv5 over the ingest id is stable across attempts *and* restarts, and+ still distinguishes two events that carry different ids. An absent/empty+ id returns ``None``; :meth:`LakeWriter.write_event` fills that from the+ Kafka coordinates, which are equally replay-stable.+ """+ if raw_id is None:+ return None+ text = str(raw_id)+ if not text:+ return None+ try:+ return str(uuid.UUID(text))+ except (ValueError, AttributeError, TypeError):+ return str(uuid.uuid5(_EVENT_ID_NAMESPACE, f"ingest:{text}"))+def _get(obj: Any, *path: str) -> Any:cur: Any = obj@@ -346,18 +383,58 @@ def event_to_row(message: dict[str, Any]) -> dict[str, Any] | None:**_activity_columns(ocsf),}- # Only set a deterministic event_id when the ingest id is a real UUID;- # otherwise let ClickHouse default generateUUIDv4().+ # Only carry the ingest id when it identifies the event. A UUID is used+ # verbatim; a non-UUID id is mapped through the fixed namespace so a replay+ # (including one after a process restart) keeps the same row identity.+ # `write_event` fills a missing id from the Kafka coordinates, because the+ # driver cannot leave a column to its DEFAULT: it reads `row[name]` for+ # every column named in the INSERT.raw_id = message.get("id") or message.get("event_id")- try:- row["event_id"] = str(uuid.UUID(str(raw_id)))- except (TypeError, ValueError):- row["event_id"] = None+ row["event_id"] = _stable_event_id(raw_id)return row+def _is_connection_lake_error(exc: BaseException) -> bool:+ """Whether a failed lake insert looks like transport, not bad data.++ A ClickHouse outage and a schema mismatch both raise from ``execute``. They+ need different answers: retain the batch for the outage, but count and+ eventually discard a batch the server keeps rejecting. Guessing wrong in+ the outage direction loses events; guessing wrong in the data direction+ grows the buffer until it hits its explicit bound.+ """+ name = type(exc).__name__.lower()+ if any(marker in name for marker in ("network", "socket", "timeout", "connection", "unavailable")):+ return True+ text = str(exc).lower()+ return any(+ marker in text+ for marker in (+ "connection",+ "connect",+ "refused",+ "reset",+ "timed out",+ "timeout",+ "unavailable",+ "clickhouse down",+ "server is not",+ "can't connect",+ "cannot connect",+ )+ )++class LakeWriter:- """Batched, fail-soft ClickHouse writer for the ``aisoc.raw_events`` lake."""+ """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.+ """def __init__(self,@@ -369,7 +446,23 @@ class LakeWriter:password: str = "",batch_size: int = 100,batch_max_age_seconds: float = 2.0,+ max_buffer_rows: int | None = None,+ reconnect_base_seconds: float | None = None,+ reconnect_max_seconds: float | None = None,+ max_data_failures: int | None = None,+ client_factory: Any | 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+ # `test_backtest_lake_live.py` load THIS file by path precisely so the+ # fusion service's `app` package never has to be on `sys.path` beside+ # the API service's identically-named one. A module-scope+ # `from app.core.config import ...` resolves to whichever `app` the+ # process happens to hold — the API's, whose config pulls in+ # `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+self._host = hostself._port = portself._database = database@@ -377,37 +470,101 @@ class LakeWriter:self._password = passwordself._batch_size = max(1, batch_size)self._batch_max_age = batch_max_age_seconds+ self._max_buffer_rows = max(self._batch_size, int(max_buffer_rows or settings.lake_max_buffer_rows))+ base_seconds = reconnect_base_seconds if reconnect_base_seconds is not None else settings.lake_reconnect_base_seconds+ self._reconnect_base = max(0.0, float(base_seconds))+ self._reconnect_max = max(self._reconnect_base, float(reconnect_max_seconds or settings.lake_reconnect_max_seconds))+ self._max_data_failures = max(1, int(max_data_failures or settings.lake_max_data_failures))+ self._client_factory = client_factoryself._client: Any | None = Noneself._buffer: list[dict[str, Any]] = []self._buffer_started_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+ self._next_reconnect_at = 0.0+ self._reconnect_attempt = 0+ self._data_failures = 0self.rows_written = 0self.flush_failures = 0+ self.rows_dropped = 0+ self.connect_failures = 0+ self.reconnects = 0async def start(self) -> None:if self._disabled:return- try:- from clickhouse_driver import Client # noqa: PLC0415-- self._client = Client(- host=self._host,- port=self._port,- database=self._database,- user=self._user,- password=self._password or "",- connect_timeout=10,- )+ self._client = self._make_client()+ if self._client is not None:logger.info("lake_writer.started", host=self._host, database=self._database)++ def _make_client(self) -> Any | None:+ try:+ if self._client_factory is not None:+ client = self._client_factory()+ else:+ from clickhouse_driver import Client # noqa: PLC0415++ client = Client(+ host=self._host,+ port=self._port,+ database=self._database,+ user=self._user,+ password=self._password or "",+ connect_timeout=10,+ send_receive_timeout=30,+ )except ImportError:self._disabled = Truelogger.warning("lake_writer.disabled_no_driver")+ return Noneexcept Exception as exc: # noqa: BLE001 — degrade, never crash the worker- self._disabled = True- logger.error("lake_writer.connect_failed", error=str(exc))+ self.connect_failures += 1+ self._schedule_reconnect()+ logger.error(+ "lake_writer.connect_failed",+ error=str(exc),+ retry_in_seconds=round(max(0.0, self._next_reconnect_at - time.monotonic()), 1),+ )+ return None++ was_degraded = self._reconnect_attempt > 0+ self._reconnect_attempt = 0+ self._next_reconnect_at = 0.0+ if was_degraded:+ self.reconnects += 1+ logger.info("lake_writer.reconnected", host=self._host)+ return client++ def _schedule_reconnect(self) -> None:+ exponent = min(self._reconnect_attempt, 16)+ delay = min(self._reconnect_max, self._reconnect_base * (2**exponent))+ # Full jitter over [delay/2, delay) avoids a thundering herd of fusion+ # replicas reconnecting to the same ClickHouse at the same instant.+ self._next_reconnect_at = time.monotonic() + (delay / 2) + (random.random() * delay / 2)+ self._reconnect_attempt += 1++ def _ensure_client(self) -> Any | None:+ if self._client is not None:+ return self._client+ if time.monotonic() < self._next_reconnect_at:+ return None+ self._client = self._make_client()+ return self._clientasync 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",+ )if self._client is not None:try:await asyncio.to_thread(self._client.disconnect)@@ -415,23 +572,77 @@ class LakeWriter:logger.warning("lake_writer.disconnect_failed", error=str(exc))self._client = None- async def write_event(self, message: dict[str, Any]) -> bool:+ async def write_event(+ self,+ message: dict[str, Any],+ *,+ topic: str | None = None,+ partition: int | None = None,+ offset: int | None = None,+ ) -> bool:"""Buffer one normalized event for the lake. Returns True if buffered.- Flushes automatically when the buffer reaches ``batch_size``.+ 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.++ ``topic``/``partition``/``offset`` are the Kafka coordinates of the+ record being archived. They are the fallback identity for an envelope+ that carries no ingest id: the same record re-delivered after a restart+ has the same coordinates, so it keeps the same lake ``event_id``."""if self._disabled:return Falserow = event_to_row(message)if row is None:return False+ if row["event_id"] is None:+ # The driver must still *bind* every column: it builds a block from+ # the INSERT's column list and reads `row[name]` for each column,+ # so an omitted key is a KeyError before a byte is sent — not the+ # column DEFAULT. The id is deterministic, so a retry of a+ # 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:await self.flush()+ self._enforce_buffer_capacity()return True+ @staticmethod+ def _fallback_event_id(+ row: dict[str, Any],+ *,+ topic: str | None,+ partition: int | None,+ offset: int | None,+ ) -> str:+ """Identity for an event with neither an ingest id nor a UUID one.++ Kafka coordinates are preferred because they distinguish two distinct+ records that happen to carry identical content. A direct caller that+ supplies neither coordinates nor an id gets a content hash: still+ stable across restarts, but byte-identical events collapse to one id.+ The consumer always supplies coordinates, so production does not take+ that branch.+ """+ if topic is not None and partition is not None and offset is not None:+ return str(uuid.uuid5(_EVENT_ID_NAMESPACE, f"kafka:{topic}:{partition}:{offset}"))+ material = json.dumps(+ {+ "tenant_id": row.get("tenant_id"),+ "event_time": row.get("event_time"),+ "class_uid": row.get("class_uid"),+ "ocsf_json": row.get("ocsf_json"),+ },+ default=str,+ sort_keys=True,+ )+ 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:await self.flush()@@ -439,19 +650,24 @@ class LakeWriter:async def flush(self) -> None:if self._disabled or not self._buffer:return- batch = self._buffer- self._buffer = []- client = self._client+ client = 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+def _insert() -> None:# clickhouse-driver executes INSERT ... VALUES with a list of dicts.- # Coerce the typed columns (IPv6) to the objects the driver binds,- # and omit event_id when None so the column DEFAULT applies.+ # Coerce the typed columns (IPv6) to the objects the driver binds.+ # Every column in `_COLUMNS` must be a key in every row: the driver+ # reads `row[name]` per column, so a missing key raises KeyError+ # before a byte is sent and the column DEFAULT never gets a chance.rows: list[dict[str, Any]] = []for row in batch:- out = {k: v for k, v in row.items() if not (k == "event_id" and v is None)}+ out = dict(row)out["source_ip"] = _to_ip_obj(row["source_ip"])out["dest_ip"] = _to_ip_obj(row["dest_ip"])rows.append(out)@@ -460,13 +676,76 @@ class LakeWriter:try:await asyncio.to_thread(_insert)self.rows_written += len(batch)- except Exception as exc: # noqa: BLE001 — best-effort archival; drop the batch+ self._data_failures = 0+ except 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()+ raise+ except Exception as exc: # noqa: BLE001 — never raise into the consumerself.flush_failures += 1- logger.error("lake_writer.flush_failed", error=str(exc), dropped=len(batch))+ connection_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.+ self._client = None+ 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+ 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++ logger.error(+ "lake_writer.flush_failed",+ error=str(exc),+ retained=len(self._buffer),+ dropped_on_overflow=overflow,+ retryable=connection_error,+ retry_in_seconds=round(max(0.0, self._next_reconnect_at - time.monotonic()), 1),+ )++ 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 overflowdef metrics(self) -> dict[str, int]:return {"rows_written": self.rows_written,"flush_failures": self.flush_failures,"buffered": len(self._buffer),+ "rows_dropped": self.rows_dropped,+ "connect_failures": self.connect_failures,+ "reconnects": self.reconnects,}diff --git a/services/fusion/app/workers/consumer.py b/services/fusion/app/workers/consumer.pyindex c75cdebc9..2e30323a2 100644--- a/services/fusion/app/workers/consumer.py+++ b/services/fusion/app/workers/consumer.py@@ -7,11 +7,12 @@ results back to Kafka, and persists non-duplicate alerts to Postgres.import asyncioimport contextlibimport json+import randomimport timefrom typing import Anyimport structlog-from aiokafka import AIOKafkaConsumer, AIOKafkaProducer+from aiokafka import AIOKafkaConsumer, AIOKafkaProducer, TopicPartitionfrom app.core.config import settingsfrom app.core.kafka_security import kafka_client_kwargs@@ -42,6 +43,7 @@ _METRICS = {"persisted": 0,"persist_unavailable": 0,"persist_failed": 0,+ "persist_retryable": 0,"laked": 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@@ -51,9 +53,70 @@ _METRICS = {"dead_lettered": 0,"errors": 0,"ai_assets_observed": 0,+ # Durability counters. `retried` counts message-level attempts after a+ # transient failure; `retry_exhausted` counts a message whose bounded+ # budget ran out; `recovery_holds` counts the catastrophic case where the+ # store *and* the DLQ are down and the message is deliberately held+ # uncommitted until one returns.+ "retried": 0,+ "retry_exhausted": 0,+ "recovery_holds": 0,+ "publish_failed": 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.+ "durable_capture": 0,}+class _UnparseableRecord:+ """A Kafka value that is not UTF-8 JSON.++ The deserializer runs inside aiokafka's fetch, before the consume loop sees+ a record, so letting ``json.loads`` raise there ends the iterator and stops+ fusion: one malformed byte string becomes a remote kill switch. Carrying the+ text instead lets the normal dead-letter path capture it with its offset.+ """++ __slots__ = ("text",)++ def __init__(self, raw: bytes | None) -> None:+ self.text = (raw or b"").decode("utf-8", errors="replace")+++def _decode_record_value(raw: bytes | None) -> Any:+ """Deserialize a Kafka value, or mark it for the DLQ instead of raising.++ aiokafka applies this while building the record. An exception here is not a+ per-message failure the loop can catch — it propagates out of the iterator+ and terminates consumption.+ """+ try:+ return json.loads((raw or b"").decode("utf-8"))+ except (UnicodeDecodeError, ValueError, TypeError, RecursionError):+ # JSONDecodeError is a ValueError; RecursionError covers a deeply+ # nested body that would otherwise take the iterator down too.+ return _UnparseableRecord(raw)+++class RetryableProcessingError(RuntimeError):+ """A transient failure: re-running the message could succeed.++ The consumer must not commit the Kafka offset for this message. The sink+ has already classified the failure (connection lost, timeout, pool+ exhausted); this type is how that classification crosses the service+ boundary without string matching in the loop.+ """+++class PermanentProcessingError(RuntimeError):+ """A deterministic failure: a retry would fail the same way.++ Captured by the DLQ and only then committed. Examples: an unknown tenant+ (foreign-key violation) or a row the database rejects as invalid.+ """++#: How often the worker sweeps for derived sessions that have gone quiet.#: A quarter of the idle window, so a session is closed within roughly#: DERIVED_IDLE_SECONDS of its last event rather than up to twice that.@@ -101,11 +164,27 @@ class FusionWorker:# A poison message must never vanish silently; default to a structured# logging DLQ so persistence-free deployments still get the signal.self._dlq: DeadLetterQueue = dlq or LoggingDLQ()+ #: Whether a successful DLQ capture is durable storage. The default+ #: `LoggingDLQ` is not: it emits a line and returns True. In that mode+ #: a committed offset means "processed", not "durably captured", and+ #: the service must say so rather than let the invariant be inferred+ #: from the retry machinery.+ self._durable_capture = bool(getattr(self._dlq, "durable", False))+ _METRICS["durable_capture"] = int(self._durable_capture)self._consumer: AIOKafkaConsumer | None = Noneself._producer: AIOKafkaProducer | None = Noneself._running = Falseself._attached = Falseself._flush_task: asyncio.Task | None = None+ #: Signalled by stop() so retry sleeps wake immediately instead of+ #: making shutdown wait out an exponential backoff.+ self._stop_event = asyncio.Event()+ #: Set while the consume loop is running, cleared when it exits. stop()+ #: waits on this so it never closes the Kafka clients underneath an+ #: in-flight message; an unfinished message is left uncommitted.+ self._loop_done = asyncio.Event()+ self._loop_done.set()+ self._inflight = 0@propertydef engine(self) -> FusionEngine:@@ -122,7 +201,19 @@ class FusionWorker:"""return self._attached+ @property+ def durable_capture(self) -> bool:+ """Whether a committed offset implies a durable capture on failure.++ False in the explicitly persistence-free mode: the default+ `LoggingDLQ` writes a log line, and a deployment with+ ``AISOC_ALERT_SINK_ENABLED=false`` persists no alert rows either. The+ retry/hold machinery still runs, but it cannot make a log line durable.+ """+ return self._durable_capture+async def start(self) -> None:+ self._stop_event.clear()topics = [settings.kafka_topic_alerts_raw]# Subscribe to raw_events when EITHER promotion or lake archival needs# it — the lake must fill even if promotion is turned off.@@ -141,7 +232,7 @@ class FusionWorker:# processed (see _consume_loop), not on a background timer that could# commit an in-flight message before processing finishes.enable_auto_commit=False,- value_deserializer=lambda m: json.loads(m.decode("utf-8")),+ value_deserializer=_decode_record_value,**kafka_client_kwargs(),)self._producer = AIOKafkaProducer(@@ -168,6 +259,15 @@ class FusionWorker:# months of unrelated activity under one id.self._flush_task = asyncio.create_task(self._periodic_flush())self._running = True+ if not self._durable_capture:+ logger.warning(+ "fusion.persistence_free_mode",+ dlq=type(self._dlq).__name__,+ alert_sink=self._sink is not None,+ detail=(+ "no durable DLQ is configured; dead letters are log-only and a committed offset means processed, not durably captured"+ ),+ )logger.info("Fusion worker started",consumer_group=settings.kafka_consumer_group,@@ -207,11 +307,37 @@ class FusionWorker:async def stop(self) -> None:self._running = False+ # Wake any retry/backoff sleep. Without this a 30s backoff would make+ # every rolling restart look like a hang.+ self._stop_event.set()if self._flush_task is not None:self._flush_task.cancel()with contextlib.suppress(asyncio.CancelledError):_ = await self._flush_task # await the cancellation to settleself._flush_task = None++ # Let an in-flight message finish (and, if it succeeded, commit)+ # before tearing the clients down. Closing Kafka underneath the loop+ # was a race: the message could be half-processed while its offset+ # looked committed. On timeout we proceed with the offset uncommitted+ # so Kafka re-delivers it.+ #+ # Only wait when a message is actually in flight. An idle loop is+ # blocked in the consumer iterator and cannot observe `_running`; if+ # we waited on it here, every clean shutdown would burn the full grace+ # period for a message that does not exist. Closing the consumer below+ # wakes that iterator instead.+ if not self._loop_done.is_set() and self._inflight > 0:+ try:+ await asyncio.wait_for(self._loop_done.wait(), timeout=max(0.0, settings.shutdown_grace_seconds))+ except TimeoutError:+ logger.warning(+ "fusion.shutdown_grace_expired",+ grace_seconds=settings.shutdown_grace_seconds,+ inflight=self._inflight,+ detail="in-flight message left uncommitted; Kafka will re-deliver it",+ )+if self._consumer:await self._consumer.stop()if self._producer:@@ -224,7 +350,7 @@ class FusionWorker:# not discard up to 30 seconds of sightings.if self._ai_assets is not None:await self._ai_assets.flush()- logger.info("Fusion worker stopped", metrics=_METRICS)+ logger.info("Fusion worker stopped", metrics=_METRICS, inflight=self._inflight)async def _consume_loop(self) -> None:# `start()` is the only caller and assigns `_consumer` before getting@@ -239,40 +365,228 @@ class FusionWorker:# readiness probe app/main.py registers. Cleared in the ``finally`` so# every exit path reports the same way, including one that raises.self._attached = True+ self._loop_done.clear()try:async for msg in consumer:- if not self._running:+ if not self._running or self._stop_event.is_set():break+ self._inflight += 1try:- await self._process_message(msg.value, topic=msg.topic, partition=msg.partition, offset=msg.offset)- except Exception as exc:- _METRICS["errors"] += 1- logger.error("Failed to process message", error=str(exc), exc_info=True)- else:+ handled = await self._handle_message(msg)++ if not handled:+ # The message could not be made durable and could not+ # be captured. Do not commit: leaving the offset+ # untouched is the only outcome that guarantees Kafka+ # re-delivers it.+ logger.error(+ "fusion.message_not_durable",+ topic=msg.topic,+ partition=msg.partition,+ offset=msg.offset,+ detail="offset not committed; the message will be re-delivered",+ )+ break+# At-least-once: commit only after the message is handled# (validated + laked + promoted, or dead-lettered). A crash- # before this line re-delivers the in-flight message on restart- # instead of losing it. Commit failure => reprocess on restart.+ # before this line re-delivers the in-flight message on+ # restart instead of losing it. Commit failure => reprocess+ # on restart.+ #+ # Commit *this* partition's next offset, not every consumed+ # position. ``commit()`` with no argument acknowledges all+ # partitions up to the fetcher's position, which can include+ # records from another partition that have been fetched but+ # not handled yet. That is the same skip-ahead defect this+ # loop exists to prevent, one partition over.+ checkpoint = {TopicPartition(msg.topic, msg.partition): msg.offset + 1}try:- await consumer.commit()+ await consumer.commit(checkpoint)except Exception as commit_exc: # noqa: BLE001logger.warning("fusion.commit_failed", error=str(commit_exc))- # Flush any stale lake batch so archival isn't stranded during a- # low-traffic window (batch fills by size OR age).- #- # Guarded, because this await sat outside the per-message- # try/except: a ClickHouse outage raising here left the- # ``async for`` entirely and stopped fusion consuming, with the- # archive fault reported as nothing at all. Archival falling- # behind must not cost the alert path.- if self._lake is not None:- try:- await self._lake.flush_if_stale()- except Exception as flush_exc: # noqa: BLE001 — the lake is not the alert path- _METRICS["errors"] += 1- logger.error("fusion.lake_flush_failed", error=str(flush_exc), exc_info=True)++ # Flush any stale lake batch so archival isn't stranded+ # during a low-traffic window (batch fills by size OR age).+ #+ # Guarded, because this await sat outside the per-message+ # try/except: a ClickHouse outage raising here left the+ # ``async for`` entirely and stopped fusion consuming, with+ # the archive fault reported as nothing at all. Archival+ # falling behind must not cost the alert path.+ if self._lake is not None:+ try:+ await self._lake.flush_if_stale()+ except Exception as flush_exc: # noqa: BLE001 — the lake is not the alert path+ _METRICS["errors"] += 1+ logger.error("fusion.lake_flush_failed", error=str(flush_exc), exc_info=True)+ finally:+ # Decremented only after commit and lake flush. ``stop()``+ # uses this counter to decide whether it must wait: hitting+ # zero while a commit is still in flight would let shutdown+ # close the consumer underneath it.+ self._inflight -= 1++ if not self._running or self._stop_event.is_set():+ breakfinally:self._attached = False+ self._loop_done.set()++ async def _handle_message(self, msg: Any) -> bool:+ """Process one Kafka record, returning whether its offset may commit.++ Transient failures are retried with exponential backoff + jitter. When+ the bounded budget is exhausted the message is captured by the DLQ; if+ the DLQ is also unreachable the message is held (and never committed)+ until either store returns, because the alternative — committing a+ message that exists nowhere durable — is the silent loss this loop+ exists to prevent.++ ``False`` means "do not commit"; the consume loop stops rather than+ racing ahead of an un-durable offset.+ """+ if isinstance(msg.value, _UnparseableRecord):+ # The deserializer could not parse this record, so it never became+ # a dict the pipeline could validate. Capture it like any other+ # poison message; a failed capture holds the offset.+ return await self._dead_letter_or_hold(+ topic=msg.topic,+ payload=msg.value.text,+ reason="kafka value is not valid JSON",+ partition=msg.partition,+ offset=msg.offset,+ )++ attempt = 0+ max_retries = max(0, settings.consumer_max_retries)+ while True:+ if not self._running or self._stop_event.is_set():+ return False+ try:+ await self._process_message(+ msg.value,+ topic=msg.topic,+ partition=msg.partition,+ offset=msg.offset,+ )+ return True+ except asyncio.CancelledError:+ raise+ except RetryableProcessingError as exc:+ attempt += 1+ if attempt <= max_retries:+ _METRICS["retried"] += 1+ delay = self._retry_delay(attempt)+ logger.warning(+ "fusion.message_retry",+ attempt=attempt,+ max_retries=max_retries,+ retry_in_seconds=round(delay, 2),+ topic=msg.topic,+ partition=msg.partition,+ offset=msg.offset,+ error=str(exc),+ )+ if not await self._sleep_with_shutdown(delay):+ return False+ continue++ _METRICS["retry_exhausted"] += 1+ logger.error(+ "fusion.retry_exhausted",+ attempts=attempt,+ topic=msg.topic,+ partition=msg.partition,+ offset=msg.offset,+ error=str(exc),+ )+ captured = await self._dead_letter_or_hold(+ topic=msg.topic,+ payload=msg.value,+ reason=f"transient processing failure after {attempt} attempts: {exc}",+ partition=msg.partition,+ offset=msg.offset,+ )+ return captured+ except PermanentProcessingError as exc:+ # `persist_failed` is incremented by the sink path itself;+ # counting it here too would double-report one rejected row.+ _METRICS["errors"] += 1+ return await self._dead_letter_or_hold(+ topic=msg.topic,+ payload=msg.value,+ reason=f"permanent processing failure: {exc}",+ partition=msg.partition,+ offset=msg.offset,+ )+ except Exception as exc:+ # An unexpected exception is not safe to commit past: the old+ # loop logged it and then committed the *next* message's+ # offset, skipping this one permanently. Capture it instead.+ _METRICS["errors"] += 1+ logger.error(+ "fusion.unhandled_processing_error",+ topic=msg.topic,+ partition=msg.partition,+ offset=msg.offset,+ error=str(exc),+ exc_info=True,+ )+ return await self._dead_letter_or_hold(+ topic=msg.topic,+ payload=msg.value,+ reason=f"unhandled processing error: {exc}",+ partition=msg.partition,+ offset=msg.offset,+ )++ def _retry_delay(self, attempt: int) -> float:+ """Capped exponential backoff with jitter.++ ``attempt`` is 1-based. The upper half of the exponential window is+ used so retries do not all land on the same millisecond; the cap means+ a long outage settles into a steady probe rather than unbounded waits.+ """+ base = max(0.0, settings.consumer_retry_base_seconds)+ cap = max(base, settings.consumer_retry_max_seconds)+ window = min(cap, base * (2 ** min(attempt - 1, 16)))+ return window * (0.5 + random.random() * 0.5)++ async def _sleep_with_shutdown(self, seconds: float) -> bool:+ """Sleep, waking early on shutdown. False means shutdown was requested."""+ if seconds <= 0:+ await asyncio.sleep(0)+ return self._running and not self._stop_event.is_set()+ try:+ await asyncio.wait_for(self._stop_event.wait(), timeout=seconds)+ except TimeoutError:+ return self._running+ return False++ async def _dead_letter_or_hold(self, **kwargs: Any) -> bool:+ """Capture a message, or hold it uncommitted while the DLQ is down.++ Returns True only once the message is in a durable capture (or the+ logging DLQ, which is the configured sink and always succeeds). A+ failure to capture is *not* a licence to commit.+ """+ while self._running and not self._stop_event.is_set():+ if await self._dead_letter(**kwargs):+ return True+ _METRICS["recovery_holds"] += 1+ logger.critical(+ "fusion.recovery_hold",+ topic=kwargs.get("topic"),+ partition=kwargs.get("partition"),+ offset=kwargs.get("offset"),+ reason=kwargs.get("reason"),+ retry_in_seconds=settings.consumer_recovery_retry_seconds,+ detail="primary store and DLQ unavailable; message held uncommitted",+ )+ if not await self._sleep_with_shutdown(max(0.1, settings.consumer_recovery_retry_seconds)):+ return False+ return Falseasync def _dead_letter(self,@@ -285,16 +599,18 @@ class FusionWorker:tenant_id: str | None = None,partition: int | None = None,offset: int | None = None,- ) -> None:+ ) -> bool:"""Route a poison message to the DLQ instead of dropping it silently.``partition`` and ``offset`` are carried through because the excerptstored alongside them is a triage record, not the event: replaying arefused message means re-reading it from Kafka, and these are the onlyway back to it (deferral 5b).++ Returns whether the capture succeeded. Callers deciding whether to+ commit must use the answer: a failed DLQ write is not a capture."""- _METRICS["dead_lettered"] += 1- await safe_record(+ recorded = await safe_record(self._dlq,DeadLetter.build(topic=topic,@@ -307,6 +623,9 @@ class FusionWorker:offset=offset,),)+ if recorded:+ _METRICS["dead_lettered"] += 1+ return recordedasync def _process_message(self, payload: dict, topic: str | None = None, partition: int | None = None, offset: int | None = None@@ -329,7 +648,7 @@ class FusionWorker:alerts_raw_topic=settings.kafka_topic_alerts_raw,)if not validation.ok:- await self._dead_letter(+ if not await self._dead_letter(topic=resolved_topic,payload=payload,reason=validation.reason,@@ -338,7 +657,10 @@ class FusionWorker:tenant_id=validation.tenant_id,partition=partition,offset=offset,- )+ ):+ # A refused message whose capture failed is still unhandled.+ # Returning here would let the loop commit its offset.+ raise PermanentProcessingError(f"dead-letter capture failed for {validation.reason}")return# Declared ahead of the branch because the tail call below is shared.@@ -368,7 +690,7 @@ 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):+ if self._lake is not None and await self._lake.write_event(payload, topic=resolved_topic, partition=partition, offset=offset):_METRICS["laked"] += 1# Depth 6.1 — the observed AI estate is built here rather than by@@ -434,16 +756,18 @@ class FusionWorker:except Exception as exc:# Deep validation failure — dead-letter it (the schema layer# only caught gross shape); never silently drop.- await self._dead_letter(+ reason = f"RawAlert validation failed: {exc}"+ if not await self._dead_letter(topic=resolved_topic,payload=payload,- reason=f"RawAlert validation failed: {exc}",+ reason=reason,schema_version=validation.schema_version,source_event_id=validation.source_event_id,tenant_id=validation.tenant_id,partition=partition,offset=offset,- )+ ):+ raise PermanentProcessingError(f"dead-letter capture failed for {reason}") from excreturnawait self._fuse_and_persist(alert, source_event_id=validation.source_event_id, session=session)@@ -490,21 +814,46 @@ class FusionWorker:_METRICS["persisted"] += 1elif result.outcome is PersistOutcome.UNAVAILABLE:_METRICS["persist_unavailable"] += 1+ _METRICS["persist_retryable"] += 1elif result.outcome is PersistOutcome.FAILED:_METRICS["persist_failed"] += 1+ if result.retryable:+ _METRICS["persist_retryable"] += 1++ if not result.durable:+ # The offset must not move until the row is known to exist.+ # A transient failure is retried (with the Kafka message still+ # uncommitted); a permanent one is dead-lettered by the loop.+ if result.retryable or result.outcome is PersistOutcome.UNAVAILABLE:+ raise RetryableProcessingError(f"alert {fused.id} not durable: {result.outcome.value}")+ raise PermanentProcessingError(f"alert {fused.id} rejected by the alert store: {result.outcome.value}")# Publish fused alert (even duplicates, so downstream can track),# carrying the durable row id + persistence outcome (issue #568).+ # Publishing only after durability means a downstream consumer never+ # sees a row id that does not exist in Postgres.envelope = fused.model_dump(mode="json")envelope["alert_row_id"] = result.alert_idenvelope["persist_outcome"] = result.outcome.valueproducer = self._producerif producer is None: # pragma: no cover — assigned by start()raise RuntimeError("fusion produced a fused alert before the Kafka producer started")- await producer.send(- settings.kafka_topic_alerts_fused,- value=envelope,- )+ try:+ await asyncio.wait_for(+ producer.send(+ settings.kafka_topic_alerts_fused,+ value=envelope,+ ),+ timeout=max(0.1, settings.kafka_send_timeout_seconds),+ )+ except asyncio.CancelledError:+ raise+ except Exception as exc:+ # 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.+ _METRICS["publish_failed"] += 1+ raise RetryableProcessingError(f"fused alert publish failed: {exc}") from exc@staticmethoddef get_metrics() -> dict:diff --git a/services/fusion/tests/test_alert_sink.py b/services/fusion/tests/test_alert_sink.pyindex 65fa4c1d9..c41a0c238 100644--- a/services/fusion/tests/test_alert_sink.py+++ b/services/fusion/tests/test_alert_sink.py@@ -58,19 +58,29 @@ def _fused(decision: FusionDecision = FusionDecision.NEW_ALERT) -> FusedAlert:)+_UNSET = object()++class _StubConn:- def __init__(self, row):+ def __init__(self, row, surviving=_UNSET):self._row = row+ # The reconciliation SELECT and the INSERT are two different+ # statements. A single scripted row cannot answer both without+ # pretending the insert happened when it was filtered out.+ self._surviving = row if surviving is _UNSET else survivingself.calls: list[tuple] = []async def fetchrow(self, sql, *args):self.calls.append((sql, args))+ lowered = sql.lower().lstrip()+ if lowered.startswith("select") and "from alerts" in lowered and "dedup_hash" in lowered:+ return self._survivingreturn self._rowclass _StubPool:- def __init__(self, row):- self.conn = _StubConn(row)+ def __init__(self, row, surviving=_UNSET):+ self.conn = _StubConn(row, surviving=surviving)@asynccontextmanagerasync def _acquire(self):@@ -95,12 +105,36 @@ def test_iocs_and_entities_extraction():@pytest.mark.asyncio-async def test_duplicate_decision_is_never_persisted():+async def test_duplicate_decision_is_verified_before_it_is_trusted():+ """A DUPLICATE verdict is a hint, not proof that the row exists.++ Fusion writes the dedup fingerprint to Redis before the insert. A crash in+ that window leaves a fingerprint with no row, and the old sink returned+ DUPLICATE without writing anything — permanent loss. The sink now verifies+ the surviving row; when it exists, no second row is written.+ """+ surviving_id = uuid.uuid4()sink = AlertSink("postgresql://x")- sink._pool = _StubPool(row={"id": uuid.uuid4()}) # would succeed if called+ sink._pool = _StubPool(row=None, surviving={"id": surviving_id})result = await sink.persist(_fused(FusionDecision.DUPLICATE))assert result.outcome is PersistOutcome.DUPLICATE- assert sink._pool.conn.calls == []+ assert result.alert_id == str(surviving_id)+ sqls = [sql for sql, _ in sink._pool.conn.calls]+ assert any("FROM alerts" in sql for sql in sqls)+ assert not any("INSERT INTO alerts" in sql for sql in sqls)+++async def test_stale_duplicate_hint_repairs_the_missing_row():+ """The fingerprint survived a crash, but the row did not. Insert it."""+ fused = _fused(FusionDecision.DUPLICATE)+ sink = AlertSink("postgresql://x")+ sink._pool = _StubPool(row={"id": fused.id}, surviving=None)+ result = await sink.persist(fused)+ assert result.outcome is PersistOutcome.INSERTED+ assert result.alert_id == str(fused.id)+ inserts = [sql for sql, _ in sink._pool.conn.calls if "INSERT INTO alerts" in sql]+ assert len(inserts) == 1@pytest.mark.asyncio@@ -133,13 +167,17 @@ async def test_new_alert_is_inserted_with_canonical_id_and_provenance():@pytest.mark.asyncioasync def test_dedup_hit_returns_duplicate():- pool = _StubPool(row=None) # WHERE NOT EXISTS / ON CONFLICT filtered it out+ fused = _fused()+ # WHERE NOT EXISTS filtered the insert out, and the reconciliation read+ # resolves the row that filtered it.+ pool = _StubPool(row=None, surviving={"id": fused.id})sink = AlertSink("postgresql://x")sink._pool = pool- result = await sink.persist(_fused())+ result = await sink.persist(fused)assert result.outcome is PersistOutcome.DUPLICATE- assert result.alert_id == str(_fused().id) # canonical id still known+ assert result.alert_id == str(fused.id)assert result.durable is True+ assert result.verified is True@pytest.mark.asyncio@@ -156,6 +194,26 @@ async def test_db_unavailable_is_distinct_from_duplicate(monkeypatch):assert result.durable is False+async def test_unverifiable_duplicate_is_not_durable(monkeypatch):+ """A correct fusion verdict is not proof of a durable row.++ If the database cannot be asked, the consumer must retry rather than+ commit a duplicate that may never have been written.+ """+ sink = AlertSink("postgresql://nope:[email protected]:1/none")++ async def _fail_start():+ sink._pool = None++ monkeypatch.setattr(sink, "start", _fail_start)+ result = await sink.persist(_fused(FusionDecision.DUPLICATE))+ assert result.outcome is PersistOutcome.DUPLICATE+ assert result.verified is False+ assert result.durable is False+ assert result.retryable is True++@pytest.mark.asyncioasync def test_persist_exception_is_failed_not_duplicate():class _BoomPool(_StubPool):@@ -169,6 +227,44 @@ async def test_persist_exception_is_failed_not_duplicate():assert result.durable is False+async def test_a_broken_pool_is_replaced_without_a_fusion_restart(monkeypatch):+ """A stale pool used to return FAILED forever after Postgres returned."""+ fused = _fused()++ class _BrokenPool:+ def __init__(self):+ self.closed = False++ def acquire(self):+ raise OSError("connection reset by peer")++ async def close(self):+ self.closed = True++ broken = _BrokenPool()+ recovered = _StubPool(row={"id": fused.id})+ sink = AlertSink("postgresql://x")+ sink._pool = broken++ async def reconnect():+ sink._pool = recovered++ monkeypatch.setattr(sink, "start", reconnect)++ first = await sink.persist(fused)+ assert first.outcome is PersistOutcome.FAILED+ assert first.retryable is True+ assert first.durable is False+ assert broken.closed is True+ assert sink._pool is None++ second = await sink.persist(fused)+ assert second.outcome is PersistOutcome.INSERTED+ assert second.durable is True+ assert sink._pool is recovered++def test_deterministic_id_is_replay_stable():# Same tenant + content ⇒ same canonical id across independent builds.a = _fused().alertdiff --git a/services/fusion/tests/test_alert_sink_concurrent_dedup.py b/services/fusion/tests/test_alert_sink_concurrent_dedup.pynew file mode 100644index 000000000..7cf143b86--- /dev/null+++ b/services/fusion/tests/test_alert_sink_concurrent_dedup.py@@ -0,0 +1,324 @@+"""Concurrent writers must not persist two visible rows for one fingerprint.++Migration 120 adds the database-level guarantee: a partial unique index+``uq_alerts_tenant_dedup`` on ``alerts(tenant_id, dedup_hash)``. These tests+exercise the sink's half of that contract with scripted connections — the+loser of the race gets a ``UniqueViolationError`` from the INSERT and must+resolve the winner's row instead of reporting a failure (which would+dead-letter an alert that is already durable) or writing a second alert.++They are deterministic statement-level tests, **not** proof of live PostgreSQL+concurrency. The real-container insert path is gated by+``.github/workflows/integration.yml``; no PostgreSQL instance was available in+this environment. What is pinned here is the sink's handling of the error the+index produces, the tenant scope of the key, and the migration's shape and+precondition.+"""++from __future__ import annotations++import uuid+from contextlib import asynccontextmanager+from pathlib import Path++import asyncpg+import pytest+from app.models.alert import AlertSeverity, FusedAlert, FusionDecision, RawAlert+from app.services.alert_sink import (+ _DEDUP_UNIQUE_INDEX,+ AlertSink,+ PersistOutcome,+)++TENANT = uuid.UUID("00000000-0000-0000-0000-000000000001")+OTHER_TENANT = uuid.UUID("00000000-0000-0000-0000-000000000002")++MIGRATION = Path(__file__).resolve().parents[3] / "services" / "api" / "migrations" / "120_alerts_tenant_dedup_unique.sql"+++class _FixedFingerprintAlert(RawAlert):+ """A raw alert whose dedup hash is supplied rather than derived.++ ``RawAlert.fingerprint()`` includes the tenant, so two tenants cannot+ naturally produce the same hash. The database index is still scoped by+ tenant, and this subclass lets the test prove that the sink passes the+ tenant through rather than relying on the hash alone.+ """++ fixed_fingerprint: str++ def fingerprint(self) -> str:+ return self.fixed_fingerprint+++def _fused(+ *,+ tenant: uuid.UUID = TENANT,+ fingerprint: str | None = None,+ decision: FusionDecision = FusionDecision.NEW_ALERT,+) -> FusedAlert:+ common = {+ "tenant_id": tenant,+ "source": "CrowdStrike Falcon",+ "title": "Credential dumping via LSASS access",+ "severity": AlertSeverity.CRITICAL,+ "src_ip": "10.20.30.40",+ "hostname": "WIN-DC01",+ "username": "svc-backup",+ "mitre_techniques": ["T1003"],+ "source_event_ids": ["evt-1"],+ }+ raw: RawAlert+ if fingerprint is None:+ raw = RawAlert(**common)+ else:+ raw = _FixedFingerprintAlert(**common, fixed_fingerprint=fingerprint)+ raw.id = raw.deterministic_id()+ return FusedAlert(id=raw.id, tenant_id=tenant, fusion_decision=decision, alert=raw)+++def _dedup_conflict() -> asyncpg.UniqueViolationError:+ exc = asyncpg.UniqueViolationError('duplicate key value violates unique constraint "uq_alerts_tenant_dedup"')+ exc.constraint_name = _DEDUP_UNIQUE_INDEX+ return exc+++def _other_unique_conflict() -> asyncpg.UniqueViolationError:+ exc = asyncpg.UniqueViolationError('duplicate key value violates unique constraint "uq_alerts_tenant_idempotency"')+ exc.constraint_name = "uq_alerts_tenant_idempotency"+ return exc+++class _Pool:+ def __init__(self, conn: object) -> None:+ self.conn = conn++ @asynccontextmanager+ async def _acquire(self):+ yield self.conn++ def acquire(self):+ return self._acquire()+++class _RaceConn:+ """Answers the INSERT with a scripted outcome and the SELECT with a row."""++ def __init__(self, insert_outcome, surviving):+ self._insert_outcome = insert_outcome+ self._surviving = surviving+ self.calls: list[tuple] = []++ async def fetchrow(self, sql, *args):+ self.calls.append((sql, args))+ lowered = sql.lower().lstrip()+ if lowered.startswith("select") and "from alerts" in lowered and "dedup_hash" in lowered:+ return self._surviving+ if isinstance(self._insert_outcome, BaseException):+ raise self._insert_outcome+ return self._insert_outcome++ async def execute(self, sql, *args):+ self.calls.append((sql, args))+ return "UPDATE 1"+++class _IndexConn:+ """A tiny model of the unique index, not PostgreSQL.++ It enforces uniqueness on ``(tenant_id, dedup_hash)`` so the test can pin+ the key the sink relies on. It is deliberately not described as a live+ concurrency test.+ """++ def __init__(self) -> None:+ self.rows: dict[tuple[uuid.UUID, str], uuid.UUID] = {}+ self.calls: list[tuple] = []++ async def fetchrow(self, sql, *args):+ self.calls.append((sql, args))+ lowered = sql.lower().lstrip()+ if lowered.startswith("select") and "from alerts" in lowered and "dedup_hash" in lowered:+ key = (args[0], args[1])+ row_id = self.rows.get(key)+ return {"id": row_id} if row_id is not None else None++ # _INSERT_SQL: $1 = id, $2 = tenant_id, $11 = dedup_hash.+ key = (args[1], args[10])+ if key in self.rows:+ raise _dedup_conflict()+ self.rows[key] = args[0]+ return {"id": args[0]}++ async def execute(self, sql, *args):+ self.calls.append((sql, args))+ return "UPDATE 1"+++def _inserts(conn: _RaceConn | _IndexConn) -> list[str]:+ return [sql for sql, _ in conn.calls if "INSERT INTO alerts" in sql]+++async def test_losing_writer_resolves_the_winner_instead_of_inserting_a_second_row():+ """The race the unique index closes: different ids, same tenant + hash."""+ first = _fused(fingerprint="same-fingerprint")+ # A writer that supplies its own id (not the deterministic one) still has+ # the same logical alert. This is the case the primary-key conflict alone+ # could not catch.+ second = first.model_copy(update={"id": uuid.uuid4()})+ assert second.id != first.id++ conn = _IndexConn()+ sink = AlertSink("postgresql://x")+ sink._pool = _Pool(conn)++ inserted = await sink.persist(first)+ raced = await sink.persist(second)++ assert inserted.outcome is PersistOutcome.INSERTED+ assert raced.outcome is PersistOutcome.DUPLICATE+ assert raced.alert_id == str(first.id), "the loser must return the durable winner id"+ assert raced.verified is True+ assert raced.durable is True+ assert len(conn.rows) == 1, "the unique index must leave exactly one visible row"+++async def test_an_unnamed_unique_conflict_still_resolves_the_visible_row():+ """Drivers that do not name the index must not turn a dedup into a loss."""+ fused = _fused(fingerprint="unnamed-conflict")+ exc = asyncpg.UniqueViolationError("duplicate key value violates unique constraint")+ assert exc.constraint_name is None++ conn = _RaceConn(exc, surviving={"id": fused.id})+ sink = AlertSink("postgresql://x")+ sink._pool = _Pool(conn)++ result = await sink.persist(fused)++ assert result.outcome is PersistOutcome.DUPLICATE+ assert result.alert_id == str(fused.id)+ assert result.verified is True+++async def test_conflict_without_a_visible_winner_is_retryable_not_durable():+ """An ambiguous conflict must not be reported as a successful duplicate."""+ fused = _fused(fingerprint="ambiguous")+ conn = _RaceConn(_dedup_conflict(), surviving=None)+ sink = AlertSink("postgresql://x")+ sink._pool = _Pool(conn)++ result = await sink.persist(fused)++ assert result.outcome is PersistOutcome.FAILED+ assert result.retryable is True+ assert result.verified is False+ assert result.durable is False+++async def test_replay_after_an_unresolved_conflict_resolves_the_visible_row():+ """A retry after the ambiguous window must settle on the winner, not fail."""+ fused = _fused(fingerprint="replay")++ first_conn = _RaceConn(_dedup_conflict(), surviving=None)+ first_sink = AlertSink("postgresql://x")+ first_sink._pool = _Pool(first_conn)+ first = await first_sink.persist(fused)+ assert first.outcome is PersistOutcome.FAILED+ assert first.retryable is True++ # On the retry the winner's row is visible, so the WHERE NOT EXISTS guard+ # filters the insert and the reconciliation read resolves it.+ second_conn = _RaceConn(None, surviving={"id": fused.id})+ second_sink = AlertSink("postgresql://x")+ second_sink._pool = _Pool(second_conn)+ second = await second_sink.persist(fused)++ assert second.outcome is PersistOutcome.DUPLICATE+ assert second.alert_id == str(fused.id)+ assert second.verified is True+++async def test_unrelated_unique_violation_is_not_converted_into_a_duplicate():+ """Only the dedup index means duplicate; other constraints stay errors."""+ fused = _fused(fingerprint="other-constraint")+ conn = _RaceConn(_other_unique_conflict(), surviving={"id": uuid.uuid4()})+ sink = AlertSink("postgresql://x")+ sink._pool = _Pool(conn)++ result = await sink.persist(fused)++ assert result.outcome is PersistOutcome.FAILED+ assert result.retryable is False, "a constraint violation is not retryable"+ assert result.durable is False+ assert len(_inserts(conn)) == 1, "the sink must not retry the insert inside one persist call"+++async def test_two_tenants_with_the_same_fingerprint_both_persist():+ """Uniqueness is per tenant, not per hash alone."""+ conn = _IndexConn()+ sink = AlertSink("postgresql://x")+ sink._pool = _Pool(conn)++ first = await sink.persist(_fused(tenant=TENANT, fingerprint="shared-hash"))+ second = await sink.persist(_fused(tenant=OTHER_TENANT, fingerprint="shared-hash"))++ assert first.outcome is PersistOutcome.INSERTED+ assert second.outcome is PersistOutcome.INSERTED+ assert len(conn.rows) == 2+ assert {key[0] for key in conn.rows} == {TENANT, OTHER_TENANT}+++async def test_batch_path_has_the_same_conflict_semantics():+ """`persist_many` must not drift from `persist` on the dedup conflict."""+ first = _fused(fingerprint="batch-race")+ second = first.model_copy(update={"id": uuid.uuid4()})++ conn = _IndexConn()+ sink = AlertSink("postgresql://x")+ sink._pool = _Pool(conn)++ results = await sink.persist_many([first, second])++ assert [r.outcome for r in results] == [+ PersistOutcome.INSERTED,+ PersistOutcome.DUPLICATE,+ ]+ assert results[1].alert_id == str(first.id)+ assert results[1].verified is True+ assert len(conn.rows) == 1+++def test_migration_is_a_partial_unique_index_scoped_per_tenant():+ sql = MIGRATION.read_text(encoding="utf-8")++ assert _DEDUP_UNIQUE_INDEX in sql+ assert "CREATE UNIQUE INDEX IF NOT EXISTS uq_alerts_tenant_dedup" in sql+ assert "ON alerts (tenant_id, dedup_hash)" in sql+ assert "WHERE dedup_hash IS NOT NULL" in sql+++def test_migration_refuses_existing_duplicates_without_rewriting_rows():+ sql = MIGRATION.read_text(encoding="utf-8")+ upper = sql.upper()++ assert "GROUP BY tenant_id, dedup_hash" in sql+ assert "HAVING count(*) > 1" in sql+ assert "RAISE EXCEPTION" in sql+ assert "DELETE FROM ALERTS" not in upper+ assert "UPDATE ALERTS" not in upper+ assert "TRUNCATE" not in upper+++def test_migration_rejects_an_invalid_index_left_by_a_failed_concurrent_build():+ """`IF NOT EXISTS` must not mistake an invalid index for a guarantee."""+ sql = MIGRATION.read_text(encoding="utf-8")++ assert "indisvalid" in sql+ assert "index uq_alerts_tenant_dedup exists but is invalid" in sqldiff --git a/services/fusion/tests/test_alert_sink_issue_1244.py b/services/fusion/tests/test_alert_sink_issue_1244.pyindex 46dc12276..0100ed0dd 100644--- a/services/fusion/tests/test_alert_sink_issue_1244.py+++ b/services/fusion/tests/test_alert_sink_issue_1244.py@@ -59,15 +59,24 @@ def _fused(return FusedAlert(id=raw.id, tenant_id=TENANT, fusion_decision=decision, alert=raw)+_UNSET = object()++class _StubConn:"""Records every statement, and answers fetchrow with a scripted row."""- def __init__(self, row):+ def __init__(self, row, surviving=_UNSET):self._row = row+ # The duplicate-reconciliation SELECT is a different statement from+ # the INSERT; both can be scripted independently.+ self._surviving = row if surviving is _UNSET else survivingself.calls: list[tuple] = []async def fetchrow(self, sql, *args):self.calls.append((sql, args))+ lowered = sql.lower().lstrip()+ if lowered.startswith("select") and "from alerts" in lowered and "dedup_hash" in lowered:+ return self._survivingreturn self._rowasync def execute(self, sql, *args):@@ -76,8 +85,8 @@ class _StubConn:class _StubPool:- def __init__(self, row):- self.conn = _StubConn(row)+ def __init__(self, row, surviving=_UNSET):+ self.conn = _StubConn(row, surviving=surviving)@asynccontextmanagerasync def _acquire(self):@@ -197,7 +206,9 @@ async def test_the_batch_path_writes_the_same_columns() -> None:@pytest.mark.asyncioasync def test_a_dedup_hit_records_the_second_events_id() -> None:"""The defect behind "522 events formed 0 correlation instances"."""- pool = _StubPool(row=None) # WHERE NOT EXISTS filtered the insert out+ # WHERE NOT EXISTS filtered the insert out; the reconciliation read finds+ # the surviving row that filtered it.+ pool = _StubPool(row=None, surviving={"id": uuid.uuid4()})sink = AlertSink("postgresql://x")sink._pool = poolfused = _fused(source_event_ids=["evt-2"])@@ -221,7 +232,7 @@ async def test_a_dedup_hit_records_the_second_events_id() -> None:@pytest.mark.asyncioasync def test_a_fusion_decided_duplicate_is_also_recorded() -> None:"""Fusion's own DUPLICATE verdict returns before the insert is attempted."""- pool = _StubPool(row=None)+ pool = _StubPool(row=None, surviving={"id": uuid.uuid4()})sink = AlertSink("postgresql://x")sink._pool = pool@@ -260,19 +271,25 @@ async def test_an_event_with_no_source_id_issues_no_dedup_update() -> None:@pytest.mark.asyncio-async def test_a_duplicate_verdict_survives_an_unreachable_database() -> None:- """Recording the provenance must not make DUPLICATE depend on the DB.+async def test_a_duplicate_verdict_survives_an_unreachable_database(monkeypatch) -> None:+ """The verdict survives, but it is not reported as durable.- Fusion decided; an outage changes only whether we can write the id down.- The early return has to stay ahead of `_ensure_pool`, or a DUPLICATE- starts reporting UNAVAILABLE and the consumer retries a decision that- was already made.+ Fusion decided duplicate; an outage changes only whether we can verify the+ surviving row. The outcome stays DUPLICATE (so the value is not rewritten+ to UNAVAILABLE), and `verified=False` tells the consumer to retry rather+ than commit a row that may not exist."""sink = AlertSink("postgresql://nope:[email protected]:1/none")- sink._pool = None++ async def _fail_start():+ sink._pool = None++ monkeypatch.setattr(sink, "start", _fail_start)result = await sink.persist(_fused(FusionDecision.DUPLICATE))assert result.outcome is PersistOutcome.DUPLICATE+ assert result.verified is False+ assert result.durable is False@pytest.mark.asyncio@@ -284,8 +301,8 @@ async def test_a_failing_dedup_update_does_not_change_the_outcome() -> None:self.calls.append((sql, args))raise RuntimeError("connection reset")- pool = _StubPool(row=None)- pool.conn = _BoomConn(row=None)+ pool = _StubPool(row=None, surviving={"id": uuid.uuid4()})+ pool.conn = _BoomConn(row=None, surviving={"id": uuid.uuid4()})sink = AlertSink("postgresql://x")sink._pool = pooldiff --git a/services/fusion/tests/test_cache_fallback.py b/services/fusion/tests/test_cache_fallback.pynew file mode 100644index 000000000..8b905743c--- /dev/null+++ b/services/fusion/tests/test_cache_fallback.py@@ -0,0 +1,179 @@+"""Redis is a cache, not the alert store. An outage must degrade, not raise.++The failure being pinned: ``Deduplicator.is_duplicate`` and+``Correlator.correlate`` let ``RedisError`` escape into the fusion engine.+Depending on the caller that either wedged the partition or was swallowed and+its offset committed — with Postgres, the actual source of truth, never+consulted. Both now fail open, and the degradation is counted so it is visible+rather than inferred.+"""++from __future__ import annotations++import pytest+from app.models.alert import AlertSeverity, FusionDecision, RawAlert+from app.services.correlator import Correlator+from app.services.deduplicator import Deduplicator+from app.services.fusion_engine import FusionEngine+from redis.exceptions import ConnectionError as RedisConnectionError+++class _DownRedis:+ async def get(self, *_a, **_k): # noqa: ANN002, ANN003, ANN202+ raise RedisConnectionError("redis is down")++ async def set(self, *_a, **_k): # noqa: ANN002, ANN003, ANN202+ raise RedisConnectionError("redis is down")+++class _HealingRedis:+ def __init__(self) -> None:+ self.down = True+ self.values: dict[str, bytes] = {}++ async def get(self, key): # noqa: ANN001, ANN202+ if self.down:+ raise RedisConnectionError("redis is down")+ return self.values.get(key)++ async def set(self, key, value, **_k): # noqa: ANN001, ANN003, ANN202+ if self.down:+ raise RedisConnectionError("redis is down")+ self.values[key] = str(value).encode()+ return True+++def _alert() -> RawAlert:+ return RawAlert(+ tenant_id="00000000-0000-0000-0000-000000000001",+ source="CrowdStrike Falcon",+ title="Suspicious PowerShell",+ severity=AlertSeverity.HIGH,+ src_ip="10.20.30.40",+ hostname="WIN-DC01",+ mitre_tactics=["Execution"],+ )+++async def test_dedup_fails_open_when_redis_is_down():+ dedup = Deduplicator(_DownRedis())+ is_dup, original = await dedup.is_duplicate(_alert())+ assert (is_dup, original) == (False, None)+ # The write path must not raise either; the DB guard still suppresses the row.+ await dedup.register(_alert())+ metrics = dedup.metrics()+ assert metrics["degraded"] is True+ assert metrics["read_fallbacks"] == 1+ assert metrics["write_fallbacks"] == 1+++async def test_dedup_reports_recovery_after_redis_returns():+ redis = _HealingRedis()+ dedup = Deduplicator(redis)+ assert await dedup.is_duplicate(_alert()) == (False, None)+ assert dedup.metrics()["degraded"] is True++ redis.down = False+ await dedup.register(_alert())+ assert dedup.metrics()["degraded"] is False+ is_dup, original = await dedup.is_duplicate(_alert())+ assert is_dup is True+ assert original is not None+++async def test_correlation_returns_a_single_alert_incident_when_redis_is_down():+ correlator = Correlator(_DownRedis())+ alert = _alert()+ alert.id = alert.deterministic_id()++ correlated, incident = await correlator.correlate(alert)+ assert correlated is False+ assert incident.alert_count == 1+ assert incident.alert_ids == [str(alert.id)]+ assert incident.tenant_id == alert.tenant_id+ assert correlator.metrics()["degraded"] is True+ assert correlator.metrics()["fallbacks"] == 1+++class _CorruptRedis:+ """Redis answers, but with bytes no incident can be parsed from."""++ def __init__(self, payload: bytes) -> None:+ self.payload = payload++ async def get(self, _key): # noqa: ANN001, ANN202+ return self.payload++ async def set(self, _key, _value, **_k): # noqa: ANN001, ANN003, ANN202+ return True+++async def test_dedup_treats_a_corrupt_value_as_a_cache_miss():+ """An undecodable dedup value must not raise into the engine.++ Failing open is safe: Postgres still owns uniqueness, so the worst case is+ a downstream duplicate decision rather than a lost alert.+ """+ dedup = Deduplicator(_CorruptRedis(b"\xff\xfe"))+ is_dup, original = await dedup.is_duplicate(_alert())+ assert (is_dup, original) == (False, None)+++async def test_a_non_uuid_duplicate_reference_does_not_fail_the_alert():+ """A decodable but non-UUID dedup value is still cache data.++ The duplicate verdict stands; only the back-reference is dropped, rather+ than raising ``ValueError`` from the engine and dead-lettering a good alert.+ """++ class _DupDedup:+ async def is_duplicate(self, _alert): # noqa: ANN001, ANN202+ return True, "not-a-uuid"++ async def register(self, _alert): # noqa: ANN001, ANN202+ return None++ class _UnusedCorrelator:+ async def correlate(self, _alert): # noqa: ANN001, ANN202+ raise AssertionError("a duplicate must not reach correlation")++ engine = FusionEngine(_DupDedup(), _UnusedCorrelator())+ fused = await engine.process(_alert())++ assert fused.fusion_decision is FusionDecision.DUPLICATE+ assert fused.duplicate_of is None++[email protected]("payload", [b"not-json{", b"\xff\xfe"])+async def test_correlation_treats_a_corrupt_payload_as_a_cache_miss(payload):+ """Redis is a cache. A truncated or undecodable entry must not dead-letter+ an otherwise valid alert: it reads as "no existing incident"."""+ correlator = Correlator(_CorruptRedis(payload))+ alert = _alert()+ alert.id = alert.deterministic_id()++ correlated, incident = await correlator.correlate(alert)+ assert correlated is False+ assert incident.alert_count == 1+ assert incident.alert_ids == [str(alert.id)]+ assert correlator.metrics()["degraded"] is False+++async def test_correlation_reports_recovery_after_redis_returns():+ redis = _HealingRedis()+ correlator = Correlator(redis)+ await correlator.correlate(_alert())+ assert correlator.metrics()["degraded"] is True++ redis.down = False+ correlated, incident = await correlator.correlate(_alert())+ assert correlated is False+ assert incident.alert_count == 1+ assert correlator.metrics()["degraded"] is Falsediff --git a/services/fusion/tests/test_consumer_dlq.py b/services/fusion/tests/test_consumer_dlq.pyindex d157d041c..99b72d7b2 100644--- a/services/fusion/tests/test_consumer_dlq.py+++ b/services/fusion/tests/test_consumer_dlq.py@@ -16,7 +16,7 @@ import pytestfrom app.core.config import settingsfrom app.models.alert import FusionDecisionfrom app.services.dlq import InMemoryDLQ-from app.workers.consumer import FusionWorker+from app.workers.consumer import FusionWorker, PermanentProcessingErrorpytestmark = pytest.mark.asyncio@@ -98,7 +98,16 @@ async def test_invalid_raw_alert_is_dead_lettered_not_silently_dropped():worker._engine.process.assert_not_awaited() # noqa: SLF001-async def test_dead_letter_never_crashes_the_consumer_when_sink_fails():+async def test_failed_dead_letter_is_not_reported_as_handled():+ """A poison message whose capture failed must not let the offset commit.++ The old contract returned cleanly when the DLQ raised. The consume loop+ read that as success and committed the offset, so the poison message+ existed only in a log line. The capture failure now propagates as a+ permanent processing failure; `_handle_message` holds the message+ uncommitted until a DLQ accepts it (or shutdown).+ """+class ExplodingDLQ:async def record(self, dead_letter): # noqa: ANN001, ARG002raise RuntimeError("dlq sink down")@@ -106,5 +115,5 @@ async def test_dead_letter_never_crashes_the_consumer_when_sink_fails():engine = SimpleNamespace(process=AsyncMock())worker = FusionWorker(engine=engine, sink=None, dlq=ExplodingDLQ())worker._producer = AsyncMock() # noqa: SLF001- # Poison message + failing DLQ: must return cleanly, not raise.- await worker._process_message({"tenant_id": TENANT}, topic=RAW_EVENTS) # noqa: SLF001+ with pytest.raises(PermanentProcessingError):+ await worker._process_message({"tenant_id": TENANT}, topic=RAW_EVENTS) # noqa: SLF001diff --git a/services/fusion/tests/test_consumer_durability.py b/services/fusion/tests/test_consumer_durability.pynew file mode 100644index 000000000..5019d1f09--- /dev/null+++ b/services/fusion/tests/test_consumer_durability.py@@ -0,0 +1,552 @@+"""Durability regression tests for the fusion consumer's ack boundary.++The defect these pin: a per-message exception was logged, the loop moved on,+and the *next* successful message committed past the failed offset. A Postgres+outage therefore became permanent event loss. These tests drive the retry /+classification machinery directly (no Kafka) and assert the two invariants that+make loss impossible:++* the offset is committed only when the message is durable or captured;+* a transient failure is retried with a bounded backoff, and a failure to+ capture is held uncommitted rather than acknowledged.+"""++from __future__ import annotations++import asyncio+import json+from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest+from aiokafka import TopicPartition+from app.core.config import settings+from app.models.alert import AlertSeverity, FusedAlert, FusionDecision, RawAlert+from app.services.alert_sink import AlertSink, PersistOutcome, PersistResult+from app.services.dlq import InMemoryDLQ, LoggingDLQ+from app.services.dlq_sink import PostgresDLQ+from app.workers.consumer import (+ FusionWorker,+ PermanentProcessingError,+ RetryableProcessingError,+ _decode_record_value,+ _UnparseableRecord,+)+++def _msg(offset: int = 0) -> SimpleNamespace:+ return SimpleNamespace(+ value={"tenant_id": "00000000-0000-0000-0000-000000000001", "nonsense": True},+ topic=settings.kafka_topic_raw_events,+ partition=0,+ offset=offset,+ )+++def _worker(dlq=None) -> FusionWorker:+ # The worker only ever awaits `engine.process`, so a namespace carrying+ # that one attribute is the whole contract this suite needs.+ worker = FusionWorker(engine=SimpleNamespace(process=AsyncMock()), dlq=dlq) # type: ignore[arg-type]+ worker._running = True # noqa: SLF001 — this test drives the loop directly+ worker._stop_event.clear() # noqa: SLF001+ return worker+++def _retry_settings(monkeypatch: pytest.MonkeyPatch, *, attempts: int) -> None:+ monkeypatch.setattr(settings, "consumer_max_retries", attempts)+ monkeypatch.setattr(settings, "consumer_retry_base_seconds", 0.0)+ monkeypatch.setattr(settings, "consumer_retry_max_seconds", 0.0)+ monkeypatch.setattr(settings, "consumer_recovery_retry_seconds", 0.01)+++async def test_transient_failure_is_retried_then_committed(monkeypatch):+ _retry_settings(monkeypatch, attempts=3)+ worker = _worker()+ worker._process_message = AsyncMock( # noqa: SLF001+ side_effect=[RetryableProcessingError("db unavailable"), None]+ )++ before = worker.get_metrics()["retried"]+ assert await worker._handle_message(_msg()) is True # noqa: SLF001+ assert worker._process_message.await_count == 2 # noqa: SLF001+ assert worker.get_metrics()["retried"] == before + 1+++async def test_retry_exhaustion_captures_before_allowing_commit(monkeypatch):+ _retry_settings(monkeypatch, attempts=2)+ dlq = InMemoryDLQ()+ worker = _worker(dlq)+ worker._process_message = AsyncMock( # noqa: SLF001+ side_effect=RetryableProcessingError("postgres still down")+ )++ before = worker.get_metrics()["retry_exhausted"]+ assert await worker._handle_message(_msg(offset=17)) is True # noqa: SLF001+ assert worker._process_message.await_count == 3 # initial + 2 retries # noqa: SLF001+ assert worker.get_metrics()["retry_exhausted"] == before + 1+ assert len(dlq.records) == 1+ assert dlq.records[0].offset == 17+ assert "transient processing failure" in dlq.records[0].reason+++async def test_permanent_failure_is_captured_without_retrying(monkeypatch):+ _retry_settings(monkeypatch, attempts=5)+ dlq = InMemoryDLQ()+ worker = _worker(dlq)+ worker._process_message = AsyncMock( # noqa: SLF001+ side_effect=PermanentProcessingError("unknown tenant")+ )++ assert await worker._handle_message(_msg()) is True # noqa: SLF001+ assert worker._process_message.await_count == 1 # noqa: SLF001+ assert len(dlq.records) == 1+ assert "permanent processing failure" in dlq.records[0].reason+++def test_log_only_capture_is_not_reported_as_durable():+ """The default sink is a log line, and the worker must say so.++ ``durable_capture`` is the runtime half of the documented persistence-free+ mode: a committed offset is only evidence of survival when the DLQ is+ storage. The default and an explicitly-injected ``LoggingDLQ`` both report+ false rather than inheriting a claim from the retry machinery.+ """+ for worker in (_worker(), _worker(LoggingDLQ())):+ assert worker.durable_capture is False+ assert worker.get_metrics()["durable_capture"] == 0+++def test_a_storage_backed_dlq_reports_durable_capture():+ worker = _worker(PostgresDLQ(lambda: None))+ assert worker.durable_capture is True+ assert worker.get_metrics()["durable_capture"] == 1+++async def test_persistence_free_mode_commits_a_log_only_capture(monkeypatch):+ """The configured exception to the durability invariant, pinned.++ With the default ``LoggingDLQ`` there is nowhere durable to capture to, so+ a successful "capture" is a structured log line and the offset commits.+ The worker still retries and dead-letters, but this mode must not be+ described as loss-proof: ``durable_capture`` is false and ``main.py``+ warns. If the default ever becomes storage-backed, this test is the signal+ that the documented mode changed.+ """+ _retry_settings(monkeypatch, attempts=0)+ worker = _worker()+ worker._process_message = AsyncMock( # noqa: SLF001+ side_effect=PermanentProcessingError("unknown tenant")+ )+ consumer = _FakeConsumer([_msg(0)])+ worker._consumer = consumer # noqa: SLF001++ await worker._consume_loop() # noqa: SLF001++ assert worker.durable_capture is False+ assert len(consumer.commits) == 1+ assert worker.get_metrics()["dead_lettered"] >= 1+++async def test_unhandled_exception_is_captured_not_committed(monkeypatch):+ _retry_settings(monkeypatch, attempts=5)+ dlq = InMemoryDLQ()+ worker = _worker(dlq)+ worker._process_message = AsyncMock(side_effect=RuntimeError("bug in the engine")) # noqa: SLF001++ assert await worker._handle_message(_msg()) is True # noqa: SLF001+ assert len(dlq.records) == 1+ assert "unhandled processing error" in dlq.records[0].reason+++async def test_failed_dlq_holds_the_message_without_acknowledging(monkeypatch):+ """When the store and the DLQ are both down, the message is not committed."""++ class ExplodingDLQ:+ async def record(self, dead_letter): # noqa: ANN001, ARG002+ raise RuntimeError("dlq also down")++ _retry_settings(monkeypatch, attempts=0)+ worker = _worker(ExplodingDLQ())+ worker._process_message = AsyncMock( # noqa: SLF001+ side_effect=RetryableProcessingError("postgres down")+ )++ task = asyncio.create_task(worker._handle_message(_msg())) # noqa: SLF001+ await asyncio.sleep(0.05)+ assert not task.done(), "a message with no durable home must not be acknowledged"++ worker._running = False # noqa: SLF001 — shutdown must break the hold+ worker._stop_event.set() # noqa: SLF001+ assert await asyncio.wait_for(task, timeout=1.0) is False+ assert worker.get_metrics()["recovery_holds"] >= 1+++async def test_a_dlq_that_reports_failure_holds_the_message_without_acknowledging(monkeypatch):+ """``PostgresDLQ`` does not raise when its pool is down; it returns False.++ Reporting that as success would commit an offset for a message that now+ exists nowhere durable. The consumer must treat an explicit False as a+ failed capture and hold the offset, exactly as it does for an exception.+ """++ class FailingDLQ:+ async def record(self, dead_letter): # noqa: ANN001, ARG002+ return False++ _retry_settings(monkeypatch, attempts=0)+ worker = _worker(FailingDLQ())+ worker._process_message = AsyncMock( # noqa: SLF001+ side_effect=RetryableProcessingError("postgres down")+ )++ task = asyncio.create_task(worker._handle_message(_msg())) # noqa: SLF001+ await asyncio.sleep(0.05)+ assert not task.done(), "a False capture must not be mistaken for a durable one"++ worker._running = False # noqa: SLF001+ worker._stop_event.set() # noqa: SLF001+ assert await asyncio.wait_for(task, timeout=1.0) is False+ assert worker.get_metrics()["recovery_holds"] >= 1+++def test_a_non_json_record_becomes_a_capture_instead_of_an_iterator_crash():+ """aiokafka applies the deserializer inside the fetch.++ An exception there escapes the ``async for`` and stops consumption, so one+ malformed byte string would halt fusion. The value must become something the+ normal dead-letter path can carry.+ """+ value = _decode_record_value(b"\xffnot json")+ assert isinstance(value, _UnparseableRecord)+ assert "not json" in value.text+++def test_the_real_aiokafka_deserializer_boundary_does_not_raise():+ """Exercise aiokafka's own record construction, not just our helper.++ ``PartitionRecords._consumer_record`` is where aiokafka applies+ ``value_deserializer`` while unpacking a fetch. Proving the helper is+ correct is not enough: a raw ``json.loads`` raises *here*, before the+ consume loop can see the record, and that exception ends the iterator.+ """+ fetcher = pytest.importorskip("aiokafka.consumer.fetcher")+ build_record = getattr(fetcher.PartitionRecords, "_consumer_record", None)+ if build_record is None: # pragma: no cover — future aiokafka layout+ pytest.skip("aiokafka no longer exposes PartitionRecords._consumer_record")++ record = SimpleNamespace(+ key=None,+ value=b"\xffnot json",+ offset=9,+ timestamp=0,+ timestamp_type=0,+ checksum=0,+ headers=[],+ )+ holder = SimpleNamespace(_key_deserializer=None, _value_deserializer=_decode_record_value)++ out = build_record(holder, TopicPartition(settings.kafka_topic_raw_events, 2), record)+ assert isinstance(out.value, _UnparseableRecord)+ assert (out.partition, out.offset) == (2, 9)++ # Negative control: the same boundary with the obvious deserializer raises.+ holder._value_deserializer = lambda raw: json.loads(raw.decode("utf-8"))+ with pytest.raises(UnicodeDecodeError):+ build_record(holder, TopicPartition(settings.kafka_topic_raw_events, 2), record)+++async def test_a_non_json_record_is_dead_lettered_with_its_offset(monkeypatch):+ _retry_settings(monkeypatch, attempts=0)+ dlq = InMemoryDLQ()+ worker = _worker(dlq)+ msg = SimpleNamespace(+ value=_UnparseableRecord(b"{bad json"),+ topic=settings.kafka_topic_raw_events,+ partition=0,+ offset=5,+ )++ assert await worker._handle_message(msg) is True # noqa: SLF001+ assert len(dlq.records) == 1+ assert dlq.records[0].offset == 5+ assert "not valid JSON" in dlq.records[0].reason+++async def test_a_hold_ends_when_the_dlq_recovers_without_a_restart(monkeypatch):+ """The hold is a retry loop, not a terminal state.++ Once the DLQ can write again the same in-flight message is captured and its+ offset may commit — no process restart required.+ """++ class FlakyDLQ:+ def __init__(self) -> None:+ self.calls = 0++ async def record(self, dead_letter): # noqa: ANN001, ARG002+ self.calls += 1+ return self.calls >= 3++ _retry_settings(monkeypatch, attempts=0)+ dlq = FlakyDLQ()+ worker = _worker(dlq)+ worker._process_message = AsyncMock( # noqa: SLF001+ side_effect=RetryableProcessingError("postgres down")+ )++ assert await asyncio.wait_for(worker._handle_message(_msg()), timeout=2.0) is True # noqa: SLF001+ assert dlq.calls == 3+ assert worker.get_metrics()["recovery_holds"] >= 2+++class _FakeConsumer:+ def __init__(self, messages):+ self._messages = list(messages)+ self.commits: list[dict] = []+ self.stopped = False++ def __aiter__(self): # noqa: ANN204+ return self++ async def __anext__(self): # noqa: ANN204+ if not self._messages:+ raise StopAsyncIteration+ return self._messages.pop(0)++ async def commit(self, offsets=None): # noqa: ANN001, ANN201+ self.commits.append(offsets)++ async def stop(self): # noqa: ANN201+ self.stopped = True+++async def test_consume_loop_commits_only_after_success():+ worker = _worker()+ consumer = _FakeConsumer([_msg(0)])+ worker._consumer = consumer # noqa: SLF001+ worker._handle_message = AsyncMock(return_value=True) # noqa: SLF001++ await worker._consume_loop() # noqa: SLF001+ assert len(consumer.commits) == 1+ # The *next* offset for this partition only. A bare commit() acknowledges+ # every fetched partition and can skip records another partition has not+ # handed to the worker yet.+ assert consumer.commits[0] == {TopicPartition(settings.kafka_topic_raw_events, 0): 1}+ assert worker._loop_done.is_set() # noqa: SLF001+++async def test_consume_loop_does_not_commit_a_failed_message():+ """The exact old defect: process fails, then the next commit skips it."""+ worker = _worker()+ consumer = _FakeConsumer([_msg(0), _msg(1)])+ worker._consumer = consumer # noqa: SLF001+ worker._handle_message = AsyncMock(return_value=False) # noqa: SLF001++ await worker._consume_loop() # noqa: SLF001+ assert consumer.commits == []+ assert worker._attached is False # noqa: SLF001+ assert worker._loop_done.is_set() # noqa: SLF001+++async def test_stop_waits_for_the_in_flight_message_before_closing_clients():+ """Shutdown must not close Kafka underneath a message being persisted."""+ worker = _worker()+ consumer = _FakeConsumer([])+ worker._consumer = consumer # noqa: SLF001+ worker._loop_done.clear() # noqa: SLF001 — pretend the loop is in a message+ worker._inflight = 1 # noqa: SLF001++ async def finish_message(): # noqa: ANN202+ await asyncio.sleep(0.05)+ worker._loop_done.set() # noqa: SLF001++ finish = asyncio.create_task(finish_message())+ started = asyncio.get_running_loop().time()+ await worker.stop()+ elapsed = asyncio.get_running_loop().time() - started++ assert elapsed >= 0.04, "stop() closed the clients before the message finished"+ assert consumer.stopped is True+ assert worker._running is False # noqa: SLF001+ assert worker._stop_event.is_set() # noqa: SLF001+ # Drained through `gather` rather than a bare `await finish`: the bare form+ # reads to CodeQL as `py/ineffectual-statement`. Same reason as the comment+ # in `dlq.KafkaDLQ.record`.+ await asyncio.gather(finish)+++async def test_stop_is_bounded_when_a_message_never_finishes(monkeypatch):+ """The grace period is finite; the offset is simply left uncommitted."""+ monkeypatch.setattr(settings, "shutdown_grace_seconds", 0.05)+ worker = _worker()+ consumer = _FakeConsumer([])+ worker._consumer = consumer # noqa: SLF001+ worker._loop_done.clear() # noqa: SLF001+ worker._inflight = 1 # noqa: SLF001++ started = asyncio.get_running_loop().time()+ await worker.stop()+ elapsed = asyncio.get_running_loop().time() - started++ assert elapsed < 1.0+ assert consumer.stopped is True+++async def test_stop_does_not_wait_out_the_grace_period_when_idle(monkeypatch):+ """An idle consume loop is blocked on Kafka; closing it is the wakeup."""+ monkeypatch.setattr(settings, "shutdown_grace_seconds", 5.0)+ worker = _worker()+ consumer = _FakeConsumer([])+ worker._consumer = consumer # noqa: SLF001+ worker._loop_done.clear() # noqa: SLF001 — loop is waiting for a record+ worker._inflight = 0 # noqa: SLF001++ started = asyncio.get_running_loop().time()+ await worker.stop()+ elapsed = asyncio.get_running_loop().time() - started++ assert elapsed < 1.0+ assert consumer.stopped is True+++async def test_inflight_stays_positive_through_commit_and_lake_flush():+ """Shutdown decides whether to wait by reading ``_inflight``.++ Decrementing it before the commit (or the lake flush) lets ``stop()`` see an+ idle worker and close Kafka underneath an acknowledgement that is still in+ flight. The counter must stay positive until both have finished.+ """+ worker = _worker()+ observed: dict[str, int] = {}++ class _ObservingConsumer(_FakeConsumer):+ async def commit(self, offsets=None): # noqa: ANN001, ANN201+ observed["commit"] = worker._inflight # noqa: SLF001+ await super().commit(offsets)++ class _ObservingLake:+ async def flush_if_stale(self) -> None:+ observed["lake"] = worker._inflight # noqa: SLF001++ consumer = _ObservingConsumer([_msg(0)])+ worker._consumer = consumer # noqa: SLF001+ worker._lake = _ObservingLake() # type: ignore[assignment] # noqa: SLF001+ worker._handle_message = AsyncMock(return_value=True) # noqa: SLF001++ await worker._consume_loop() # noqa: SLF001++ assert observed == {"commit": 1, "lake": 1}+ assert worker._inflight == 0 # noqa: SLF001+++def test_retry_backoff_is_bounded_and_jittered(monkeypatch):+ monkeypatch.setattr(settings, "consumer_retry_base_seconds", 0.5)+ monkeypatch.setattr(settings, "consumer_retry_max_seconds", 30.0)+ worker = _worker()++ first = worker._retry_delay(1) # noqa: SLF001+ assert 0.25 <= first <= 0.5+ # The exponential window is capped; no attempt can sleep past the cap.+ assert all(0.0 < worker._retry_delay(n) <= 30.0 for n in range(1, 40)) # noqa: SLF001+ assert worker._retry_delay(30) >= 15.0 # noqa: SLF001 — capped window, still jittered+++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)+++async def test_unavailable_persist_raises_retryable_and_does_not_publish():+ alert = _alert()+ fused = _fused(alert)+ worker = FusionWorker(engine=SimpleNamespace(process=AsyncMock(return_value=fused)), sink=AsyncMock())+ worker._sink.persist = AsyncMock( # noqa: SLF001+ return_value=PersistResult(PersistOutcome.UNAVAILABLE, str(fused.id), retryable=True)+ )+ worker._producer = AsyncMock() # noqa: SLF001++ with pytest.raises(RetryableProcessingError):+ await worker._fuse_and_persist(alert) # noqa: SLF001+ worker._producer.send.assert_not_awaited() # noqa: SLF001+++async def test_permanent_persist_failure_raises_permanent():+ alert = _alert()+ fused = _fused(alert)+ worker = FusionWorker(engine=SimpleNamespace(process=AsyncMock(return_value=fused)), sink=AsyncMock())+ worker._sink.persist = AsyncMock( # noqa: SLF001+ return_value=PersistResult(PersistOutcome.FAILED, None, retryable=False)+ )+ worker._producer = AsyncMock() # noqa: SLF001++ with pytest.raises(PermanentProcessingError):+ await worker._fuse_and_persist(alert) # noqa: SLF001+ worker._producer.send.assert_not_awaited() # noqa: SLF001+++async def test_publish_failure_after_a_durable_row_is_retryable():+ """The row exists; the notification does not. Re-delivery republishes it."""+ alert = _alert()+ fused = _fused(alert)+ worker = FusionWorker(engine=SimpleNamespace(process=AsyncMock(return_value=fused)), sink=AsyncMock())+ worker._sink.persist = AsyncMock( # noqa: SLF001+ return_value=PersistResult(PersistOutcome.INSERTED, str(fused.id))+ )+ worker._producer = AsyncMock() # noqa: SLF001+ worker._producer.send.side_effect = RuntimeError("kafka down") # noqa: SLF001++ with pytest.raises(RetryableProcessingError):+ await worker._fuse_and_persist(alert) # noqa: SLF001+ assert worker.get_metrics()["publish_failed"] >= 1+++async def test_alert_sink_duplicate_reconciliation_is_used_by_the_worker():+ """End-to-end at the worker boundary: DUPLICATE must verify the row.++ A sink double is used here; the SQL path itself is covered by+ test_alert_sink.py and the live integration job.+ """+ alert = _alert()+ fused = _fused(alert)+ sink = AlertSink.__new__(AlertSink)++ async def verify(_fused): # noqa: ANN001, ANN202+ return PersistResult(PersistOutcome.DUPLICATE, str(fused.id), verified=False, retryable=True)++ sink.persist = verify # type: ignore[method-assign]+ worker = FusionWorker(engine=SimpleNamespace(process=AsyncMock(return_value=fused)), sink=sink)+ worker._producer = AsyncMock() # noqa: SLF001++ with pytest.raises(RetryableProcessingError):+ await worker._fuse_and_persist(alert) # noqa: SLF001+ worker._producer.send.assert_not_awaited() # noqa: SLF001diff --git a/services/fusion/tests/test_dlq.py b/services/fusion/tests/test_dlq.pyindex 15a8f3731..d069ed909 100644--- a/services/fusion/tests/test_dlq.py+++ b/services/fusion/tests/test_dlq.py@@ -3,7 +3,7 @@from __future__ import annotationsimport pytest-from app.services.dlq import DeadLetter, InMemoryDLQ, LoggingDLQ, safe_record+from app.services.dlq import DeadLetter, InMemoryDLQ, KafkaDLQ, LoggingDLQ, safe_recorddef test_dead_letter_build_truncates_payload_and_keeps_lineage():@@ -54,9 +54,129 @@ async def test_safe_record_swallows_sink_failure():assert ok is False+async def test_safe_record_reports_an_explicit_capture_failure():+ """A sink that cannot persist (notably PostgresDLQ with no pool) returns+ False instead of raising. Reporting that as success would let the consumer+ commit an offset for a message that exists nowhere durable."""++ class FailingDLQ:+ async def record(self, dead_letter): # noqa: ANN001, ARG002+ return False++ ok = await safe_record(FailingDLQ(), DeadLetter.build(topic="t", reason="r", schema_version="v1", payload={}))+ assert ok is False+++async def test_safe_record_accepts_a_legacy_none_returning_sink():+ """The original protocol returned None. Such a sink raises on failure, so+ None still means the record was accepted."""++ class LegacyDLQ:+ async def record(self, dead_letter): # noqa: ANN001, ARG002+ return None++ ok = await safe_record(LegacyDLQ(), DeadLetter.build(topic="t", reason="r", schema_version="v1", payload={}))+ assert ok is True++@pytest.mark.asyncioasync def test_logging_dlq_does_not_raise():- await LoggingDLQ().record(DeadLetter.build(topic="t", reason="r", schema_version="v1", payload={"x": 1}))+ ok = await LoggingDLQ().record(DeadLetter.build(topic="t", reason="r", schema_version="v1", payload={"x": 1}))+ assert ok is True+++def test_only_storage_backed_dlqs_claim_durable_capture():+ """A successful ``record`` is not automatically a durable capture.++ The consumer commits an offset after a successful capture. That is only+ safe if the capture outlives the process: a log line and an in-memory list+ do not, and neither does a broker send without an acknowledgement. The flag+ is what lets the worker report the persistence-free mode instead of+ silently implying the invariant holds.+ """+ assert LoggingDLQ.durable is False+ assert InMemoryDLQ.durable is False+ assert KafkaDLQ.durable is True+++class _AckFuture:+ """What ``AIOKafkaProducer.send`` returns: a future, not the write."""++ def __init__(self, *, fail: bool = False) -> None:+ self.awaited = False+ self._fail = fail++ def __await__(self): # noqa: ANN204+ async def _wait() -> None:+ self.awaited = True+ if self._fail:+ raise RuntimeError("broker rejected the write")++ return _wait().__await__()+++class _Producer:+ def __init__(self, future: _AckFuture) -> None:+ self.future = future+ self.sent: list[tuple[str, dict]] = []++ async def send(self, topic, *, value): # noqa: ANN001, ANN201+ self.sent.append((topic, value))+ return self.future+++async def test_kafka_dlq_waits_for_the_broker_acknowledgement():+ """``send`` only enqueues; the future is the acknowledgement.++ Returning True without awaiting it would let the consumer commit an offset+ for a dead letter that a later producer failure can still lose.+ """+ future = _AckFuture()+ producer = _Producer(future)++ ok = await KafkaDLQ(producer).record(DeadLetter.build(topic="t", reason="r", schema_version="v1", payload={}))++ assert ok is True+ assert producer.sent[0][0] == "aisoc.alerts.dlq"+ assert future.awaited is True+++async def test_kafka_dlq_reports_a_failed_acknowledgement_as_a_failed_capture():+ future = _AckFuture(fail=True)+ producer = _Producer(future)++ ok = await safe_record(KafkaDLQ(producer), DeadLetter.build(topic="t", reason="r", schema_version="v1", payload={}))++ assert ok is False+ assert future.awaited is True+++async def test_kafka_dlq_does_not_accept_a_send_without_an_acknowledgement():+ """A producer that returns no future is not evidence of a durable write."""++ class _NoAckProducer:+ async def send(self, topic, *, value): # noqa: ANN001, ANN201, ARG002+ return None++ ok = await safe_record(KafkaDLQ(_NoAckProducer()), DeadLetter.build(topic="t", reason="r", schema_version="v1", payload={}))++ assert ok is False+++async def test_a_sink_without_the_flag_defaults_to_not_durable():+ """Older/custom sinks cannot inherit durability by omission."""++ class CustomSink:+ async def record(self, dead_letter): # noqa: ANN001, ARG002+ return True++ assert getattr(CustomSink(), "durable", False) is Falseif __name__ == "__main__": # pragma: no coverdiff --git a/services/fusion/tests/test_dlq_sink.py b/services/fusion/tests/test_dlq_sink.pyindex 55baf1424..6fd087911 100644--- a/services/fusion/tests/test_dlq_sink.py+++ b/services/fusion/tests/test_dlq_sink.py@@ -51,10 +51,14 @@ def _letter(**overrides: object) -> DeadLetter:class TestRecording:+ def test_the_sink_declares_durable_capture(self) -> None:+ """A committed INSERT is storage; the consumer may commit past it."""+ assert PostgresDLQ.durable is True+@pytest.mark.asyncioasync def test_writes_the_letter(self) -> None:pool = _pool()- await PostgresDLQ(lambda: pool).record(_letter())+ assert await PostgresDLQ(lambda: pool).record(_letter()) is Truepool._conn.execute.assert_awaited_once()args = pool._conn.execute.await_args.argsassert "aisoc_dead_letters" in args[0]@@ -74,8 +78,10 @@ class TestRecording:@pytest.mark.asyncioasync def test_no_pool_yet_is_logged_not_crashed(self) -> None:"""The pool opens during worker startup, after the DLQ is built.- A dead letter arriving in that window must not raise."""- await PostgresDLQ(lambda: None).record(_letter())+ A dead letter arriving in that window must not raise — but it also+ did not get captured, so it must report False. Otherwise the consumer+ commits an offset for a message that exists nowhere durable."""+ assert await PostgresDLQ(lambda: None).record(_letter()) is False@pytest.mark.asyncioasync def test_a_callable_pool_is_resolved_at_record_time(self) -> None:@@ -85,7 +91,7 @@ class TestRecording:holder: list = [None]sink = PostgresDLQ(lambda: holder[0])holder[0] = pool- await sink.record(_letter())+ assert await sink.record(_letter()) is Truepool._conn.execute.assert_awaited_once()@@ -96,13 +102,44 @@ class TestItCannotStopThePipeline:consuming. If recording that decision can raise, the DLQ becomes asecond way for one bad event to halt everything."""pool = _pool(AsyncMock(side_effect=RuntimeError("connection refused")))- await PostgresDLQ(lambda: pool).record(_letter()) # must not raise+ assert await PostgresDLQ(lambda: pool).record(_letter()) is False # must not raise@pytest.mark.asyncioasync def test_an_unacquirable_pool_is_swallowed(self) -> None:pool = MagicMock()pool.acquire = MagicMock(side_effect=RuntimeError("pool exhausted"))- await PostgresDLQ(lambda: pool).record(_letter()) # must not raise+ assert await PostgresDLQ(lambda: pool).record(_letter()) is False # must not raise+++class TestPoolRecovery:+ @pytest.mark.asyncio+ async def test_a_missing_pool_is_rebuilt_through_the_ensure_callback(self) -> None:+ """During a recovery hold no alert is being persisted.++ The DLQ shares the sink's pool, so without an explicit reconnect the+ hold would never end after Postgres returns.+ """+ pool = _pool()+ calls = {"n": 0}++ async def ensure(): # noqa: ANN202+ calls["n"] += 1+ return pool++ assert await PostgresDLQ(lambda: None, ensure_pool=ensure).record(_letter()) is True+ assert calls["n"] == 1+ pool._conn.execute.assert_awaited_once()++ @pytest.mark.asyncio+ async def test_a_failed_pool_is_invalidated_for_the_next_attempt(self) -> None:+ pool = _pool(AsyncMock(side_effect=RuntimeError("server closed the connection")))+ invalidated = {"n": 0}++ async def invalidate() -> None:+ invalidated["n"] += 1++ assert await PostgresDLQ(lambda: pool, invalidate_pool=invalidate).record(_letter()) is False+ assert invalidated["n"] == 1class TestTenantParsing:@@ -124,7 +161,7 @@ class TestTenantParsing:a guess would put another tenant's name on someone else's baddata."""pool = _pool()- await PostgresDLQ(lambda: pool).record(_letter(tenant_id=None))+ assert await PostgresDLQ(lambda: pool).record(_letter(tenant_id=None)) is Trueassert pool._conn.execute.await_args.args[1] is Nonediff --git a/services/fusion/tests/test_lake_writer.py b/services/fusion/tests/test_lake_writer.pyindex 5cad0358e..485b0c013 100644--- a/services/fusion/tests/test_lake_writer.py+++ b/services/fusion/tests/test_lake_writer.py@@ -1,13 +1,17 @@"""Phase A1 — ClickHouse lake writer tests.Proves the OCSF->column mapping, batching (size + age + stop flush), IP/UUID-coercion, and the fail-soft contract (a ClickHouse error drops the batch and-never raises into the consumer). Uses a fake client so no live ClickHouse is-needed; the live-container assertion is the integration.yml gate.+coercion, and the fail-soft contract (a ClickHouse outage retains the batch,+reconnects without a restart, and never raises into the consumer; only+overflow or repeated data errors discard rows, with an explicit counter).+Uses a fake client so no live ClickHouse is needed; the live-container+assertion is the integration.yml gate."""from __future__ import annotations+import uuid+import pytestfrom app.services.lake_writer import LakeWriter, event_to_row@@ -40,10 +44,11 @@ class _FakeClient:def __init__(self) -> None:self.inserted: list[dict] = []self.fail = False+ self.error = "clickhouse down"def execute(self, sql, rows=None, **kwargs): # noqa: ANN001if self.fail:- raise RuntimeError("clickhouse down")+ raise RuntimeError(self.error)if rows:self.inserted.extend(rows)return []@@ -86,11 +91,25 @@ async def test_missing_ip_coerced_to_null_ipv6():assert row["dest_ip"] == "::"-async def test_non_uuid_event_id_left_none_for_default():+async def test_a_non_uuid_event_id_gets_a_deterministic_uuid():+ """The mapping must still yield a bindable id, and it must be stable.++ A random id generated at buffer time was stable across a retry but not+ across a process restart: replaying the same Kafka message after a crash+ produced a second lake identity, so `LIMIT 1 BY event_id` could not+ collapse it.+ """msg = _message()msg["id"] = "not-a-uuid"- row = event_to_row(msg)- assert row["event_id"] is None+ first = event_to_row(msg)+ second = event_to_row(msg)+ assert first["event_id"] is not None+ assert uuid.UUID(first["event_id"])+ assert first["event_id"] == second["event_id"]+ # Different ingest ids stay distinct.+ other = _message()+ other["id"] = "another-id"+ assert event_to_row(other)["event_id"] != first["event_id"]async def test_no_ocsf_or_bad_tenant_returns_none():@@ -125,6 +144,19 @@ 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.+ """+ w, fake = _writer_with_fake(batch_size=100, reconnect_base_seconds=0, reconnect_max_seconds=0)+ fake.fail = True+ await w.write_event(_message())+ await w.stop()+ assert w.metrics()["rows_dropped"] == 1++async def test_flush_if_stale_flushes_old_buffer():w, fake = _writer_with_fake(batch_size=100, batch_max_age_seconds=0.0)await w.write_event(_message())@@ -132,25 +164,191 @@ async def test_flush_if_stale_flushes_old_buffer():assert len(fake.inserted) == 1-async def test_omits_none_event_id_from_insert_row():- w, fake = _writer_with_fake(batch_size=1)+async def test_a_non_uuid_ingest_id_still_binds_every_column():+ """The driver cannot leave a column to its DEFAULT.++ `clickhouse-driver` builds a RowOrientedBlock from the INSERT's column list+ and reads ``row[name]`` for each one. The old writer omitted ``event_id``+ when ingest's id was not a UUID, so the block raised ``KeyError`` before a+ byte was sent; the batch was then retried as a *data* error and eventually+ dropped, taking valid rows in the same batch with it.+ """+ block_module = pytest.importorskip("clickhouse_driver.block")+ from app.services.lake_writer import _COLUMNS++ w, fake = _writer_with_fake(batch_size=2)msg = _message()msg["id"] = "not-a-uuid"+ await w.write_event(_message()) # a valid row in the same batch+ await w.write_event(msg) # triggers the flush++ assert len(fake.inserted) == 2+ for row in fake.inserted:+ assert row["event_id"]+ uuid.UUID(row["event_id"])+ # Exactly what the real client does in send_data(): the row must carry+ # a key for every column named in the INSERT.+ block_module.RowOrientedBlock([(c, "String") for c in _COLUMNS], [row], types_check=False)+++async def test_a_generated_event_id_is_stable_across_a_retry():+ """A retry re-sends the same buffered row.++ A fresh id per attempt would leave `LIMIT 1 BY event_id` unable to collapse+ a batch that was partially sent before the failure.+ """+ w, fake = _writer_with_fake(batch_size=1, reconnect_base_seconds=0, reconnect_max_seconds=0)+ msg = _message()+ msg["id"] = "not-a-uuid"+ fake.fail = Trueawait w.write_event(msg)- assert "event_id" not in fake.inserted[0]+ generated = w._buffer[0]["event_id"] # noqa: SLF001 — the retained row+ assert generated++ fake.fail = False+ w._client = fake # noqa: SLF001 — skip the reconnect delay+ await w.flush()+ assert fake.inserted[0]["event_id"] == generated+++async def test_a_non_uuid_ingest_id_is_stable_across_a_process_restart():+ """The same Kafka message replayed by a new process keeps one identity.++ This is the restart half of the retry test above. Ingest normally emits+ UUIDs, but the topic accepts envelopes from other producers; those used to+ receive `uuid.uuid4()` per process, so a crash-and-replay archived the same+ event twice with two identities.+ """+ msg = _message()+ msg["id"] = "not-a-uuid"++ before, fake_before = _writer_with_fake(batch_size=1)+ await before.write_event(msg)++ after, fake_after = _writer_with_fake(batch_size=1) # a fresh process+ await after.write_event(msg)++ assert fake_before.inserted[0]["event_id"] == fake_after.inserted[0]["event_id"]+++async def test_an_event_with_no_id_uses_stable_kafka_coordinates():+ """An envelope with no ingest id is identified by where it lives.++ Replaying the same partition/offset after a restart must resolve to the+ same id, while a different offset is a different event even when the body+ is byte-identical.+ """+ msg = _message()+ del msg["id"]+ assert event_to_row(msg)["event_id"] is None # mapping alone has no identity++ first, fake_first = _writer_with_fake(batch_size=1)+ await first.write_event(msg, topic="aisoc.raw_events", partition=3, offset=42)++ replay, fake_replay = _writer_with_fake(batch_size=1)+ await replay.write_event(msg, topic="aisoc.raw_events", partition=3, offset=42)++ other, fake_other = _writer_with_fake(batch_size=1)+ await other.write_event(msg, topic="aisoc.raw_events", partition=3, offset=43)++ assert fake_first.inserted[0]["event_id"] == fake_replay.inserted[0]["event_id"]+ assert fake_other.inserted[0]["event_id"] != fake_first.inserted[0]["event_id"]# ── Fail-soft ────────────────────────────────────────────────────────────────-async def test_flush_failure_drops_batch_and_does_not_raise():- w, fake = _writer_with_fake(batch_size=2)+async def test_flush_failure_retains_batch_and_never_raises():+ """A ClickHouse outage must not silently discard the archive batch.++ The old writer dropped it. The batch is now retained and retried; the+ failure is still visible in `flush_failures`.+ """+ w, fake = _writer_with_fake(batch_size=2, reconnect_base_seconds=0, reconnect_max_seconds=0)fake.fail = Trueawait w.write_event(_message())await w.write_event(_message()) # triggers flush -> failsassert w.flush_failures == 1assert w.rows_written == 0- assert w.metrics()["buffered"] == 0 # batch was dropped, not re-buffered+ assert w.metrics()["buffered"] == 2 # retained for the next attempt++ # Recovery: the same batch is written once ClickHouse accepts it, with no+ # process restart and no loss.+ fake.fail = False+ w._client = fake # noqa: SLF001 — skip the reconnect delay in this unit test+ await w.flush()+ assert len(fake.inserted) == 2+ assert w.rows_written == 2+ 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)+ fake.fail = True+ for _ in range(3):+ await w.write_event(_message()) # each write attempts a flush, all fail+ metrics = w.metrics()+ assert metrics["buffered"] == 2+ assert metrics["rows_dropped"] == 1+++async def test_data_errors_are_bounded_and_dropped_loudly():+ """A batch the server keeps rejecting must not grow forever.++ 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.+ """+ w, fake = _writer_with_fake(+ batch_size=2,+ max_data_failures=2,+ reconnect_base_seconds=0,+ reconnect_max_seconds=0,+ )+ fake.fail = True+ fake.error = "Code: 47. DB::Exception: missing column tenant_id"+ await w.write_event(_message())+ await w.write_event(_message()) # first data failure+ w._client = fake # noqa: SLF001 — retry without waiting for reconnect+ await w.flush() # second data failure reaches the bound+ assert w.flush_failures == 2+ assert w.metrics()["buffered"] == 0+ assert w.metrics()["rows_dropped"] == 2+++async def test_connect_failure_is_retried_instead_of_permanently_disabling():+ """A missing ClickHouse is recoverable; only a missing driver is final."""+ clients = [_FakeClient()]+ calls = {"n": 0}++ def factory(): # noqa: ANN202+ calls["n"] += 1+ return clients[0]++ w = LakeWriter(+ host="x",+ batch_size=1,+ reconnect_base_seconds=0,+ reconnect_max_seconds=0,+ client_factory=factory,+ )+ await w.start()+ assert calls["n"] == 1+ await w.write_event(_message())+ assert w.rows_written == 1++ # Simulate a dropped connection: the next flush rebuilds the client from+ # the factory rather than disabling the writer.+ w._client = None # noqa: SLF001+ clients[0].fail = True+ await w.write_event(_message()) # fails, drops its client+ clients[0].fail = False+ w._next_reconnect_at = 0.0 # noqa: SLF001 — eligible immediately+ await w.flush()+ assert calls["n"] >= 2+ assert w.rows_written == 2+ assert await w.write_event(_message()) is True # still enabled, not disabledasync def test_disabled_writer_is_noop():