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
feat(connectors): make the ingest checkpoint a declared contract, and adopt it (10b) (#1039)
Beenu Aroraed5bd4052fc5
diff --git a/services/connectors/app/connectors/aws_cloudtrail.py b/services/connectors/app/connectors/aws_cloudtrail.pyindex e19831d0e..97a0aeaf5 100644--- a/services/connectors/app/connectors/aws_cloudtrail.py+++ b/services/connectors/app/connectors/aws_cloudtrail.py@@ -286,6 +286,10 @@ class AWSCloudTrailConnector(BaseConnector):def capabilities(cls) -> tuple[Capability, ...]:return (Capability.PULL_ALERTS,)+ #: Ingest cursor (10b). `lookup_events` returns `EventTime` and `EventId` on every record; normalize() already reads both.+ checkpoint_time_field = ("EventTime",)+ checkpoint_id_field = ("EventId",)+def __init__(self,region: str = "us-east-1",@@ -385,7 +389,11 @@ class AWSCloudTrailConnector(BaseConnector):)continue- return [self.normalize(e) for e in all_events]+ # Once, over the aggregate: the lookup helper runs per event name,+ # so a cursor applied there would order and de-duplicate each name's+ # page against the others' and advance the checkpoint several times+ # per poll.+ return [self.normalize(e) for e in self.apply_checkpoint(all_events)]@staticmethoddef _lookup_for_attribute(diff --git a/services/connectors/app/connectors/azure_activity.py b/services/connectors/app/connectors/azure_activity.pyindex 11756d174..e51eb6bf2 100644--- a/services/connectors/app/connectors/azure_activity.py+++ b/services/connectors/app/connectors/azure_activity.py@@ -94,6 +94,10 @@ class AzureActivityConnector(BaseConnector):# Azure Activity Logs are control-plane audit events, not security alerts.return (Capability.PULL_AUDIT,)+ #: Ingest cursor (10b). Activity Log entries carry `eventTimestamp` and `eventDataId`; normalize() falls back to `id` and so does this.+ checkpoint_time_field = ("eventTimestamp",)+ checkpoint_id_field = ("eventDataId", "id")+def __init__(self,tenant_id: str,@@ -201,7 +205,7 @@ class AzureActivityConnector(BaseConnector):breakevents.extend(resp.json().get("value", []))- return [self.normalize(e) for e in events]+ return [self.normalize(e) for e in self.apply_checkpoint(events)]# ----------------------- normalize --------------------------diff --git a/services/connectors/app/connectors/base.py b/services/connectors/app/connectors/base.pyindex 717b194a6..97a8670e7 100644--- a/services/connectors/app/connectors/base.py+++ b/services/connectors/app/connectors/base.py@@ -437,6 +437,120 @@ class BaseConnector(ABC):"""Normalize a raw event to a common AiSOC alert schema."""return raw+ # ----------------------------- ingest checkpoints (10b) -------------------+ #+ # 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.+ #+ # What was missing was adoption, and the reason it stayed missing is worth+ # keeping. The scheduler reached the connector through+ # ``getattr(connector, "set_checkpoint", None)``, which is simply absent on+ # a connector that has not implemented it — so eighty-three of the+ # eighty-four silently did nothing, at ``logger.debug``, and there was no+ # way to ask a connector whether it checkpoints at all. A duck-typed+ # optional protocol has no failing state; it only has a quiet one.+ #+ # So the contract lives here. The default is still not-checkpointing —+ # that has to stay true, because a connector whose cursor fields nobody has+ # identified must not pretend to have one — but it is now *declared*+ # not-checkpointing, which :meth:`checkpoints` can answer and a gate can+ # count.+ #+ # Adopting is two class attributes. A connector names the field carrying+ # each row's event time and the field carrying a stable per-row id, and the+ # generic machinery below does the rest: order by ``(time, id)``, drop+ # anything at or before the incoming cursor (which is what suppresses the+ # duplicates an overlapping poll window produces), and stage the advanced+ # value for the scheduler to persist.+ #+ # The tie-breaker is not optional. Two events in the same second are+ # ordinary, and a cursor on time alone either loses the second one or+ # replays the first forever.++ #: Field on a raw row carrying its event time. ``None`` means this+ #: connector does not checkpoint, which is the honest default.+ checkpoint_time_field: tuple[str, ...] = ()++ #: Field carrying a stable per-row identifier, used to break ties within+ #: the same timestamp. Required alongside ``checkpoint_time_field``.+ checkpoint_id_field: tuple[str, ...] = ()++ #: Staged by :meth:`apply_checkpoint`, read by the scheduler after ingest+ #: accepts the batch. Declared here so it has one type rather than being+ #: introduced inside a branch.+ _incoming_checkpoint: dict[str, str] | None = None+ _next_checkpoint: dict[str, str] | None = None++ @classmethod+ def checkpoints(cls) -> bool:+ """Whether this connector resumes from a persisted cursor.++ The question the ``getattr`` could not answer. A connector that+ returns False re-reads its overlap window after a restart, which is+ safe and means a long outage loses events older than that window.+ """+ return bool(cls.checkpoint_time_field and cls.checkpoint_id_field)++ def set_checkpoint(self, checkpoint: dict[str, Any] | None) -> None:+ """Seed the poll with the last-accepted cursor (the scheduler owns it)."""+ if isinstance(checkpoint, dict) and (checkpoint.get("time") or checkpoint.get("id")):+ self._incoming_checkpoint = {"time": str(checkpoint.get("time") or ""), "id": str(checkpoint.get("id") or "")}+ else:+ self._incoming_checkpoint = None++ 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.+ """+ return self._next_checkpoint++ def _row_time(self, row: dict[str, Any]) -> str:+ return self._first_present(row, self.checkpoint_time_field)++ def _row_id(self, row: dict[str, Any]) -> str:+ return self._first_present(row, self.checkpoint_id_field)++ @staticmethod+ def _first_present(row: dict[str, Any], fields: tuple[str, ...]) -> str:+ for field_name in fields:+ value = row.get(field_name)+ if value not in (None, ""):+ return str(value)+ return ""++ def apply_checkpoint(self, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Order, de-duplicate against the cursor, and stage the advance.++ A no-op for a connector that does not declare its cursor fields, so+ it is safe to call unconditionally from ``fetch_alerts``.+ """+ if not self.checkpoints():+ return rows++ ordered = sorted(rows, key=lambda r: (self._row_time(r), self._row_id(r)))+ cursor = self._incoming_checkpoint or {}+ cursor_key = (str(cursor.get("time") or ""), str(cursor.get("id") or ""))++ fresh: list[dict[str, Any]] = []+ for row in ordered:+ if cursor_key[0] and (self._row_time(row), self._row_id(row)) <= cursor_key:+ continue+ fresh.append(row)++ # Staged, never persisted here. Advancing on read rather than on+ # accept is the bug the scheduler's ordering exists to avoid: a batch+ # that ingest rejects must be re-read, not skipped.+ if fresh:+ last = fresh[-1]+ self._next_checkpoint = {"time": self._row_time(last), "id": self._row_id(last)}+ else:+ self._next_checkpoint = None+ return fresh+# ----------------------------- federated search --------------------------# Connectors that opt into federated search override ``supports_federated_search``diff --git a/services/connectors/app/connectors/m365_audit.py b/services/connectors/app/connectors/m365_audit.pyindex 97fd8d134..e3da4fd76 100644--- a/services/connectors/app/connectors/m365_audit.py+++ b/services/connectors/app/connectors/m365_audit.py@@ -90,6 +90,10 @@ class M365AuditConnector(BaseConnector):# Microsoft 365 Unified Audit Log — control-plane / mailbox audit events.return (Capability.PULL_AUDIT,)+ #: Ingest cursor (10b). Management Activity API records carry `CreationTime` and `Id`; normalize() already reads both.+ checkpoint_time_field = ("CreationTime",)+ checkpoint_id_field = ("Id",)+def __init__(self, tenant_id: str, client_id: str, client_secret: str):self._tenant_id = tenant_idself._client_id = client_id@@ -251,7 +255,7 @@ class M365AuditConnector(BaseConnector):# Some content types wrap the array; tolerate both.events.extend(body.get("value", []))- return [self.normalize(e) for e in events]+ return [self.normalize(e) for e in self.apply_checkpoint(events)]# ----------------------- normalize --------------------------diff --git a/services/connectors/app/connectors/okta.py b/services/connectors/app/connectors/okta.pyindex 0a46932e1..99e35fc0a 100644--- a/services/connectors/app/connectors/okta.py+++ b/services/connectors/app/connectors/okta.py@@ -70,6 +70,11 @@ class OktaConnector(BaseConnector):Capability.REVOKE_SESSION,)+ #: Ingest cursor (10b). Okta System Log events carry `published` and a+ #: `uuid`; normalize() already reads both (created_at / external_id).+ checkpoint_time_field = ("published",)+ checkpoint_id_field = ("uuid",)+def __init__(self, domain: str, api_token: str):self._domain = domain.rstrip("/")self._api_token = api_token@@ -120,7 +125,7 @@ class OktaConnector(BaseConnector):if resp.status_code == 200:events.extend(resp.json())- return [self.normalize(e) for e in events]+ return [self.normalize(e) for e in self.apply_checkpoint(events)]def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:outcome = raw.get("outcome", {})diff --git a/services/connectors/app/connectors/splunk.py b/services/connectors/app/connectors/splunk.pyindex bc14be813..6bcf5de89 100644--- a/services/connectors/app/connectors/splunk.py+++ b/services/connectors/app/connectors/splunk.py@@ -100,6 +100,11 @@ class SplunkConnector(BaseConnector):Capability.CREATE_NOTABLE_EVENT,)+ #: Splunk stamps `_time` on every result and `_cd` is its stable+ #: per-event address; `event_id` wins when a saved search projects one.+ checkpoint_time_field = ("_time", "event_time")+ checkpoint_id_field = ("event_id", "_cd")+def __init__(self,base_url: str,@@ -116,27 +121,8 @@ class SplunkConnector(BaseConnector):self._page_size = max(1, int(page_size))except (TypeError, ValueError):self._page_size = _DEFAULT_PAGE_SIZE- # Checkpoint plumbing (#529). ``_checkpoint`` is the last-accepted- # (event_time, tie-breaker id) fed in by the scheduler before a poll;- # ``_next_checkpoint`` is the advanced value the scheduler persists- # *after* ingest accepts the batch. Both are ``{"time","id"}`` dicts.- self._checkpoint: dict[str, str] | None = None- self._next_checkpoint: dict[str, str] | None = None-- def set_checkpoint(self, checkpoint: dict[str, Any] | None) -> None:- """Seed the poll with the last-accepted checkpoint (scheduler-owned)."""- if isinstance(checkpoint, dict) and (checkpoint.get("time") or checkpoint.get("id")):- self._checkpoint = {"time": str(checkpoint.get("time") or ""), "id": str(checkpoint.get("id") or "")}- else:- self._checkpoint = None-- def get_checkpoint(self) -> dict[str, str] | None:- """Return the advanced checkpoint after a fetch, or None if unchanged.-- The scheduler persists this only once ingest has accepted the batch, so- a failed ingest never advances the checkpoint (#529).- """- return self._next_checkpoint+ # Checkpoint plumbing (#529) lives on BaseConnector (10b); the two+ # cursor fields declared above are all this connector contributes.def _headers(self) -> dict[str, str]:return {@@ -251,32 +237,15 @@ class SplunkConnector(BaseConnector):offset += len(page)return rows- @staticmethod- def _event_time(row: dict[str, Any]) -> str:- return str(row.get("_time") or row.get("event_time") or "")-- @staticmethod- def _event_tiebreak(row: dict[str, Any]) -> str:- return str(row.get("event_id") or row.get("_cd") or "")-def _order_and_checkpoint(self, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:- """Sort by a stable (event_time, tie-breaker) tuple, drop anything at or- before the incoming checkpoint (suppresses overlapping-window- duplicates), and stage the advanced checkpoint for the scheduler."""- ordered = sorted(rows, key=lambda r: (self._event_time(r), self._event_tiebreak(r)))- cp = self._checkpoint or {}- cp_key = (str(cp.get("time") or ""), str(cp.get("id") or ""))- fresh: list[dict[str, Any]] = []- for row in ordered:- if cp_key[0] and (self._event_time(row), self._event_tiebreak(row)) <= cp_key:- continue- fresh.append(row)- if fresh:- last = fresh[-1]- self._next_checkpoint = {"time": self._event_time(last), "id": self._event_tiebreak(last)}- else:- self._next_checkpoint = None- return fresh+ """Order, drop anything at or before the cursor, and stage the advance.++ The implementation moved to :meth:`BaseConnector.apply_checkpoint` in+ 10b so the other eighty-three connectors can adopt it by declaring two+ field names; this connector kept the behaviour and the tests that pin+ it. Retained as a named method because those tests drive it directly.+ """+ return self.apply_checkpoint(rows)async def query(self, unified: UnifiedQuery) -> list[dict[str, Any]]:"""Run a translated SPL search and return raw rows.diff --git a/services/connectors/app/scheduler.py b/services/connectors/app/scheduler.pyindex e1511c7c4..97e94182b 100644--- a/services/connectors/app/scheduler.py+++ b/services/connectors/app/scheduler.py@@ -442,14 +442,20 @@ class ConnectorScheduler:await self._record_failure(target.id)return- # Seed the connector's ingest checkpoint (#529) if it supports one, so a- # restart resumes from the last-accepted event instead of re-scanning.- setter = getattr(connector, "set_checkpoint", None)- if callable(setter):- try:- setter((target.connector_config or {}).get("checkpoint"))- except Exception: # never let checkpoint seeding break a poll- logger.debug("connector.scheduler.checkpoint_seed_failed id=%s", connector_id)+ # Seed the connector's ingest checkpoint (#529) so a restart resumes+ # from the last-accepted event instead of re-scanning.+ #+ # This used to be `getattr(connector, "set_checkpoint", None)`. The+ # method is on BaseConnector now (10b), so the call is direct — and+ # the reason that matters is that the getattr had no failing state.+ # It was simply absent on eighty-three of the eighty-four connectors,+ # so the seed silently did nothing for almost all of them at+ # `logger.debug`, and nothing could report which. Whether a connector+ # checkpoints is now a question its class answers.+ try:+ connector.set_checkpoint((target.connector_config or {}).get("checkpoint"))+ except Exception: # never let checkpoint seeding break a poll+ logger.debug("connector.scheduler.checkpoint_seed_failed id=%s", connector_id)# The schema lives in connector_config; use it for fetch lookback.# We deliberately default to the same poll interval, so a 5-min@@ -573,14 +579,12 @@ class ConnectorScheduler:# 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.- getter = getattr(connector, "get_checkpoint", None)- if callable(getter):- try:- new_checkpoint = getter()- 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)+ 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 drift was detected, persist that fact *before* marking the# poll successful so the UI reflects "drifted" status alongsidediff --git a/services/connectors/tests/test_checkpoint_contract.py b/services/connectors/tests/test_checkpoint_contract.pynew file mode 100644index 000000000..c1a1ed0cb--- /dev/null+++ b/services/connectors/tests/test_checkpoint_contract.py@@ -0,0 +1,198 @@+"""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+implementing it, and the scheduler reached it through+`getattr(connector, "set_checkpoint", None)`, which on the other 83 was+simply absent.++That is the shape worth testing against. A duck-typed optional protocol has+no failing state, only a quiet one: the seed no-opped at `logger.debug` and+nothing could report which connectors resumed and which re-read their+overlap window. So these tests hold two things — the machinery is correct,+and the *count* of adopters is visible rather than assumed.+"""++from __future__ import annotations++from typing import Any++import pytest+from app.connectors import CONNECTOR_REGISTRY+from app.connectors.base import BaseConnector, ConnectorSchema+++class _Cursored(BaseConnector):+ connector_id = "test_cursored"+ connector_name = "Cursored"+ connector_category = "siem"+ checkpoint_time_field: tuple[str, ...] = ("ts",)+ checkpoint_id_field: tuple[str, ...] = ("uid",)++ @classmethod+ def schema(cls) -> ConnectorSchema: # pragma: no cover - not exercised+ raise NotImplementedError++ async def test_connection(self) -> dict[str, Any]: # pragma: no cover+ raise NotImplementedError++ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]: # pragma: no cover+ raise NotImplementedError+++class _Uncursored(_Cursored):+ connector_id = "test_uncursored"+ checkpoint_time_field: tuple[str, ...] = ()+ checkpoint_id_field: tuple[str, ...] = ()+++def _row(ts: str, uid: str) -> dict[str, Any]:+ return {"ts": ts, "uid": uid}+++class TestTheContractIsAskable:+ def test_a_connector_that_declares_both_fields_checkpoints(self) -> None:+ assert _Cursored.checkpoints() is True++ def test_the_default_is_not_checkpointing_and_says_so(self) -> None:+ """The honest default. A connector whose cursor fields nobody has+ identified must not pretend to have one — but it is now *declared*+ not-checkpointing, which is the difference from an absent method."""+ assert _Uncursored.checkpoints() is False++ def test_a_time_field_without_a_tie_breaker_does_not_count(self) -> None:+ """Two events in the same second are ordinary. A cursor on time alone+ either loses the second one or replays the first forever."""++ class _HalfDeclared(_Cursored):+ connector_id = "test_half"+ checkpoint_id_field: tuple[str, ...] = ()++ assert _HalfDeclared.checkpoints() is False++ def test_every_connector_answers_the_question(self) -> None:+ """The property the getattr could not provide: ask any of the 84."""+ for connector_id, cls in CONNECTOR_REGISTRY.items():+ assert isinstance(cls.checkpoints(), bool), connector_id+ assert callable(cls.set_checkpoint)+ assert callable(cls.get_checkpoint)+++class TestTheMachineryIsCorrect:+ def test_rows_are_ordered_by_time_then_id(self) -> None:+ c = _Cursored()+ rows = [_row("t3", "c"), _row("t1", "b"), _row("t1", "a")]++ assert [r["uid"] for r in c.apply_checkpoint(rows)] == ["a", "b", "c"]++ def test_anything_at_or_before_the_cursor_is_dropped(self) -> None:+ """This is what suppresses the duplicates an overlapping poll+ window produces — the reason the overlap is safe to keep."""+ c = _Cursored()+ c.set_checkpoint({"time": "t2", "id": "b"})+ rows = [_row("t1", "a"), _row("t2", "b"), _row("t2", "c"), _row("t3", "d")]++ assert [r["uid"] for r in c.apply_checkpoint(rows)] == ["c", "d"]++ def test_the_cursor_advances_to_the_last_fresh_row(self) -> None:+ c = _Cursored()+ c.apply_checkpoint([_row("t1", "a"), _row("t2", "b")])++ assert c.get_checkpoint() == {"time": "t2", "id": "b"}++ def test_nothing_new_leaves_the_cursor_unmoved(self) -> None:+ """`None` rather than the old value: the scheduler writes only what+ moved, so a poll that found nothing must not rewrite the row."""+ c = _Cursored()+ c.set_checkpoint({"time": "t9", "id": "z"})++ assert c.apply_checkpoint([_row("t1", "a")]) == []+ assert c.get_checkpoint() is None++ def test_two_rows_sharing_a_timestamp_both_survive(self) -> None:+ c = _Cursored()+ kept = c.apply_checkpoint([_row("t1", "a"), _row("t1", "b")])++ assert {r["uid"] for r in kept} == {"a", "b"}++ def test_a_connector_that_does_not_checkpoint_passes_rows_through(self) -> None:+ """Safe to call unconditionally from any `fetch_alerts`."""+ c = _Uncursored()+ rows = [_row("t3", "c"), _row("t1", "a")]++ assert c.apply_checkpoint(rows) == rows+ assert c.get_checkpoint() is None++ def test_a_malformed_seed_is_treated_as_no_cursor(self) -> None:+ c = _Cursored()+ for junk in (None, {}, {"time": "", "id": ""}, "not-a-dict"):+ c.set_checkpoint(junk) # type: ignore[arg-type]+ assert c.apply_checkpoint([_row("t1", "a")]) == [_row("t1", "a")]+++class TestAdoptionIsCountedNotAssumed:+ #: Every connector that resumes from a persisted cursor, with the fields+ #: it resumes on. Shrink-only in the sense that matters: a connector+ #: dropping out of this list fails the test rather than going quiet,+ #: which is exactly what the `getattr` could not do.+ EXPECTED = {+ "splunk": (("_time", "event_time"), ("event_id", "_cd")),+ "okta": (("published",), ("uuid",)),+ "m365_audit": (("CreationTime",), ("Id",)),+ "aws_cloudtrail": (("EventTime",), ("EventId",)),+ "azure_activity": (("eventTimestamp",), ("eventDataId", "id")),+ }++ def test_the_adopters_are_exactly_the_ones_recorded(self) -> None:+ actual = {cid for cid, cls in CONNECTOR_REGISTRY.items() if cls.checkpoints()}++ assert actual == set(self.EXPECTED), (+ "the set of checkpointing connectors changed. Adding one is good — record it here. "+ "Losing one silently is the defect this replaces."+ )++ @pytest.mark.parametrize("connector_id", sorted(EXPECTED))+ def test_each_adopter_declares_the_fields_recorded_for_it(self, connector_id: str) -> None:+ cls = CONNECTOR_REGISTRY[connector_id]+ time_fields, id_fields = self.EXPECTED[connector_id]++ assert cls.checkpoint_time_field == time_fields+ assert cls.checkpoint_id_field == id_fields++ def test_the_rest_are_honestly_not_checkpointing(self) -> None:+ """Not a failure. A connector without a declared cursor re-reads its+ overlap window after a restart, which is safe and loses events older+ than that window. The number is here so the gap is legible."""+ without = sorted(cid for cid, cls in CONNECTOR_REGISTRY.items() if not cls.checkpoints())++ assert len(without) == len(CONNECTOR_REGISTRY) - len(self.EXPECTED)+ assert len(CONNECTOR_REGISTRY) >= 84+++class TestTheSchedulerNoLongerDuckTypes:+ def test_it_calls_the_contract_directly(self) -> None:+ """The getattr is what made 83 silent no-ops invisible."""+ from pathlib import Path++ source = (Path(__file__).resolve().parents[1] / "app" / "scheduler.py").read_text(encoding="utf-8")+ # Comments stripped first: the scheduler's own comment quotes the+ # pattern it replaced, and a gate that cannot tell code from prose+ # about the code fires on its own explanation.+ code = "\n".join(line for line in source.splitlines() if not line.lstrip().startswith("#"))++ assert 'getattr(connector, "set_checkpoint"' not in code+ assert 'getattr(connector, "get_checkpoint"' not in code+ 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."""+ from pathlib import Path++ source = (Path(__file__).resolve().parents[1] / "app" / "scheduler.py").read_text(encoding="utf-8")+ accept_index = source.index('accepted = int(result.get("accepted", 0) or 0)')+ advance_index = source.index("new_checkpoint = connector.get_checkpoint()")++ assert accept_index < advance_index