Repository navigation
feat(reliability): idempotency keys at execution trigger boundaries (#525) - #1019
Conversation
…525) Add an `Idempotency-Key` contract at every execution-creating trigger boundary so the same key within 24h yields exactly one execution. Duplicates short-circuit with the original result (`X-Idempotent-Replay: true`, in-flight → 409) instead of dispatching a second execution. Closes the producer-boundary dedup gap that the unified funnel made more acute — webhook re-deliveries, MCP client retries, and scheduler→backend network blips no longer create phantom executions. Enforcement lives at the router layer (not solely TaskExecutionService) because sync /chat runs an inline path and /api/webhooks/{token} creates no execution itself: - /chat, /task (async+sync, self-task), /api/internal/execute-task, /api/webhooks/{token} (auto-derives a key from token+body_hash), /api/agents/{name}/fan-out - scheduler sends a deterministic `Idempotency-Key: sched:{execution_id}` - MCP chat_with_agent / fan_out forward a deterministic key over call args New `idempotency_keys` table — PRIMARY KEY (scope, key) is the atomic claim; cross-process safe across uvicorn workers + the standalone scheduler. db/idempotency.py (CRUD) + services/idempotency_service.py (derivation + begin/complete/fail, fail-open). The header is optional on chat/task/MCP (absent → no dedup, full back-compat); upfront at-capacity rejections release the claim so the caller can retry. Every replay emits an `idempotent_replay` audit event; the 24h TTL purge is folded into the cleanup-service retention sweep. Documented as Architectural Invariant #18 — new trigger types must accept an idempotency key before merge. 18 unit tests cover the claim lifecycle (atomic claim, in-flight, completed replay, release, expiry re-claim, purge, scope isolation), key derivation, and the begin/complete/fail decision flow. Related to #525 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…rs (#525) The webhook rate-limit unit tests load webhooks.py via importlib with the heavy backend deps stubbed (database, services, services.platform_audit_service). #525 added `from services import idempotency_service` to webhooks.py, which the stub set didn't cover — collection errored under HEAD (13 regression-diff failures). Add a no-op idempotency_service stub (begin() returns a disabled, no-replay decision) so these tests keep exercising rate limiting only. Related to #525 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Resolve by running |
vybe
left a comment
There was a problem hiding this comment.
Approved via /validate-pr with full in-code verification.
Verified the load-bearing parts: atomic claim is INSERT-or-IntegrityError→read-surviving-row (not a TOCTOU SELECT-then-INSERT), serialized by SQLite write-lock across uvicorn workers + the standalone scheduler; fail-open is implemented at every begin/attach/complete/fail (any db error → proceed without dedup, never blocks a real execution); the webhook boundary handles replay→409 (in-flight) / 202+X-Idempotent-Replay (completed), releases the claim on dispatch failure so a legit re-delivery isn't wedged, and truncates the token in audit logs; TTL uses iso_cutoff() (Invariant #16); migration is PRAGMA-guarded and idempotent. Docs + new Invariant #18 + 18 tests. Three surfaces synced (MCP client.ts/chat.ts).
Resolving the benign append-collisions in database.py + migrations.py (named migrations — no renumber) and CI-gating the merge.
Heads-up: #1024 will then conflict on the two test_webhook_rate_limit_* files (stubbed here).
Resolve append-collisions (keep-both, no migration renumber — named migrations): - database.py: keep both the idempotency (#525) and #740 loop ops — import, __init__ instance, and delegation method blocks; restore section divider. - migrations.py: keep _migrate_idempotency_keys_table alongside dev's _migrate_agent_loops_tables (#740) + _migrate_users_suspended_at (#995); all three appended to MIGRATIONS. Each migration is PRAGMA/column-guarded so list order is irrelevant. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Summary
Adds an
Idempotency-Keycontract at every execution-creating trigger boundary (RELIABILITY-006). The same key within a 24h window yields exactly one execution; duplicates short-circuit with the original result (HTTP 200/202 + X-Idempotent-Replay: true, in-flight duplicate →409) instead of dispatching a second execution.Closes the producer-boundary dedup gap the unified funnel made more acute: webhook re-deliveries, MCP client retries, and scheduler→backend network blips no longer create phantom executions.
Design
Enforcement at the router layer (not solely
TaskExecutionService) — because sync/chatruns an inline path and/api/webhooks/{token}creates no execution itself:POST /chat,POST /task(async+sync, self-task)Idempotency-KeyheaderPOST /api/internal/execute-taskPOST /api/webhooks/{token}(token, body_hash)POST /api/agents/{name}/fan-outsched:{execution_id}chat_with_agent/fan_outStorage: new
idempotency_keystable —PRIMARY KEY (scope, idempotency_key)is the atomic claim; cross-process safe across uvicorn workers + the standalone scheduler (one SQLite file).db/idempotency.py(CRUD) +services/idempotency_service.py(key derivation +begin/complete/fail, fail-open — the dedup layer never blocks a real execution).Lifecycle:
claim(in_flight) →attach_execution→complete(stores replay snapshot) /release(failed first attempt can retry; never removes a completed row). Rows past the 24h TTL are re-claimed as new and purged by the cleanup-service retention sweep.Behavior notes
execution_idis reused across an HTTP resend of the same dispatch, so a transient 5xx + resend dedupes; intentional feat(scheduler): retry mechanism for failed scheduled executions #271 retries (fresh execution_id) are not suppressed.idempotent_replayaudit event (duplicate-storms observable).Docs
requirements.mdRELIABILITY-006,architecture.mdtable + invariant, orchestration plan row marked shipped.Testing
tests/test_idempotency.py— 18 unit tests: atomic claim, in-flight, completed replay, release, 24h expiry re-claim, purge, scope isolation, key derivation, begin/complete/fail decisions. All green.py_compile+ standalone DB init verified (schema + migration Replace context bar with success rate bar on Dashboard, Timeline, and Agents page #60 both create the table;DatabaseManagerdelegation round-trips). MCP TypeScript builds clean (tsc).Related to #525
🤖 Generated with Claude Code