Skip to content

feat(reliability): idempotency keys at execution trigger boundaries (#525) - #1019

Merged
vybe merged 3 commits into
devfrom
feature/525-idempotency-keys
Jun 2, 2026
Merged

vybe merged 3 commits into
devfrom
feature/525-idempotency-keys

Conversation

@dolho

@dolho dolho commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

Summary

Adds an Idempotency-Key contract 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 /chat runs an inline path and /api/webhooks/{token} creates no execution itself:

Boundary Key source
POST /chat, POST /task (async+sync, self-task) optional Idempotency-Key header
POST /api/internal/execute-task scheduler-supplied header
POST /api/webhooks/{token} header or auto-derived (token, body_hash)
POST /api/agents/{name}/fan-out optional header (replays the whole batch)
scheduler dispatch deterministic sched:{execution_id}
MCP chat_with_agent / fan_out deterministic key over call args

Storage: new idempotency_keys table — 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

  • Header is optional on chat/task/MCP → absent means no dedup (full back-compat).
  • Webhook always derives a key when none supplied (covers naive senders that retry without idempotency awareness).
  • Scheduler's per-fire execution_id is 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.
  • Every replay emits an idempotent_replay audit event (duplicate-storms observable).

Docs

  • Architectural Invariant Unified Executions Dashboard (EXEC-022) #18 added (new trigger types must accept an idempotency key before merge).
  • requirements.md RELIABILITY-006, architecture.md table + 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; DatabaseManager delegation round-trips). MCP TypeScript builds clean (tsc).

Related to #525

🤖 Generated with Claude Code

dolho and others added 2 commits June 2, 2026 11:52
…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]>
@github-actions

github-actions Bot commented Jun 2, 2026

Copy link
Copy Markdown

⚠️ Nightly unit-suite check skipped — merge conflict against dev.

Resolve by running git merge dev locally and pushing the result. The next nightly run will re-test once the conflict is gone.

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@vybe
vybe merged commit 1bb8f27 into dev Jun 2, 2026
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants