Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
fix(connectors): acknowledge a queue only after ingest confirms the batch (#1526)
Beenu Arorafb79501a7336
diff --git a/.github/workflows/connector-scheduler-live.yml b/.github/workflows/connector-scheduler-live.ymlindex fa9b33f28..ec2625df4 100644--- a/.github/workflows/connector-scheduler-live.yml+++ b/.github/workflows/connector-scheduler-live.yml@@ -103,6 +103,60 @@ jobs:ISOLATION_CONNECTOR_DSN: ${{ env.CONNECTOR_DSN }}run: python -m pytest ../../tests/isolation/test_connector_scheduler_live.py -v --tb=short+ # Phase 3. Two properties that only a real socket and a real database+ # can show: that nothing reaches `:acknowledge` while ingest has not+ # confirmed the batch, and that the cursor survives the JSONB round+ # trip it is written through. A fake engine recording the dict it was+ # handed proves the scheduler called it, not that the value comes back+ # — which is how `record_checkpoint` double-encoded its patch for the+ # whole life of the feature while every scheduler test passed.+ - name: A queue is acknowledged only after ingest confirms the batch+ working-directory: services/connectors+ env:+ ISOLATION_CONNECTOR_DSN: ${{ env.CONNECTOR_DSN }}+ run: python -m pytest ../../tests/isolation/test_queue_acknowledgement_live.py -v --tb=short++ # The negative control for it, re-injecting the pre-fix acknowledgement+ # placement: acking inside the pull loop, once the entries are in a+ # local list and before the scheduler has pushed anything anywhere.+ #+ # If the suite still passes with that back, it is not observing the+ # subscription and proves nothing about durability.+ - name: The gate fails when the subscription is acknowledged during the fetch+ working-directory: services/connectors+ env:+ ISOLATION_CONNECTOR_DSN: ${{ env.CONNECTOR_DSN }}+ run: |+ cp app/connectors/gcp_pubsub.py /tmp/gcp_pubsub.bak+ python - <<'PY'+ import pathlib, sys+ p = pathlib.Path("app/connectors/gcp_pubsub.py")+ s = p.read_text()+ staged = " self.stage_acknowledgement(ack_ids)"+ if staged not in s:+ print("negative control could not find the staging call; the connector has "+ "been reshaped and this control proves nothing")+ sys.exit(1)+ p.write_text(s.replace(staged, "\n".join([+ " if ack_ids:",+ " _resp = await client.post(",+ " f\"{_PUBSUB_ROOT}/{self._subscription_path}:acknowledge\",",+ " headers=self._auth.headers(token),",+ " json={\"ackIds\": ack_ids},",+ " )",+ " _resp.raise_for_status()",+ ]), 1))+ PY+ if python -m pytest ../../tests/isolation/test_queue_acknowledgement_live.py -q >/dev/null 2>&1; then+ cp /tmp/gcp_pubsub.bak app/connectors/gcp_pubsub.py+ echo "FAIL: the suite passed with the subscription acknowledged during the fetch."+ echo " It is not observing the acknowledgement, so it cannot show durability."+ exit 1+ fi+ cp /tmp/gcp_pubsub.bak app/connectors/gcp_pubsub.py+ echo "OK: acknowledging before ingest confirms the batch makes the suite fail, as it must."+ python -m pytest ../../tests/isolation/test_queue_acknowledgement_live.py -q+# The negative control, and it re-injects the real defect.## `next_run_time=None` is what shipped. Measured: four of the fivediff --git a/apps/docs/docs/connectors/aws-cloudtrail-s3.md b/apps/docs/docs/connectors/aws-cloudtrail-s3.mdindex bf67e6447..a4e249f52 100644--- a/apps/docs/docs/connectors/aws-cloudtrail-s3.md+++ b/apps/docs/docs/connectors/aws-cloudtrail-s3.md@@ -24,7 +24,7 @@ AWS CloudTrail organisation trail delivered to S3 and announced on SQS. Reads ma| `secret_key` | Secret Access Key | secret | no | — | **encrypted at rest** · Required only when supplying a static access key above. || `include_data_events` | Include data events | boolean | no | `True` | S3 / Lambda / DynamoDB data events. These answer 'what did they read', and are the highest-volume thing in the trail — most land at info severity. || `include_flow_logs` | Include VPC flow logs | boolean | no | `True` | VPC flow logs published to the same bucket (key prefix .../vpcflowlogs/...). |-| `visibility_timeout_seconds` | Receive visibility timeout (seconds) | number | no | `300` | How long a received message is hidden from other consumers. Must comfortably exceed one poll, or an object is re-announced while this poll is still reading it. |+| `visibility_timeout_seconds` | Receive visibility timeout (seconds) | number | no | `300` | How long a received message is hidden from other consumers. Messages are not deleted until ingest confirms their events, so this has to cover a poll and the push that follows it — not just the poll. AiSOC stops receiving once it has spent half the timeout, and a message whose visibility lapses first is redelivered and de-duplicated rather than lost. Set a redrive policy on the queue so a notification naming an unreadable object is quarantined to a dead-letter queue instead of retried forever. |:::note Credential handling`secret_key` is encrypted at rest by the credential vault before the row is written, and decrypted only at poll time. The value is never logged and never returned by the API — a read of the saved connector shows the field as set, not its contents. See [credential vault](../operations/credentials.md).diff --git a/apps/docs/docs/connectors/gcp-pubsub.md b/apps/docs/docs/connectors/gcp-pubsub.mdindex e46012f4f..24031e675 100644--- a/apps/docs/docs/connectors/gcp-pubsub.md+++ b/apps/docs/docs/connectors/gcp-pubsub.md@@ -22,7 +22,7 @@ Google Cloud logs streamed through a Cloud Logging sink onto a Pub/Sub subscript| `project_id` | Project ID (of the subscription) | string | yes | — | The project the Pub/Sub subscription lives in, which may differ from the projects the sink reads. || `subscription_id` | Subscription ID | string | yes | — | A pull subscription on the topic your log sink publishes to. Push subscriptions are not read by this connector. || `service_account_json` | Service account JSON key | secret | yes | — | **encrypted at rest** · Needs roles/pubsub.subscriber on the subscription. Paste the entire key file; it is encrypted at rest by the credential vault. |-| `ack_deadline_seconds` | Acknowledgement deadline (seconds) | number | no | `120` | Recorded for the setup guide and compared against the subscription at test time. A deadline shorter than one poll redelivers messages this connector is still reading. |+| `ack_deadline_seconds` | Acknowledgement deadline (seconds) | number | no | `120` | Recorded for the setup guide and compared against the subscription at test time. Messages stay unacknowledged until ingest confirms them, so the deadline has to cover a poll and the push that follows it — not just the poll. AiSOC stops pulling once it has spent half the deadline, and a message whose deadline lapses first is redelivered and de-duplicated rather than lost. |:::note Credential handling`service_account_json` is encrypted at rest by the credential vault before the row is written, and decrypted only at poll time. The value is never logged and never returned by the API — a read of the saved connector shows the field as set, not its contents. See [credential vault](../operations/credentials.md).diff --git a/docs/remediation/phase-3-queue-acknowledgement.md b/docs/remediation/phase-3-queue-acknowledgement.mdnew file mode 100644index 000000000..b3cb2999b--- /dev/null+++ b/docs/remediation/phase-3-queue-acknowledgement.md@@ -0,0 +1,548 @@+# Phase 3 — queue acknowledgement and checkpoint semantics++Scope: `services/connectors/**`. Two findings were handed over; a third was+found while building the live proof for them and is worse than either.++The question this phase answers is **what "accepted" means**. An HTTP 200 from+a service that only buffered, an in-memory list, or a coroutine that has been+created but not awaited are all insufficient. Acknowledgement requires+recoverable downstream acceptance.++On this tree that bar is met in exactly one place, and it genuinely is met+there: `services/ingest` awaits `PublishBatch`, whose writer is configured+`RequiredAcks: kafka.RequireAll` with a synchronous `WriteMessages`, and+answers HTTP 500 if it fails. So a 200 carrying `accepted == submitted` means+the broker acknowledged on all replicas. Its graph fan-out is explicitly+non-blocking (`_ = h.graph.WriteEvent(...)`) and is not part of the guarantee.++Everything below is about getting the connectors to wait for that answer.++---++## Finding 4 — acknowledgement preceded durable acceptance++**Status: reproduced and fixed.**++### Affected production path++`ConnectorScheduler._poll_one` → `connector.fetch_alerts()` → *returns* →+normalize → tenant filter rules → schema fingerprint →+`IngestClient.push_events` → `record_checkpoint`.++Both queue-backed connectors answered the source **inside `fetch_alerts`**,+several steps before anything durable had seen the events:++| Connector | Pre-fix behaviour |+| --- | --- |+| `gcp_pubsub` | `POST :acknowledge` once the batch was appended to a local `list` |+| `aws_cloudtrail_s3` | `sqs:DeleteMessage` once an object's records were in that same list |++The comment on the Pub/Sub site — *"Acknowledge after the batch is in `rows`,+never before: a failure between the two has to cost a duplicate, not a gap"* —+is sound reasoning that stops one layer short. Being in a Python list is not+durability, and `fetch_alerts` returns long before the push.++So on a crash, or on any ingest 5xx, the messages were gone from the source+with no second copy anywhere. Checkpoint withholding could not help: the+scheduler's existing withholding logic is well built and fires correctly, but a+cursor held back over data that has already been deleted from a queue protects+nothing.++### Regression tests++| Test | Property |+| --- | --- |+| `test_gcp_pubsub.py::TestTheAckOutlivesTheFetch::test_nothing_is_acknowledged_while_the_entries_are_only_in_a_list` | the subscription still holds them after a fetch |+| `test_aws_cloudtrail_s3.py::TestTheHandleOutlivesTheFetch::test_a_message_is_not_deleted_while_its_records_are_only_in_a_list` | the receipt survives the fetch |+| `test_aws_cloudtrail_s3.py::TestTheHandleOutlivesTheFetch::test_an_unreadable_object_still_withholds_the_whole_message` | partial acceptance at the source end: one notification, several objects |+| `test_scheduler.py::test_a_fetch_that_ingest_rejects_leaves_the_message_on_the_queue` | fetch succeeds, ingest 500, nothing acknowledged |+| `test_scheduler.py::test_the_rejected_batch_is_recovered_in_full_on_the_next_poll` | **completeness** — the events actually come back |+| `test_scheduler.py::test_a_partially_accepted_batch_is_not_acknowledged` | 200 with `rejected > 0` acknowledges nothing |+| `test_scheduler.py::test_a_child_event_that_cannot_be_normalized_withholds_the_acknowledgement` | one unusable child event of a multi-event notification |+| `test_scheduler.py::test_a_fully_accepted_batch_is_acknowledged_and_does_not_come_back` | the other direction — the queue must still drain |+| `test_scheduler.py::test_the_checkpoint_is_durable_before_the_acknowledgement_is_sent` | ordering: cursor persisted first |+| `test_scheduler.py::test_a_redelivery_after_a_lost_acknowledgement_is_not_a_duplicate` | crash, or refused handle, in that window |+| `tests/isolation/test_queue_acknowledgement_live.py::TestIngestRefusesTheBatch` | the same, through a real socket and real Postgres |++The scheduler tests drive a queue double that **really drains on ack and+really redelivers otherwise**, so "was the event lost?" is a question the test+can ask rather than assert. A mock that records an ack call cannot model the+consequence that makes this class of bug possible — the message leaving the+queue — which is why none of the existing mock-based scheduler tests saw it.++### Fix++Fetching and acknowledging are now separate operations.++- `BaseConnector` gained `stage_acknowledgement`, `pending_acknowledgements`,+ `take_pending_acknowledgements`, `discard_acknowledgements` and+ `commit_acknowledgements`, returning an `AcknowledgementResult(requested,+ confirmed, failed)`.+- Each connector's `fetch_alerts` stages its handles instead of answering.+- The scheduler commits them under **exactly the condition the checkpoint+ already used**: counts present in the response, `rejected == 0`, and+ `accepted == len(kept)`. Anything else calls `discard_acknowledgements` and+ logs `acknowledgement_withheld` with the message count and the reason.+- The commit runs **after** the checkpoint write, deliberately. A crash+ between the two leaves messages that will be redelivered and a cursor that+ recognises them. The other order leaves a source that has forgotten them and+ a cursor that never recorded them.+- `commit_acknowledgements` on the base class is a no-op only when nothing was+ staged, and raises otherwise, so a connector that stages handles without+ implementing the commit fails loudly instead of holding a queue open.+- Both connectors report what the source **confirmed**, not what they asked+ for, so a delete nobody has permission to make is visible instead of+ presenting as a queue that never drains.++This is the smallest change that establishes the guarantee: it reuses the+staging-and-commit shape the checkpoint already had, and the acceptance+predicate is the same one, so the two cannot drift apart.++### The bound, and why it is a bound rather than an extension++An SQS visibility timeout and a Pub/Sub ack deadline are both finite, so+"hold the handle until ingest confirms" needs an explicit answer.++**The bound chosen:** a poll stops taking new work once it has spent+`acknowledgement_hold_fraction` (0.5) of the source's deadline while holding+at least one handle. The remaining half is the downstream budget — normalize,+filter, fingerprint, push to ingest, persist the cursor. With the shipped+defaults that is 60 s of a 120 s Pub/Sub ack deadline and 150 s of a 300 s SQS+visibility timeout. Whatever the poll did not take stays on the source, which+is what `CollectionBudget.backlog_stays_on_the_queue` already describes.++**If it overruns anyway**, the handle expires, the source refuses it, and the+message is redelivered — a duplicate, which the identity cursor suppresses,+and never a gap. The failure mode of the bound is in the safe direction.++**Why not extend the deadline** (`ChangeMessageVisibility` /+`modifyAckDeadline`): an extension is another network call that can fail, on+exactly the path whose failure mode this phase exists to remove, and it needs+a background task holding a timer across the scheduler's own call into ingest.+Stopping early needs no call, cannot fail, and degrades to a duplicate. An+extension becomes worth reconsidering if a deployment's poll legitimately+cannot fit in half a deadline — the log line+`gcp_pubsub.ack_deadline_reserve_reached` / `cloudtrail_s3.visibility_reserve_reached`+names that situation when it happens.++The two operator-facing timeout fields now say the timeout has to cover a poll+**and the push that follows it**, which is a larger number than before. Those+help texts are the source of the generated connector pages, which were+regenerated.++### Durable quarantine for source data that can never be read++A notification naming an object that cannot be read — deleted object, a bucket+policy the task role does not satisfy, a truncated upload — is withheld on+every poll by design, because the alternative is dropping audit data on a+transient S3 error. That is correct, and unbounded.++The bound belongs to the queue rather than to a spool built here: SQS's own+**redrive policy** moves a message to a dead-letter queue after+`maxReceiveCount` receives, preserving the original payload, and Pub/Sub has+a dead-letter topic. Both are durable quarantine with an explicit record, and+neither needs code. What was missing was any way to know it was happening, so+the connector now requests `ApproximateReceiveCount` (SQS omits it unless+asked) and logs `cloudtrail_s3.message_redelivered_repeatedly` at five+receives, naming the redrive policy as the remedy. Five because SQS's default+`maxReceiveCount` is 10 and AWS advises against going below 5, so the warning+lands near where a correctly configured queue would already be quarantining.++### Compatibility++- No change for the other 85 connectors: they stage nothing, so+ `commit_acknowledgements` returns a zero result and the scheduler's new step+ is a no-op. Verified live — `test_connector_scheduler_live.py` (which drives+ Okta, a watermark connector) passes unchanged.+- A message that can never become events — an `s3:TestEvent`, an undecodable+ body, an empty Pub/Sub payload — is still consumed, but now rides along with+ its batch's acknowledgement. It contributes no rows, so a poll containing+ only such messages submits an empty batch, which `IngestClient.push_events`+ short-circuits to `{"accepted": 0, "rejected": 0}`; that satisfies the+ acceptance predicate and the queue still drains.+- In-batch duplicates are not collapsed. That is unchanged from the watermark,+ and deliberate: every record read out of one S3 object shares its object+ key, so collapsing within a batch would discard an object's tail.++---++## Finding 5 — a monotonic watermark over an unordered queue++**Status: reproduced and fixed.**++### Affected production path++`BaseConnector.apply_checkpoint`, called from both connectors' `fetch_alerts`.+It sorts rows by `(event_time, record_id)`, drops everything at or below the+incoming cursor, and advances the cursor to the batch **maximum**.++That is correct for an ordered, time-windowed API poll — which is what its+design comment describes, and the five API connectors keep it. It is wrong for+a queue:++- Pub/Sub guarantees no ordering unless the topic was created with message+ ordering **and** the publisher sets an ordering key. A Cloud Logging sink+ sets none — the connector's own module docstring says so.+- S3 event notifications over SQS are unordered by construction.++So an event whose `event_time` was older than the batch maximum was discarded+**on first sight**, with no counter and no log, and because its message had+already been acknowledged it was unrecoverable.++A second, smaller part of the same finding: the Pub/Sub module docstring+claimed the cursor "tolerates a late arrival by re-reading its own overlap —+which is why the cursor is a de-duplicator here rather than a watermark that+may skip". That described an intent the base class does not implement. It has+been corrected to describe what the code does.++### Regression tests++| Test | Property |+| --- | --- |+| `test_gcp_pubsub.py::TestAnOlderEntryArrivingLaterSurvives::test_an_entry_older_than_the_last_batch_is_still_emitted` | a previously unseen older event survives |+| `test_aws_cloudtrail_s3.py::TestAnOlderObjectAnnouncedLaterSurvives::test_an_event_older_than_the_last_batch_is_still_emitted` | the same, per object |+| `...::test_a_genuine_redelivery_of_the_same_object_is_still_suppressed` | **duplicate handling** — the other half |+| `...::test_two_distinct_events_sharing_a_timestamp_both_survive` | a shared timestamp is not a collision |+| `test_checkpoint_contract.py::TestIdentityDedupMachinery` (9 tests) | the machinery, including the bound and the scoping |+| `test_checkpoint_contract.py::TestUnorderedSourcesDoNotCarryAWatermark` | the declarations, recorded rather than assumed |+| `tests/isolation/...::TestTheCursorRoundTripsThroughPostgres` | all of it through a real database |++### Fix++The two queue connectors declare `dedup_identity_field` instead of the+watermark pair. `apply_checkpoint` dispatches on which was declared;+declaring both is refused in `__init_subclass__`, at import, because a+connector carrying both would silently use one of them.++Identity dedup keeps a bounded set of identities seen before, never reorders+rows (arrival order is the only order a queue has), and drops a row only when+that exact identity has been seen.++| Connector | Identity | Why that one |+| --- | --- | --- |+| `gcp_pubsub` | `record_id`, the vendor `messageId` | stable across redelivery; `ackId` is **not** — a fresh one is minted each time the message is handed over |+| `aws_cloudtrail_s3` | `object_key` | every record of an object shares it, and the object is this connector's atomic unit (a message is answered only when every object it names was read in full). Keying on the object keeps the set to the few hundred keys one poll can announce rather than the 20,000 records they may hold |++Properties worth stating:++- **Bound.** `max_dedup_identities` defaults to 10,000, stored as 16-hex+ (64-bit) truncated SHA-256 digests. Measured: 195.3 KiB of JSONB at the cap,+ 11.7 KiB for a realistic CloudTrail poll of 600 object keys. The window that+ must stay covered is the batch in flight — accepted downstream but not yet+ acknowledged — which is at most one poll. Falling off the end re-emits an+ event; it never drops one. Truncation is logged.+- **Scope.** The digest includes the connector id, so two sources minting the+ same record id cannot suppress each other. Tenant scope is structural: the+ cursor lives on one connector *instance* row, which belongs to one tenant.+- **A row with no identity is kept**, not guessed at, and counted+ (`connector.dedup.row_without_identity`) — it cannot be proven a duplicate,+ so it is not treated as one.+- **Compatibility.** A deployment upgrading in place has a `{"time", "id"}`+ cursor in `connector_config.checkpoint`. It is ignored rather than read,+ because reading it would reinstate the behaviour being removed; the cost is+ re-emitting at most one poll's worth once, and the queue only holds+ unacknowledged messages. Pinned by+ `test_a_watermark_cursor_left_by_an_earlier_release_is_ignored`, offline and+ live. Rolling the code back is also safe: the old watermark finds no `time`+ key, treats it as no cursor, and re-reads what is on the queue — duplicates,+ not loss.++### `azure_event_hubs` — source-confirmed, deliberately not changed++It declares the same `(event_time, record_id)` watermark and shares the+out-of-order weakness: Capture files are written per partition, and+`EnqueuedTimeUtc` is not globally ordered across partitions, so a late file+can carry records below the watermark and be dropped on sight.++It is **not** converted, for a reason that matters: its blob container is+never drained, and `_list_paths` lists it from the beginning on every poll. A+bounded identity set would roll over and re-emit the oldest capture files for+ever, which is worse than the defect. Its data is also *re-readable* — nothing+is destroyed by a read, unlike an acked queue message — so a dropped record is+recoverable by resetting the cursor, where a dropped queue message is not.++It needs a different fix (a listing cursor on the capture path, which sorts+chronologically within a partition, plus per-partition rather than global+watermarks). That is recorded here and in+`test_checkpoint_contract.py::test_a_blob_store_that_is_relisted_every_poll_keeps_its_watermark`,+which states the reasoning so the next reader does not "fix" it by symmetry.++---++## Finding 6 — persisting a cursor destroyed the connector's configuration++**Status: found during this phase, reproduced against live Postgres, fixed.**+Older than findings 4 and 5, and broader: it affects every connector that+declares a cursor, not only the two queue-backed ones.++### What happened++`connector_repo.record_checkpoint` built its patch as:++```python+patch = cast(json.dumps({"checkpoint": checkpoint}), JSONB)+```++`cast` declares the bind parameter's type, so SQLAlchemy's JSONB bind+processor serialised the already-serialised string a **second** time and+Postgres received a JSON *string scalar*. `jsonb || <scalar>` coerces both+operands to arrays, so one successful checkpointed poll rewrote+`connector_config` from an object to an array.++Measured against Postgres 16 with the shipped code:++```+after ONE successful checkpointed poll:+ connector_config type : list+ value : [{'filter_rules': [{'field': 'x'}], 'poll_interval_seconds': 120},+ '{"checkpoint": {"time": "2026-10-08T11:00:00Z", "id": "evt-1"}}']+ next poll : CRASHES -> AttributeError: 'list' object has no attribute 'items'+ poll_interval_seconds : LOST+ filter_rules : LOST+```++The next poll raises at `scheduler.py` reading `connector_config.items()`, the+poll's broad handler files that as a failure, and the instance goes unhealthy+**permanently**. Three consequences:++1. No connector has ever resumed from a persisted cursor on any deployment —+ `connector_config -> 'checkpoint'` is `NULL` on the corrupted shape, so+ `set_checkpoint` was always seeded with nothing.+2. The instance stops polling altogether after its first successful poll.+3. Its poll interval and tenant filter rules are no longer readable.++### Why nothing caught it++Every scheduler test patches `record_checkpoint` with a fake that appends the+dict it was handed, so **this statement had never been executed by a test**.+The contract suite covers the in-memory machinery and never reaches SQL. The+test double was more capable than the real thing, precisely at the boundary+the defect lived on.++### Fix++The patch is bound as a mapping with a JSONB type, serialised once, and the+`coalesce` default is a SQL literal rather than a second `cast(...)` carrying+the identical bug. Rows already corrupted are recovered on read by+`_recover_connector_config`: the configuration is the mapping element and the+cursor is inside the encoded string, so an upgraded deployment resumes without+an operator running anything and without re-reading its overlap.++### Regression tests++`tests/isolation/test_queue_acknowledgement_live.py`:+`TestPersistingACursorDoesNotCorruptTheConfig` (config stays an object, the+next poll still runs, the poll interval survives) and+`TestACorruptedConfigIsRecoveredOnRead`.++---++## Verification performed++Commands and results, in order. The connectors venv was built from the+service's own locked set (`python3 scripts/service_requirements.py connectors+--locked`) on Python 3.11.15.++| Check | Command | Result |+| --- | --- | --- |+| Connectors suite | `python -m pytest tests/ -q` (in `services/connectors`) | **1230 passed** |+| Live scheduler (pre-existing) | `pytest tests/isolation/test_connector_scheduler_live.py` | **5 passed** |+| Live queue acknowledgement (new) | `pytest tests/isolation/test_queue_acknowledgement_live.py` | **11 passed** |+| Lint | `ruff check services/ scripts/ tests/ tools/` | All checks passed |+| Format | `ruff format --check .` | 2596 files already formatted |+| Types | `python3 scripts/check_mypy_baseline.py` | OK — no tree got worse |+| Collection-path gate | `python3 scripts/check_cloud_native_collection.py` | OK — 3 paths |+| Gate self-test | `… --self-test` | 11 PASS, including "catches a collector with no resumable cursor" |+| Marketplace parity | `python3 scripts/check_marketplace_index_parity.py` | OK |+| Attribution | `python3 scripts/check_attribution.py --diff-base origin/main` | OK |+| Competitor names | `python3 scripts/check_competitor_names.py` | OK |+| Machine paths | `python3 scripts/check_machine_paths.py` | OK — 13204 files |++Live runs used Postgres 16-alpine in Docker with every migration in+`services/api/migrations/` applied in order and the `aisoc_app` runtime role,+matching `connector-scheduler-live.yml`.++### Negative controls++Each reverts one half of the fix and requires the corresponding test to fail+again. Run, not reasoned about; the tree was restored and re-verified green+(1230 passed) afterwards.++| Reverted | Test | Result |+| --- | --- | --- |+| Pub/Sub ack back inside the pull loop | `…::test_nothing_is_acknowledged_while_the_entries_are_only_in_a_list` | **1 failed** |+| Pub/Sub watermark back in place of identity | `…::test_an_entry_older_than_the_last_batch_is_still_emitted` | **1 failed** |+| CloudTrail delete back inside the receive loop | `…::test_a_message_is_not_deleted_while_its_records_are_only_in_a_list` | **1 failed** |+| CloudTrail watermark back in place of identity | `…::test_an_event_older_than_the_last_batch_is_still_emitted` | **1 failed** |+| Scheduler acknowledges regardless of acceptance | `…::test_a_partially_accepted_batch_is_not_acknowledged` | **1 failed** |+| Scheduler acknowledges before the checkpoint write | `…::test_the_checkpoint_is_durable_before_the_acknowledgement_is_sent` | **1 failed** |+| Pre-fix ack placement, against the **live** suite | `test_queue_acknowledgement_live.py` | **3 of 11 failed** |+| `record_checkpoint` double-encode, against the live suite | `test_queue_acknowledgement_live.py` | **7 of 11 failed** |++The last two are wired into `connector-scheduler-live.yml` as a step, so the+live suite cannot silently stop proving anything.++One artefact worth recording because it looked like a defect and was not:+control 6 moves a block without changing the file's byte count, so a+same-second restore let CPython reuse the patched `.pyc` — the "restored" tree+reported a failure that was not in its source. The control script purges+`__pycache__` on every restore.++---++## Bounded recovery for source data already missed++Only for deployments that ran the affected releases. What is recoverable+depends on whether the source destroys data on read.++### CloudTrail on S3 — recoverable, bounded by the bucket's lifecycle policy++The **objects still exist**; only the SQS notifications naming them were+deleted. So an event dropped by the watermark can be recovered for as long as+the bucket keeps the object.++1. Establish the window. The last-known-good point is the `event_time` in the+ old checkpoint:+ ```sql+ SELECT id, name, connector_type, connector_config -> 'checkpoint'+ FROM connectors+ WHERE connector_type IN ('aws_cloudtrail_s3', 'gcp_pubsub');+ ```+ On a row corrupted by finding 6 the cursor is the encoded string in the+ array's second element.+2. Re-announce the objects for that window onto the queue — the same shape S3+ sends, which the connector already parses:+ ```bash+ aws s3api list-objects-v2 --bucket "$TRAIL_BUCKET" \+ --prefix "AWSLogs/$ORG_ID/$ACCOUNT/CloudTrail/$REGION/2026/10/08/" \+ --query 'Contents[].Key' --output text \+ | tr '\t' '\n' \+ | while read -r key; do+ aws sqs send-message --queue-url "$QUEUE_URL" --message-body \+ "$(jq -nc --arg b "$TRAIL_BUCKET" --arg k "$key" \+ '{Records:[{s3:{bucket:{name:$b},object:{key:$k}}}]}')"+ done+ ```+3. Re-reading an object the connector already emitted is safe — the identity+ cursor suppresses it, and anything genuinely missed is emitted once.++Bound: the trail bucket's own retention. CloudTrail objects are not deleted by+the connector, so a bucket with no expiry rule has everything.++### Pub/Sub — mostly **not** recoverable from the subscription++An acknowledged message is gone. `subscriptions.seek` can replay acknowledged+messages **only** if the subscription was created with `retainAckedMessages`+enabled, and only inside its `messageRetentionDuration`. Both are vendor+settings AiSOC does not set, and `retainAckedMessages` defaults to off, so on+a default subscription the answer is no.++Check before assuming either way:++```bash+gcloud pubsub subscriptions describe "$SUBSCRIPTION" \+ --format='value(retainAckedMessages, messageRetentionDuration)'+# If retainAckedMessages is true, and only then:+gcloud pubsub subscriptions seek "$SUBSCRIPTION" --time="$RFC3339_TIMESTAMP"+```++The **source** is the better path. A Cloud Logging sink is a copy of data that+Cloud Logging also retains in its own buckets (`_Default` keeps 30 days unless+changed), so a gap can be re-read from Logging itself for the affected window+rather than from the subscription — which is what the sibling+`gcp_cloud_audit` connector does. Verify the retention on the bucket the sink+reads before relying on it:++```bash+gcloud logging buckets describe _Default --location=global --format='value(retentionDays)'+```++### Distinguishing the two, because it decides what to tell an operator++| | CloudTrail on S3 | Pub/Sub |+| --- | --- | --- |+| What the acknowledgement destroyed | the **notification** | the **message** |+| Does the payload survive it? | yes — the object is still in the bucket | no, unless `retainAckedMessages` was on |+| Recovery | re-announce the objects (above) | seek, if retained; otherwise re-read Cloud Logging |+| Bound | the bucket's lifecycle policy | `messageRetentionDuration`, or Logging's own retention |++### Repairing a `connector_config` corrupted by finding 6++Not required — it is recovered on read, so connectors resume on upgrade with+no operator action. For anyone who wants the column itself clean:++```sql+-- Inspect first. This should return zero rows on a healthy deployment.+SELECT id, name, connector_type+FROM connectors+WHERE jsonb_typeof(connector_config) <> 'object';++-- Repair: fold the array back into the object it should have been.+UPDATE connectors SET connector_config = (+ SELECT coalesce(jsonb_object_agg(k, v), '{}'::jsonb)+ FROM jsonb_array_elements(connector_config) AS e,+ jsonb_each(CASE WHEN jsonb_typeof(e) = 'object' THEN e ELSE '{}'::jsonb END) AS kv(k, v)+) || coalesce((+ SELECT (e #>> '{}')::jsonb+ FROM jsonb_array_elements(connector_config) AS e+ WHERE jsonb_typeof(e) = 'string'+ LIMIT 1+), '{}'::jsonb)+WHERE jsonb_typeof(connector_config) = 'array';+```++Take a backup first, and re-run the `SELECT` afterwards to confirm it returns+nothing.++Executed against Postgres 16 inside a transaction, on a row written into the+exact corrupted shape, and rolled back. Measured:++```+ before | array | [{"filter_rules": [{"field": "x"}], "poll_interval_seconds": 120},+ "{\"checkpoint\": {\"time\": \"2026-10-08T11:00:00Z\", \"id\": \"evt-1\"}}"]+ after | object | {"checkpoint": {"id": "evt-1", "time": "2026-10-08T11:00:00Z"},+ "filter_rules": [{"field": "x"}], "poll_interval_seconds": 120}+ remaining corrupt rows | 0+```++Both halves come back: the configuration and the cursor that was trapped+inside the encoded string.++---++## Remaining limitations++Stated rather than implied.++1. **Duplicates are possible and bounded; loss is not.** A crash between+ ingest accepting and the checkpoint write — one database round trip — leaves+ a redelivery nothing can recognise. Moving the acknowledgement earlier would+ shrink that window and reopen the loss window, which is the wrong trade.+2. **The dedup set is bounded at 10,000 identities.** A redelivery of+ something older than that is re-emitted. It cannot drop an event.+3. **`azure_event_hubs` still carries the out-of-order watermark**, by the+ reasoning above. Its data is re-readable, so the consequence is a recoverable+ drop rather than an unrecoverable one, but it is still a silent one.+4. **In-batch duplicates are not collapsed**, unchanged from before.+5. **No vendor was contacted.** Every test here drives a local socket or a+ boto3 double. The request and response shapes come from recorded+ vendor-shaped fixtures, and the claim is that the connector handles those+ shapes — not that it has been run against a real AWS account or a real GCP+ project. **A live run against a genuine SQS queue and a genuine Pub/Sub+ subscription has not been performed and would be worth doing**; in+ particular the behaviour of a receipt handle whose visibility has lapsed,+ and of an expired `ackId`, is taken from vendor documentation rather than+ observed here.+6. **Kafka was not in the loop.** The durability claim rests on reading+ `services/ingest` — `PublishBatch` awaited, `RequiredAcks: RequireAll`, 500+ on error — and the live suite's ingest stand-in returns the same contract+ over a real socket. The Go service itself was not run, and no broker+ acknowledgement was observed end to end in this work.+7. **`AISOC_SERVICE_TOKEN` is unset in the live runs**, so the ingest client+ logs that its pushes would be refused 401. The stand-in accepts them, which+ is right for testing the acknowledgement ordering but means authentication+ to ingest is not exercised by this suite.+8. **Only the Pub/Sub half of the live suite exists.** The CloudTrail+ connector's live coverage is the boto3-double suite, because standing up a+ credible SQS and S3 pair needs either real AWS or a LocalStack dependency+ this repository does not currently take.diff --git a/scripts/check_cloud_native_collection.py b/scripts/check_cloud_native_collection.pyindex 28ba63a05..0a13b4387 100644--- a/scripts/check_cloud_native_collection.py+++ b/scripts/check_cloud_native_collection.py@@ -22,8 +22,22 @@ that looks right in a demo, and each is a rule here:**It resumes.** A queue collector that restarts and re-reads from "now"loses every object delivered while it was down; one that re-reads from thebeginning replays the whole bucket. Both are silent. The connector has to-declare the cursor fields the base class's ``apply_checkpoint`` orders and-de-duplicates on.+declare a cursor the base class's ``apply_checkpoint`` de-duplicates on,+in one of the two shapes that exist:++* ``checkpoint_time_field`` *and* ``checkpoint_id_field`` — a monotonic+ ``(event_time, id)`` high-water mark, correct where arrival order follows+ event order, which is a time-windowed API poll or an object store listed+ oldest-first.+* ``dedup_identity_field`` — a bounded set of seen identities, which is+ what an *unordered* source needs. Phase 3: on a queue a high-water mark+ discards an out-of-order arrival the only time it will ever be offered,+ and the message carrying it has already been acknowledged. Pub/Sub orders+ nothing without an ordering key, and a Cloud Logging sink sets none; S3+ notifications over SQS are unordered by construction.++Declaring both is refused by ``BaseConnector.__init_subclass__`` at import,+because they answer the same question two different ways.**It stops.** A backlog can be arbitrarily deep — an SQS queue after anoutage, a Pub/Sub subscription with a week of retention — and a poll that@@ -118,6 +132,14 @@ class Declared:checkpoint_id: boolbudget: boolbudget_leaves_backlog: bool+ #: The second shape a resumable cursor comes in: a bounded set of seen+ #: identities, for a source whose arrival order is not its event order.+ dedup_identity: bool = False++ @property+ def resumes(self) -> bool:+ """Whether the connector declares a cursor of either shape."""+ return (self.checkpoint_time and self.checkpoint_id) or self.dedup_identitydef _class_attribute_values(tree: ast.Module, attr: str) -> list[ast.expr]:@@ -167,6 +189,7 @@ def read_declaration(root: Path, path: CollectionPath) -> Declared:checkpoint_time = any(_is_nonempty_tuple(v) for v in _class_attribute_values(tree, "checkpoint_time_field"))checkpoint_id = any(_is_nonempty_tuple(v) for v in _class_attribute_values(tree, "checkpoint_id_field"))+ dedup_identity = any(_is_nonempty_tuple(v) for v in _class_attribute_values(tree, "dedup_identity_field"))budget = Falseleaves_backlog = False@@ -180,7 +203,7 @@ def read_declaration(root: Path, path: CollectionPath) -> Declared:reason = kwargs.get("backlog_stays_on_the_queue")if isinstance(reason, ast.Constant) and isinstance(reason.value, str) and reason.value.strip():leaves_backlog = True- return Declared(True, checkpoint_time, checkpoint_id, budget, leaves_backlog)+ return Declared(True, checkpoint_time, checkpoint_id, budget, leaves_backlog, dedup_identity)def registered_ids(root: Path) -> set[str]:@@ -244,12 +267,13 @@ def evaluate(root: Path, paths: tuple[CollectionPath, ...] = REQUIRED_PATHS) ->f"({REGISTRY_REL}), so the catalogue, the setup wizard and the scheduler cannot reach it.")- if not (declared.checkpoint_time and declared.checkpoint_id):+ if not declared.resumes:failures.append(- f"{path.connector_id}: declares no resumable cursor "- f"(needs a non-empty checkpoint_time_field and checkpoint_id_field in {where}). "- f"A queue collector without one either loses everything delivered while it was down "- f"or replays the backlog, and both are silent."+ f"{path.connector_id}: declares no resumable cursor in {where} — needs either "+ f"checkpoint_time_field and checkpoint_id_field (a high-water mark, for a source whose "+ f"arrival order follows its event order) or dedup_identity_field (a bounded set of seen "+ f"identities, for an unordered queue). A queue collector without one either loses "+ f"everything delivered while it was down or replays the backlog, and both are silent.")if not declared.budget:@@ -334,8 +358,13 @@ def _self_test() -> int:encoding="utf-8",)elif kind == "CHECKPOINT" and module.is_file():+ # Both shapes, because either one satisfies the rule and+ # disabling only the one this connector happens to use today+ # would stop proving anything the day it switches.module.write_text(- module.read_text(encoding="utf-8").replace("checkpoint_id_field = (", "checkpoint_id_field_disabled = ("),+ module.read_text(encoding="utf-8")+ .replace("checkpoint_id_field = (", "checkpoint_id_field_disabled = (")+ .replace("dedup_identity_field = (", "dedup_identity_field_disabled = ("),encoding="utf-8",)elif kind == "BUDGET" and module.is_file():diff --git a/scripts/mypy_baseline.json b/scripts/mypy_baseline.jsonindex 16a33007c..664f989c5 100644--- a/scripts/mypy_baseline.json+++ b/scripts/mypy_baseline.json@@ -1,9 +1,9 @@{"(environment)": {"flags": "--no-color-output --no-error-summary --no-site-packages --no-incremental",- "mypy": "2.4.0",+ "mypy": "2.3.1","mypy_major": "2",- "python": "3.11"+ "python": "3.14"},"(unmanaged)": {"plugins/mttr-widget/plugin.py": {diff --git a/services/api/app/data/connector_catalog_fallback.json b/services/api/app/data/connector_catalog_fallback.jsonindex baf86b659..635fd31d2 100644--- a/services/api/app/data/connector_catalog_fallback.json+++ b/services/api/app/data/connector_catalog_fallback.json@@ -245,7 +245,7 @@},{"default": 300,- "help_text": "How long a received message is hidden from other consumers. Must comfortably exceed one poll, or an object is re-announced while this poll is still reading it.",+ "help_text": "How long a received message is hidden from other consumers. Messages are not deleted until ingest confirms their events, so this has to cover a poll and the push that follows it \u2014 not just the poll. AiSOC stops receiving once it has spent half the timeout, and a message whose visibility lapses first is redelivered and de-duplicated rather than lost. Set a redrive policy on the queue so a notification naming an unreadable object is quarantined to a dead-letter queue instead of retried forever.","label": "Receive visibility timeout (seconds)","name": "visibility_timeout_seconds","required": false,@@ -1612,7 +1612,7 @@},{"default": 120,- "help_text": "Recorded for the setup guide and compared against the subscription at test time. A deadline shorter than one poll redelivers messages this connector is still reading.",+ "help_text": "Recorded for the setup guide and compared against the subscription at test time. Messages stay unacknowledged until ingest confirms them, so the deadline has to cover a poll and the push that follows it \u2014 not just the poll. AiSOC stops pulling once it has spent half the deadline, and a message whose deadline lapses first is redelivered and de-duplicated rather than lost.","label": "Acknowledgement deadline (seconds)","name": "ack_deadline_seconds","required": false,diff --git a/services/connectors/app/connectors/aws_cloudtrail_s3.py b/services/connectors/app/connectors/aws_cloudtrail_s3.pyindex 7f6d466d5..aa45673f9 100644--- a/services/connectors/app/connectors/aws_cloudtrail_s3.py+++ b/services/connectors/app/connectors/aws_cloudtrail_s3.py@@ -37,21 +37,35 @@ How a poll works2. For each announced object, ``s3:GetObject`` and gunzip. The key says whatis inside — CloudTrail JSON, a CloudTrail digest (skipped: it is asignature over other files, not events), or VPC flow-log text.-3. Every record becomes one envelope carrying its event time and a stable- id, so the base class's checkpoint can order and de-duplicate them.-4. ``sqs:DeleteMessage`` once the object's records are out. Delete-after,- never delete-before: a crash between the two redelivers the object, and a- duplicate is recoverable where a silently dropped object is not.+3. Every record becomes one envelope carrying its event time, a stable id and+ the key of the object it came out of, which is what the base class+ de-duplicates on.+4. ``sqs:DeleteMessage`` once **ingest has confirmed** every event from every+ object the message named. Not once the records are out: this function+ returns long before the scheduler pushes to ingest, so deleting here drops+ messages on the floor whenever that push fails, and a deleted SQS message+ cannot be replayed from anywhere. The handles are staged and+ :meth:`commit_acknowledgements` answers the queue once the verdict is in.Resumption and backpressure---------------------------The queue *is* the cursor. Nothing is lost while this connector is down,because an undeleted message returns after its visibility timeout, and the-trail keeps writing to S3 regardless. The declared checkpoint is the second-layer: redelivery is normal in SQS (at-least-once), so the ``(event_time,-record_id)`` cursor suppresses the re-read of an object the previous poll-had already emitted but whose delete did not land.+trail keeps writing to S3 regardless. The declared cursor is the second+layer: redelivery is normal in SQS (at-least-once), so a set of seen object+keys suppresses the re-read of an object the previous poll already emitted+but whose delete did not land.++It is a set and not a high-water mark on purpose. S3 notifications over SQS+arrive in no particular order, so an object whose events are older than the+previous batch's newest is an ordinary first arrival — and a watermark would+discard it on sight, after its announcing message had already been deleted.++A second bound applies while receipt handles are held: the poll stops+receiving once it has spent half the visibility timeout, leaving the rest for+ingest. Overrunning costs a duplicate rather than a gap, because a receipt+whose visibility has lapsed is refused and its message redelivers.``collection_budget`` bounds the poll. A queue that accumulated through asix-hour outage holds six hours of an estate's control plane, and draining@@ -79,6 +93,7 @@ from __future__ import annotationsimport gzipimport ipaddressimport json+import timefrom datetime import UTC, datetimefrom typing import Anyfrom urllib.parse import unquote_plus@@ -88,6 +103,7 @@ import structlogfrom app.connectors.aws_cloudtrail import _event_severity as _management_event_severityfrom app.connectors.aws_vpc_flow import _parse_v2_record, _record_severityfrom app.connectors.base import (+ AcknowledgementResult,BaseConnector,Capability,CollectionBudget,@@ -134,6 +150,12 @@ _DESTRUCTIVE_DATA_EVENTS = frozenset(#: misdirected bucket does not.MAX_OBJECT_BYTES = 256 * 1024 * 1024+#: Receives after which a notification is called out as stuck. SQS's default+#: ``maxReceiveCount`` for a redrive policy is 10 and AWS's own guidance is+#: not to go below 5, so warning at 5 names the problem at about the point a+#: correctly-configured queue would be quarantining it anyway.+_POISON_RECEIVE_COUNT = 5+def _data_event_severity(event_name: str, error_code: str | None) -> str:"""Severity for a CloudTrail *data* event.@@ -220,19 +242,22 @@ class AWSCloudTrailS3Connector(BaseConnector):connector_name = "AWS CloudTrail (S3 + SQS)"connector_category = "cloud"- #: `record_id` is `<object key>#<index>`, stable across a redelivery of- #: the same object, which is what makes the cursor suppress the duplicate- #: SQS guarantees it will eventually produce.- checkpoint_time_field = ("event_time",)- checkpoint_id_field = ("record_id",)+ #: The object key, which every record read out of that object shares and+ #: which is stable across a redelivery of its notification — so one entry+ #: suppresses a re-read of the whole object. Deliberately coarser than+ #: `record_id`: the object is this connector's atomic unit (a message is+ #: only answered when every object it named was read in full), and keying+ #: on the object keeps the retained set to the few hundred keys one poll+ #: can announce rather than the twenty thousand records they hold.+ dedup_identity_field = ("object_key",)collection_budget = CollectionBudget(max_batches_per_poll=20,max_events_per_poll=20_000,backlog_stays_on_the_queue=(- "Only a fully-emitted object's SQS message is deleted, so anything the budget stops short of is "- "still on the queue and the next poll receives it. A six-hour backlog therefore drains over "- "several polls instead of in one pass."+ "No message is deleted until ingest confirms the batch, so anything the budget stops short of is "+ "still on the queue and the next poll receives it, and so is anything ingest refused. A six-hour "+ "backlog therefore drains over several polls instead of in one pass."),)@@ -302,8 +327,12 @@ class AWSCloudTrailS3Connector(BaseConnector):required=False,default=300,help_text=(- "How long a received message is hidden from other consumers. Must comfortably exceed "- "one poll, or an object is re-announced while this poll is still reading it."+ "How long a received message is hidden from other consumers. Messages are not deleted "+ "until ingest confirms their events, so this has to cover a poll and the push that "+ "follows it — not just the poll. AiSOC stops receiving once it has spent half the "+ "timeout, and a message whose visibility lapses first is redelivered and de-duplicated "+ "rather than lost. Set a redrive policy on the queue so a notification naming an "+ "unreadable object is quarantined to a dead-letter queue instead of retried forever."),),],@@ -392,16 +421,34 @@ class AWSCloudTrailS3Connector(BaseConnector):objects_read = 0truncated = False+ started = time.monotonic()+for _ in range(budget.max_batches_per_poll):if len(rows) >= budget.max_events_per_poll:truncated = Truebreak+ if self.pending_acknowledgements() and self.acknowledgement_hold_exhausted(time.monotonic() - started):+ # Receipts already held are closer to lapsing than to being+ # deleted. Receiving another batch would widen a window that+ # is already half the timeout, so the rest stays on the queue.+ truncated = True+ logger.info(+ "cloudtrail_s3.visibility_reserve_reached",+ held=len(self.pending_acknowledgements()),+ visibility_timeout_seconds=self._visibility_timeout,+ detail="remainder stays on the queue for the next poll",+ )+ breaktry:received = sqs.receive_message(QueueUrl=self._queue_url,MaxNumberOfMessages=10,VisibilityTimeout=self._visibility_timeout,WaitTimeSeconds=1,+ # Asked for explicitly because SQS omits it otherwise, and+ # it is the only signal that a notification is stuck in a+ # retry loop rather than the queue being quiet.+ AttributeNames=["ApproximateReceiveCount"],)except Exception as exc:logger.warning("cloudtrail_s3.receive_failed", error=str(exc))@@ -413,13 +460,17 @@ class AWSCloudTrailS3Connector(BaseConnector):for message in messages:handle = message.get("ReceiptHandle")+ self._warn_if_poisoned(message)announced = _s3_notifications(message.get("Body") or "")if not announced:# An s3:TestEvent, or a message this queue should not be- # carrying. Either way it will never become events, so- # delete it rather than let it redeliver forever.+ # carrying. Either way it will never become events, so it+ # rides along with this batch's acknowledgement rather+ # than redelivering for ever. It contributes no rows, so+ # an all-test-event poll is an empty batch that ingest+ # accepts trivially and the queue still drains.if handle:- self._delete(sqs, handle)+ self.stage_acknowledgement([handle])continueemitted_all = True@@ -442,7 +493,10 @@ class AWSCloudTrailS3Connector(BaseConnector):logger.warning("cloudtrail_s3.object_failed", bucket=bucket, key=key, error=str(exc))if emitted_all and handle:- self._delete(sqs, handle)+ # Staged, not deleted. Every object this message named was+ # read, but "read" is not "durable" — the push to ingest+ # happens after this function returns.+ self.stage_acknowledgement([handle])if len(rows) >= budget.max_events_per_poll:truncated = True@@ -463,19 +517,77 @@ class AWSCloudTrailS3Connector(BaseConnector):return [self.normalize(row) for row in self.apply_checkpoint(rows)]- def _delete(self, sqs: Any, receipt_handle: str) -> None:- """Acknowledge one notification.+ def acknowledgement_deadline_seconds(self) -> int:+ """The visibility timeout, which is how long a receipt handle lasts."""+ return self._visibility_timeout++ def _warn_if_poisoned(self, message: dict[str, Any]) -> None:+ """Say so when a message keeps coming back.++ A notification naming an object that can never be read — deleted+ object, a bucket policy the task role does not satisfy, a truncated+ upload — is withheld on every poll by design, because the alternative+ is dropping audit data on a transient S3 error. That is correct and it+ is also an infinite retry if nothing bounds it.++ The bound belongs to the queue, not here: SQS's own redrive policy+ moves a message to a dead-letter queue after N receives, which is a+ durable quarantine with the original payload intact and needs no code.+ What this does is make the situation visible, because+ ``ApproximateReceiveCount`` is the only evidence an operator has that+ the queue is retrying rather than idle.+ """+ try:+ received = int((message.get("Attributes") or {}).get("ApproximateReceiveCount") or 0)+ except (TypeError, ValueError):+ return+ if received >= _POISON_RECEIVE_COUNT:+ logger.warning(+ "cloudtrail_s3.message_redelivered_repeatedly",+ receive_count=received,+ message_id=str(message.get("MessageId") or "")[:64],+ detail=(+ "this notification has been withheld on every poll because an object it names could not be read; "+ "set a redrive policy on the queue so it is quarantined to a dead-letter queue rather than retried forever"+ ),+ )++ async def commit_acknowledgements(self) -> AcknowledgementResult:+ """Delete the staged notifications.++ Called by the scheduler only once ingest has confirmed every event in+ the batch reached Kafka. A fresh SQS client because the one the fetch+ used is local to it; the receipt handles stay valid for as long as+ their visibility timeout has left to run.- Failing to delete is not fatal and must not abort the poll: the- message redelivers, the object is read again, and the checkpoint- drops the duplicate. Logged at warning because a delete that keeps- failing is a permissions problem that will otherwise present as a- queue that never drains.+ A delete that does not land is not fatal and must not raise: the+ message redelivers, the object is read again, and the object-key+ cursor drops the duplicate. Counted rather than only logged, because+ a delete that keeps failing is a permissions problem that otherwise+ presents as a queue that never drains."""+ handles = self.take_pending_acknowledgements()+ if not handles:+ return AcknowledgementResult(requested=0, confirmed=0, failed=0)try:- sqs.delete_message(QueueUrl=self._queue_url, ReceiptHandle=receipt_handle)- except Exception as exc:- logger.warning("cloudtrail_s3.delete_failed", error=str(exc))+ sqs = self._client("sqs")+ except RuntimeError as exc:+ logger.warning("cloudtrail_s3.ack_client_init_failed", count=len(handles), error=str(exc))+ return AcknowledgementResult(requested=len(handles), confirmed=0, failed=len(handles))++ confirmed = 0+ failed = 0+ for handle in handles:+ try:+ sqs.delete_message(QueueUrl=self._queue_url, ReceiptHandle=handle)+ except Exception as exc:+ # Per handle, not per batch: one lapsed receipt among twenty+ # must not strand the nineteen that are still good.+ failed += 1+ logger.warning("cloudtrail_s3.delete_failed", error=str(exc))+ else:+ confirmed += 1+ return AcknowledgementResult(requested=len(handles), confirmed=confirmed, failed=failed)def _read_object(self, s3: Any, bucket: str, key: str, kind: str) -> list[dict[str, Any]]:"""Fetch one object and turn it into envelopes."""diff --git a/services/connectors/app/connectors/base.py b/services/connectors/app/connectors/base.pyindex 306869e4c..c06c3ca64 100644--- a/services/connectors/app/connectors/base.py+++ b/services/connectors/app/connectors/base.py@@ -18,15 +18,20 @@ for ``"secret"``) is caught at import time, not at form-render time.from __future__ import annotations+import hashlibfrom abc import ABC, abstractmethodfrom collections.abc import Iterablefrom dataclasses import asdict, dataclass, fieldfrom enum import Enumfrom typing import TYPE_CHECKING, Any, Literal+import structlog+if TYPE_CHECKING:from app.federated.query import UnifiedQuery+logger = structlog.get_logger()+# ---------------------------------------------------------------------------# Capability taxonomy (Workstream 4)@@ -374,6 +379,30 @@ class CollectionBudget:raise ValueError("a bounded poll must say where the remainder goes; an unexplained bound reads as data loss")+@dataclass(frozen=True)+class AcknowledgementResult:+ """What answering the source actually achieved.++ Phase 3. A connector used to acknowledge inside its own fetch and log a+ failure at ``warning``, which meant the scheduler could not tell a+ drained queue from one that is silently refusing every delete — and the+ two look identical from a poll that reports success either way.++ ``failed`` is the number that matters: those messages will be redelivered,+ so the next poll re-reads source data that downstream has already+ accepted. That is a duplicate, which is survivable, but it is a fact about+ the deployment an operator should be able to see rather than infer from a+ backlog that never shrinks.+ """++ #: Handles the connector tried to answer.+ requested: int+ #: Handles the source confirmed. These will not be redelivered.+ confirmed: int+ #: Handles the source refused or that expired. These will be redelivered.+ failed: int++@dataclass(frozen=True)class ConnectorSchema:"""Self-describing schema for a connector.@@ -541,6 +570,31 @@ class BaseConnector(ABC):# 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.+ #+ # ----------------------------- and where it is wrong (phase 3) -----------+ #+ # Everything above assumes the source hands rows over in roughly event+ # order, which is true of a time-windowed API poll and is what makes a+ # high-water mark safe there: anything at or below the cursor really has+ # been seen.+ #+ # A queue makes no such promise. Pub/Sub gives no ordering unless the+ # topic was created with message ordering *and* the publisher sets an+ # ordering key, which a Cloud Logging sink does not; S3 notifications over+ # SQS are unordered by construction. On those sources an event older than+ # the last batch's newest is an ordinary first arrival, and a high-water+ # mark discards it the only time it will ever be offered.+ #+ # Such a connector declares :attr:`dedup_identity_field` instead. The+ # queue is what guarantees nothing is lost — an unacknowledged message+ # comes back — so the cursor's only remaining job is to recognise the+ # duplicate that at-least-once delivery will eventually produce, and a set+ # of identities does that without needing an order. Rows keep their+ # arrival order, because arrival order is the only order the source has.+ #+ # The set is bounded, and the direction of the bound is the point: falling+ # off the end of it costs a duplicate, where falling outside a watermark+ # cost the event. See :attr:`max_dedup_identities`.#: Field on a raw row carrying its event time. ``None`` means this#: connector does not checkpoint, which is the honest default.@@ -556,11 +610,55 @@ class BaseConnector(ABC):#: sentence rather than only two numbers.collection_budget: CollectionBudget | None = None+ #: Field carrying a stable, source-scoped identity for a row. Declaring it+ #: switches the cursor from a monotonic event-time watermark to a bounded+ #: set of seen identities — the right shape for an unordered queue, where+ #: "older than the last batch" does not mean "already seen".+ #:+ #: The identity must survive a redelivery of the same source data. A+ #: Pub/Sub ``messageId`` does; its ``ackId`` does not, because the vendor+ #: mints a fresh one every time it hands the message over.+ dedup_identity_field: tuple[str, ...] = ()++ #: How many identities the cursor remembers. Sized to cover more than one+ #: poll's worth for the connectors that declare it, because the window+ #: that needs covering is "accepted downstream but not yet acknowledged",+ #: which is at most the batch in flight. Exceeding it re-emits an event,+ #: which fusion and the lake can collapse; it never drops one.+ #:+ #: Stored as 16-hex truncated digests rather than raw identities: an+ #: object key is long and names a customer's bucket layout, and bounding+ #: the width bounds the JSONB this writes to a connector row (~190 kB at+ #: the default) regardless of what the source calls things.+ max_dedup_identities: int = 10_000+#: 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+ _next_checkpoint: dict[str, Any] | None = None++ #: Identities seeded from the persisted cursor, in the order they were+ #: last seen, so the bound forgets the oldest first.+ _incoming_seen: tuple[str, ...] = ()++ #: Source-side handles — SQS receipt handles, Pub/Sub ack ids — for+ #: messages whose events are in this poll's batch. Staged during the+ #: fetch, committed by the scheduler once ingest confirms the batch is+ #: durable. See :meth:`stage_acknowledgement`.+ _pending_acks: tuple[str, ...] = ()++ def __init_subclass__(cls, **kwargs: Any) -> None:+ super().__init_subclass__(**kwargs)+ # Checked at import rather than at poll time: a connector declaring+ # both schemes would silently use one of them, and which one is an+ # implementation detail of a dispatch nobody reads twice.+ if cls.dedup_identity_field and (cls.checkpoint_time_field or cls.checkpoint_id_field):+ raise ValueError(+ f"connector '{cls.connector_id}' declares both an event-time watermark and a dedup identity. "+ "They answer the same question two different ways: pick the watermark for an ordered API poll, "+ "the identity for an unordered queue."+ )@classmethoddef checkpoints(cls) -> bool:@@ -570,16 +668,42 @@ class BaseConnector(ABC):returns False re-reads its overlap window after a restart, which issafe and means a long outage loses events older than that window."""+ if cls.dedup_identity_field:+ return Truereturn bool(cls.checkpoint_time_field and cls.checkpoint_id_field)+ @classmethod+ def seen_tokens(cls, identities: Iterable[str]) -> list[str]:+ """Dedup tokens for ``identities``, in order.++ The connector id is part of the digest so two sources that happen to+ mint the same record id cannot suppress each other's events. Tenant+ scoping is structural rather than hashed in: the cursor lives on one+ connector *instance* row, which belongs to exactly one tenant.+ """+ prefix = cls.connector_id.encode("utf-8")+ return [hashlib.sha256(prefix + b"\x00" + str(identity).encode("utf-8")).hexdigest()[:16] for identity in identities]+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 = None+ self._incoming_seen = ()+ if not isinstance(checkpoint, dict):+ return+ if self.dedup_identity_field:+ # A connector switched from a watermark to identity dedup finds+ # the old `{"time", "id"}` shape in its config. Reading it would+ # reinstate exactly the behaviour this replaced, so it is ignored+ # — at the cost of re-emitting whatever the last poll emitted+ # once, which is the safe direction.+ seen = checkpoint.get("seen")+ if isinstance(seen, list):+ self._incoming_seen = tuple(str(token) for token in seen if token)+ return+ if 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:+ def get_checkpoint(self) -> dict[str, Any] | None:"""The advanced cursor after a fetch, or ``None`` if nothing moved.The scheduler persists this only once ingest has accepted every@@ -588,6 +712,101 @@ class BaseConnector(ABC):"""return self._next_checkpoint+ # ----------------------------- acknowledgement (phase 3) -----------------+ #+ # Separating "we have the data" from "the data is safe" is the whole of+ # finding 4. A connector reading a queue used to answer the source inside+ # ``fetch_alerts``, once the rows were in a local list — but a list is not+ # durability, and ``fetch_alerts`` returns long before the scheduler+ # pushes to ingest. A crash or a 5xx in that gap took messages that are no+ # longer redeliverable, and no cursor can help once a message is gone.+ #+ # So the fetch *stages* the source's handles and the scheduler commits+ # them, because the scheduler is the only layer that sees ingest's answer.+ # Acceptance means broker-confirmed Kafka delivery: ``services/ingest``+ # awaits ``PublishBatch`` with ``RequiredAcks: RequireAll`` and answers+ # 500 on failure, so a 200 with ``accepted == submitted`` is a real+ # guarantee. (Its graph fan-out is deliberately non-blocking and is not+ # part of that guarantee.)+ #+ # The bound: an SQS visibility timeout and a Pub/Sub ack deadline are+ # finite, so a held handle has an expiry. A connector that holds handles+ # stops taking new work once the poll has spent its share of the deadline+ # (see ``acknowledgement_hold_fraction``), leaving the rest for ingest and+ # the checkpoint write. Overrunning anyway costs a duplicate — the handle+ # is refused and the message redelivers — never a gap.++ #: Share of the source's acknowledgement deadline a poll may spend before+ #: it stops collecting. The remainder is the downstream budget: normalize,+ #: filter, push to ingest, persist the cursor. Half each is deliberately+ #: generous on both sides rather than tuned; the failure mode either way+ #: is a duplicate.+ acknowledgement_hold_fraction: float = 0.5++ def stage_acknowledgement(self, handles: Iterable[str]) -> None:+ """Record source handles to be answered once the batch is durable."""+ fresh = tuple(str(handle) for handle in handles if handle)+ if fresh:+ self._pending_acks = self._pending_acks + fresh++ def pending_acknowledgements(self) -> list[str]:+ """Handles staged by this poll and not yet committed."""+ return list(self._pending_acks)++ def take_pending_acknowledgements(self) -> list[str]:+ """Claim the staged handles, clearing them.++ Claiming before the vendor call rather than after means a handle is+ never committed twice if the call partially succeeds and is retried.+ """+ handles = list(self._pending_acks)+ self._pending_acks = ()+ return handles++ def discard_acknowledgements(self) -> None:+ """Drop the staged handles without answering the source.++ What the scheduler does when ingest did not accept the batch. The+ messages redeliver after their visibility timeout or ack deadline,+ which is the entire reason they were not deleted.+ """+ self._pending_acks = ()++ async def commit_acknowledgements(self) -> AcknowledgementResult:+ """Answer the source for every staged handle.++ The default is a no-op *only* when nothing was staged. A connector+ that stages handles and does not implement this would hold them to+ the end of the poll and then drop them, so the queue would never+ drain — louder here than as a backlog nobody attributes to us.+ """+ if not self._pending_acks:+ return AcknowledgementResult(requested=0, confirmed=0, failed=0)+ raise NotImplementedError(+ f"connector '{self.connector_id}' stages acknowledgements but does not implement commit_acknowledgements()"+ )++ def acknowledgement_deadline_seconds(self) -> int:+ """Seconds a staged handle stays valid, or 0 when there is no deadline.++ Overridden by connectors whose source enforces one: SQS reports the+ visibility timeout it was asked for, Pub/Sub the subscription's ack+ deadline.+ """+ return 0++ def acknowledgement_hold_exhausted(self, elapsed_seconds: float) -> bool:+ """Whether this poll has spent its share of the acknowledgement deadline.++ Called from a fetch loop before taking another batch. False when the+ source has no deadline, so a connector without one is unbounded by+ this and bounded by its ``collection_budget`` alone.+ """+ deadline = self.acknowledgement_deadline_seconds()+ if deadline <= 0:+ return False+ return elapsed_seconds >= deadline * self.acknowledgement_hold_fraction+def _row_time(self, row: dict[str, Any]) -> str:return self._first_present(row, self.checkpoint_time_field)@@ -602,12 +821,19 @@ class BaseConnector(ABC):return str(value)return ""+ def _row_identity(self, row: dict[str, Any]) -> str:+ return self._first_present(row, self.dedup_identity_field)+def apply_checkpoint(self, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:- """Order, de-duplicate against the cursor, and stage the advance.+ """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``.+ it is safe to call unconditionally from ``fetch_alerts``. Dispatches+ on which cursor the connector declared: an event-time watermark for an+ ordered poll, a bounded identity set for an unordered queue."""+ if self.dedup_identity_field:+ return self._apply_identity_dedup(rows)if not self.checkpoints():return rows@@ -631,6 +857,70 @@ class BaseConnector(ABC):self._next_checkpoint = Nonereturn fresh+ def _apply_identity_dedup(self, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Drop rows this cursor has already seen; keep everything else.++ No ordering and no comparison against a watermark: on an unordered+ source the only thing that makes a row a duplicate is having seen that+ exact identity before.++ Rows are not de-duplicated against *each other* within one batch. The+ same object announced twice in one poll stays twice, which is what the+ watermark did too — the atom here is the cross-poll redelivery that+ at-least-once delivery guarantees, and collapsing within a batch would+ break a connector whose rows legitimately share an identity (every+ record read out of one S3 object shares its object key).+ """+ known = set(self._incoming_seen)+ fresh: list[dict[str, Any]] = []+ this_batch: list[str] = []+ unidentified = 0++ for row in rows:+ identity = self._row_identity(row)+ if not identity:+ # Cannot be proven a duplicate, so it is not treated as one.+ # Counted because a source that stopped emitting its id would+ # otherwise present as a quietly growing duplicate rate.+ unidentified += 1+ fresh.append(row)+ continue+ token = self.seen_tokens([identity])[0]+ if token in known:+ continue+ fresh.append(row)+ this_batch.append(token)++ if unidentified:+ logger.warning(+ "connector.dedup.row_without_identity",+ connector=self.connector_id,+ field=self.dedup_identity_field,+ rows=unidentified,+ detail="emitted without de-duplication; a redelivery of these cannot be recognised",+ )++ if not this_batch:+ self._next_checkpoint = None+ return fresh++ # Oldest first, so truncation forgets what is least likely to still+ # be in flight. The window that must stay covered is this batch: it is+ # the one that has been accepted downstream but not yet acknowledged.+ retained = [token for token in self._incoming_seen if token not in set(this_batch)] + this_batch+ if len(retained) > self.max_dedup_identities:+ dropped = len(retained) - self.max_dedup_identities+ retained = retained[dropped:]+ logger.info(+ "connector.dedup.identities_truncated",+ connector=self.connector_id,+ dropped=dropped,+ kept=len(retained),+ detail="a redelivery older than the retained window would be re-emitted, not dropped",+ )+ self._next_checkpoint = {"seen": retained}+ return fresh+# ----------------------------- federated search --------------------------# Connectors that opt into federated search override ``supports_federated_search``diff --git a/services/connectors/app/connectors/gcp_pubsub.py b/services/connectors/app/connectors/gcp_pubsub.pyindex 1f9295192..e225207bb 100644--- a/services/connectors/app/connectors/gcp_pubsub.py+++ b/services/connectors/app/connectors/gcp_pubsub.py@@ -26,34 +26,48 @@ Resumption and backpressure---------------------------The subscription is the cursor. A message is redelivered until it is-acknowledged, so a restart mid-poll costs a duplicate rather than a gap, and-the declared ``(event_time, record_id)`` checkpoint suppresses that-duplicate downstream. Acknowledgement happens **after** the batch has been-turned into events, never before.+acknowledged, so a restart mid-poll costs a duplicate rather than a gap.++Acknowledgement happens after **ingest has confirmed the batch is durable**,+not merely after the batch has been turned into events. That distinction is+the one this connector originally got wrong: it acknowledged once the+entries were in a local list, while the push to ingest happens later, in the+scheduler, after ``fetch_alerts`` has already returned. A crash or a 5xx in+that gap took messages the subscription had been told to forget, and no+cursor can recover a message that is gone. So the fetch stages its ack ids+and :meth:`commit_acknowledgements` answers the subscription once the+scheduler has ingest's verdict.``collection_budget`` bounds the poll, because a subscription holds up toseven days of retention and a sink on an organisation's Data Access logsfills that quickly. Unacknowledged messages stay on the subscription and the-next poll pulls them.+next poll pulls them. A second bound applies for as long as ack ids are+held: the poll stops pulling once it has spent half the subscription's ack+deadline, leaving the rest for ingest. Overrunning anyway costs a duplicate,+because an expired ack id is refused and its message redelivers.A note on ordering: Pub/Sub does not guarantee order unless the topic iscreated with message ordering enabled *and* the publisher sets an ordering-key, which Cloud Logging sinks do not. The checkpoint therefore sorts by-``(event_time, record_id)`` within each poll and tolerates a late arrival by-re-reading its own overlap — which is why the cursor is a de-duplicator here-rather than a watermark that may skip.+key, which Cloud Logging sinks do not. So this connector does **not** keep an+event-time high-water mark — an entry older than the last batch's newest is+an ordinary first arrival here, and a watermark would discard it the only+time it is ever offered. It de-duplicates on ``messageId``, which the vendor+keeps stable across a redelivery (``ackId`` is not: a fresh one is minted+every time the message is handed over)."""from __future__ import annotationsimport base64import json+import timefrom typing import Anyimport httpximport structlogfrom app.connectors.base import (+ AcknowledgementResult,BaseConnector,Capability,CollectionBudget,@@ -150,16 +164,18 @@ class GCPPubSubConnector(BaseConnector):connector_name = "GCP Pub/Sub (log sink)"connector_category = "cloud"- checkpoint_time_field = ("event_time",)- checkpoint_id_field = ("record_id",)+ #: `record_id` is the vendor's `messageId`, which is stable across a+ #: redelivery. Not an event-time watermark: a sink sets no ordering key,+ #: so "older than the last batch" is not "already seen" here.+ dedup_identity_field = ("record_id",)collection_budget = CollectionBudget(max_batches_per_poll=20,max_events_per_poll=20_000,backlog_stays_on_the_queue=(- "Only messages whose entries were emitted are acknowledged. Anything the budget stops short of "- "stays unacknowledged on the subscription and is redelivered on the next poll, so a backlog "- "drains over several polls rather than in one pass."+ "Nothing is acknowledged until ingest confirms the batch, so anything the budget stops short of "+ "stays unacknowledged on the subscription and is redelivered on the next poll, and so does "+ "anything ingest refused. A backlog drains over several polls rather than in one pass."),)@@ -210,7 +226,10 @@ class GCPPubSubConnector(BaseConnector):default=120,help_text=("Recorded for the setup guide and compared against the subscription at test time. "- "A deadline shorter than one poll redelivers messages this connector is still reading."+ "Messages stay unacknowledged until ingest confirms them, so the deadline has to cover "+ "a poll and the push that follows it — not just the poll. AiSOC stops pulling once it "+ "has spent half the deadline, and a message whose deadline lapses first is redelivered "+ "and de-duplicated rather than lost."),),],@@ -294,11 +313,27 @@ class GCPPubSubConnector(BaseConnector):logger.warning("gcp_pubsub.auth_failed", error=str(exc))return []+ started = time.monotonic()+async with httpx.AsyncClient(timeout=30.0) as client:for _ in range(budget.max_batches_per_poll):if len(rows) >= budget.max_events_per_poll:truncated = Truebreak+ if self.pending_acknowledgements() and self.acknowledgement_hold_exhausted(time.monotonic() - started):+ # Ack ids already held are closer to expiry than to being+ # answered. Taking another batch would widen a window that+ # is already most of the deadline, so the remainder stays+ # on the subscription.+ truncated = True+ logger.info(+ "gcp_pubsub.ack_deadline_reserve_reached",+ subscription=self._subscription_path,+ held=len(self.pending_acknowledgements()),+ ack_deadline_seconds=self._ack_deadline,+ detail="remainder stays unacknowledged on the subscription for the next poll",+ )+ breaktry:resp = await client.post(f"{_PUBSUB_ROOT}/{self._subscription_path}:pull",@@ -345,10 +380,11 @@ class GCPPubSubConnector(BaseConnector):})- # Acknowledge after the batch is in `rows`, never before: a- # failure between the two has to cost a duplicate, not a gap.- if ack_ids:- await self._acknowledge(client, token, ack_ids)+ # Staged, not acknowledged. Being in `rows` is not durability+ # and this function cannot observe anything that is: the push+ # to ingest happens after it returns. The scheduler commits+ # these once it has ingest's answer.+ self.stage_acknowledgement(ack_ids)if len(received) < _PULL_SIZE:break@@ -363,20 +399,45 @@ class GCPPubSubConnector(BaseConnector):return [self.normalize(row) for row in self.apply_checkpoint(rows)]- async def _acknowledge(self, client: httpx.AsyncClient, token: str, ack_ids: list[str]) -> None:+ def acknowledgement_deadline_seconds(self) -> int:+ """The subscription's ack deadline, which is how long an ackId lives."""+ return self._ack_deadline++ async def commit_acknowledgements(self) -> AcknowledgementResult:+ """Acknowledge the staged ack ids.++ Called by the scheduler only once ingest has confirmed the whole batch+ reached Kafka. A fresh client because the one the fetch used is long+ closed; the ack ids themselves stay valid until the deadline expires,+ independent of any connection.++ Not fatal, and not silent. A refused or expired ack id means the+ message redelivers, the identity cursor drops the duplicate, and a+ persistent failure shows as a subscription that never drains — which+ an operator can only diagnose if it was counted.+ """+ ack_ids = self.take_pending_acknowledgements()+ if not ack_ids:+ return AcknowledgementResult(requested=0, confirmed=0, failed=0)try:- resp = await client.post(- f"{_PUBSUB_ROOT}/{self._subscription_path}:acknowledge",- headers=self._auth.headers(token),- json={"ackIds": ack_ids},- )- resp.raise_for_status()+ token = await self._auth.token()+ async with httpx.AsyncClient(timeout=30.0) as client:+ resp = await client.post(+ f"{_PUBSUB_ROOT}/{self._subscription_path}:acknowledge",+ headers=self._auth.headers(token),+ json={"ackIds": ack_ids},+ )+ resp.raise_for_status()except Exception as exc:- # Not fatal, and not silent. The messages redeliver, the- # checkpoint drops the duplicates, and a persistent failure here- # shows as a subscription that never drains — which an operator- # can only diagnose if it was logged.- logger.warning("gcp_pubsub.ack_failed", count=len(ack_ids), error=str(exc))+ logger.warning(+ "gcp_pubsub.ack_failed",+ subscription=self._subscription_path,+ count=len(ack_ids),+ error=str(exc),+ detail="these messages will be redelivered and de-duplicated on messageId",+ )+ return AcknowledgementResult(requested=len(ack_ids), confirmed=0, failed=len(ack_ids))+ return AcknowledgementResult(requested=len(ack_ids), confirmed=len(ack_ids), failed=0)def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:entry = _as_dict(raw.get("entry"))diff --git a/services/connectors/app/db/connector_repo.py b/services/connectors/app/db/connector_repo.pyindex df99fb334..9dc661495 100644--- a/services/connectors/app/db/connector_repo.py+++ b/services/connectors/app/db/connector_repo.py@@ -31,8 +31,9 @@ from sqlalchemy import (String,Table,Text,- cast,+ bindparam,func,+ literal_column,select,update,)@@ -119,6 +120,47 @@ class ConnectorInstance:last_backfill_at: datetime | None = None+def _recover_connector_config(value: Any) -> dict[str, Any]:+ """The config object, recovering the array a previous release could write.++ ``record_checkpoint`` double-encoded its patch, so Postgres coerced the+ merge to an array and every connector that checkpointed once was left with+ ``[{...the real config...}, "{\\"checkpoint\\": {...}}"]``. The poll that+ followed raised on ``.items()`` and the instance went unhealthy for good.++ Reading that shape back is recovery, not tolerance of a current bug: the+ write path can no longer produce it, and an operator who upgrades should+ not have to run SQL to get their connectors polling again. Both halves are+ recoverable — the config is the mapping element, and the cursor is inside+ the encoded string — so a resumed connector does not re-read its overlap+ either.++ Anything else unrecognisable becomes ``{}``, which is what the caller's+ ``or {}`` already meant.+ """+ if isinstance(value, dict):+ return value+ if not isinstance(value, list):+ return {}++ recovered: dict[str, Any] = {}+ checkpoint: Any = None+ for element in value:+ if isinstance(element, dict):+ recovered.update(element)+ continue+ if isinstance(element, str):+ try:+ decoded = json.loads(element)+ except (TypeError, ValueError):+ continue+ if isinstance(decoded, dict):+ checkpoint = decoded.get("checkpoint", checkpoint)+ if checkpoint is not None and "checkpoint" not in recovered:+ recovered["checkpoint"] = checkpoint+ return recovered++def _instance_from_row(row: Any) -> ConnectorInstance:"""Map one result row onto the dataclass.@@ -132,7 +174,7 @@ def _instance_from_row(row: Any) -> ConnectorInstance:connector_type=row.connector_type,is_enabled=row.is_enabled,auth_config=row.auth_config or {},- connector_config=row.connector_config or {},+ connector_config=_recover_connector_config(row.connector_config),health_status=row.health_status,last_sync=row.last_sync,events_ingested=row.events_ingested,@@ -336,8 +378,30 @@ async def record_checkpoint(re-scans a bounded overlap rather than skipping events."""now = datetime.now(UTC)- patch = cast(json.dumps({"checkpoint": checkpoint}), JSONB)- merged = func.coalesce(connectors_table.c.connector_config, cast("{}", JSONB)).op("||")(patch)+ # Bound as a mapping with a JSONB type, serialised exactly once.+ #+ # `cast(json.dumps(...), JSONB)` -- what this was -- serialises twice:+ # `cast` declares the bind's type as JSONB, so SQLAlchemy's JSONB bind+ # processor encodes the string it was handed, and Postgres receives a JSON+ # *string scalar* rather than an object. `jsonb || <scalar>` then coerces+ # both operands to arrays, so one successful checkpointed poll rewrote+ # `connector_config` from+ # {"poll_interval_seconds": 120, "filter_rules": [...]}+ # to+ # [{"poll_interval_seconds": 120, ...}, "{\"checkpoint\": {...}}"]+ # and the *next* poll raised `AttributeError: 'list' object has no+ # attribute 'items'` on reading it, which the poll's broad handler+ # recorded as a failure. The instance went unhealthy and stayed there,+ # with its poll interval and its filter rules no longer readable.+ #+ # Nothing caught it because every scheduler test patches this function+ # with a fake that records the dict it was handed, so the statement below+ # had never been executed by a test. `tests/isolation/+ # test_queue_acknowledgement_live.py` now runs it against real Postgres.+ patch = bindparam("checkpoint_patch", {"checkpoint": checkpoint}, JSONB, unique=True)+ # A literal rather than another `cast(...)` bind, for the same reason.+ empty = literal_column("'{}'::jsonb")+ merged = func.coalesce(connectors_table.c.connector_config, empty).op("||")(patch)stmt = update(connectors_table).where(connectors_table.c.id == connector_id).values(connector_config=merged, updated_at=now)await connection.execute(stmt)diff --git a/services/connectors/app/scheduler.py b/services/connectors/app/scheduler.pyindex 4835a11da..b8336f463 100644--- a/services/connectors/app/scheduler.py+++ b/services/connectors/app/scheduler.py@@ -631,6 +631,10 @@ class ConnectorScheduler:connector_id,target.connector_type,)+ # A fetch that raised part-way may already have staged handles for+ # the batches it did read. None of it reached ingest, so none of+ # it may be acknowledged.+ self._discard_acknowledgements(connector, connector_id, reason="fetch_failed", staged=0)await self._record_failure(target.id)return@@ -728,6 +732,12 @@ class ConnectorScheduler:connector_id,len(kept),)+ # Nothing reached Kafka, so nothing may be acknowledged. Dropping+ # the staged handles leaves the messages on the source to be+ # redelivered; discarding explicitly rather than letting the+ # connector fall out of scope so the intent is legible here, at+ # the one place that knows ingest refused.+ self._discard_acknowledgements(connector, connector_id, reason="ingest_failed", staged=len(kept))await self._record_failure(target.id)return@@ -761,6 +771,26 @@ class ConnectorScheduler:counts_present,)+ # Only now may the source be told to forget the messages. Withholding+ # a cursor is not enough on a queue: a cursor over data that has+ # already been deleted from the queue protects nothing, which is why+ # the connectors stage their receipt handles and ack ids instead of+ # answering the source inside their own fetch.+ #+ # After the checkpoint write, deliberately. A crash between the two+ # leaves messages that will be redelivered and a cursor that+ # recognises them; the other order leaves a source that has forgotten+ # them and a cursor that has not recorded them.+ if batch_fully_accepted:+ await self._commit_acknowledgements(connector, connector_id, target.connector_type)+ else:+ self._discard_acknowledgements(+ connector,+ connector_id,+ reason="batch_not_fully_accepted",+ staged=len(kept),+ )+# If drift was detected, persist that fact *before* marking the# poll successful so the UI reflects "drifted" status alongside# "healthy". Both writes are independent transactions; the order@@ -954,6 +984,74 @@ class ConnectorScheduler:connector_id,)+ async def _commit_acknowledgements(self, connector: Any, connector_id: uuid.UUID, connector_type: str) -> None:+ """Answer the source for a batch ingest confirmed is durable.++ Never raises into the poll. A failed acknowledgement costs a+ redelivery, which the connector's identity cursor de-duplicates, so+ the poll was still a success — but the count is logged because a+ connector whose acknowledgements never land is a queue that never+ drains, and that is otherwise indistinguishable from a quiet source.+ """+ try:+ result = await connector.commit_acknowledgements()+ except NotImplementedError:+ # A connector that stages handles without implementing the commit.+ # Loud: the queue will not drain, and nothing else would say so.+ logger.error(+ "connector.scheduler.acknowledge_unimplemented id=%s type=%s",+ connector_id,+ connector_type,+ )+ return+ except Exception:+ logger.exception(+ "connector.scheduler.acknowledge_failed id=%s type=%s",+ connector_id,+ connector_type,+ )+ return++ requested = int(getattr(result, "requested", 0) or 0)+ failed = int(getattr(result, "failed", 0) or 0)+ if failed:+ logger.warning(+ "connector.scheduler.acknowledge_partial id=%s type=%s requested=%d confirmed=%d failed=%d",+ connector_id,+ connector_type,+ requested,+ int(getattr(result, "confirmed", 0) or 0),+ failed,+ )+ elif requested:+ logger.debug(+ "connector.scheduler.acknowledged id=%s type=%s count=%d",+ connector_id,+ connector_type,+ requested,+ )++ def _discard_acknowledgements(self, connector: Any, connector_id: uuid.UUID, *, reason: str, staged: int) -> None:+ """Leave the source holding its messages, and say that it happened.++ The silent version of this is the defect: a poll that fetched, failed+ to ship and left no trace reads as a quiet source on the next poll.+ """+ try:+ pending = len(connector.pending_acknowledgements())+ connector.discard_acknowledgements()+ except Exception: # never let acknowledgement bookkeeping break a poll+ logger.debug("connector.scheduler.discard_failed id=%s", connector_id)+ return+ if pending:+ logger.warning(+ "connector.scheduler.acknowledgement_withheld id=%s reason=%s messages=%d events=%d",+ connector_id,+ reason,+ pending,+ staged,+ )+async def _sync_vulnerability_findings(self, connector: Any, target: Any) -> None:"""Materialise a scanner's findings as vulnerability rows, if it has any.diff --git a/services/connectors/tests/test_aws_cloudtrail_s3.py b/services/connectors/tests/test_aws_cloudtrail_s3.pyindex 190c810b9..f4a1743cc 100644--- a/services/connectors/tests/test_aws_cloudtrail_s3.py+++ b/services/connectors/tests/test_aws_cloudtrail_s3.py@@ -213,17 +213,24 @@ class TestAPoll:connector = _connector(sqs, _FakeS3(_objects()), include_flow_logs=False)assert await connector.fetch_alerts() == []- assert sqs.deleted == ["h1"], "a filtered-out object still consumes its notification"+ assert connector.pending_acknowledgements() == ["h1"], "a filtered-out object still consumes its notification"-class TestAcknowledgementIsTheCheckpoint:+class TestTheQueueIsTheCursor:@pytest.mark.asyncio- async def test_a_fully_read_object_acknowledges_its_message(self) -> None:+ async def test_a_fully_read_object_answers_its_message_once_ingest_has(self) -> None:+ """Read in full, so the message becomes answerable — but only the+ scheduler, holding ingest's verdict, may answer it."""sqs = _FakeSQS([[_message("h1", _fixture("sqs_s3_notification.json"))]])connector = _connector(sqs, _FakeS3(_objects()))await connector.fetch_alerts()+ assert connector.pending_acknowledgements() == ["h1"]+ assert sqs.deleted == []++ await connector.commit_acknowledgements()+assert sqs.deleted == ["h1"]@pytest.mark.asyncio@@ -255,16 +262,252 @@ class TestAcknowledgementIsTheCheckpoint:resumed.set_checkpoint(cursor)assert await resumed.fetch_alerts() == []+ assert resumed.pending_acknowledgements() == ["h2"], "a duplicate is still a message that has to leave the queue"@pytest.mark.asyncioasync def test_an_undecodable_notification_is_consumed_rather_than_looped(self) -> None:"""A message that can never become events has to leave the queue, or- it redelivers until its retention expires."""+ it redelivers until its retention expires. It rides along with the+ batch: it contributes no rows, so an all-garbage poll submits an empty+ batch, ingest accepts it trivially, and the queue still drains."""sqs = _FakeSQS([[_message("h1", "not json at all")]])connector = _connector(sqs, _FakeS3(_objects()))assert await connector.fetch_alerts() == []+ assert connector.pending_acknowledgements() == ["h1"]++ await connector.commit_acknowledgements()++ assert sqs.deleted == ["h1"]+++class TestTheHandleOutlivesTheFetch:+ """Phase 3, finding 4. Deleting the receipt is the irreversible step.++ ``fetch_alerts`` returning is not downstream acceptance — the scheduler+ pushes to ingest *after* it returns, and ingest is the first hop that+ writes anything durable. A delete issued inside the pull loop therefore+ drops the message on the floor whenever the push that follows fails, and+ an SQS message that has been deleted cannot be replayed from anywhere.+ """++ @pytest.mark.asyncio+ async def test_a_message_is_not_deleted_while_its_records_are_only_in_a_list(self) -> None:+ """Being in a Python list is not durability.++ The fix is not "delete later in the same function"; it is that the+ delete cannot happen in this function at all, because nothing this+ function can observe proves the records survived.+ """+ sqs = _FakeSQS([[_message("h1", _fixture("sqs_s3_notification.json"))]])+ connector = _connector(sqs, _FakeS3(_objects()))++ alerts = await connector.fetch_alerts()++ assert len(alerts) == 3, "the records are read"+ assert sqs.deleted == [], "but nothing downstream has accepted them yet, so the receipt must survive the fetch"++ @pytest.mark.asyncio+ async def test_the_handle_is_staged_for_the_scheduler_to_commit(self) -> None:+ """Staged, not acknowledged. The scheduler owns the commit because it+ is the only layer that sees ingest's answer."""+ sqs = _FakeSQS([[_message("h1", _fixture("sqs_s3_notification.json"))]])+ connector = _connector(sqs, _FakeS3(_objects()))++ await connector.fetch_alerts()++ assert connector.pending_acknowledgements() == ["h1"]++ @pytest.mark.asyncio+ async def test_committing_deletes_exactly_what_was_staged(self) -> None:+ sqs = _FakeSQS([[_message("h1", _fixture("sqs_s3_notification.json"))]])+ connector = _connector(sqs, _FakeS3(_objects()))+ await connector.fetch_alerts()++ result = await connector.commit_acknowledgements()+assert sqs.deleted == ["h1"]+ assert (result.requested, result.confirmed, result.failed) == (1, 1, 0)+ assert connector.pending_acknowledgements() == [], "a committed handle is not re-committed"++ @pytest.mark.asyncio+ async def test_discarding_leaves_the_message_on_the_queue(self) -> None:+ """What the scheduler does when ingest did not accept the batch. The+ message redelivers after its visibility timeout, which is the entire+ point of not having deleted it."""+ sqs = _FakeSQS([[_message("h1", _fixture("sqs_s3_notification.json"))]])+ connector = _connector(sqs, _FakeS3(_objects()))+ await connector.fetch_alerts()++ connector.discard_acknowledgements()++ assert sqs.deleted == []+ assert connector.pending_acknowledgements() == []++ @pytest.mark.asyncio+ async def test_an_unreadable_object_still_withholds_the_whole_message(self) -> None:+ """Partial acceptance at the source end: one notification can name+ several objects, and a message is only answerable when every object it+ names was read."""+ body = json.dumps(+ {+ "Records": [+ {"s3": {"bucket": {"name": "b"}, "object": {"key": CLOUDTRAIL_KEY}}},+ {"s3": {"bucket": {"name": "b"}, "object": {"key": "AWSLogs/o-x/1/CloudTrail/us-east-1/2026/10/08/missing.json.gz"}}},+ ]+ }+ )+ sqs = _FakeSQS([[_message("h1", body)]])+ connector = _connector(sqs, _FakeS3({CLOUDTRAIL_KEY: _objects()[CLOUDTRAIL_KEY]}))++ alerts = await connector.fetch_alerts()++ assert len(alerts) == 3, "the readable object's records are still emitted"+ assert connector.pending_acknowledgements() == [], "but the message is not answerable while one object is unread"+ assert sqs.deleted == []++ @pytest.mark.asyncio+ async def test_a_failed_delete_is_reported_rather_than_assumed(self) -> None:+ """A delete that does not land means the message redelivers. The+ scheduler cannot react to what it is not told."""+ sqs = _FakeSQS([[_message("h1", _fixture("sqs_s3_notification.json"))]])++ def _refuse(**_kwargs: Any) -> dict[str, Any]:+ raise RuntimeError("AccessDenied: sqs:DeleteMessage")++ connector = _connector(sqs, _FakeS3(_objects()))+ await connector.fetch_alerts()+ sqs.delete_message = _refuse # type: ignore[method-assign]++ result = await connector.commit_acknowledgements()++ assert (result.requested, result.confirmed, result.failed) == (1, 0, 1)+++class TestAnOlderObjectAnnouncedLaterSurvives:+ """Phase 3, finding 5.++ S3 event notifications over SQS are unordered by construction, so an+ object whose events are older than the previous batch's newest event is+ an ordinary arrival, not a duplicate. A monotonic ``(event_time,+ record_id)`` high-water mark discards it on first sight, and because the+ announcing message was already deleted there is nothing left to replay.+ """++ @staticmethod+ def _object_at(event_time: str, event_id: str) -> bytes:+ """A vendor-shaped CloudTrail object with one record at a chosen time."""+ return gzip.compress(+ json.dumps(+ {+ "Records": [+ {+ "eventID": event_id,+ "eventTime": event_time,+ "eventName": "ConsoleLogin",+ "eventSource": "signin.amazonaws.com",+ "eventCategory": "Management",+ "awsRegion": "us-east-1",+ "recipientAccountId": "123456789012",+ "sourceIPAddress": "198.51.100.24",+ "userIdentity": {"type": "IAMUser", "userName": "late-arrival"},+ }+ ]+ }+ ).encode()+ )++ @staticmethod+ def _notification(key: str) -> str:+ return json.dumps({"Records": [{"s3": {"bucket": {"name": "b"}, "object": {"key": key}}}]})++ @pytest.mark.asyncio+ async def test_an_event_older_than_the_last_batch_is_still_emitted(self) -> None:+ newer_key = "AWSLogs/o-x/1/CloudTrail/us-east-1/2026/10/08/newer.json.gz"+ older_key = "AWSLogs/o-x/1/CloudTrail/us-east-1/2026/10/08/older.json.gz"+ objects = {+ newer_key: self._object_at("2026-10-08T11:00:00Z", "newer-1"),+ older_key: self._object_at("2026-10-08T09:00:00Z", "older-1"),+ }++ first = _connector(_FakeSQS([[_message("h1", self._notification(newer_key))]]), _FakeS3(objects))+ assert len(await first.fetch_alerts()) == 1+ cursor = first.get_checkpoint()+ assert cursor is not None++ resumed = _connector(_FakeSQS([[_message("h2", self._notification(older_key))]]), _FakeS3(objects))+ resumed.set_checkpoint(cursor)+ alerts = await resumed.fetch_alerts()++ assert [a["external_id"] for a in alerts] == ["older-1"], (+ "an out-of-order arrival on an unordered queue is a new event, not a duplicate — "+ "and its notification has already been deleted, so dropping it here loses it for good"+ )++ @pytest.mark.asyncio+ async def test_a_genuine_redelivery_of_the_same_object_is_still_suppressed(self) -> None:+ """The other half, and the reason the cursor cannot simply be deleted.+ SQS is at-least-once: the same object does arrive twice."""+ key = "AWSLogs/o-x/1/CloudTrail/us-east-1/2026/10/08/same.json.gz"+ objects = {key: self._object_at("2026-10-08T11:00:00Z", "same-1")}++ first = _connector(_FakeSQS([[_message("h1", self._notification(key))]]), _FakeS3(objects))+ assert len(await first.fetch_alerts()) == 1+ cursor = first.get_checkpoint()++ resumed = _connector(_FakeSQS([[_message("h2", self._notification(key))]]), _FakeS3(objects))+ resumed.set_checkpoint(cursor)++ assert await resumed.fetch_alerts() == [], "the same object read twice must not become two alerts"++ @pytest.mark.asyncio+ async def test_two_distinct_events_sharing_a_timestamp_both_survive(self) -> None:+ key_a = "AWSLogs/o-x/1/CloudTrail/us-east-1/2026/10/08/a.json.gz"+ key_b = "AWSLogs/o-x/1/CloudTrail/us-east-1/2026/10/08/b.json.gz"+ objects = {+ key_a: self._object_at("2026-10-08T11:00:00Z", "tie-a"),+ key_b: self._object_at("2026-10-08T11:00:00Z", "tie-b"),+ }++ first = _connector(_FakeSQS([[_message("h1", self._notification(key_a))]]), _FakeS3(objects))+ await first.fetch_alerts()+ cursor = first.get_checkpoint()++ resumed = _connector(_FakeSQS([[_message("h2", self._notification(key_b))]]), _FakeS3(objects))+ resumed.set_checkpoint(cursor)++ assert [a["external_id"] for a in await resumed.fetch_alerts()] == ["tie-b"]+++class TestTheHoldIsBounded:+ """An SQS visibility timeout is finite, so holding a receipt is only safe+ for as long as the timeout has left to run. The poll stops taking new work+ rather than collecting a batch it cannot answer for."""++ @pytest.mark.asyncio+ async def test_the_poll_stops_taking_new_work_near_the_visibility_deadline(self, monkeypatch: pytest.MonkeyPatch) -> None:+ from app.connectors import aws_cloudtrail_s3 as module++ clock = {"now": 0.0}+ monkeypatch.setattr(module.time, "monotonic", lambda: clock["now"])++ batches = [[_message(f"h{i}", _fixture("sqs_s3_notification.json"))] for i in range(4)]+ sqs = _FakeSQS(batches)++ real_receive = sqs.receive_message++ def _receive_then_age(**kwargs: Any) -> dict[str, Any]:+ # Each receive burns 20s of a 30s timeout, so the second one puts+ # the poll past the half-timeout reserve.+ clock["now"] += 20.0+ return real_receive(**kwargs)++ sqs.receive_message = _receive_then_age # type: ignore[method-assign]+ connector = _connector(sqs, _FakeS3(_objects()), visibility_timeout_seconds=30)++ await connector.fetch_alerts()++ assert sqs.receive_calls == 1, "a second batch would be held past the point the first receipt can be trusted"class TestBackpressure:@@ -300,7 +543,7 @@ class TestBackpressure:# taken off the queue and are still there for the next poll.assert sqs.receive_calls == 1assert len(alerts) == 3, "the object is the atomic unit, so the bound overshoots by at most one object"- assert sqs.deleted == ["h0"]+ assert connector.pending_acknowledgements() == ["h0"]@pytest.mark.asyncioasync def test_the_visibility_timeout_reaches_the_receive_call(self) -> None:diff --git a/services/connectors/tests/test_checkpoint_contract.py b/services/connectors/tests/test_checkpoint_contract.pyindex 0192b5100..4454875e0 100644--- a/services/connectors/tests/test_checkpoint_contract.py+++ b/services/connectors/tests/test_checkpoint_contract.py@@ -47,6 +47,13 @@ class _Uncursored(_Cursored):checkpoint_id_field: tuple[str, ...] = ()+class _Identified(_Uncursored):+ """A queue-shaped connector: dedups on identity, never on event time."""++ connector_id = "test_identified"+ dedup_identity_field: tuple[str, ...] = ("rid",)++def _row(ts: str, uid: str) -> dict[str, Any]:return {"ts": ts, "uid": uid}@@ -142,22 +149,28 @@ class TestAdoptionIsCountedNotAssumed:"m365_audit": (("CreationTime",), ("Id",)),"aws_cloudtrail": (("EventTime",), ("EventId",)),"azure_activity": (("eventTimestamp",), ("eventDataId", "id")),- # Depth plan 4.1. These three read a queue or an object store rather- # than a time-windowed API, so the cursor is doing a different job:- # the queue already guarantees nothing is lost, and the cursor exists- # to drop the duplicate that at-least-once delivery guarantees will- # eventually arrive. All three therefore carry a synthetic- # `record_id` built from the object or message identity, which is- # what makes it stable across a re-read.- "aws_cloudtrail_s3": (("event_time",), ("record_id",)),- "gcp_pubsub": (("event_time",), ("record_id",)),+ # Depth plan 4.1. Reads an object store rather than a time-windowed+ # API, so the cursor is doing a different job: the store already+ # guarantees nothing is lost, and the cursor exists to drop the+ # re-read that listing the container from the beginning produces. It+ # therefore carries a synthetic `record_id` built from the capture+ # path and sequence number, which is what makes it stable.+ #+ # Phase 3 removed `aws_cloudtrail_s3` and `gcp_pubsub` from this+ # table. Both read an *unordered* queue, where a high-water mark+ # discards a late arrival the only time it is ever offered; they+ # dedup on identity instead and are recorded in+ # `TestUnorderedSourcesDoNotCarryAWatermark`. This one stays because+ # its container is never drained and is re-listed from the start on+ # every poll, which a bounded identity set cannot survive."azure_event_hubs": (("event_time",), ("record_id",)),}def test_the_adopters_are_exactly_the_ones_recorded(self) -> None:actual = {cid for cid, cls in CONNECTOR_REGISTRY.items() if cls.checkpoints()}+ identity_based = set(TestUnorderedSourcesDoNotCarryAWatermark.UNORDERED)- assert actual == set(self.EXPECTED), (+ assert actual == set(self.EXPECTED) | identity_based, ("the set of checkpointing connectors changed. Adding one is good — record it here. ""Losing one silently is the defect this replaces.")@@ -175,11 +188,150 @@ class TestAdoptionIsCountedNotAssumed:overlap window after a restart, which is safe and loses events olderthan 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())+ adopters = len(self.EXPECTED) + len(TestUnorderedSourcesDoNotCarryAWatermark.UNORDERED)- assert len(without) == len(CONNECTOR_REGISTRY) - len(self.EXPECTED)+ assert len(without) == len(CONNECTOR_REGISTRY) - adoptersassert len(CONNECTOR_REGISTRY) >= 84+class TestUnorderedSourcesDoNotCarryAWatermark:+ """Phase 3, finding 5.++ A monotonic ``(event_time, record_id)`` high-water mark is right for an+ ordered, time-windowed API poll — that is what the design comment on+ ``apply_checkpoint`` describes and it is sound. It is wrong for a queue.+ Neither Pub/Sub (no ordering key from a Cloud Logging sink) nor an S3+ notification over SQS is ordered, so an event older than the last batch's+ newest is an ordinary first arrival. A watermark discards it, silently,+ and the message that carried it has already been acknowledged.+ """++ #: Sources whose arrival order is not their event order. These dedup on a+ #: stable identity instead; the queue itself is what guarantees no gap.+ UNORDERED = {+ "aws_cloudtrail_s3": ("object_key",),+ "gcp_pubsub": ("record_id",),+ }++ @pytest.mark.parametrize("connector_id", sorted(UNORDERED))+ def test_it_dedups_on_an_identity_rather_than_a_time(self, connector_id: str) -> None:+ cls = CONNECTOR_REGISTRY[connector_id]++ assert cls.dedup_identity_field == self.UNORDERED[connector_id]+ assert cls.checkpoint_time_field == (), "an event-time watermark over an unordered source drops unseen events"+ assert cls.checkpoint_id_field == ()++ @pytest.mark.parametrize("connector_id", sorted(UNORDERED))+ def test_it_still_resumes_from_a_persisted_cursor(self, connector_id: str) -> None:+ """Identity dedup is a cursor too. Dropping out of the checkpointing+ set would mean the scheduler stopped seeding it at all."""+ assert CONNECTOR_REGISTRY[connector_id].checkpoints() is True++ def test_a_blob_store_that_is_relisted_every_poll_keeps_its_watermark(self) -> None:+ """``azure_event_hubs`` reads Capture files from a container that is+ never drained, and lists it from the beginning on every poll. The+ watermark is doing load-bearing work there: a bounded identity set+ would roll over and re-emit the oldest files for ever. It has the+ same out-of-order weakness across partitions, but its source is+ re-readable rather than destroyed, so the fix is a different one.+ """+ cls = CONNECTOR_REGISTRY["azure_event_hubs"]++ assert cls.dedup_identity_field == ()+ assert cls.checkpoint_time_field == ("event_time",)+++class TestIdentityDedupMachinery:+ @pytest.fixture()+ def connector(self) -> _Identified:+ return _Identified()++ def test_an_older_row_never_seen_before_is_kept(self, connector: _Identified) -> None:+ """The whole finding, at the level the logic lives."""+ connector.set_checkpoint({"seen": _Identified.seen_tokens(["later"])})++ kept = connector.apply_checkpoint([{"rid": "earlier", "ts": "t1"}])++ assert [r["rid"] for r in kept] == ["earlier"]++ def test_a_row_already_seen_is_dropped(self, connector: _Identified) -> None:+ connector.set_checkpoint({"seen": _Identified.seen_tokens(["dupe"])})++ assert connector.apply_checkpoint([{"rid": "dupe", "ts": "t1"}]) == []++ def test_the_staged_cursor_carries_this_batch(self, connector: _Identified) -> None:+ connector.apply_checkpoint([{"rid": "a"}, {"rid": "b"}])+ staged = connector.get_checkpoint()++ assert staged is not None+ assert set(staged["seen"]) == set(_Identified.seen_tokens(["a", "b"]))++ def test_rows_are_not_reordered(self, connector: _Identified) -> None:+ """Arrival order is the only order a queue has; imposing an event-time+ sort on it implies a guarantee the source does not make."""+ kept = connector.apply_checkpoint([{"rid": "c", "ts": "t3"}, {"rid": "a", "ts": "t1"}])++ assert [r["rid"] for r in kept] == ["c", "a"]++ def test_a_row_with_no_identity_is_kept_rather_than_guessed_at(self, connector: _Identified) -> None:+ kept = connector.apply_checkpoint([{"rid": ""}, {"rid": "a"}])++ assert len(kept) == 2, "an unidentifiable row cannot be proven a duplicate, so it is not treated as one"++ def test_the_set_is_bounded_and_forgets_the_oldest_first(self) -> None:+ """The bound's failure mode is a duplicate, never a drop — the+ opposite of the watermark it replaces."""++ class _Small(_Identified):+ connector_id = "test_small"+ max_dedup_identities = 3++ connector = _Small()+ connector.set_checkpoint({"seen": _Small.seen_tokens(["a", "b", "c"])})+ connector.apply_checkpoint([{"rid": "d"}])+ staged = connector.get_checkpoint()++ assert staged is not None+ assert len(staged["seen"]) == 3+ assert _Small.seen_tokens(["a"])[0] not in staged["seen"]+ assert _Small.seen_tokens(["d"])[0] in staged["seen"]++ def test_an_identity_is_scoped_to_its_connector(self) -> None:+ """Two sources can mint the same record id. The token binds the+ connector so one cannot suppress the other's event; the tenant scope+ comes from the per-instance row the cursor is stored on."""++ class _Other(_Identified):+ connector_id = "test_other_identified"++ assert _Identified.seen_tokens(["same"]) != _Other.seen_tokens(["same"])++ def test_a_watermark_cursor_left_by_an_earlier_release_is_ignored(self) -> None:+ """Compatibility. A connector upgraded in place finds a+ ``{"time", "id"}`` cursor in its config, and must neither crash on it+ nor resurrect the behaviour it replaced."""+ connector = _Identified()+ connector.set_checkpoint({"time": "t9", "id": "z"})++ kept = connector.apply_checkpoint([{"rid": "a", "ts": "t1"}])++ assert [r["rid"] for r in kept] == ["a"]++ def test_declaring_both_schemes_is_refused(self) -> None:+ """They answer the same question two different ways, and a connector+ carrying both would silently use one of them.++ Refused when the class is defined rather than when it is polled: an+ import-time error names the connector on startup, where a poll-time+ one would surface as whichever dispatch happened to win.+ """+ with pytest.raises(ValueError, match="both an event-time watermark and a dedup identity"):+ # Built with `type` rather than a `class` statement so there is no+ # name to leave unbound: defining the class *is* the call under+ # test, and `__init_subclass__` raises before anything is bound.+ type("_Both", (_Cursored,), {"connector_id": "test_both", "dedup_identity_field": ("uid",)})++class TestTheSchedulerNoLongerDuckTypes:def test_it_calls_the_contract_directly(self) -> None:"""The getattr is what made 83 silent no-ops invisible."""diff --git a/services/connectors/tests/test_gcp_pubsub.py b/services/connectors/tests/test_gcp_pubsub.pyindex 25f3d82a6..01c707fec 100644--- a/services/connectors/tests/test_gcp_pubsub.py+++ b/services/connectors/tests/test_gcp_pubsub.py@@ -14,6 +14,7 @@ does when a key field is missing.from __future__ import annotations+import base64import jsonfrom pathlib import Pathfrom typing import Any@@ -132,12 +133,17 @@ class TestAPoll:@pytest.mark.asyncio@respx.mock- async def test_every_message_in_the_batch_is_acknowledged(self, service_account_json: str) -> None:+ async def test_every_message_in_the_batch_is_eventually_acknowledged(self, service_account_json: str) -> None:+ """Every message the poll consumed is answered — once the scheduler+ commits. A connector that never acknowledges is not safe, it is a+ subscription that never drains."""_mock_token()respx.post(_PULL_URL).mock(side_effect=[httpx.Response(200, json=_pull_response()), httpx.Response(200, json={})])ack = respx.post(_ACK_URL).mock(return_value=httpx.Response(200, json={}))- await _connector(service_account_json).fetch_alerts()+ connector = _connector(service_account_json)+ await connector.fetch_alerts()+ await connector.commit_acknowledgements()assert ack.calledassert json.loads(ack.calls.last.request.content)["ackIds"] == [@@ -232,10 +238,248 @@ class TestAPoll:)ack = respx.post(_ACK_URL).mock(return_value=httpx.Response(200, json={}))- assert await _connector(service_account_json).fetch_alerts() == []+ connector = _connector(service_account_json)+ assert await connector.fetch_alerts() == []+ await connector.commit_acknowledgements()+assert json.loads(ack.calls.last.request.content)["ackIds"] == ["ack-empty"]+def _entry(timestamp: str, insert_id: str) -> str:+ """One base64-encoded ``LogEntry``, the shape a sink publishes."""+ return base64.b64encode(+ json.dumps(+ {+ "insertId": insert_id,+ "timestamp": timestamp,+ "severity": "NOTICE",+ "logName": "projects/example-logging/logs/cloudaudit.googleapis.com%2Factivity",+ "resource": {"type": "gce_instance", "labels": {"project_id": "example-prod"}},+ "protoPayload": {"methodName": "v1.compute.instances.insert", "authenticationInfo": {"principalEmail": "[email protected]"}},+ }+ ).encode()+ ).decode()+++def _received(message_id: str, ack_id: str, timestamp: str, insert_id: str) -> dict[str, Any]:+ return {"ackId": ack_id, "message": {"messageId": message_id, "publishTime": timestamp, "data": _entry(timestamp, insert_id)}}+++class TestTheAckOutlivesTheFetch:+ """Phase 3, finding 4. Acknowledging is the irreversible step.++ A Pub/Sub ack makes the subscription forget the message. The existing+ tests pin that the ack comes after the entries are *decoded*, which is one+ layer short of the thing that matters: ``fetch_alerts`` returns, and only+ then does the scheduler push to ingest. Between those two points the+ messages exist nowhere but a local list.+ """++ @pytest.mark.asyncio+ @respx.mock+ async def test_nothing_is_acknowledged_while_the_entries_are_only_in_a_list(self, service_account_json: str) -> None:+ _mock_token()+ respx.post(_PULL_URL).mock(side_effect=[httpx.Response(200, json=_pull_response()), httpx.Response(200, json={})])+ ack = respx.post(_ACK_URL).mock(return_value=httpx.Response(200, json={}))++ alerts = await _connector(service_account_json).fetch_alerts()++ assert len(alerts) == 3, "the entries are decoded"+ assert not ack.called, "but nothing durable has accepted them, so the subscription must still hold them"++ @pytest.mark.asyncio+ @respx.mock+ async def test_the_ack_ids_are_staged_for_the_scheduler(self, service_account_json: str) -> None:+ _mock_token()+ respx.post(_PULL_URL).mock(side_effect=[httpx.Response(200, json=_pull_response()), httpx.Response(200, json={})])+ respx.post(_ACK_URL).mock(return_value=httpx.Response(200, json={}))++ connector = _connector(service_account_json)+ await connector.fetch_alerts()++ assert connector.pending_acknowledgements() == [+ "UAYWLF1GSFE3GQhoUQ5PXIz90001",+ "UAYWLF1GSFE3GQhoUQ5PXIz90002",+ "UAYWLF1GSFE3GQhoUQ5PXIz90003",+ ]++ @pytest.mark.asyncio+ @respx.mock+ async def test_committing_acknowledges_exactly_what_was_staged(self, service_account_json: str) -> None:+ _mock_token()+ respx.post(_PULL_URL).mock(side_effect=[httpx.Response(200, json=_pull_response()), httpx.Response(200, json={})])+ ack = respx.post(_ACK_URL).mock(return_value=httpx.Response(200, json={}))+ connector = _connector(service_account_json)+ await connector.fetch_alerts()++ result = await connector.commit_acknowledgements()++ assert json.loads(ack.calls.last.request.content)["ackIds"] == [+ "UAYWLF1GSFE3GQhoUQ5PXIz90001",+ "UAYWLF1GSFE3GQhoUQ5PXIz90002",+ "UAYWLF1GSFE3GQhoUQ5PXIz90003",+ ]+ assert (result.requested, result.confirmed, result.failed) == (3, 3, 0)+ assert connector.pending_acknowledgements() == []++ @pytest.mark.asyncio+ @respx.mock+ async def test_discarding_leaves_the_subscription_holding_them(self, service_account_json: str) -> None:+ _mock_token()+ respx.post(_PULL_URL).mock(side_effect=[httpx.Response(200, json=_pull_response()), httpx.Response(200, json={})])+ ack = respx.post(_ACK_URL).mock(return_value=httpx.Response(200, json={}))+ connector = _connector(service_account_json)+ await connector.fetch_alerts()++ connector.discard_acknowledgements()++ assert not ack.called+ assert connector.pending_acknowledgements() == []++ @pytest.mark.asyncio+ @respx.mock+ async def test_an_expired_ack_deadline_is_reported_rather_than_assumed(self, service_account_json: str) -> None:+ """The bounded-hold failure mode. Pub/Sub answers 400 for an ack id+ whose deadline has passed; the message is already being redelivered,+ so the honest outcome is a counted failure, not a silent success."""+ _mock_token()+ respx.post(_PULL_URL).mock(side_effect=[httpx.Response(200, json=_pull_response()), httpx.Response(200, json={})])+ respx.post(_ACK_URL).mock(return_value=httpx.Response(400, json={"error": "ack id expired"}))+ connector = _connector(service_account_json)+ await connector.fetch_alerts()++ result = await connector.commit_acknowledgements()++ assert (result.requested, result.confirmed, result.failed) == (3, 0, 3)++ @pytest.mark.asyncio+ @respx.mock+ async def test_an_empty_payload_message_is_still_staged(self, service_account_json: str) -> None:+ """It produced no event, so no downstream acceptance will ever cover+ it — but leaving it unacknowledged forever is how a subscription stops+ draining. It rides along with the batch's own acknowledgement."""+ _mock_token()+ respx.post(_PULL_URL).mock(+ side_effect=[+ httpx.Response(200, json={"receivedMessages": [{"ackId": "ack-empty", "message": {"messageId": "1", "data": ""}}]}),+ httpx.Response(200, json={}),+ ]+ )+ connector = _connector(service_account_json)++ assert await connector.fetch_alerts() == []+ assert connector.pending_acknowledgements() == ["ack-empty"]+++class TestAnOlderEntryArrivingLaterSurvives:+ """Phase 3, finding 5.++ The module docstring says the cursor "tolerates a late arrival by+ re-reading its own overlap", which is not what the base class does: it+ keeps a single monotonic ``(event_time, record_id)`` high-water mark and+ drops anything at or below it. A sink sets no ordering key, so a late+ entry is routine — and it is discarded the first time it is ever seen.+ """++ @pytest.mark.asyncio+ @respx.mock+ async def test_an_entry_older_than_the_last_batch_is_still_emitted(self, service_account_json: str) -> None:+ _mock_token()+ respx.post(_PULL_URL).mock(+ side_effect=[+ httpx.Response(200, json={"receivedMessages": [_received("m-new", "ack-new", "2026-10-08T11:00:00Z", "newer")]}),+ httpx.Response(200, json={}),+ ]+ )+ first = _connector(service_account_json)+ assert len(await first.fetch_alerts()) == 1+ cursor = first.get_checkpoint()+ assert cursor is not None++ respx.post(_PULL_URL).mock(+ side_effect=[+ httpx.Response(200, json={"receivedMessages": [_received("m-old", "ack-old", "2026-10-08T09:00:00Z", "older")]}),+ httpx.Response(200, json={}),+ ]+ )+ resumed = _connector(service_account_json)+ resumed.set_checkpoint(cursor)++ assert [a["external_id"] for a in await resumed.fetch_alerts()] == ["older"], (+ "Pub/Sub gives no ordering without an ordering key, so this entry has never been seen before"+ )++ @pytest.mark.asyncio+ @respx.mock+ async def test_a_genuine_redelivery_is_still_suppressed(self, service_account_json: str) -> None:+ """Pub/Sub is at-least-once, so the same message really does arrive+ twice whenever an ack does not land. Removing the cursor outright+ would trade a silent drop for a silent duplicate."""+ _mock_token()+ same = [_received("m-1", "ack-1", "2026-10-08T11:00:00Z", "entry-1")]+ respx.post(_PULL_URL).mock(side_effect=[httpx.Response(200, json={"receivedMessages": same}), httpx.Response(200, json={})])+ first = _connector(service_account_json)+ assert len(await first.fetch_alerts()) == 1+ cursor = first.get_checkpoint()++ # Redelivered: same messageId, a fresh ackId, exactly as Pub/Sub does it.+ redelivered = [_received("m-1", "ack-1-again", "2026-10-08T11:00:00Z", "entry-1")]+ respx.post(_PULL_URL).mock(side_effect=[httpx.Response(200, json={"receivedMessages": redelivered}), httpx.Response(200, json={})])+ resumed = _connector(service_account_json)+ resumed.set_checkpoint(cursor)++ assert await resumed.fetch_alerts() == []++ @pytest.mark.asyncio+ @respx.mock+ async def test_two_entries_sharing_a_timestamp_both_survive(self, service_account_json: str) -> None:+ _mock_token()+ respx.post(_PULL_URL).mock(+ side_effect=[+ httpx.Response(200, json={"receivedMessages": [_received("m-a", "ack-a", "2026-10-08T11:00:00Z", "tie-a")]}),+ httpx.Response(200, json={}),+ ]+ )+ first = _connector(service_account_json)+ await first.fetch_alerts()+ cursor = first.get_checkpoint()++ respx.post(_PULL_URL).mock(+ side_effect=[+ httpx.Response(200, json={"receivedMessages": [_received("m-b", "ack-b", "2026-10-08T11:00:00Z", "tie-b")]}),+ httpx.Response(200, json={}),+ ]+ )+ resumed = _connector(service_account_json)+ resumed.set_checkpoint(cursor)++ assert [a["external_id"] for a in await resumed.fetch_alerts()] == ["tie-b"]+++class TestTheHoldIsBounded:+ @pytest.mark.asyncio+ @respx.mock+ async def test_the_poll_stops_pulling_near_the_ack_deadline(self, service_account_json: str, monkeypatch: pytest.MonkeyPatch) -> None:+ """A held ackId is only good until the deadline expires, so the poll+ stops taking new messages rather than collecting a batch whose first+ half it can no longer answer for."""+ from app.connectors import gcp_pubsub as module++ clock = {"now": 0.0}+ monkeypatch.setattr(module.time, "monotonic", lambda: clock["now"])+ _mock_token()++ def _slow_pull(_request: httpx.Request) -> httpx.Response:+ clock["now"] += 20.0+ return httpx.Response(200, json={"receivedMessages": _pull_response()["receivedMessages"] * 84})++ pull = respx.post(_PULL_URL).mock(side_effect=_slow_pull)++ await _connector(service_account_json, ack_deadline_seconds=30).fetch_alerts()++ assert pull.call_count == 1++class TestBackpressure:def test_the_budget_is_declared_and_says_where_the_remainder_goes(self) -> None:budget = GCPPubSubConnector.collection_budgetdiff --git a/services/connectors/tests/test_scheduler.py b/services/connectors/tests/test_scheduler.pyindex 69a8ad914..00661972d 100644--- a/services/connectors/tests/test_scheduler.py+++ b/services/connectors/tests/test_scheduler.py@@ -21,6 +21,7 @@ from typing import Anyfrom unittest.mock import AsyncMock, MagicMockimport pytest+from app.connectors.base import AcknowledgementResult, BaseConnector, ConnectorSchemafrom app.db.connector_repo import ConnectorInstancefrom app.scheduler import ConnectorScheduler, _coerce_poll_interval@@ -1192,3 +1193,285 @@ async def test_poll_refuses_a_stored_internal_destination(monkeypatch):fake_connector_class.assert_not_called()assert fake_engine.failure_calls == [inst.id]assert fake_engine.success_calls == []+++# ---------------------------------------------------------------------------+# Phase 3 — acknowledgement waits for durable downstream acceptance+#+# These drive a connector over a queue that really behaves like one, rather+# than a MagicMock. The defect under test is an acknowledgement that lands+# before durability, and a mock records the call without modelling its+# consequence: the message leaving the queue. This queue drains on ack and+# redelivers everything that was never acked, so "was the event lost?" is a+# question the test can actually ask.+# ---------------------------------------------------------------------------+++class _AtLeastOnceQueue:+ """A queue with the one property that makes this class of bug possible.++ An acknowledged message is gone for good; an unacknowledged one comes+ back. Nothing here is more capable than SQS or Pub/Sub — in particular+ there is no second copy of an acked message anywhere, which is precisely+ why acking early cannot be undone.+ """++ def __init__(self, messages: list[dict[str, Any]], *, refuse_acks: bool = False) -> None:+ self._messages: dict[str, dict[str, Any]] = {m["handle"]: m for m in messages}+ self.receive_calls = 0+ self.acked: list[str] = []+ #: Models a handle the source refuses — a lapsed visibility timeout,+ #: an expired ack deadline, a missing delete permission. The message+ #: stays, which is what makes the redelivery real rather than asserted.+ self.refuse_acks = refuse_acks++ def receive(self) -> list[dict[str, Any]]:+ self.receive_calls += 1+ return [dict(m) for m in self._messages.values()]++ def ack(self, handles: list[str]) -> None:+ for handle in handles:+ if self.refuse_acks:+ continue+ self._messages.pop(handle, None)+ self.acked.append(handle)++ @property+ def depth(self) -> int:+ return len(self._messages)+++class _QueueBackedConnector(BaseConnector):+ """The smallest honest queue connector: pull, stage, let the caller commit."""++ connector_id = "test_queue_backed"+ connector_name = "Queue backed"+ connector_category = "cloud"+ dedup_identity_field: tuple[str, ...] = ("record_id",)++ #: Set by the test. The scheduler constructs a fresh instance per poll,+ #: so per-poll state cannot live on the instance — same as production.+ queue: Any = None+ #: Record ids whose ``normalize`` should raise, to model one child event+ #: of a multi-event notification failing.+ broken: frozenset[str] = frozenset()++ def __init__(self, **_config: Any) -> None:+ """Accept whatever the scheduler hands over, like a real connector.++ Not decoration: without it the scheduler's ``TypeError`` guard catches+ the construction, records a failure and returns before polling — and+ a test asserting "the message was not acknowledged" then passes+ because nothing ran at all.+ """++ @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]]:+ rows: list[dict[str, Any]] = []+ for message in type(self).queue.receive():+ rows.extend(message["rows"])+ self.stage_acknowledgement([message["handle"]])+ return [self.normalize(row) for row in self.apply_checkpoint(rows)]++ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:+ if raw.get("record_id") in type(self).broken:+ raise ValueError(f"cannot normalize {raw['record_id']}")+ return {"source": self.connector_id, "raw_event": raw, "external_id": raw["record_id"]}++ async def commit_acknowledgements(self) -> AcknowledgementResult:+ handles = self.take_pending_acknowledgements()+ queue = type(self).queue+ before = queue.depth+ queue.ack(handles)+ # Derived from what the queue actually did, not from what was asked.+ # A result that reports success for every handle it was handed is the+ # exact shape that hides a delete nobody is allowed to make.+ confirmed = before - queue.depth+ return AcknowledgementResult(requested=len(handles), confirmed=confirmed, failed=len(handles) - confirmed)+++def _queue_message(handle: str, *record_ids: str) -> dict[str, Any]:+ return {"handle": handle, "rows": [{"record_id": rid, "event_time": f"2026-10-08T11:00:0{i}Z"} for i, rid in enumerate(record_ids)]}+++def _queue_scheduler(+ monkeypatch: Any,+ queue: _AtLeastOnceQueue,+ ingest: _FakeIngestClient,+ *,+ broken: frozenset[str] = frozenset(),+ checkpoint: dict[str, Any] | None = None,+) -> tuple[ConnectorScheduler, ConnectorInstance, _FakeEngine]:+ config: dict[str, Any] = {"poll_interval_seconds": 60}+ if checkpoint is not None:+ config["checkpoint"] = checkpoint+ inst = _make_instance(connector_type="test_queue_backed", connector_config=config)+ monkeypatch.setattr(_QueueBackedConnector, "queue", queue)+ monkeypatch.setattr(_QueueBackedConnector, "broken", broken)+ monkeypatch.setattr("app.scheduler.CONNECTOR_REGISTRY", {"test_queue_backed": _QueueBackedConnector})+ engine = _FakeEngine([inst])+ # The fakes are structural stand-ins, deliberately narrower than the real+ # clients — the point of this module, and the reason every other test here+ # does the same.+ scheduler = ConnectorScheduler(engine=engine, ingest_client=ingest, vault=_FakeVault()) # type: ignore[arg-type]+ return scheduler, inst, engine+++async def test_a_fetch_that_ingest_rejects_leaves_the_message_on_the_queue(monkeypatch):+ """Finding 4, stated as the property that matters: no loss.++ The fetch succeeds, ingest answers 500, and the only acceptable outcome is+ that the message is still there to be read again.+ """+ from app.ingest_client import IngestClientError++ queue = _AtLeastOnceQueue([_queue_message("h1", "r1", "r2")])+ ingest = _FakeIngestClient()+ ingest.exc = IngestClientError("ingest down")+ scheduler, inst, engine = _queue_scheduler(monkeypatch, queue, ingest)++ await scheduler._poll_one(connector_id=inst.id)++ assert queue.acked == [], "acknowledging here deletes the only copy of the events"+ assert queue.depth == 1+ assert engine.failure_calls == [inst.id]+ assert engine.checkpoint_calls == []+++async def test_the_rejected_batch_is_recovered_in_full_on_the_next_poll(monkeypatch):+ """Completeness, not just 'the handle survived'. The second poll has to+ produce the same events, because that is what 'not lost' means."""+ from app.ingest_client import IngestClientError++ queue = _AtLeastOnceQueue([_queue_message("h1", "r1", "r2")])+ ingest = _FakeIngestClient()+ ingest.exc = IngestClientError("ingest down")+ scheduler, inst, _engine = _queue_scheduler(monkeypatch, queue, ingest)+ await scheduler._poll_one(connector_id=inst.id)++ ingest.exc = None+ ingest.accepted = 2+ await scheduler._poll_one(connector_id=inst.id)++ assert [e["external_id"] for e in (ingest.last_payload or {})["events"]] == ["r1", "r2"]+ assert queue.acked == ["h1"]+ assert queue.depth == 0+++async def test_a_partially_accepted_batch_is_not_acknowledged(monkeypatch):+ """Ingest reports per-event normalization failures as HTTP 200 with+ counts, so a 200 is not a guarantee. One rejected event means the whole+ notification stays answerable."""+ queue = _AtLeastOnceQueue([_queue_message("h1", "r1", "r2")])+ ingest = _FakeIngestClient(accepted=1, rejected=1)+ scheduler, inst, engine = _queue_scheduler(monkeypatch, queue, ingest)++ await scheduler._poll_one(connector_id=inst.id)++ assert queue.acked == []+ assert queue.depth == 1+ assert engine.checkpoint_calls == []+++async def test_a_child_event_that_cannot_be_normalized_withholds_the_acknowledgement(monkeypatch):+ """One notification, several events, one of them unusable. The scheduler's+ normalizer returns the raw row rather than raising, so the batch reaches+ ingest with an event ingest will reject — and the ack has to wait for that+ answer rather than assume it."""+ queue = _AtLeastOnceQueue([_queue_message("h1", "r1", "r2")])+ ingest = _FakeIngestClient(accepted=1, rejected=1)+ scheduler, inst, _engine = _queue_scheduler(monkeypatch, queue, ingest, broken=frozenset({"r2"}))++ await scheduler._poll_one(connector_id=inst.id)++ assert queue.acked == []+ assert queue.depth == 1+++async def test_a_fully_accepted_batch_is_acknowledged_and_does_not_come_back(monkeypatch):+ """The other direction. A guarantee that never acknowledges is not a+ guarantee, it is a queue that never drains."""+ queue = _AtLeastOnceQueue([_queue_message("h1", "r1", "r2")])+ ingest = _FakeIngestClient(accepted=2)+ scheduler, inst, engine = _queue_scheduler(monkeypatch, queue, ingest)++ await scheduler._poll_one(connector_id=inst.id)++ assert queue.acked == ["h1"]+ assert queue.depth == 0+ assert engine.success_calls == [inst.id]+++async def test_the_checkpoint_is_durable_before_the_acknowledgement_is_sent(monkeypatch):+ """Process exits after acceptance but before acknowledgement.++ The ordering is what makes that survivable: the identities are persisted+ first, so the redelivery that follows a crash in this window is+ recognised as one. Acking first would make the crash lose nothing but+ would make a *failed* ack indistinguishable from a successful one.+ """+ queue = _AtLeastOnceQueue([_queue_message("h1", "r1")])+ ingest = _FakeIngestClient(accepted=1)+ scheduler, inst, engine = _queue_scheduler(monkeypatch, queue, ingest)+ order: list[str] = []++ real_ack = _AtLeastOnceQueue.ack++ def _record_ack(self: _AtLeastOnceQueue, handles: list[str]) -> None:+ order.append("ack")+ real_ack(self, handles)++ monkeypatch.setattr(_AtLeastOnceQueue, "ack", _record_ack)+ original_record = scheduler._record_checkpoint++ async def _record_checkpoint(*args: Any, **kwargs: Any) -> None:+ order.append("checkpoint")+ await original_record(*args, **kwargs)++ monkeypatch.setattr(scheduler, "_record_checkpoint", _record_checkpoint)++ await scheduler._poll_one(connector_id=inst.id)++ assert order == ["checkpoint", "ack"]+ assert engine.checkpoint_calls, "the dedup identities have to reach the database before the queue forgets the message"+++async def test_a_redelivery_after_a_lost_acknowledgement_is_not_a_duplicate(monkeypatch):+ """Accepted downstream, checkpointed, acknowledgement never landed.++ Covers both the crash in that window and a source that refused the+ handle; they are the same situation from the next poll's point of view.+ The event must not be submitted twice, and the message must still leave.+ """+ queue = _AtLeastOnceQueue([_queue_message("h1", "r1")], refuse_acks=True)+ ingest = _FakeIngestClient(accepted=1)+ scheduler, inst, engine = _queue_scheduler(monkeypatch, queue, ingest)++ await scheduler._poll_one(connector_id=inst.id)++ assert [e["external_id"] for e in (ingest.last_payload or {})["events"]] == ["r1"]+ assert queue.depth == 1, "the refused handle means the message is still there"+ persisted = engine.checkpoint_calls[-1]["checkpoint"]++ # The redelivery, against a source that now accepts the acknowledgement.+ resumed_queue = _AtLeastOnceQueue([_queue_message("h1", "r1")])+ resumed_ingest = _FakeIngestClient(accepted=0)+ resumed, inst2, _engine2 = _queue_scheduler(monkeypatch, resumed_queue, resumed_ingest, checkpoint=persisted)++ await resumed._poll_one(connector_id=inst2.id)++ assert (resumed_ingest.last_payload or {})["events"] == [], "the event was already accepted downstream once"+ assert resumed_queue.acked == ["h1"], "and the message still has to leave the queue"diff --git a/tests/isolation/test_queue_acknowledgement_live.py b/tests/isolation/test_queue_acknowledgement_live.pynew file mode 100644index 000000000..cdae9188f--- /dev/null+++ b/tests/isolation/test_queue_acknowledgement_live.py@@ -0,0 +1,575 @@+"""A queue is answered only once ingest has confirmed the batch, end to end.++Phase 3, findings 4 and 5. The unit suites pin the connector's behaviour and+the scheduler's ordering against fakes. This one drives the whole path — real+``ConnectorScheduler``, real ``IngestClient``, the real Pub/Sub connector with+its real ``httpx`` client and a genuinely signed JWT assertion, a real HTTP+socket standing in for the subscription, and real Postgres holding the+connector row and its cursor.++Why the live version is not redundant+-------------------------------------+Two of the properties cannot be observed anywhere else.++**The cursor has to survive Postgres.** ``record_checkpoint`` merges the+cursor into ``connector_config`` with the JSONB ``||`` operator and+``set_checkpoint`` parses it back on the next poll. Phase 3 changed the shape+that travels through there from ``{"time", "id"}`` to ``{"seen": [...]}``. A+fake engine that records the dict it was handed proves the scheduler called+it; it cannot prove the value round-trips, that the shallow merge replaces+the old shape rather than leaving both, or that the next poll reads back what+the last one wrote.++**"Not acknowledged" has to be observed at the socket.** The guarantee is+about an HTTP request that must not be made. A stubbed method can only show+that a Python call did not happen; a server that records every request to+``:acknowledge`` shows that nothing reached the subscription.++The acknowledgement endpoint here answers 200 and records, and the ingest+stub answers whatever the test tells it to. Neither is more capable than the+real thing in the direction that matters: no stub ever acknowledges on its+own, and the subscription really does hand the same messages back until it+is told not to.++The negative control lives in the phase document and in+``scripts/`` -- reverting the ack placement makes the first test here fail+because ``:acknowledge`` is called during the fetch.+"""++from __future__ import annotations++import contextlib+import json+import os+import threading+import uuid+from http.server import BaseHTTPRequestHandler, HTTPServer+from typing import Any++import pytest+import pytest_asyncio++pytestmark = [+ pytest.mark.asyncio(loop_scope="module"),+ pytest.mark.skipif(+ not os.environ.get("ISOLATION_CONNECTOR_DSN", "").strip(),+ reason="ISOLATION_CONNECTOR_DSN is not set; this suite needs live infrastructure",+ ),+]++_PROJECT = "example-logging"+_SUBSCRIPTION = "aisoc-live-sub"+++def _dsn() -> str:+ value = os.environ.get("ISOLATION_CONNECTOR_DSN", "").strip()+ if not value:+ pytest.skip("ISOLATION_CONNECTOR_DSN is not set; this suite needs a live Postgres")+ return value+++def _entry(timestamp: str, insert_id: str) -> str:+ import base64++ return base64.b64encode(+ json.dumps(+ {+ "insertId": insert_id,+ "timestamp": timestamp,+ "severity": "NOTICE",+ "logName": f"projects/{_PROJECT}/logs/cloudaudit.googleapis.com%2Factivity",+ "resource": {"type": "gce_instance", "labels": {"project_id": "example-prod"}},+ "protoPayload": {+ "methodName": "v1.compute.instances.insert",+ "authenticationInfo": {"principalEmail": "[email protected]"},+ },+ }+ ).encode()+ ).decode()+++class _Subscription(BaseHTTPRequestHandler):+ """A real socket standing in for one Pub/Sub subscription.++ Holds messages until they are acknowledged, which is the property the+ whole guarantee rests on: an unacknowledged message is handed back.+ """++ #: messageId -> (ackId, publishTime, insertId)+ held: dict[str, tuple[str, str, str]] = {}+ acknowledged: list[list[str]] = []+ pulls = 0++ @classmethod+ def reset(cls, messages: dict[str, tuple[str, str, str]]) -> None:+ cls.held = dict(messages)+ cls.acknowledged = []+ cls.pulls = 0++ def _json(self, payload: dict[str, Any], status: int = 200) -> None:+ body = json.dumps(payload).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def do_POST(self) -> None: # noqa: N802+ length = int(self.headers.get("Content-Length", 0))+ raw = self.rfile.read(length) if length else b"{}"++ if self.path.endswith("/token"):+ # Deliberately not shaped like a Google token. A `ya29.` prefix is+ # what a real one carries, and the secret scanner is right to+ # flag it in a tracked file even when the value is invented.+ self._json({"access_token": "stub-token", "expires_in": 3599})+ return++ if self.path.endswith(":pull"):+ type(self).pulls += 1+ received = [+ {+ "ackId": ack_id,+ "message": {"messageId": message_id, "publishTime": published, "data": _entry(published, insert_id)},+ }+ for message_id, (ack_id, published, insert_id) in type(self).held.items()+ ]+ self._json({"receivedMessages": received})+ return++ if self.path.endswith(":acknowledge"):+ ack_ids = list(json.loads(raw.decode()).get("ackIds") or [])+ type(self).acknowledged.append(ack_ids)+ # Only now does the subscription forget them.+ for message_id, (ack_id, _published, _insert) in list(type(self).held.items()):+ if ack_id in ack_ids:+ type(self).held.pop(message_id, None)+ self._json({})+ return++ self._json({}, status=404)++ def do_GET(self) -> None: # noqa: N802+ self._json({"topic": f"projects/{_PROJECT}/topics/t", "ackDeadlineSeconds": 120})++ def log_message(self, *_args) -> None: # noqa: ANN002+ """Quiet: the default handler prints to stderr on every request."""+++class _Ingest(BaseHTTPRequestHandler):+ """Stands in for ``services/ingest``, answering what the test dictates."""++ received: list[dict[str, Any]] = []+ #: ``(status, accepted_of, rejected)``. ``accepted_of`` is "how many of+ #: the submitted events to report accepted"; ``None`` means all of them.+ behaviour: tuple[int, int | None, int] = (200, None, 0)++ @classmethod+ def reset(cls, behaviour: tuple[int, int | None, int] = (200, None, 0)) -> None:+ cls.received = []+ cls.behaviour = behaviour++ def do_POST(self) -> None: # noqa: N802+ length = int(self.headers.get("Content-Length", 0))+ raw = self.rfile.read(length) if length else b"{}"+ submitted = 0+ with contextlib.suppress(Exception):+ payload = json.loads(raw.decode())+ events = payload.get("events") or []+ submitted = len(events)+ type(self).received.append({"tenant": self.headers.get("X-Tenant-ID"), "events": events})++ status, accepted_of, rejected = type(self).behaviour+ if status >= 500:+ body = b'{"error":"failed to publish events"}'+ self.send_response(status)+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)+ return++ accepted = submitted if accepted_of is None else accepted_of+ body = json.dumps({"accepted": accepted, "rejected": rejected}).encode()+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def log_message(self, *_args) -> None: # noqa: ANN002+ """Quiet."""+++def _serve(handler) -> tuple[HTTPServer, str]: # noqa: ANN001+ server = HTTPServer(("127.0.0.1", 0), handler)+ threading.Thread(target=server.serve_forever, daemon=True).start()+ return server, f"http://127.0.0.1:{server.server_port}"++[email protected](scope="module")+def subscription():+ server, url = _serve(_Subscription)+ yield url+ server.shutdown()++[email protected](scope="module")+def ingest():+ server, url = _serve(_Ingest)+ yield url+ server.shutdown()++[email protected](scope="module")+def service_account(subscription: str) -> str:+ """A real RSA key, so the JWT assertion the connector mints is really signed."""+ from cryptography.hazmat.primitives import serialization+ from cryptography.hazmat.primitives.asymmetric import rsa++ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)+ pem = key.private_bytes(+ encoding=serialization.Encoding.PEM,+ format=serialization.PrivateFormat.PKCS8,+ encryption_algorithm=serialization.NoEncryption(),+ ).decode("ascii")+ return json.dumps(+ {+ "type": "service_account",+ "project_id": _PROJECT,+ "private_key": pem,+ "client_email": "[email protected]",+ "token_uri": f"{subscription}/token",+ }+ )++[email protected](scope="module", autouse=True)+def pubsub_root(subscription: str):+ """Point the connector's API root at the local socket.++ The base URL, not the logic: the real client, the real signing, the real+ request shapes and the real response parsing all stay on the path.+ """+ from app.connectors import gcp_pubsub as module++ previous = module._PUBSUB_ROOT+ module._PUBSUB_ROOT = f"{subscription}/v1"+ yield+ module._PUBSUB_ROOT = previous++[email protected](scope="module", autouse=True)+def allow_loopback():+ """The documented operator path for a vendor on a named internal host.++ The scheduled-poll SSRF guard refuses loopback unconditionally otherwise+ (GHSA-cq4g-g6wp-4m2w), and would correctly refuse to poll this stub.+ """+ previous = os.environ.get("AISOC_SSRF_ALLOW_HOSTS")+ os.environ["AISOC_SSRF_ALLOW_HOSTS"] = "127.0.0.1"+ yield+ if previous is None:+ os.environ.pop("AISOC_SSRF_ALLOW_HOSTS", None)+ else:+ os.environ["AISOC_SSRF_ALLOW_HOSTS"] = previous+++@pytest_asyncio.fixture(scope="module", loop_scope="module")+async def engine():+ pytest.importorskip("asyncpg")+ from sqlalchemy.ext.asyncio import create_async_engine++ created = create_async_engine(_dsn(), future=True)+ yield created+ await created.dispose()+++@pytest_asyncio.fixture(loop_scope="module")+async def connector_row(engine, service_account): # noqa: ANN001+ """One enabled Pub/Sub connector, written the way the console writes it."""+ import sqlalchemy+ from app.security.credential_vault import get_vault++ tenant_id = uuid.uuid4()+ connector_id = uuid.uuid4()+ auth = get_vault().encrypt_dict(+ {+ "project_id": _PROJECT,+ "subscription_id": _SUBSCRIPTION,+ "service_account_json": service_account,+ }+ )++ async with engine.begin() as conn:+ await conn.execute(+ sqlalchemy.text("INSERT INTO tenants (id, name, slug) VALUES (:i, :n, :s) ON CONFLICT DO NOTHING"),+ {"i": tenant_id, "n": f"q-{tenant_id.hex[:8]}", "s": f"q-{tenant_id.hex[:8]}"},+ )+ await conn.execute(+ sqlalchemy.text(+ "INSERT INTO connectors "+ "(id, tenant_id, connector_type, name, is_enabled, auth_config, connector_config) "+ "VALUES (:i, :t, 'gcp_pubsub', 'live-queue-ack', true, CAST(:a AS jsonb), CAST(:c AS jsonb))"+ ),+ {"i": connector_id, "t": tenant_id, "a": json.dumps(auth), "c": json.dumps({"poll_interval_seconds": 300})},+ )++ yield {"tenant_id": str(tenant_id), "connector_id": connector_id}++ async with engine.begin() as conn:+ await conn.execute(sqlalchemy.text("DELETE FROM connectors WHERE id = :i"), {"i": connector_id})+++@pytest_asyncio.fixture(loop_scope="module")+async def scheduler(engine, ingest): # noqa: ANN001+ """The real scheduler. Polls are driven directly rather than on a timer:+ the timer is covered by ``test_connector_scheduler_live`` and what is+ under test here is the ordering within one poll."""+ from app.ingest_client import IngestClient+ from app.scheduler import ConnectorScheduler+ from app.security.credential_vault import get_vault++ instance = ConnectorScheduler(engine=engine, ingest_client=IngestClient(base_url=ingest), vault=get_vault())+ yield instance+++async def _stored_checkpoint(engine, connector_id: uuid.UUID) -> dict[str, Any] | None: # noqa: ANN001+ import sqlalchemy++ async with engine.connect() as conn:+ result = await conn.execute(+ sqlalchemy.text("SELECT connector_config -> 'checkpoint' AS cp FROM connectors WHERE id = :i"),+ {"i": connector_id},+ )+ row = result.first()+ if row is None or row.cp is None:+ return None+ return row.cp if isinstance(row.cp, dict) else json.loads(row.cp)+++class TestIngestRefusesTheBatch:+ async def test_the_subscription_is_not_acknowledged_and_keeps_the_messages(self, scheduler, engine, connector_row) -> None: # noqa: ANN001+ """Fetch succeeds, ingest answers 500. Nothing may be acknowledged,+ and the messages have to still be there."""+ _Subscription.reset({"m-1": ("ack-1", "2026-10-08T11:00:00Z", "entry-1")})+ _Ingest.reset((500, None, 0))++ await scheduler._poll_one(connector_id=connector_row["connector_id"])++ assert _Subscription.pulls >= 1, "the poll did happen"+ assert _Ingest.received, "and it reached ingest"+ assert _Subscription.acknowledged == [], "nothing may be acknowledged when ingest refused the batch"+ assert set(_Subscription.held) == {"m-1"}, "so the subscription still holds the message"+ assert await _stored_checkpoint(engine, connector_row["connector_id"]) is None++ async def test_the_next_poll_recovers_the_batch_in_full(self, scheduler, engine, connector_row) -> None: # noqa: ANN001+ """Completeness. 'Not lost' means the events come back."""+ _Subscription.reset({"m-1": ("ack-1", "2026-10-08T11:00:00Z", "entry-1")})+ _Ingest.reset((500, None, 0))+ await scheduler._poll_one(connector_id=connector_row["connector_id"])++ _Ingest.reset((200, None, 0))+ await scheduler._poll_one(connector_id=connector_row["connector_id"])++ submitted = [event["external_id"] for entry in _Ingest.received for event in entry["events"]]+ assert submitted == ["entry-1"]+ assert _Subscription.acknowledged == [["ack-1"]]+ assert _Subscription.held == {}, "and only now does the subscription forget it"+++class TestIngestAcceptsOnlyPartOfTheBatch:+ async def test_nothing_is_acknowledged(self, scheduler, engine, connector_row) -> None: # noqa: ANN001+ """Ingest reports per-event normalization failures as HTTP 200 with+ counts, so a 200 is not on its own a guarantee."""+ _Subscription.reset(+ {+ "m-1": ("ack-1", "2026-10-08T11:00:00Z", "entry-1"),+ "m-2": ("ack-2", "2026-10-08T11:00:01Z", "entry-2"),+ }+ )+ _Ingest.reset((200, 1, 1))++ await scheduler._poll_one(connector_id=connector_row["connector_id"])++ assert _Subscription.acknowledged == []+ assert set(_Subscription.held) == {"m-1", "m-2"}+ assert await _stored_checkpoint(engine, connector_row["connector_id"]) is None+++class TestPersistingACursorDoesNotCorruptTheConfig:+ """Found while building the live path above, and not a phase 3 defect —+ it shipped with the cursor itself and affects every connector that has+ one, not only the queue-backed two.++ ``record_checkpoint`` bound its patch with ``cast(json.dumps(...),+ JSONB)``, which serialises twice: Postgres received a JSON string scalar,+ ``jsonb || <scalar>`` coerced both sides to arrays, and one successful+ checkpointed poll rewrote ``connector_config`` from an object to+ ``[{...the config...}, "{\\"checkpoint\\": ...}"]``. The next poll raised+ ``AttributeError: 'list' object has no attribute 'items'`` reading it, the+ poll's broad handler filed that as a failure, and the instance went+ unhealthy permanently with its poll interval and filter rules unreadable.++ Invisible because every scheduler test patches ``record_checkpoint`` with+ a fake that records the dict it was handed, so this statement had never+ been executed by a test at all.+ """++ async def test_the_config_is_still_an_object_afterwards(self, scheduler, engine, connector_row) -> None: # noqa: ANN001+ import sqlalchemy++ _Subscription.reset({"m-1": ("ack-1", "2026-10-08T11:00:00Z", "entry-1")})+ _Ingest.reset((200, None, 0))++ await scheduler._poll_one(connector_id=connector_row["connector_id"])++ async with engine.connect() as conn:+ result = await conn.execute(+ sqlalchemy.text("SELECT jsonb_typeof(connector_config) AS kind FROM connectors WHERE id = :i"),+ {"i": connector_row["connector_id"]},+ )+ row = result.first()++ assert row is not None+ assert row.kind == "object", (+ f"connector_config is a JSON {row.kind}; the merge coerced it, which destroys the instance's "+ "configuration and makes the next poll raise on .items()"+ )++ async def test_the_next_poll_still_runs(self, scheduler, engine, connector_row) -> None: # noqa: ANN001+ """The consequence, stated as the thing an operator would notice."""+ _Subscription.reset({"m-1": ("ack-1", "2026-10-08T11:00:00Z", "entry-1")})+ _Ingest.reset((200, None, 0))+ await scheduler._poll_one(connector_id=connector_row["connector_id"])++ _Subscription.reset({"m-2": ("ack-2", "2026-10-08T12:00:00Z", "entry-2")})+ _Ingest.reset((200, None, 0))+ await scheduler._poll_one(connector_id=connector_row["connector_id"])++ assert [e["external_id"] for entry in _Ingest.received for e in entry["events"]] == ["entry-2"], (+ "the second poll produced nothing, so persisting the first cursor broke the instance"+ )++ async def test_the_poll_interval_survives(self, scheduler, engine, connector_row) -> None: # noqa: ANN001+ """Not only the cursor. The array swallowed the whole config object,+ so the interval and any filter rules went with it."""+ import sqlalchemy++ _Subscription.reset({"m-1": ("ack-1", "2026-10-08T11:00:00Z", "entry-1")})+ _Ingest.reset((200, None, 0))+ await scheduler._poll_one(connector_id=connector_row["connector_id"])++ async with engine.connect() as conn:+ result = await conn.execute(+ sqlalchemy.text("SELECT connector_config -> 'poll_interval_seconds' AS interval FROM connectors WHERE id = :i"),+ {"i": connector_row["connector_id"]},+ )+ row = result.first()++ assert row is not None and row.interval is not None, "the instance's poll interval is no longer readable"+++class TestACorruptedConfigIsRecoveredOnRead:+ async def test_a_connector_left_as_an_array_polls_again(self, scheduler, engine, connector_row) -> None: # noqa: ANN001+ """Recovery for a deployment that already ran the previous release.++ The row is written into the exact shape that release produced, and the+ connector has to resume without an operator running SQL.+ """+ import sqlalchemy++ corrupted = [+ {"poll_interval_seconds": 300},+ json.dumps({"checkpoint": {"time": "2026-10-08T01:00:00Z", "id": "legacy"}}),+ ]+ async with engine.begin() as conn:+ await conn.execute(+ sqlalchemy.text("UPDATE connectors SET connector_config = CAST(:c AS jsonb) WHERE id = :i"),+ {"c": json.dumps(corrupted), "i": connector_row["connector_id"]},+ )++ _Subscription.reset({"m-1": ("ack-1", "2026-10-08T11:00:00Z", "entry-1")})+ _Ingest.reset((200, None, 0))+ await scheduler._poll_one(connector_id=connector_row["connector_id"])++ assert [e["external_id"] for entry in _Ingest.received for e in entry["events"]] == ["entry-1"], (+ "a connector corrupted by the previous release never polls again"+ )+ assert _Subscription.acknowledged == [["ack-1"]]+++class TestTheCursorRoundTripsThroughPostgres:+ async def test_it_is_persisted_as_a_set_of_identities(self, scheduler, engine, connector_row) -> None: # noqa: ANN001+ """The shape phase 3 changed, read back out of the database."""+ _Subscription.reset({"m-1": ("ack-1", "2026-10-08T11:00:00Z", "entry-1")})+ _Ingest.reset((200, None, 0))++ await scheduler._poll_one(connector_id=connector_row["connector_id"])+ stored = await _stored_checkpoint(engine, connector_row["connector_id"])++ assert stored is not None+ assert set(stored) == {"seen"}, "the old (time, id) watermark shape must not survive alongside it"+ from app.connectors.gcp_pubsub import GCPPubSubConnector++ assert stored["seen"] == GCPPubSubConnector.seen_tokens(["m-1"])++ async def test_a_redelivery_is_suppressed_by_what_the_database_holds(self, scheduler, engine, connector_row) -> None: # noqa: ANN001+ """The whole point of keeping a cursor at all. Pub/Sub is+ at-least-once, and the suppression has to work across the process+ boundary — which means across Postgres."""+ _Subscription.reset({"m-1": ("ack-1", "2026-10-08T11:00:00Z", "entry-1")})+ _Ingest.reset((200, None, 0))+ await scheduler._poll_one(connector_id=connector_row["connector_id"])+ assert [e["external_id"] for entry in _Ingest.received for e in entry["events"]] == ["entry-1"]++ # Redelivered with a fresh ackId, exactly as the vendor does it.+ _Subscription.reset({"m-1": ("ack-1-again", "2026-10-08T11:00:00Z", "entry-1")})+ _Ingest.reset((200, None, 0))+ await scheduler._poll_one(connector_id=connector_row["connector_id"])++ assert [e["external_id"] for entry in _Ingest.received for e in entry["events"]] == [], (+ "the cursor read back from Postgres did not recognise the duplicate"+ )+ assert _Subscription.acknowledged == [["ack-1-again"]], "a duplicate is still a message that has to leave"++ async def test_an_older_entry_arriving_later_is_still_emitted(self, scheduler, engine, connector_row) -> None: # noqa: ANN001+ """Finding 5, through the real database.++ A sink sets no ordering key, so this entry has never been seen — and+ under the watermark it replaced it would have been dropped on sight,+ after its message had already been acknowledged.+ """+ _Subscription.reset({"m-new": ("ack-new", "2026-10-08T11:00:00Z", "newer")})+ _Ingest.reset((200, None, 0))+ await scheduler._poll_one(connector_id=connector_row["connector_id"])+ assert [e["external_id"] for entry in _Ingest.received for e in entry["events"]] == ["newer"]++ _Subscription.reset({"m-old": ("ack-old", "2026-10-08T09:00:00Z", "older")})+ _Ingest.reset((200, None, 0))+ await scheduler._poll_one(connector_id=connector_row["connector_id"])++ assert [e["external_id"] for entry in _Ingest.received for e in entry["events"]] == ["older"]++ async def test_a_watermark_cursor_left_by_an_earlier_release_is_ignored(self, scheduler, engine, connector_row) -> None: # noqa: ANN001+ """Upgrade compatibility, against the database an upgrade finds.++ A deployment running the previous release has a ``{"time", "id"}``+ cursor in this column. Reading it would reinstate the behaviour phase+ 3 removed; the safe reading is to ignore it and re-emit at most one+ poll's worth.+ """+ import sqlalchemy++ async with engine.begin() as conn:+ await conn.execute(+ sqlalchemy.text("UPDATE connectors SET connector_config = connector_config || CAST(:p AS jsonb) WHERE id = :i"),+ {"p": json.dumps({"checkpoint": {"time": "2026-10-08T23:00:00Z", "id": "zzz"}}), "i": connector_row["connector_id"]},+ )++ _Subscription.reset({"m-1": ("ack-1", "2026-10-08T11:00:00Z", "entry-1")})+ _Ingest.reset((200, None, 0))+ await scheduler._poll_one(connector_id=connector_row["connector_id"])++ assert [e["external_id"] for entry in _Ingest.received for e in entry["events"]] == ["entry-1"], (+ "an event older than the stale watermark was dropped, so the watermark is still being read"+ )