Skip to content

armgit / AiSOC

Public Imported from GitHub
0

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

feat(dlq): replay refused messages from a Kafka offset, once the cause is fixed (5b) (#1036)

Beenu Arorabb43b13a62c8
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index bb1bfbec6..16e790322 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -7708,6 +7708,89 @@ paths:
Reconciliation Get
security:
- HTTPBearer: []
+ /api/v1/health/dead-letters/replay:
+ post:
+ tags:
+ - health
+ summary: Replay Dead Letters
+ description: 'Re-read a bounded range of refused messages and replay what now
+ passes.
+
+
+ The action that follows a dead-letter queue, and the one Phase 5 left
+
+ undone: the backlog was reportable and nothing could drain it.
+
+
+ Safe rather than merely possible, in four ways.
+
+
+ *Deliberate.* The range is `(topic, partition, start_offset)`, supplied by
+
+ the caller. There is no "replay the backlog" — the excerpt stored on a
+
+ dead-letter row is a truncated triage record, not the event, so the
+
+ replay re-reads the real message from Kafka and the operator says which.
+
+
+ *Bounded.* `max_messages` is capped at 1000 by this request model, again
+
+ by the fusion service, and again by a CHECK constraint on the audit
+
+ table. A bound in one place is a bound the next caller skips.
+
+
+ *Authorised and attributable.* `connectors:write` rather than the
+
+ identity-only dependency the sibling GET carries, because this one
+
+ re-injects production traffic. The row records who asked.
+
+
+ *Observable, and honest about failure.* One `aisoc_dlq_replays` row per
+
+ request including dry runs, written before fusion is called so an
+
+ attempt that hangs still left evidence, and a failed replay reports the
+
+ reason rather than a zero that reads like "nothing to do".
+
+
+ The property that makes it safe at all is in fusion: every message is
+
+ re-validated by the validator that refused it, and one that still fails
+
+ is refused again instead of being produced. Replaying a poison batch into
+
+ the consumer that rejected it reproduces the outage, so a preview whose
+
+ `would_pass` is zero is the answer "your fix has not landed".
+
+
+ Defaults to a dry run. Pass `execute: true` once the preview is clean.'
+ operationId: replay_dead_letters_api_v1_health_dead_letters_replay_post
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/DlqReplayRequest'
+ required: true
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/DlqReplayResponse'
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ security:
+ - HTTPBearer: []
/api/v1/insights/soc:
get:
tags:
@@ -21975,6 +22058,88 @@ components:
type: object
title: DismissTuningRequest
description: Body for ``POST /detection/tuning/{rule_id}/dismiss``.
+ DlqReplayRequest:
+ properties:
+ topic:
+ type: string
+ maxLength: 200
+ minLength: 1
+ title: Topic
+ partition:
+ type: integer
+ minimum: 0.0
+ title: Partition
+ start_offset:
+ type: integer
+ minimum: 0.0
+ title: Start Offset
+ max_messages:
+ type: integer
+ maximum: 1000.0
+ minimum: 1.0
+ title: Max Messages
+ default: 100
+ execute:
+ type: boolean
+ title: Execute
+ default: false
+ type: object
+ required:
+ - topic
+ - partition
+ - start_offset
+ title: DlqReplayRequest
+ description: An explicit, bounded range of refused messages to re-check.
+ DlqReplayResponse:
+ properties:
+ replay_id:
+ type: string
+ format: uuid
+ title: Replay Id
+ status:
+ type: string
+ title: Status
+ executed:
+ type: boolean
+ title: Executed
+ messages_read:
+ type: integer
+ title: Messages Read
+ default: 0
+ would_pass:
+ type: integer
+ title: Would Pass
+ default: 0
+ refused:
+ type: integer
+ title: Refused
+ default: 0
+ produced:
+ type: integer
+ title: Produced
+ default: 0
+ refusals:
+ additionalProperties:
+ type: integer
+ type: object
+ title: Refusals
+ produced_offsets:
+ items:
+ type: integer
+ type: array
+ title: Produced Offsets
+ error:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Error
+ type: object
+ required:
+ - replay_id
+ - status
+ - executed
+ title: DlqReplayResponse
+ description: What the replay found, and what it did about it.
DriftEntry:
properties:
ruleId:
diff --git a/services/api/app/api/v1/endpoints/health.py b/services/api/app/api/v1/endpoints/health.py
index 8bc906f50..7cac5050f 100644
--- a/services/api/app/api/v1/endpoints/health.py
+++ b/services/api/app/api/v1/endpoints/health.py
@@ -75,18 +75,20 @@ from __future__ import annotations
import logging
from datetime import UTC, datetime, timedelta
-from typing import Any
+from typing import Annotated, Any
-from fastapi import APIRouter
+from fastapi import APIRouter, Depends
from sqlalchemy import and_, func, select, text
-from app.api.v1.deps import AuthUser, DBSession
+from app.api.v1.deps import AuthUser, CurrentUser, DBSession, require_permission
from app.api.v1.endpoints.metrics import PipelineHealth, PipelineStage
from app.core.config import settings
+from app.db.rls import TenantDBSession
from app.models.alert import Alert
from app.models.connector import Connector
from app.services.audit_hash import verify_chain_breaks
from app.services.connector_freshness import compute_freshness
+from app.services.dlq_replay_gateway import DlqReplayRequest, DlqReplayResponse, run_replay
from app.services.fleet_health import assess_fleet
from app.services.replay_evaluation.vendors import replayable_connector_ids
@@ -930,3 +932,45 @@ async def get_shadow_reconciliation_health(
for r in rows
],
}
+
+
[email protected]("/dead-letters/replay", response_model=DlqReplayResponse)
+async def replay_dead_letters(
+ request: DlqReplayRequest,
+ user: Annotated[CurrentUser, Depends(require_permission("connectors:write"))],
+ db: TenantDBSession,
+) -> DlqReplayResponse:
+ """Re-read a bounded range of refused messages and replay what now passes.
+
+ The action that follows a dead-letter queue, and the one Phase 5 left
+ undone: the backlog was reportable and nothing could drain it.
+
+ Safe rather than merely possible, in four ways.
+
+ *Deliberate.* The range is `(topic, partition, start_offset)`, supplied by
+ the caller. There is no "replay the backlog" — the excerpt stored on a
+ dead-letter row is a truncated triage record, not the event, so the
+ replay re-reads the real message from Kafka and the operator says which.
+
+ *Bounded.* `max_messages` is capped at 1000 by this request model, again
+ by the fusion service, and again by a CHECK constraint on the audit
+ table. A bound in one place is a bound the next caller skips.
+
+ *Authorised and attributable.* `connectors:write` rather than the
+ identity-only dependency the sibling GET carries, because this one
+ re-injects production traffic. The row records who asked.
+
+ *Observable, and honest about failure.* One `aisoc_dlq_replays` row per
+ request including dry runs, written before fusion is called so an
+ attempt that hangs still left evidence, and a failed replay reports the
+ reason rather than a zero that reads like "nothing to do".
+
+ The property that makes it safe at all is in fusion: every message is
+ re-validated by the validator that refused it, and one that still fails
+ is refused again instead of being produced. Replaying a poison batch into
+ the consumer that rejected it reproduces the outage, so a preview whose
+ `would_pass` is zero is the answer "your fix has not landed".
+
+ Defaults to a dry run. Pass `execute: true` once the preview is clean.
+ """
+ return await run_replay(db, tenant_id=user.tenant_id, requested_by=user.user_id, request=request)
diff --git a/services/api/app/services/dlq_replay_gateway.py b/services/api/app/services/dlq_replay_gateway.py
new file mode 100644
index 000000000..b0bbf61be
--- /dev/null
+++ b/services/api/app/services/dlq_replay_gateway.py
@@ -0,0 +1,233 @@
+"""The operator door onto a dead-letter replay (deferral 5b).
+
+``services/fusion`` executes the replay, because it owns the three things a
+safe one needs in one place: the topic, the producer, and the validator that
+refused the messages. This module is the half that belongs to the API —
+authorisation, the tenant session, and the durable record of the action —
+which is the same split ``siem_writeback`` and the playbook action bridge
+already use, for the same reason: the API holds the credential and the
+session, the other service holds the domain.
+
+What this adds over a plain proxy
+---------------------------------
+**A row before the call, not after.** ``aisoc_dlq_replays`` is written with
+``status = 'queued'`` before fusion is contacted and updated when it answers.
+A replay that starts and never returns leaves evidence that it started; a row
+written only on success would make the interesting case — the one that
+hung — the invisible one.
+
+**Dry run unless asked otherwise, at this layer too.** The default is
+``execute=False`` here, in the request model, and in fusion. Three defaults
+rather than one because the dangerous direction is a caller who omits the
+field, and each layer has a different caller.
+
+**The bound restated.** :data:`MAX_REPLAY_MESSAGES` is checked here as well
+as by fusion and by a CHECK constraint in migration 075. A bound that lives
+only in a request model is a bound a service-to-service caller skips.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import uuid
+from typing import Any
+
+import httpx
+from pydantic import BaseModel, Field
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import AsyncSession
+
+logger = logging.getLogger("aisoc.dlq_replay")
+
+#: Mirrors ``services/fusion/app/services/dlq_replay.MAX_REPLAY_MESSAGES`` and
+#: the CHECK constraint in migration 075.
+MAX_REPLAY_MESSAGES = 1000
+
+_TENANT_HEADER = "X-AiSOC-Tenant-ID"
+
+#: A replay reads up to a thousand messages and may produce them. It is
+#: slower than an entity-risk lookup and must not be cut off mid-flight,
+#: because a timed-out replay leaves an operator unable to say what was
+#: produced.
+_REPLAY_TIMEOUT_SECONDS = 120.0
+
+
+class DlqReplayRequest(BaseModel):
+ """An explicit, bounded range of refused messages to re-check."""
+
+ topic: str = Field(min_length=1, max_length=200)
+ partition: int = Field(ge=0)
+ start_offset: int = Field(ge=0)
+ max_messages: int = Field(default=100, ge=1, le=MAX_REPLAY_MESSAGES)
+ execute: bool = False
+
+
+class DlqReplayResponse(BaseModel):
+ """What the replay found, and what it did about it."""
+
+ replay_id: uuid.UUID
+ status: str
+ executed: bool
+
+ messages_read: int = 0
+ #: How many would pass the validation that refused them. On a dry run
+ #: this is the whole answer: it is the operator's evidence that the cause
+ #: is fixed, before anything is produced.
+ would_pass: int = 0
+ #: How many still fail, and were therefore refused a second time rather
+ #: than replayed into the consumer that refused them first.
+ refused: int = 0
+ produced: int = 0
+
+ refusals: dict[str, int] = Field(default_factory=dict)
+ produced_offsets: list[int] = Field(default_factory=list)
+ error: str | None = None
+
+
+def _fusion_url() -> str:
+ return (os.getenv("FUSION_SERVICE_URL") or os.getenv("FUSION_URL") or "").rstrip("/")
+
+
+def _headers(tenant_id: uuid.UUID) -> dict[str, str]:
+ headers = {_TENANT_HEADER: str(tenant_id)}
+ token = (os.getenv("AISOC_FUSION_SERVICE_TOKEN") or os.getenv("AISOC_SERVICE_TOKEN") or "").strip()
+ if token:
+ headers["Authorization"] = f"Bearer {token}"
+ return headers
+
+
+_INSERT = text(
+ """
+ INSERT INTO aisoc_dlq_replays
+ (tenant_id, topic, topic_partition, start_offset, max_messages, executed, requested_by)
+ VALUES (:tenant_id, :topic, :partition, :start_offset, :max_messages, :executed, :requested_by)
+ RETURNING id
+ """
+)
+
+_COMPLETE = text(
+ """
+ UPDATE aisoc_dlq_replays
+ SET status = :status, messages_read = :messages_read, would_pass = :would_pass,
+ refused = :refused, produced = :produced, error = :error, completed_at = now()
+ WHERE id = :id AND tenant_id = :tenant_id
+ """
+)
+
+
+async def run_replay(
+ db: AsyncSession,
+ *,
+ tenant_id: uuid.UUID,
+ requested_by: uuid.UUID | None,
+ request: DlqReplayRequest,
+) -> DlqReplayResponse:
+ """Record the request, ask fusion to run it, record the outcome."""
+ replay_id = (
+ await db.execute(
+ _INSERT,
+ {
+ "tenant_id": str(tenant_id),
+ "topic": request.topic,
+ "partition": request.partition,
+ "start_offset": request.start_offset,
+ "max_messages": request.max_messages,
+ "executed": request.execute,
+ "requested_by": str(requested_by) if requested_by else None,
+ },
+ )
+ ).scalar_one()
+ # Committed before the call, deliberately: the evidence that a replay was
+ # attempted must survive the attempt failing.
+ await db.commit()
+
+ base = _fusion_url()
+ if not base:
+ return await _fail(
+ db,
+ replay_id,
+ tenant_id,
+ request,
+ "FUSION_SERVICE_URL is not set, so there is no service to run the replay. "
+ "This is a configuration gap, not an empty dead-letter queue.",
+ )
+
+ payload: dict[str, Any] = {
+ "topic": request.topic,
+ "partition": request.partition,
+ "start_offset": request.start_offset,
+ "max_messages": request.max_messages,
+ "execute": request.execute,
+ }
+ try:
+ async with httpx.AsyncClient(timeout=_REPLAY_TIMEOUT_SECONDS) as client:
+ resp = await client.post(f"{base}/dlq/replay", json=payload, headers=_headers(tenant_id))
+ except httpx.HTTPError as exc:
+ return await _fail(db, replay_id, tenant_id, request, f"fusion unreachable: {type(exc).__name__}")
+
+ if resp.status_code >= 400:
+ detail = resp.text[:500].replace("\r", "").replace("\n", " ")
+ return await _fail(db, replay_id, tenant_id, request, f"fusion refused the replay (HTTP {resp.status_code}): {detail}")
+
+ body = resp.json()
+ await db.execute(
+ _COMPLETE,
+ {
+ "id": replay_id,
+ "tenant_id": str(tenant_id),
+ "status": "completed",
+ "messages_read": int(body.get("messages_read") or 0),
+ "would_pass": int(body.get("would_pass") or 0),
+ "refused": int(body.get("refused") or 0),
+ "produced": int(body.get("produced") or 0),
+ "error": None,
+ },
+ )
+ await db.commit()
+
+ return DlqReplayResponse(
+ replay_id=replay_id,
+ status="completed",
+ executed=bool(body.get("executed")),
+ messages_read=int(body.get("messages_read") or 0),
+ would_pass=int(body.get("would_pass") or 0),
+ refused=int(body.get("refused") or 0),
+ produced=int(body.get("produced") or 0),
+ refusals=dict(body.get("refusals") or {}),
+ produced_offsets=list(body.get("produced_offsets") or []),
+ )
+
+
+async def _fail(
+ db: AsyncSession,
+ replay_id: uuid.UUID,
+ tenant_id: uuid.UUID,
+ request: DlqReplayRequest,
+ reason: str,
+) -> DlqReplayResponse:
+ """Record a replay that could not run, and say why rather than returning zeros.
+
+ A failed replay reporting ``produced: 0`` and nothing else is
+ indistinguishable from a successful one that found nothing to do — which
+ is the reading that would let an operator believe the queue was drained.
+ """
+ await db.execute(
+ _COMPLETE,
+ {
+ "id": replay_id,
+ "tenant_id": str(tenant_id),
+ "status": "failed",
+ "messages_read": 0,
+ "would_pass": 0,
+ "refused": 0,
+ "produced": 0,
+ "error": reason[:2000],
+ },
+ )
+ await db.commit()
+ logger.warning("dlq_replay failed: %s", reason.replace("\r", "").replace("\n", " ")[:300])
+ return DlqReplayResponse(replay_id=replay_id, status="failed", executed=request.execute, error=reason)
+
+
+__all__ = ["MAX_REPLAY_MESSAGES", "DlqReplayRequest", "DlqReplayResponse", "run_replay"]
diff --git a/services/api/migrations/075_dead_letter_replay.sql b/services/api/migrations/075_dead_letter_replay.sql
new file mode 100644
index 000000000..66a65d91e
--- /dev/null
+++ b/services/api/migrations/075_dead_letter_replay.sql
@@ -0,0 +1,114 @@
+-- 075_dead_letter_replay.sql — draining the dead-letter queue (deferral 5b)
+--
+-- Phase 5 shipped the schema registry, the dead-letter queue and event-time
+-- watermarking. `GET /api/v1/health/dead-letters` reports the backlog and
+-- nothing consumed it: a dead-letter queue nobody can drain is an audit
+-- trail, not a recovery mechanism.
+--
+-- Two things were missing and both are here.
+--
+-- The coordinates. `aisoc_dead_letters` recorded topic, reason and a 2,000
+-- character excerpt — deliberately far short of the event, because the
+-- payload is untrusted by definition and storing all of it turns the table
+-- into an unbounded sink for exactly the content the pipeline refused. That
+-- reasoning still holds, and it means the row cannot be the thing replayed.
+-- The faithful copy lives in Kafka, and reaching it needs the partition and
+-- offset the consumer had in hand and discarded. Both are nullable: rows
+-- written before this migration have no coordinates and never will, and a
+-- fabricated offset would replay somebody else's message.
+--
+-- The record of the action. A replay re-injects production traffic, so it is
+-- the kind of operation whose absence from the audit log is itself the
+-- incident. `aisoc_dlq_replays` records who asked, for what range, what the
+-- re-validation found, and what was actually produced — including for a dry
+-- run, because "we checked and it would still fail" is the outcome an
+-- operator most needs to be able to point at later.
+
+ALTER TABLE aisoc_dead_letters
+ ADD COLUMN IF NOT EXISTS topic_partition INTEGER,
+ ADD COLUMN IF NOT EXISTS kafka_offset BIGINT;
+
+COMMENT ON COLUMN aisoc_dead_letters.kafka_offset IS
+ 'Offset of the refused message on its partition, or NULL when unknown. '
+ 'The excerpt cannot be replayed; this is how the real message is found again.';
+
+-- The lookup a replay does: "the refused messages on this partition, in
+-- offset order, from here". Partial, because a row with no coordinates can
+-- never be the start of one.
+CREATE INDEX IF NOT EXISTS idx_dead_letters_coordinates
+ ON aisoc_dead_letters (topic, topic_partition, kafka_offset)
+ WHERE kafka_offset IS NOT NULL;
+
+
+CREATE TABLE IF NOT EXISTS aisoc_dlq_replays (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
+
+ -- The range asked for. Explicit, never inferred: an operator naming the
+ -- partition and offset has decided what to replay, where "replay the
+ -- backlog" would let one mis-click re-inject a week of traffic.
+ topic TEXT NOT NULL,
+ topic_partition INTEGER NOT NULL,
+ start_offset BIGINT NOT NULL,
+ max_messages INTEGER NOT NULL,
+
+ -- False is the default at every layer above this. A replay that has not
+ -- been previewed is a replay nobody has checked the cause of.
+ executed BOOLEAN NOT NULL DEFAULT FALSE,
+
+ -- What the re-validation found. `refused` is the safety property: a
+ -- message that still fails the same validation that rejected it is not
+ -- produced, because replaying a poison batch into the consumer that
+ -- refused it reproduces the outage it caused.
+ messages_read INTEGER NOT NULL DEFAULT 0,
+ would_pass INTEGER NOT NULL DEFAULT 0,
+ refused INTEGER NOT NULL DEFAULT 0,
+ produced INTEGER NOT NULL DEFAULT 0,
+
+ -- 'queued' | 'completed' | 'failed'. A run that never terminates is
+ -- indistinguishable from a slow one, so the terminal states are stored
+ -- rather than inferred from the absence of a result.
+ status TEXT NOT NULL DEFAULT 'queued',
+ error TEXT,
+
+ requested_by UUID REFERENCES users(id) ON DELETE SET NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ completed_at TIMESTAMPTZ,
+
+ CONSTRAINT aisoc_dlq_replays_status_known
+ CHECK (status IN ('queued', 'completed', 'failed')),
+ -- A replay with no ceiling is the unbounded re-injection this table
+ -- exists to prevent, so the bound is a constraint and not a convention.
+ CONSTRAINT aisoc_dlq_replays_bounded
+ CHECK (max_messages > 0 AND max_messages <= 1000),
+ CONSTRAINT aisoc_dlq_replays_offset_non_negative
+ CHECK (start_offset >= 0 AND topic_partition >= 0)
+);
+
+CREATE INDEX IF NOT EXISTS idx_dlq_replays_tenant_time
+ ON aisoc_dlq_replays (tenant_id, created_at DESC);
+
+COMMENT ON TABLE aisoc_dlq_replays IS
+ 'Operator replays of refused messages from a Kafka offset. Written by '
+ 'POST /api/v1/health/dead-letters/replay; one row per request including '
+ 'dry runs, because a preview that found the cause unfixed is a finding.';
+
+-- Row-level security. The `OR current_tenant_id() IS NULL` arm is what lets
+-- the cross-tenant workers reach this table on a connection that binds no
+-- tenant; dropping it makes those silently see nothing. FORCE so the owner
+-- does not walk past, because the owner is the role that runs migrations.
+ALTER TABLE aisoc_dlq_replays ENABLE ROW LEVEL SECURITY;
+ALTER TABLE aisoc_dlq_replays FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS aisoc_dlq_replays_tenant ON aisoc_dlq_replays;
+CREATE POLICY aisoc_dlq_replays_tenant ON aisoc_dlq_replays
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+-- `ALTER DEFAULT PRIVILEGES` from 061 only covers tables created by the role
+-- that ran it, so a new table needs its grant stated.
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'aisoc_app') THEN
+ GRANT SELECT, INSERT, UPDATE ON aisoc_dlq_replays TO aisoc_app;
+ END IF;
+END
+$$;
diff --git a/services/api/tests/test_dlq_replay_gateway.py b/services/api/tests/test_dlq_replay_gateway.py
new file mode 100644
index 000000000..20a82a053
--- /dev/null
+++ b/services/api/tests/test_dlq_replay_gateway.py
@@ -0,0 +1,178 @@
+"""The operator door onto a DLQ replay (deferral 5b).
+
+Fusion owns whether a message is safe to replay. This half owns whether the
+*action* is safe to take, and the three properties below are what that means:
+the attempt is recorded before it is made, a failure says why instead of
+returning zeros that read like success, and the bound is enforced here as
+well as downstream.
+"""
+
+from __future__ import annotations
+
+import uuid
+
+import pytest
+from app.services.dlq_replay_gateway import (
+ MAX_REPLAY_MESSAGES,
+ DlqReplayRequest,
+ run_replay,
+)
+from pydantic import ValidationError
+
+
+class _FakeResult:
+ def __init__(self, value: object) -> None:
+ self._value = value
+
+ def scalar_one(self) -> object:
+ return self._value
+
+
+class _RecordingSession:
+ """Captures the statements a replay writes, in order."""
+
+ def __init__(self, replay_id: uuid.UUID | None = None) -> None:
+ self.replay_id = replay_id or uuid.uuid4()
+ self.statements: list[tuple[str, dict]] = []
+ self.commits = 0
+
+ async def execute(self, statement: object, params: dict | None = None) -> _FakeResult:
+ self.statements.append((str(statement).strip().split()[0].upper(), params or {}))
+ return _FakeResult(self.replay_id)
+
+ async def commit(self) -> None:
+ self.commits += 1
+
+
+def _request(**overrides: object) -> DlqReplayRequest:
+ base: dict = {"topic": "aisoc.raw_events", "partition": 0, "start_offset": 42, "max_messages": 10}
+ return DlqReplayRequest(**{**base, **overrides})
+
+
+class TestTheRequestShapeIsSafeByDefault:
+ def test_execute_defaults_to_a_dry_run(self) -> None:
+ """The dangerous direction is a caller who omits the field."""
+ assert _request().execute is False
+
+ @pytest.mark.parametrize(
+ "overrides",
+ [
+ {"max_messages": 0},
+ {"max_messages": MAX_REPLAY_MESSAGES + 1},
+ {"partition": -1},
+ {"start_offset": -1},
+ {"topic": ""},
+ ],
+ )
+ def test_an_unbounded_or_negative_request_is_refused_by_the_model(self, overrides: dict) -> None:
+ with pytest.raises(ValidationError):
+ _request(**overrides)
+
+ def test_the_cap_matches_the_one_fusion_and_the_migration_enforce(self) -> None:
+ """Three layers, and they must be the same number.
+
+ A bound that lives only in a request model is a bound a
+ service-to-service caller skips, so it is restated in fusion and as a
+ CHECK constraint. If they ever disagree, the weakest one is the real
+ one — which is why this reads the migration rather than trusting it.
+ """
+ from pathlib import Path
+
+ migration = Path(__file__).resolve().parents[1] / "migrations" / "075_dead_letter_replay.sql"
+ assert f"max_messages <= {MAX_REPLAY_MESSAGES}" in migration.read_text(encoding="utf-8")
+
+
+class TestTheAttemptIsRecordedBeforeItIsMade:
+ @pytest.mark.asyncio
+ async def test_the_row_is_inserted_and_committed_before_fusion_is_called(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """A replay that hangs must still have left evidence it started."""
+ session = _RecordingSession()
+ monkeypatch.delenv("FUSION_SERVICE_URL", raising=False)
+ monkeypatch.delenv("FUSION_URL", raising=False)
+
+ await run_replay(session, tenant_id=uuid.uuid4(), requested_by=uuid.uuid4(), request=_request())
+
+ assert session.statements[0][0] == "INSERT"
+ assert session.commits >= 1
+
+ @pytest.mark.asyncio
+ async def test_the_actor_is_stamped_on_the_row(self) -> None:
+ session = _RecordingSession()
+ actor = uuid.uuid4()
+
+ await run_replay(session, tenant_id=uuid.uuid4(), requested_by=actor, request=_request())
+
+ assert session.statements[0][1]["requested_by"] == str(actor)
+
+
+class TestAFailureSaysWhy:
+ @pytest.mark.asyncio
+ async def test_an_unconfigured_fusion_reports_the_reason_not_an_empty_success(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """`produced: 0` with no reason reads exactly like 'nothing to do'.
+
+ That reading is how an operator concludes a queue was drained when
+ the replay never ran at all.
+ """
+ monkeypatch.delenv("FUSION_SERVICE_URL", raising=False)
+ monkeypatch.delenv("FUSION_URL", raising=False)
+ session = _RecordingSession()
+
+ response = await run_replay(session, tenant_id=uuid.uuid4(), requested_by=None, request=_request())
+
+ assert response.status == "failed"
+ assert response.error is not None
+ assert "FUSION_SERVICE_URL" in response.error
+ assert response.produced == 0
+
+ @pytest.mark.asyncio
+ async def test_the_failure_is_written_back_to_the_row(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("FUSION_SERVICE_URL", raising=False)
+ monkeypatch.delenv("FUSION_URL", raising=False)
+ session = _RecordingSession()
+
+ await run_replay(session, tenant_id=uuid.uuid4(), requested_by=None, request=_request())
+
+ kinds = [kind for kind, _ in session.statements]
+ assert kinds == ["INSERT", "UPDATE"]
+ assert session.statements[-1][1]["status"] == "failed"
+ assert session.statements[-1][1]["error"]
+
+
+class TestASuccessfulReplayIsRecordedFaithfully:
+ @pytest.mark.asyncio
+ async def test_the_counts_fusion_reported_reach_both_the_row_and_the_response(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ import httpx
+ from app.services import dlq_replay_gateway
+
+ monkeypatch.setenv("FUSION_SERVICE_URL", "http://fusion.test")
+ body = {
+ "executed": True,
+ "messages_read": 7,
+ "would_pass": 5,
+ "refused": 2,
+ "produced": 5,
+ "refusals": {"missing or non-object 'ocsf_event'": 2},
+ "produced_offsets": [10, 11, 12, 13, 14],
+ }
+
+ class _Client:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_exc):
+ return False
+
+ async def post(self, *_args, **_kwargs):
+ return httpx.Response(200, json=body)
+
+ monkeypatch.setattr(dlq_replay_gateway.httpx, "AsyncClient", lambda **_kw: _Client())
+ session = _RecordingSession()
+
+ response = await run_replay(session, tenant_id=uuid.uuid4(), requested_by=None, request=_request(execute=True))
+
+ assert response.status == "completed"
+ assert (response.messages_read, response.would_pass, response.refused, response.produced) == (7, 5, 2, 5)
+ # The refusal reasons survive to the operator: "two failed for the
+ # same reason" is the finding, not the list of offsets.
+ assert response.refusals == {"missing or non-object 'ocsf_event'": 2}
+ assert session.statements[-1][1]["produced"] == 5
diff --git a/services/fusion/app/api/router.py b/services/fusion/app/api/router.py
index 729e4ec5d..cf4557f58 100644
--- a/services/fusion/app/api/router.py
+++ b/services/fusion/app/api/router.py
@@ -4,6 +4,7 @@ from typing import Annotated
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Query
+from pydantic import BaseModel, Field
from app.models.alert import AnalystFeedback, FusedAlert, FusionDecision, RawAlert
from app.security.tenant_scope import (
@@ -11,6 +12,7 @@ from app.security.tenant_scope import (
require_console_or_service_auth,
scoped_tenant_or_403,
)
+from app.services.dlq_replay import MAX_REPLAY_MESSAGES, ReplayRefused, replay_from_offset
from app.workers.consumer import FusionWorker
#: The console reaches this service *directly* through a Next rewrite when
@@ -205,3 +207,57 @@ async def score_confidence(alert: RawAlert, principal: ScopedPrincipal):
"confidence_score": scored.confidence_score,
"rationale": [f.model_dump() for f in scored.confidence_rationale],
}
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# Dead-letter replay (deferral 5b)
+# ─────────────────────────────────────────────────────────────────────────────
+
+
+class DlqReplayRequest(BaseModel):
+ """A bounded, explicit range to re-read and re-validate.
+
+ Every field is required except ``execute``, which defaults to a dry run.
+ There is no "replay the backlog" shape: a range somebody typed is a range
+ somebody is accountable for, and an inferred one is a mis-click away from
+ re-injecting a week of traffic.
+ """
+
+ topic: str
+ partition: int = Field(ge=0)
+ start_offset: int = Field(ge=0)
+ max_messages: int = Field(default=100, ge=1, le=MAX_REPLAY_MESSAGES)
+ #: Off by default at every layer. A replay nobody previewed is a replay
+ #: nobody has checked the cause of.
+ execute: bool = False
+
+
[email protected]("/dlq/replay")
+async def replay_dead_letters(request: DlqReplayRequest, principal: ScopedPrincipal) -> dict:
+ """Re-read a range of refused messages and produce only what now passes.
+
+ This service owns the execution because it owns the three things a safe
+ replay needs in one place: the topic, the producer, and the validator
+ that refused the messages in the first place. The operator door is
+ ``POST /api/v1/health/dead-letters/replay`` on the API, which holds the
+ permission, the tenant session and the audit row — the same split as
+ ``siem_writeback`` and the playbook action bridge, and for the same
+ reason.
+
+ A message that still fails validation is refused a second time rather
+ than produced. That is the property that stops a replay reproducing the
+ outage that filled the queue.
+ """
+ try:
+ outcome = await replay_from_offset(
+ topic=request.topic,
+ partition=request.partition,
+ start_offset=request.start_offset,
+ max_messages=request.max_messages,
+ execute=request.execute,
+ )
+ except ReplayRefused as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ except Exception as exc: # noqa: BLE001 — a broker fault is a 502, not a 500
+ raise HTTPException(status_code=502, detail=f"replay could not run: {type(exc).__name__}: {exc}") from exc
+ return outcome.as_dict()
diff --git a/services/fusion/app/services/dlq.py b/services/fusion/app/services/dlq.py
index 38a0135f4..d071f1f40 100644
--- a/services/fusion/app/services/dlq.py
+++ b/services/fusion/app/services/dlq.py
@@ -46,6 +46,12 @@ class DeadLetter:
payload_excerpt: str
source_event_id: str | None = None
tenant_id: str | None = None
+ #: Where the refused message actually lives. The excerpt above is a
+ #: triage record and is truncated on purpose; these are how the faithful
+ #: copy is found again for a replay (deferral 5b). Optional because a
+ #: dead letter can be raised from a path that never saw a Kafka record.
+ partition: int | None = None
+ offset: int | None = None
ts: str = field(default_factory=lambda: datetime.now(UTC).isoformat())
@classmethod
@@ -58,6 +64,8 @@ class DeadLetter:
payload: Any,
source_event_id: str | None = None,
tenant_id: str | None = None,
+ partition: int | None = None,
+ offset: int | None = None,
) -> DeadLetter:
try:
excerpt = json.dumps(payload, default=str)[:_MAX_PAYLOAD_CHARS]
@@ -70,6 +78,8 @@ class DeadLetter:
payload_excerpt=excerpt,
source_event_id=source_event_id,
tenant_id=tenant_id,
+ partition=partition,
+ offset=offset,
)
def to_dict(self) -> dict[str, Any]:
@@ -80,6 +90,8 @@ class DeadLetter:
"payload_excerpt": self.payload_excerpt,
"source_event_id": self.source_event_id,
"tenant_id": self.tenant_id,
+ "partition": self.partition,
+ "offset": self.offset,
"ts": self.ts,
}
diff --git a/services/fusion/app/services/dlq_replay.py b/services/fusion/app/services/dlq_replay.py
new file mode 100644
index 000000000..8a4df8737
--- /dev/null
+++ b/services/fusion/app/services/dlq_replay.py
@@ -0,0 +1,301 @@
+"""Replay refused messages from a Kafka offset, once the cause is fixed (5b).
+
+Phase 5 gave the pipeline somewhere to put a message it could not process.
+It did not give an operator a way to get one back. ``GET
+/api/v1/health/dead-letters`` reports the backlog and nothing consumed it,
+which makes the dead-letter queue an audit trail rather than a recovery
+mechanism.
+
+The obvious implementation is the dangerous one
+-----------------------------------------------
+"Re-send the dead letters" fails twice over.
+
+It cannot work. ``aisoc_dead_letters`` stores a 2,000-character excerpt, and
+that truncation is deliberate: the payload is the thing the pipeline refused,
+so it is untrusted by definition and may be large or hostile. The row is a
+triage record. The faithful copy is in Kafka, and this reads it from there.
+
+And it should not work like that anyway. Replaying a poison batch into the
+same consumer that rejected it reproduces the outage that filled the queue in
+the first place. So the safety property here is not a bound or a permission —
+those matter and are below — it is this:
+
+ **A message is re-validated before it is produced, by the same validator
+ that refused it, and one that still fails is refused again rather than
+ replayed.**
+
+That turns "the operator believes they fixed the cause" into something the
+machine checks. If the fix did not land, the replay produces nothing and says
+how many would still fail. The failure mode it removes is the one where a
+confident operator re-injects a thousand messages at 3am and takes the
+consumer down a second time.
+
+Four properties, stated because each was a decision
+----------------------------------------------------
+**Deliberate.** The caller names ``(topic, partition, start_offset)``. There
+is no "replay the backlog" and no offset inferred from a row, because a range
+somebody chose is a range somebody is accountable for.
+
+**Bounded.** ``max_messages`` is capped at :data:`MAX_REPLAY_MESSAGES` here,
+by a CHECK constraint in migration 075, and by the API's own validation. A
+read that finds nothing at the offset stops rather than waiting, so a typo'd
+offset returns an empty preview instead of hanging.
+
+**Authorised and observable** are the API's half, not this module's: the
+operator door carries the permission, stamps the actor and writes the
+``aisoc_dlq_replays`` row. This function is the execution, and returns
+everything that row needs.
+
+**Dry run is the default** everywhere above this function. ``execute=False``
+reads and validates and produces nothing, so the normal way to use this is to
+find out what would happen.
+
+Where a replayed message goes
+-----------------------------
+Back to the topic it came from, so it takes the ordinary path through the
+ordinary consumer — nothing about the processing is special-cased for a
+replay. That is safe to do twice because ``RawAlert.deterministic_id()`` is
+replay-stable and ``alert_sink`` is ``ON CONFLICT (id) DO NOTHING``; the
+ClickHouse lake is the known exception and can gain a duplicate row.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any
+
+import structlog
+
+from app.core.config import settings
+from app.services.event_schema import validate_event
+
+logger = structlog.get_logger()
+
+#: Hard ceiling on one replay. Mirrored by a CHECK constraint in migration
+#: 075 and by the API's request validation — three layers, because the one
+#: that matters is whichever the caller reaches first, and a bound that lives
+#: only in a request model is a bound a service-to-service caller skips.
+MAX_REPLAY_MESSAGES = 1000
+
+#: How long to wait for messages at the offset before concluding there are
+#: none. A replay that blocks forever on an offset past the end of the log is
+#: indistinguishable from a slow broker, and an operator cannot tell which.
+READ_TIMEOUT_MS = 5_000
+
+
+@dataclass
+class ReplayOutcome:
+ """What a replay read, refused and produced."""
+
+ topic: str
+ partition: int
+ start_offset: int
+ max_messages: int
+ executed: bool
+
+ messages_read: int = 0
+ would_pass: int = 0
+ refused: int = 0
+ produced: int = 0
+
+ #: Why each refused message was refused, deduplicated with a count. The
+ #: list of offsets is a list; "forty-eight still fail schema validation
+ #: on the same reason" is a finding.
+ refusals: dict[str, int] = field(default_factory=dict)
+ #: Offsets actually produced, so the action is reconstructable.
+ produced_offsets: list[int] = field(default_factory=list)
+ error: str | None = None
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "topic": self.topic,
+ "partition": self.partition,
+ "start_offset": self.start_offset,
+ "max_messages": self.max_messages,
+ "executed": self.executed,
+ "messages_read": self.messages_read,
+ "would_pass": self.would_pass,
+ "refused": self.refused,
+ "produced": self.produced,
+ "refusals": dict(sorted(self.refusals.items(), key=lambda kv: -kv[1])),
+ "produced_offsets": self.produced_offsets,
+ "error": self.error,
+ }
+
+
+class ReplayRefused(ValueError):
+ """The request itself is not one this service will attempt."""
+
+
+def _validate_request(topic: str, partition: int, start_offset: int, max_messages: int) -> None:
+ if not topic:
+ raise ReplayRefused("topic is required; a replay names the topic it reads from")
+ if partition < 0:
+ raise ReplayRefused(f"partition must be >= 0, got {partition}")
+ if start_offset < 0:
+ raise ReplayRefused(f"start_offset must be >= 0, got {start_offset}")
+ if max_messages < 1 or max_messages > MAX_REPLAY_MESSAGES:
+ raise ReplayRefused(f"max_messages must be between 1 and {MAX_REPLAY_MESSAGES}, got {max_messages}")
+ known = {settings.kafka_topic_raw_events, settings.kafka_topic_alerts_raw}
+ if topic not in known:
+ # Not a permissions check — a shape check. This service can only
+ # re-validate a topic whose schema it knows, and producing to one it
+ # cannot validate would skip the property the whole module is for.
+ raise ReplayRefused(
+ f"'{topic}' is not a topic this service validates ({', '.join(sorted(known))}), so a replay of it could not be re-checked"
+ )
+
+
+def classify(payload: Any, topic: str) -> tuple[bool, str]:
+ """Would this message pass the validation that refused it? With the reason."""
+ result = validate_event(
+ topic,
+ payload,
+ raw_events_topic=settings.kafka_topic_raw_events,
+ alerts_raw_topic=settings.kafka_topic_alerts_raw,
+ )
+ return result.ok, result.reason
+
+
+async def replay_from_offset(
+ *,
+ topic: str,
+ partition: int,
+ start_offset: int,
+ max_messages: int,
+ execute: bool = False,
+ consumer_factory: Any = None,
+ producer_factory: Any = None,
+) -> ReplayOutcome:
+ """Read a bounded range, re-validate it, and produce only what now passes.
+
+ ``execute=False`` is a true dry run: the producer is never constructed,
+ so a preview cannot re-inject anything even if the code below is wrong.
+
+ The factories exist for the tests, which drive the whole path without a
+ broker. Production passes neither.
+ """
+ _validate_request(topic, partition, start_offset, max_messages)
+ outcome = ReplayOutcome(
+ topic=topic,
+ partition=partition,
+ start_offset=start_offset,
+ max_messages=max_messages,
+ executed=execute,
+ )
+
+ consumer = await _build_consumer(topic, partition, start_offset, consumer_factory)
+ producer = await _build_producer(producer_factory) if execute else None
+
+ try:
+ batches = await consumer.getmany(timeout_ms=READ_TIMEOUT_MS, max_records=max_messages)
+ records = [record for partition_records in batches.values() for record in partition_records]
+ records.sort(key=lambda r: r.offset)
+
+ for record in records[:max_messages]:
+ outcome.messages_read += 1
+ ok, reason = classify(record.value, topic)
+ if not ok:
+ # The safety property. The cause is evidently not fixed for
+ # this message, so it is refused a second time rather than
+ # re-injected into the consumer that refused it first.
+ outcome.refused += 1
+ outcome.refusals[reason] = outcome.refusals.get(reason, 0) + 1
+ continue
+
+ outcome.would_pass += 1
+ if producer is None:
+ continue
+ await producer.send_and_wait(topic, value=record.value)
+ outcome.produced += 1
+ outcome.produced_offsets.append(record.offset)
+
+ logger.info(
+ "dlq_replay.completed",
+ topic=topic,
+ partition=partition,
+ start_offset=start_offset,
+ executed=execute,
+ read=outcome.messages_read,
+ would_pass=outcome.would_pass,
+ refused=outcome.refused,
+ produced=outcome.produced,
+ )
+ finally:
+ # Both are per-replay and must not outlive it: a leaked consumer keeps
+ # a broker connection open for a one-shot read.
+ for client in (consumer, producer):
+ if client is not None:
+ try:
+ await client.stop()
+ except Exception as exc: # noqa: BLE001 — teardown must not mask the outcome
+ logger.warning("dlq_replay.teardown_failed", error=str(exc))
+
+ return outcome
+
+
+async def _build_consumer(topic: str, partition: int, start_offset: int, factory: Any) -> Any:
+ if factory is not None:
+ return await factory(topic, partition, start_offset)
+
+ # Imported here so the module is importable — and unit-testable through
+ # the factories — in an environment with no Kafka client, which is how
+ # the schema-validation half is exercised without a broker.
+ from aiokafka import AIOKafkaConsumer, TopicPartition # noqa: PLC0415
+
+ consumer = AIOKafkaConsumer(
+ bootstrap_servers=settings.kafka_bootstrap_servers,
+ # No group_id, deliberately. A replay must not join the consumer
+ # group it is repairing: joining triggers a rebalance on a pipeline
+ # already in trouble, and committing offsets from a one-shot read
+ # would move the live consumer's position.
+ enable_auto_commit=False,
+ value_deserializer=_decode,
+ )
+ await consumer.start()
+ target = TopicPartition(topic, partition)
+ consumer.assign([target])
+ consumer.seek(target, start_offset)
+ return consumer
+
+
+async def _build_producer(factory: Any) -> Any:
+ if factory is not None:
+ return await factory()
+
+ from aiokafka import AIOKafkaProducer # noqa: PLC0415
+
+ producer = AIOKafkaProducer(
+ bootstrap_servers=settings.kafka_bootstrap_servers,
+ value_serializer=_encode,
+ )
+ await producer.start()
+ return producer
+
+
+def _decode(raw: bytes) -> Any:
+ import json # noqa: PLC0415
+
+ try:
+ return json.loads(raw.decode("utf-8"))
+ except (UnicodeDecodeError, json.JSONDecodeError):
+ # Undecodable is a legitimate answer and must reach the validator as
+ # one: it will refuse it, which is the correct outcome and is counted
+ # as a refusal rather than crashing the whole replay on one message.
+ return {"__undecodable__": True}
+
+
+def _encode(value: Any) -> bytes:
+ import json # noqa: PLC0415
+
+ return json.dumps(value).encode("utf-8")
+
+
+__all__ = [
+ "MAX_REPLAY_MESSAGES",
+ "READ_TIMEOUT_MS",
+ "ReplayOutcome",
+ "ReplayRefused",
+ "classify",
+ "replay_from_offset",
+]
diff --git a/services/fusion/app/services/dlq_sink.py b/services/fusion/app/services/dlq_sink.py
index 7c9d38983..8bb6dc508 100644
--- a/services/fusion/app/services/dlq_sink.py
+++ b/services/fusion/app/services/dlq_sink.py
@@ -42,8 +42,9 @@ MAX_EXCERPT = 2000
_INSERT_SQL = """
INSERT INTO aisoc_dead_letters
- (tenant_id, topic, reason, schema_version, payload_excerpt, source_event_id)
-VALUES ($1, $2, $3, $4, $5, $6)
+ (tenant_id, topic, reason, schema_version, payload_excerpt, source_event_id,
+ topic_partition, kafka_offset)
+VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
"""
@@ -95,6 +96,11 @@ class PostgresDLQ(DeadLetterQueue):
letter.schema_version,
excerpt,
letter.source_event_id,
+ # Nullable, and left null rather than guessed when the
+ # refusal came from a path with no Kafka record behind it
+ # — a fabricated offset replays somebody else's message.
+ letter.partition,
+ letter.offset,
)
except Exception as exc: # noqa: BLE001 - see the module docstring
# Losing the record of a dropped event is bad. Stopping the
diff --git a/services/fusion/app/workers/consumer.py b/services/fusion/app/workers/consumer.py
index dcc76a78d..6ed61274b 100644
--- a/services/fusion/app/workers/consumer.py
+++ b/services/fusion/app/workers/consumer.py
@@ -176,7 +176,7 @@ class FusionWorker:
if not self._running:
break
try:
- await self._process_message(msg.value, topic=msg.topic)
+ 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)
@@ -215,8 +215,16 @@ class FusionWorker:
schema_version: str = "v1",
source_event_id: str | None = None,
tenant_id: str | None = None,
+ partition: int | None = None,
+ offset: int | None = None,
) -> None:
- """Route a poison message to the DLQ instead of dropping it silently."""
+ """Route a poison message to the DLQ instead of dropping it silently.
+
+ ``partition`` and ``offset`` are carried through because the excerpt
+ stored alongside them is a triage record, not the event: replaying a
+ refused message means re-reading it from Kafka, and these are the only
+ way back to it (deferral 5b).
+ """
_METRICS["dead_lettered"] += 1
await safe_record(
self._dlq,
@@ -227,10 +235,14 @@ class FusionWorker:
payload=payload,
source_event_id=source_event_id,
tenant_id=tenant_id,
+ partition=partition,
+ offset=offset,
),
)
- async def _process_message(self, payload: dict, topic: str | None = None) -> None:
+ async def _process_message(
+ self, payload: dict, topic: str | None = None, partition: int | None = None, offset: int | None = None
+ ) -> None:
resolved_topic = topic or settings.kafka_topic_alerts_raw
# Phase A4 — UEBA anomaly stream: warm the per-entity signal cache and
@@ -256,6 +268,8 @@ class FusionWorker:
schema_version=validation.schema_version,
source_event_id=validation.source_event_id,
tenant_id=validation.tenant_id,
+ partition=partition,
+ offset=offset,
)
return
@@ -306,6 +320,8 @@ class FusionWorker:
schema_version=validation.schema_version,
source_event_id=validation.source_event_id,
tenant_id=validation.tenant_id,
+ partition=partition,
+ offset=offset,
)
return
diff --git a/services/fusion/tests/integration/__init__.py b/services/fusion/tests/integration/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/services/fusion/tests/integration/test_dlq_replay_live.py b/services/fusion/tests/integration/test_dlq_replay_live.py
new file mode 100644
index 000000000..06950dbe3
--- /dev/null
+++ b/services/fusion/tests/integration/test_dlq_replay_live.py
@@ -0,0 +1,116 @@
+"""A real replay, against a real broker.
+
+The unit tests drive `replay_from_offset` with fake clients, which proves the
+validation, the bounds and the dry-run guarantee but says nothing about the
+part most likely to be wrong: assigning a partition, seeking to an offset,
+and reading only from there. A consumer that silently reads from the
+beginning of the log would pass every unit test in the suite and re-inject
+the whole topic in production.
+
+So this seeks past a message and asserts it was not read.
+
+Skips cleanly when no broker is reachable, and says so rather than passing
+quietly — a skipped integration test that reads like a pass is how a
+never-executed gate stays green.
+
+ docker run -d --name aisoc-5b-redpanda -p 19092:19092 \
+ docker.redpanda.com/redpandadata/redpanda:v24.2.7 \
+ redpanda start --overprovisioned --smp 1 --memory 512M \
+ --node-id 0 --check=false \
+ --kafka-addr PLAINTEXT://0.0.0.0:19092 \
+ --advertise-kafka-addr PLAINTEXT://127.0.0.1:19092
+
+ AISOC_TEST_KAFKA=127.0.0.1:19092 pytest tests/integration/test_dlq_replay_live.py
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import uuid
+
+import pytest
+
+BROKER = os.getenv("AISOC_TEST_KAFKA", "").strip()
+pytestmark = pytest.mark.skipif(not BROKER, reason="set AISOC_TEST_KAFKA=host:port to run the live replay proof")
+
+TOPIC = "aisoc.raw_events"
+
+
+def _good(uid: str) -> dict:
+ return {
+ "schema_version": "v1",
+ "tenant_id": str(uuid.uuid4()),
+ "ocsf_event": {"class_uid": 2001, "metadata": {"uid": uid}},
+ }
+
+
+def _poison() -> dict:
+ """Refused for the same reason the pipeline refuses it: no ocsf_event."""
+ return {"schema_version": "v1", "tenant_id": str(uuid.uuid4())}
+
+
+async def _produce(messages: list[dict]) -> list[int]:
+ from aiokafka import AIOKafkaProducer
+
+ producer = AIOKafkaProducer(bootstrap_servers=BROKER, value_serializer=lambda v: json.dumps(v).encode())
+ await producer.start()
+ try:
+ return [(await producer.send_and_wait(TOPIC, value=m)).offset for m in messages]
+ finally:
+ await producer.stop()
+
+
[email protected](autouse=True)
+def _point_settings_at_the_test_broker(monkeypatch: pytest.MonkeyPatch):
+ from app.core import config
+
+ monkeypatch.setattr(config.settings, "kafka_bootstrap_servers", BROKER)
+ yield
+
+
+async def test_a_real_replay_seeks_refuses_and_produces() -> None:
+ from app.services.dlq_replay import replay_from_offset
+
+ # Three messages: one before the replay window, one poison, one good.
+ offsets = await _produce([_good("before-the-window"), _poison(), _good("fixed")])
+ before, poison_offset, good_offset = offsets
+ await asyncio.sleep(0.5)
+
+ # ── Dry run from the poison offset ───────────────────────────────────
+ preview = await replay_from_offset(topic=TOPIC, partition=0, start_offset=poison_offset, max_messages=10, execute=False)
+
+ # The seek actually happened: the message before the window was not read.
+ assert preview.messages_read == 2, (
+ f"read {preview.messages_read} — the consumer did not honour the seek to {poison_offset} (offset {before} should be excluded)"
+ )
+ assert preview.refused == 1
+ assert preview.would_pass == 1
+ assert preview.produced == 0, "a dry run produced a message"
+
+ # ── Execute, and confirm only the valid one lands ────────────────────
+ result = await replay_from_offset(topic=TOPIC, partition=0, start_offset=poison_offset, max_messages=10, execute=True)
+ assert result.refused == 1, "the poison message was not refused a second time"
+ assert result.produced == 1
+ assert result.produced_offsets == [good_offset]
+
+ # The replayed message is really on the topic, one past the original tail.
+ await asyncio.sleep(0.5)
+ tail = await replay_from_offset(topic=TOPIC, partition=0, start_offset=good_offset + 1, max_messages=10, execute=False)
+ assert tail.messages_read == 1, "the produced message is not on the topic"
+ assert tail.would_pass == 1
+
+
+async def test_an_offset_past_the_end_returns_empty_rather_than_hanging() -> None:
+ """A typo'd offset must be a fast empty answer, not an indefinite wait."""
+ from app.services.dlq_replay import replay_from_offset
+
+ outcome = await asyncio.wait_for(
+ replay_from_offset(topic=TOPIC, partition=0, start_offset=10_000_000, max_messages=10, execute=False),
+ timeout=30,
+ )
+ assert outcome.messages_read == 0
+ assert outcome.produced == 0
diff --git a/services/fusion/tests/test_dlq_replay.py b/services/fusion/tests/test_dlq_replay.py
new file mode 100644
index 000000000..1f8ed289f
--- /dev/null
+++ b/services/fusion/tests/test_dlq_replay.py
@@ -0,0 +1,274 @@
+"""Replaying a refused message, and refusing to replay a poison one (5b).
+
+The property under test is the one that makes this feature safe rather than
+merely possible: a message is re-validated by the validator that refused it,
+and one that still fails is refused again instead of being produced. A
+replay that skips that check reproduces the outage that filled the queue.
+
+Everything here drives the real `replay_from_offset` with fake broker
+clients, so the validation path, the bounds, the ordering and the dry-run
+guarantee are all exercised. The broker itself is proved separately, against
+a live one.
+"""
+
+from __future__ import annotations
+
+import uuid
+from types import SimpleNamespace
+
+import pytest
+from app.services.dlq_replay import (
+ MAX_REPLAY_MESSAGES,
+ ReplayRefused,
+ classify,
+ replay_from_offset,
+)
+
+TOPIC = "aisoc.raw_events"
+
+
+def _good(event_id: str = "e1") -> dict:
+ """An envelope the schema registry accepts."""
+ return {
+ "schema_version": "v1",
+ "tenant_id": str(uuid.uuid4()),
+ "ocsf_event": {"class_uid": 2001, "metadata": {"uid": event_id}},
+ }
+
+
+def _poison_missing_ocsf() -> dict:
+ return {"schema_version": "v1", "tenant_id": str(uuid.uuid4())}
+
+
+def _poison_bad_tenant() -> dict:
+ return {"schema_version": "v1", "tenant_id": "not-a-uuid", "ocsf_event": {"class_uid": 2001}}
+
+
+class _FakeConsumer:
+ """Serves a fixed set of records from an offset, like a seeked consumer."""
+
+ def __init__(self, records: list[tuple[int, dict]]) -> None:
+ self._records = records
+ self.stopped = False
+
+ async def getmany(self, *, timeout_ms: int, max_records: int) -> dict:
+ batch = [SimpleNamespace(offset=offset, value=value) for offset, value in self._records[:max_records]]
+ return {"tp": batch}
+
+ async def stop(self) -> None:
+ self.stopped = True
+
+
+class _FakeProducer:
+ def __init__(self) -> None:
+ self.sent: list[tuple[str, dict]] = []
+ self.stopped = False
+
+ async def send_and_wait(self, topic: str, *, value: dict) -> None:
+ self.sent.append((topic, value))
+
+ async def stop(self) -> None:
+ self.stopped = True
+
+
+def _factories(records: list[tuple[int, dict]]) -> tuple:
+ consumer = _FakeConsumer(records)
+ producer = _FakeProducer()
+
+ async def consumer_factory(_topic: str, _partition: int, _offset: int):
+ return consumer
+
+ async def producer_factory():
+ return producer
+
+ return consumer, producer, consumer_factory, producer_factory
+
+
+class TestThePoisonBatchIsRefusedASecondTime:
+ """The whole point. If the cause is not fixed, nothing is produced."""
+
+ @pytest.mark.asyncio
+ async def test_a_message_that_still_fails_is_not_produced(self) -> None:
+ _, producer, cf, pf = _factories([(10, _poison_missing_ocsf())])
+
+ outcome = await replay_from_offset(
+ topic=TOPIC,
+ partition=0,
+ start_offset=10,
+ max_messages=10,
+ execute=True,
+ consumer_factory=cf,
+ producer_factory=pf,
+ )
+
+ assert outcome.messages_read == 1
+ assert outcome.refused == 1
+ assert outcome.produced == 0
+ assert producer.sent == []
+
+ @pytest.mark.asyncio
+ async def test_the_refusal_reason_is_reported_with_a_count(self) -> None:
+ """A list of offsets is data; 'three failed for the same reason' is a finding."""
+ records = [(1, _poison_missing_ocsf()), (2, _poison_missing_ocsf()), (3, _poison_bad_tenant())]
+ _, _, cf, pf = _factories(records)
+
+ outcome = await replay_from_offset(
+ topic=TOPIC,
+ partition=0,
+ start_offset=1,
+ max_messages=10,
+ execute=True,
+ consumer_factory=cf,
+ producer_factory=pf,
+ )
+
+ assert outcome.refused == 3
+ assert sum(outcome.refusals.values()) == 3
+ assert len(outcome.refusals) == 2, outcome.refusals
+
+ @pytest.mark.asyncio
+ async def test_a_mixed_batch_produces_only_the_messages_that_now_pass(self) -> None:
+ records = [(1, _good("a")), (2, _poison_missing_ocsf()), (3, _good("b"))]
+ _, producer, cf, pf = _factories(records)
+
+ outcome = await replay_from_offset(
+ topic=TOPIC,
+ partition=0,
+ start_offset=1,
+ max_messages=10,
+ execute=True,
+ consumer_factory=cf,
+ producer_factory=pf,
+ )
+
+ assert (outcome.would_pass, outcome.refused, outcome.produced) == (2, 1, 2)
+ assert outcome.produced_offsets == [1, 3]
+ assert len(producer.sent) == 2
+
+ def test_classify_agrees_with_the_validator_that_refused_it(self) -> None:
+ assert classify(_good(), TOPIC)[0] is True
+ ok, reason = classify(_poison_missing_ocsf(), TOPIC)
+ assert ok is False
+ assert "ocsf_event" in reason
+
+
+class TestDryRunCannotProduce:
+ @pytest.mark.asyncio
+ async def test_a_dry_run_never_constructs_a_producer(self) -> None:
+ """Not 'does not send' — does not exist.
+
+ A preview that holds a live producer is one bug away from being a
+ replay, so the guarantee is structural rather than conditional.
+ """
+ constructed = False
+
+ async def producer_factory():
+ nonlocal constructed
+ constructed = True
+ raise AssertionError("a dry run must not build a producer")
+
+ consumer, _, cf, _ = _factories([(1, _good())])
+ outcome = await replay_from_offset(
+ topic=TOPIC,
+ partition=0,
+ start_offset=1,
+ max_messages=10,
+ execute=False,
+ consumer_factory=cf,
+ producer_factory=producer_factory,
+ )
+
+ assert constructed is False
+ assert outcome.executed is False
+ assert outcome.would_pass == 1
+ assert outcome.produced == 0
+
+ @pytest.mark.asyncio
+ async def test_a_dry_run_still_reports_what_would_happen(self) -> None:
+ records = [(1, _good("a")), (2, _poison_bad_tenant())]
+ _, _, cf, _ = _factories(records)
+
+ outcome = await replay_from_offset(topic=TOPIC, partition=0, start_offset=1, max_messages=10, execute=False, consumer_factory=cf)
+
+ assert outcome.messages_read == 2
+ assert outcome.would_pass == 1
+ assert outcome.refused == 1
+
+
+class TestItIsBounded:
+ @pytest.mark.asyncio
+ async def test_max_messages_caps_what_is_read(self) -> None:
+ _, producer, cf, pf = _factories([(i, _good(str(i))) for i in range(50)])
+
+ outcome = await replay_from_offset(
+ topic=TOPIC,
+ partition=0,
+ start_offset=0,
+ max_messages=5,
+ execute=True,
+ consumer_factory=cf,
+ producer_factory=pf,
+ )
+
+ assert outcome.messages_read == 5
+ assert len(producer.sent) == 5
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("kwargs", "fragment"),
+ [
+ ({"max_messages": 0}, "between 1 and"),
+ ({"max_messages": MAX_REPLAY_MESSAGES + 1}, "between 1 and"),
+ ({"partition": -1}, "partition must be"),
+ ({"start_offset": -1}, "start_offset must be"),
+ ({"topic": ""}, "topic is required"),
+ ({"topic": "some.other.topic"}, "not a topic this service validates"),
+ ],
+ )
+ async def test_an_unsafe_request_is_refused_before_any_broker_is_touched(self, kwargs: dict, fragment: str) -> None:
+ base: dict = {"topic": TOPIC, "partition": 0, "start_offset": 0, "max_messages": 10}
+
+ async def explode(*_args, **_kw):
+ raise AssertionError("a refused request must not reach the broker")
+
+ with pytest.raises(ReplayRefused) as excinfo:
+ await replay_from_offset(**{**base, **kwargs}, execute=True, consumer_factory=explode, producer_factory=explode)
+
+ assert fragment in str(excinfo.value)
+
+
+class TestItCleansUpAndSurvivesBadInput:
+ @pytest.mark.asyncio
+ async def test_both_clients_are_stopped(self) -> None:
+ consumer, producer, cf, pf = _factories([(1, _good())])
+
+ await replay_from_offset(
+ topic=TOPIC,
+ partition=0,
+ start_offset=1,
+ max_messages=10,
+ execute=True,
+ consumer_factory=cf,
+ producer_factory=pf,
+ )
+
+ assert consumer.stopped and producer.stopped
+
+ @pytest.mark.asyncio
+ async def test_an_undecodable_message_is_refused_rather_than_crashing_the_replay(self) -> None:
+ """One bad message must not cost the other nine their replay."""
+ records = [(1, {"__undecodable__": True}), (2, _good("b"))]
+ _, producer, cf, pf = _factories(records)
+
+ outcome = await replay_from_offset(
+ topic=TOPIC,
+ partition=0,
+ start_offset=1,
+ max_messages=10,
+ execute=True,
+ consumer_factory=cf,
+ producer_factory=pf,
+ )
+
+ assert outcome.refused == 1
+ assert outcome.produced == 1
diff --git a/services/fusion/tests/test_dlq_sink.py b/services/fusion/tests/test_dlq_sink.py
index 7b12b0c52..55baf1424 100644
--- a/services/fusion/tests/test_dlq_sink.py
+++ b/services/fusion/tests/test_dlq_sink.py
@@ -34,8 +34,11 @@ def _pool(execute: AsyncMock | None = None) -> MagicMock:
return pool
-def _letter(**overrides) -> DeadLetter:
- base = {
+def _letter(**overrides: object) -> DeadLetter:
+ # Annotated `object` rather than left bare: DeadLetter gained int
+ # `partition` / `offset` fields in 5b, so an inferred `dict[str, str]`
+ # here would make every override of one of those a type error.
+ base: dict[str, object] = {
"topic": "aisoc.raw_events",
"reason": "schema_validation_failed",
"schema_version": "v1",
@@ -44,7 +47,7 @@ def _letter(**overrides) -> DeadLetter:
"tenant_id": str(uuid.uuid4()),
}
base.update(overrides)
- return DeadLetter(**base)
+ return DeadLetter(**base) # type: ignore[arg-type] # a test builder over a heterogeneous dict
class TestRecording: