Skip to content

armgit / AiSOC

Public Imported from GitHub
0

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

fix(connectors): withhold checkpoints after partial ingest

Shreya Jha168a1f13d9ca
diff --git a/services/connectors/app/connectors/base.py b/services/connectors/app/connectors/base.py
index fda184390..306869e4c 100644
--- a/services/connectors/app/connectors/base.py
+++ b/services/connectors/app/connectors/base.py
@@ -514,7 +514,8 @@ class BaseConnector(ABC):
# The durable half of this shipped already: ``connector_repo.record_checkpoint``
# persists a cursor into ``connector_config.checkpoint``, and the scheduler
# seeds it before each poll and advances it only after ingest accepted the
- # batch, so a failed push never moves it forward.
+ # entire submitted batch, so a failed or partially rejected push never
+ # moves it forward.
#
# What was missing was adoption, and the reason it stayed missing is worth
# keeping. The scheduler reached the connector through
@@ -581,8 +582,9 @@ class BaseConnector(ABC):
def get_checkpoint(self) -> dict[str, str] | None:
"""The advanced cursor after a fetch, or ``None`` if nothing moved.
- The scheduler persists this only once ingest has accepted the batch,
- so a failed ingest never advances it.
+ The scheduler persists this only once ingest has accepted every
+ submitted event, so a failed or partially rejected ingest never
+ advances it.
"""
return self._next_checkpoint
diff --git a/services/connectors/app/scheduler.py b/services/connectors/app/scheduler.py
index 4361ba8e4..4835a11da 100644
--- a/services/connectors/app/scheduler.py
+++ b/services/connectors/app/scheduler.py
@@ -732,17 +732,34 @@ class ConnectorScheduler:
return
accepted = int(result.get("accepted", 0) or 0)
+ rejected = int(result.get("rejected", 0) or 0)
elapsed_ms = int((datetime.now(UTC) - started).total_seconds() * 1000)
- # Advance the persisted checkpoint only now that ingest has accepted the
- # batch (#529). A failed push returned earlier, so reaching here means
- # the page was accepted — this is the "advance only after accept" rule.
+ # Persist the staged cursor only after *every submitted event* was
+ # accepted. Ingest deliberately reports per-event normalization
+ # failures as HTTP 200 with accepted/rejected counts, so HTTP success
+ # alone does not prove that advancing is safe. Replaying an accepted
+ # event on the next overlapping poll is preferable to moving past a
+ # rejected event and losing it permanently.
+ counts_present = "accepted" in result and "rejected" in result
+ batch_fully_accepted = counts_present and rejected == 0 and accepted == len(kept)
try:
new_checkpoint = connector.get_checkpoint()
except Exception: # never let checkpoint bookkeeping break a poll
new_checkpoint = None
if isinstance(new_checkpoint, dict) and new_checkpoint:
- await self._record_checkpoint(target.id, new_checkpoint)
+ if batch_fully_accepted:
+ await self._record_checkpoint(target.id, new_checkpoint)
+ else:
+ logger.warning(
+ "connector.scheduler.checkpoint_withheld id=%s type=%s submitted=%d accepted=%d rejected=%d counts_present=%s",
+ connector_id,
+ target.connector_type,
+ len(kept),
+ accepted,
+ rejected,
+ counts_present,
+ )
# If drift was detected, persist that fact *before* marking the
# poll successful so the UI reflects "drifted" status alongside
@@ -815,7 +832,7 @@ class ConnectorScheduler:
connector_id,
target.connector_type,
accepted,
- int(result.get("rejected", 0) or 0),
+ rejected,
dropped_count,
"yes" if drift_detected else "no",
elapsed_ms,
diff --git a/services/connectors/tests/test_checkpoint_contract.py b/services/connectors/tests/test_checkpoint_contract.py
index 26119603f..0192b5100 100644
--- a/services/connectors/tests/test_checkpoint_contract.py
+++ b/services/connectors/tests/test_checkpoint_contract.py
@@ -1,8 +1,8 @@
"""Ingest checkpoints are a declared contract, not a duck type (10b).
The durable half shipped already: `record_checkpoint` persists a cursor, and
-the scheduler advances it only after ingest accepted the batch. What was
-missing was adoption — `splunk` was the only one of 84 connectors
+the scheduler advances it only after ingest accepted every submitted event.
+What was missing was adoption — `splunk` was the only one of 84 connectors
implementing it, and the scheduler reached it through
`getattr(connector, "set_checkpoint", None)`, which on the other 83 was
simply absent.
@@ -196,9 +196,9 @@ class TestTheSchedulerNoLongerDuckTypes:
assert "connector.set_checkpoint(" in code
assert "connector.get_checkpoint()" in code
- def test_the_advance_still_happens_only_after_ingest_accepts(self) -> None:
- """The whole safety property of the persisted cursor: a batch ingest
- rejected must be re-read, not skipped."""
+ def test_the_advance_still_requires_full_batch_acceptance(self) -> None:
+ """The whole safety property of the persisted cursor: a fully or
+ partially rejected batch must be re-read, not skipped."""
from pathlib import Path
source = (Path(__file__).resolve().parents[1] / "app" / "scheduler.py").read_text(encoding="utf-8")
@@ -206,3 +206,7 @@ class TestTheSchedulerNoLongerDuckTypes:
advance_index = source.index("new_checkpoint = connector.get_checkpoint()")
assert accept_index < advance_index
+ assert '"accepted" in result and "rejected" in result' in source
+ assert "rejected == 0" in source
+ assert "accepted == len(kept)" in source
+ assert "if batch_fully_accepted:" in source
diff --git a/services/connectors/tests/test_scheduler.py b/services/connectors/tests/test_scheduler.py
index 78f22c7c1..69a8ad914 100644
--- a/services/connectors/tests/test_scheduler.py
+++ b/services/connectors/tests/test_scheduler.py
@@ -118,6 +118,104 @@ async def test_poll_one_happy_path(monkeypatch):
assert fake_engine.failure_calls == []
+# ---------------------------------------------------------------------------
+# Checkpoints advance only after full-batch ingest acceptance
+# ---------------------------------------------------------------------------
+
+
+def _checkpointing_connector(events: list[dict[str, Any]]) -> MagicMock:
+ connector = MagicMock()
+ connector.fetch_alerts = AsyncMock(return_value=events)
+ connector.normalize = MagicMock(side_effect=lambda event: event)
+ connector.get_checkpoint.return_value = {"time": "2026-01-01T00:00:02Z", "id": "event-2"}
+ return connector
+
+
+async def test_full_ingest_acceptance_persists_the_staged_checkpoint(monkeypatch):
+ inst = _make_instance(connector_type="fake_connector")
+ events = [{"id": "event-1"}, {"id": "event-2"}]
+ connector = _checkpointing_connector(events)
+ monkeypatch.setattr("app.scheduler.CONNECTOR_REGISTRY", {"fake_connector": MagicMock(return_value=connector)})
+ engine = _FakeEngine([inst])
+ scheduler = ConnectorScheduler(
+ engine=engine,
+ ingest_client=_FakeIngestClient(accepted=2, rejected=0),
+ vault=_FakeVault(),
+ )
+
+ await scheduler._poll_one(connector_id=inst.id)
+
+ assert engine.checkpoint_calls == [
+ {
+ "connector_id": inst.id,
+ "checkpoint": {"time": "2026-01-01T00:00:02Z", "id": "event-2"},
+ }
+ ]
+
+
+ "response",
+ [
+ pytest.param({"accepted": 1, "rejected": 1}, id="partial-rejection"),
+ pytest.param({"accepted": 1, "rejected": 0}, id="accepted-count-too-small"),
+ pytest.param({"accepted": 3, "rejected": 0}, id="accepted-count-too-large"),
+ pytest.param({"accepted": 2}, id="missing-rejected-count"),
+ pytest.param({"rejected": 0}, id="missing-accepted-count"),
+ ],
+)
+async def test_incomplete_ingest_response_withholds_the_checkpoint(monkeypatch, caplog, response):
+ inst = _make_instance(connector_type="fake_connector")
+ connector = _checkpointing_connector([{"id": "event-1"}, {"id": "event-2"}])
+ monkeypatch.setattr("app.scheduler.CONNECTOR_REGISTRY", {"fake_connector": MagicMock(return_value=connector)})
+ engine = _FakeEngine([inst])
+ scheduler = ConnectorScheduler(
+ engine=engine,
+ ingest_client=_FakeIngestClient(response=response),
+ vault=_FakeVault(),
+ )
+
+ with caplog.at_level("WARNING", logger="aisoc.connectors.scheduler"):
+ await scheduler._poll_one(connector_id=inst.id)
+
+ assert engine.checkpoint_calls == []
+ assert "connector.scheduler.checkpoint_withheld" in caplog.text
+ assert "submitted=2" in caplog.text
+ assert f"accepted={int(response.get('accepted', 0) or 0)}" in caplog.text
+ assert f"rejected={int(response.get('rejected', 0) or 0)}" in caplog.text
+ assert f"counts_present={str('accepted' in response and 'rejected' in response)}" in caplog.text
+ assert "event-1" not in caplog.text
+
+
+async def test_empty_fully_processed_batch_may_persist_a_staged_checkpoint(monkeypatch):
+ """Source rows intentionally removed by filters must not replay forever."""
+ inst = _make_instance(
+ connector_type="fake_connector",
+ connector_config={
+ "filter_rules": [{"field": "severity", "op": "eq", "value": "info", "action": "drop"}],
+ },
+ )
+ connector = _checkpointing_connector([{"id": "event-2", "severity": "info"}])
+ monkeypatch.setattr("app.scheduler.CONNECTOR_REGISTRY", {"fake_connector": MagicMock(return_value=connector)})
+ engine = _FakeEngine([inst])
+ scheduler = ConnectorScheduler(
+ engine=engine,
+ ingest_client=_FakeIngestClient(accepted=0, rejected=0),
+ vault=_FakeVault(),
+ )
+
+ await scheduler._poll_one(connector_id=inst.id)
+
+ assert engine.checkpoint_calls == [
+ {
+ "connector_id": inst.id,
+ "checkpoint": {"time": "2026-01-01T00:00:02Z", "id": "event-2"},
+ }
+ ]
+
+
# ---------------------------------------------------------------------------
# Schema-Drift Sentinel + filter-rules pipeline integration
# ---------------------------------------------------------------------------
@@ -426,6 +524,7 @@ async def test_poll_one_ingest_raises(monkeypatch):
fake_connector = MagicMock()
fake_connector.fetch_alerts = AsyncMock(return_value=[{"x": 1}])
fake_connector.normalize = MagicMock(side_effect=lambda e: e)
+ fake_connector.get_checkpoint.return_value = {"time": "2026-01-01T00:00:01Z", "id": "event-1"}
monkeypatch.setattr(
"app.scheduler.CONNECTOR_REGISTRY",
{"fake_connector": MagicMock(return_value=fake_connector)},
@@ -439,6 +538,7 @@ async def test_poll_one_ingest_raises(monkeypatch):
engine: _FakeEngine = scheduler._engine # type: ignore[assignment]
assert engine.failure_calls == [inst.id]
+ assert engine.checkpoint_calls == []
@pytest.mark.asyncio
@@ -831,13 +931,14 @@ class _FakeAsyncContextManager:
class _FakeEngine:
- """Async engine fake that records record_poll_success/failure calls."""
+ """Async engine fake that records scheduler persistence calls."""
def __init__(self, instances: list[ConnectorInstance]) -> None:
self.instances = list(instances)
self.success_calls: list[uuid.UUID] = []
self.failure_calls: list[uuid.UUID] = []
self.drift_calls: list[dict[str, Any]] = []
+ self.checkpoint_calls: list[dict[str, Any]] = []
# Workstream 5: track every record_backfill_run() call so backfill
# tests can assert when the flap-suppress timestamp was stamped.
self.backfill_calls: list[uuid.UUID] = []
@@ -864,9 +965,17 @@ class _FakeVault:
class _FakeIngestClient:
- def __init__(self, accepted: int = 0) -> None:
+ def __init__(
+ self,
+ accepted: int = 0,
+ rejected: int = 0,
+ *,
+ response: dict[str, Any] | None = None,
+ ) -> None:
self.calls = 0
self.accepted = accepted
+ self.rejected = rejected
+ self.response = response
self.last_payload: dict[str, Any] | None = None
self.exc: BaseException | None = None
@@ -875,7 +984,9 @@ class _FakeIngestClient:
self.last_payload = kwargs
if self.exc is not None:
raise self.exc
- return {"accepted": self.accepted, "rejected": 0}
+ if self.response is not None:
+ return dict(self.response)
+ return {"accepted": self.accepted, "rejected": self.rejected}
async def aclose(self) -> None:
return None
@@ -916,6 +1027,13 @@ def _patch_repo_calls(monkeypatch):
) -> None:
getattr(conn.engine, "drift_calls", []).append({"connector_id": connector_id, "fingerprint": fingerprint, "details": details})
+ async def fake_record_checkpoint(
+ conn: Any,
+ connector_id: uuid.UUID,
+ checkpoint: dict[str, Any],
+ ) -> None:
+ conn.engine.checkpoint_calls.append({"connector_id": connector_id, "checkpoint": checkpoint})
+
async def fake_record_backfill_run(
conn: Any,
connector_id: uuid.UUID,
@@ -926,6 +1044,7 @@ def _patch_repo_calls(monkeypatch):
monkeypatch.setattr("app.scheduler.record_poll_success", fake_record_poll_success)
monkeypatch.setattr("app.scheduler.record_poll_failure", fake_record_poll_failure)
monkeypatch.setattr("app.scheduler.record_schema_drift", fake_record_schema_drift)
+ monkeypatch.setattr("app.scheduler.record_checkpoint", fake_record_checkpoint)
monkeypatch.setattr("app.scheduler.record_backfill_run", fake_record_backfill_run)