SmartLink Execution Mode State Machine
How sync, callback, and poll execution modes work, how they fail, how they retry, and how they fall back to each other.
1. Overview
SmartLink operations have three execution modes:
| Mode | When to use | HTTP semantics |
|---|---|---|
| Sync | Real-time lookup or validation | Single request/response; outcome is final when HTTP returns |
| Callback | Long-running external job | POST initiates work; recipient calls webhook when done |
| Poll | Long-running job without webhook support | POST initiates work; system periodically GETs status endpoint |
All three modes share the same IntegrationEvent outbox row and the same retry/circuit-breaker infrastructure. The differences are in what happens after the initial HTTP call returns.
2. Core Data Model
2.1 IntegrationEvent states
pending ──► attempting ──► succeeded
│ failed_terminal
│ failed_transient ──► pending (retry)
│ awaiting_callback
│ awaiting_poll
│ resolved_manually
| State | Meaning |
|---|---|
pending | Not yet leased by a dispatcher |
attempting | Leased; HTTP in progress |
succeeded | Terminal — success |
failed_terminal | Terminal — exhausted retries or hard failure |
failed_transient | Retryable — will be re-leased after backoff |
awaiting_callback | Waiting for webhook |
awaiting_poll | Waiting for next poll tick |
resolved_manually | Terminal — admin override |
2.2 IntegrationEventAttempt resolutions
Each outbound HTTP call creates one attempt row:
| Resolution | Meaning |
|---|---|
pending | Call in flight or awaiting webhook/poll |
success | Completed successfully |
late_success | Webhook arrived after event already terminal |
timeout | Callback budget expired |
poll_timeout | Poll budget expired |
failed_transient | Retryable failure (5xx, timeout, etc.) |
failed_terminal | Hard failure (4xx, exhausted retries) |
stale | Attempt rejected by CAS guard |
admin_override | Admin forced resolution |
admin_override_revoked | Admin override reversed |
2.3 Attempt kinds
| Kind | When created |
|---|---|
initial | First dispatch of the event |
poll_tick | Scheduled poll status check |
retry | Re-dispatch after transient failure |
mode_upgrade | Callback timed out, upgrading to poll |
status_fallback | P4 status check after callback timeout |
admin_override / admin_override_revoked | Admin action |
3. Sync Mode
┌─► succeeded (terminal)
│
pending ──lease──► attempting ──┼─► failed_terminal (terminal)
▲ │ │
│ │ └─► failed_transient ──backoff──► pending
│ │ │
│ └─5xx/0/429────────────────────────────────────┘
│
└──────circuit breaker open (re-pend with 30s cooldown)──────────┘
3.1 Flow
- Enqueue —
emit_events_for_transitioncreates row:state=pending,attempt_count=0 - Lease —
dispatch_pending_batchlocks row withSELECT … FOR UPDATE SKIP LOCKED:state=attemptingattempt_count += 1lease_until = NOW() + 300s
- Execute —
SmartLinkService.execute_for_fieldruns the HTTP call - Map outcome:
200-299→succeeded(terminal)400-499→failed_terminal(terminal)500-599,0(network error),429→failed_transient
- Retry —
failed_transientrows are re-leased after exponential backoff - Terminal — after 6 attempts or if
recipient_idempotency ∈ {not_supported, unknown}, escalate tofailed_terminal
3.2 Retry backoff
BACKOFF_SECONDS = [30, 120, 600, 3600, 21600] # 30s, 2m, 10m, 1h, 6h
MAX_ATTEMPTS = 6
Index used: BACKOFF_SECONDS[min(max(attempt_count - 1, 0), 4)]
3.3 Circuit breaker
Before every HTTP call, the dispatcher checks the per-(connector, operation) circuit breaker:
- Closed → proceed. Track consecutive failures.
- Open → revert event to
pending, setnext_retry_at = now + 30s, decrementattempt_count(so the breaker delay doesn’t consume retry budget). - Half-open → allow one probe.
record_success→ closed;record_failure→ open again.
Breaker parameters:
- Trip after
10consecutive failures - Cooldown:
30seconds
4. Callback Mode
pending ──lease──► attempting ──2xx (202)──► awaiting_callback
│
┌──────────────────────────┘
│ webhook arrives
▼
succeeded (terminal)
│
└─ late success ─► stamp late_success_at,
preserve terminal state
OR callback_timeout_check fires
│
├─ no fallback ─► timeout ─► failed_transient/terminal
│
└─ P4 fallback exists
──► status GET
├─ completed ─► succeeded
├─ failed ─► failed_terminal
└─ in_progress ─► upgrade to poll
4.1 Initial dispatch
- Allocate
IntegrationEventAttemptwithkind="initial",mode_at_attempt="callback", freshcorrelation_id - Inject
callback_urlinto payload:{settings.public_url}/api/v1/smartlink/webhooks/{correlation_id} - Call
execute_for_field - On
2xx:circuit_breaker.record_success- Extract
recipient_referencefrom body (ticket_id / reference / id / job_id / external_id) - Enter
awaiting_callback:state = awaiting_callbackawaiting_until = now + callback_timeout_seconds(default3600)- Schedule deferred
callback_timeout_checkatawaiting_until
- On non-2xx →
failed_transientorfailed_terminal, then reconcile
4.2 Webhook arrival
When the external system calls the callback URL:
- Lookup by
correlation_id - Soft-trap — reject with 400 if
success_conditionis missing (prevents untrusted webhooks from auto-completing) - Parse signature (
X-OpenGov-Signature: t=<unix>,v1=<hex>) - Replay window —
abs(now_unix - timestamp) <= 300seconds - Dual-slot HMAC verify:
- Verify against
connector.webhook_secret_current - If fail AND rotation is within 30 days → verify against
webhook_secret_previous - If both fail → 401
- Verify against
- Derive resolution from body using
response_transform+success_condition - Late-success guard — if event already terminal and resolution would be
success, writelate_successinstead of overwriting - Idempotent update —
UPDATE … WHERE resolution='pending'- If
rowcount == 0→ already resolved; incrementwebhook_duplicate_count; returnduplicate_ignored
- If
- Reconcile event state via
apply_state_transition
4.3 Callback timeout
Fired at awaiting_until by deferred job:
- No-op if attempt already resolved (webhook won the race)
- If no
poll_status_operation_id:attempt.resolution = "timeout"- Reconcile → Rule 4 (may become
failed_transientorfailed_terminal)
- If P4 fallback exists:
- Fire one status GET with payload
{"recipient_reference": …} completed→success→succeededfailed→failed_terminal→failed_terminalin_progress/ unknown →failed_transient→ upgrade to poll
- Fire one status GET with payload
5. Poll Mode
pending ──lease──► attempting ──2xx (202)──► awaiting_poll
│
◄──────────────────────────┘
│ poll_tick fires at interval
│
▼
create poll_tick attempt ──► status endpoint
│
├─ completed ─► success ─► succeeded (terminal)
│
├─ failed ─► failed_terminal ─► failed_terminal (terminal)
│
└─ in_progress / unknown ─► keep awaiting_poll,
schedule next tick if budget remains
OR poll_timeout_check fires
→ poll_timeout ─► failed_terminal (unconditional)
5.1 Initial dispatch
Same as callback but:
- No
callback_urlinjected state = awaiting_pollawaiting_until = now + poll_timeout_seconds(default3600)- Schedule first
poll_tickatnow + poll_interval_seconds(default60) - Schedule
poll_timeout_checkatawaiting_until
5.2 Poll tick
Fired at each interval by deferred job:
- No-op if
event.state != "awaiting_poll"orawaiting_until < now - If circuit breaker is open → skip tick (no HTTP, no attempt row), reschedule next tick at standard interval
- No-op if
poll_status_operation_idis missing - Create
poll_tickattempt row (kind="poll_tick",tick_sequenceincremented) - Call status endpoint with
{"recipient_reference": initial_attempt.recipient_reference} - In-tick backoff: up to 3 retries with delays
(1, 2, 4)seconds. Only the last result is recorded. - On
200-299:- Extract
body.status completed→tick_attempt.resolution="success"→ reconcile →succeededfailed→tick_attempt.resolution="failed_terminal"→ reconcile →failed_terminalin_progress/ unknown → tick attempt stayspending; schedule nextpoll_tickif budget remains; reconcile keeps event inawaiting_poll
- Extract
- On non-2xx after backoff →
failed_transient→ reconcile
5.3 Poll timeout
Fired at awaiting_until by deferred job:
- No-op if attempt already resolved
attempt.resolution = "poll_timeout"- Reconcile → Rule 5a →
failed_terminalunconditionally
Important: Poll timeout is always terminal, regardless of idempotency posture or retry budget.
6. The P4 Fallback Chain: Callback → Poll → Terminal
This is the dynamic mode upgrade path when a callback-mode event times out:
callback awaiting ──timeout──► P4 status GET
│
├─ completed ─► succeeded
├─ failed ─► failed_terminal
└─ in_progress ─► UPGRADE TO POLL
│
▼
poll awaiting
│
├─ completed ─► succeeded
├─ failed ─► failed_terminal
└─ timeout ─► failed_terminal
Upgrade mechanics (_upgrade_to_poll):
- Insert
mode_upgradeattempt withmode_at_attempt="poll",resolution="pending" - Reconcile →
state="awaiting_poll", setmode_upgraded_from="callback" - Preserve original
awaiting_until— poll inherits the remaining wall-clock budget; does NOT extend the deadline - Schedule first
poll_tickatafter_status + interval(if budget remains) - Schedule
poll_timeout_checkat originalawaiting_until
7. Reconciliation Rules
All state changes flow through apply_state_transition, which uses SELECT … FOR UPDATE on the event row and a CAS guard on last_attempt_number.
Derivation rules (evaluated in order):
| Rule | Condition | Result |
|---|---|---|
| 0 | Admin override exists AND not revoked | resolved_manually |
| 1 | Any attempt has resolution="success" | succeeded |
| 2 | Event already terminal AND any attempt has resolution="late_success" | Preserve terminal state; stamp late_success_at |
| 3 | Latest attempt resolution="pending" | Map mode_at_attempt → state (callback→awaiting_callback, poll→awaiting_poll, sync→attempting). If kind="mode_upgrade" + mode_at_attempt="poll" → set mode_upgraded_from="callback" |
| 4 | Latest resolution ∈ {failed_transient, timeout} | If recipient_idempotency ∈ {not_supported,unknown} OR attempt_count >= 6 → failed_terminal. Else failed_transient with next_retry_at = now + BACKOFF_SECONDS[idx] |
| 5 | Latest resolution="failed_terminal" | failed_terminal |
| 5a | Latest resolution="poll_timeout" | failed_terminal unconditionally |
| Stale | None of the above | Preserve current state |
CAS guard
| Incoming attempt # vs event.last_attempt_number | Action |
|---|---|
< | Reject (stale replay) |
== | Allow (timeout jobs / webhooks reconciling same attempt) |
> | Allow (normal forward progress) |
8. Circuit Breaker Interaction
| Phase | Breaker open behavior |
|---|---|
| Sync dispatch | Revert to pending, next_retry_at = now + 30s, decrement attempt_count |
| Callback initial | Same as sync |
| Poll tick | Skip tick entirely (no HTTP, no attempt row), reschedule at standard interval |
| P4 fallback | record_failure on exceptions; record_success on 2xx |
| Sync 2xx | record_success |
| Sync 4xx | Nothing — client error, recipient is healthy |
| Sync 5xx/0/429 | record_failure |
Breaker parameters:
- Trip after
10consecutive failures - Cooldown:
30seconds - Half-open allows exactly one probe
9. Idempotency
9.1 Event-level key
Generated at enqueue:
idempotency_key = f"{application_id}:{binding.id}:{now.isoformat()}"
Propagated:
IntegrationEvent.idempotency_keySmartLinkService.execute_for_field(idempotency_key=…)- HTTP
Idempotency-Keyheader
9.2 QueryLog dedup
SmartLinkService checks existing QueryLog rows by (operation_id, idempotency_key):
- Terminal
COMPLETED→ return stored response immediately - Terminal
PENDING→ raiseIdempotencyConflict - Only failed/timed out → allow retry
9.3 Retry eligibility gate
An event is never retried if:
recipient_idempotency ∈ {not_supported, unknown}→ immediatefailed_terminalattempt_count >= 6→failed_terminal
This gate applies to sync transient failures, callback timeouts, and poll failures.
9.4 Webhook idempotency
UPDATE … WHERE resolution='pending'— concurrent deliveries result induplicate_ignored- Timeout jobs no-op if
resolution != 'pending' apply_state_transitionCAS onlast_attempt_numberprevents stale overwrites
10. Timeout & Interval Reference
| Constant | Value | Where defined | Purpose |
|---|---|---|---|
LEASE_TTL_SECONDS | 300 (5 min) | dispatch.py | Worker lease expiry |
callback_timeout_seconds | 3600 (1 hr) | Operation model | Callback budget |
poll_timeout_seconds | 3600 (1 hr) | Operation model | Poll budget |
poll_interval_seconds | 60 (1 min) | Operation model | Poll tick spacing |
COOLDOWN_SECONDS | 30 | circuit_breaker.py | Breaker cooldown |
SWEEP_GRACE_MINUTES | 15 | jobs.py | Stalled event detection |
MAX_REPLAY_WINDOW_SECONDS | 300 (±5 min) | webhooks.py | Webhook timestamp tolerance |
ROTATION_OVERLAP_DAYS | 30 | webhooks.py | Previous key acceptance window |
_POLL_TICK_STATUS_BACKOFF_SECONDS | (1, 2, 4) | jobs.py | In-tick retry delays |
BACKOFF_SECONDS | [30, 120, 600, 3600, 21600] | reconciliation.py | Retry delays |
MAX_ATTEMPTS | 6 | reconciliation.py | Max dispatch attempts |
FAILURE_THRESHOLD | 10 | circuit_breaker.py | Breaker trip threshold |
11. Deferred Job Scheduling
| Job | Trigger | Schedule | Handler |
|---|---|---|---|
dispatch_batch_job | Periodic cron | Every 60s | _dispatch_batch_impl |
heartbeat_dispatcher | Periodic cron | Every 60s | _heartbeat_impl |
callback_timeout_check | Deferred | event.awaiting_until | _callback_timeout_impl |
poll_tick | Deferred | Self-rescheduling at interval | _poll_tick_impl |
poll_timeout_check | Deferred | event.awaiting_until | _poll_timeout_impl |
sweep_awaiting_events | Periodic cron | Every 5 min | _sweep_impl |
rotation_expiry_alert | Deferred | T-7, T-3, T-1 days before expiry | _run_rotation_alert |
12. Webhook Signature Verification
Signature format
Header: X-OpenGov-Signature: t=<unix_seconds>,v1=<hex_hmac_sha256>
HMAC payload
payload = f"{timestamp}.{body.decode('utf-8')}.{correlation_id}"
signature = hmac.new(
bytes.fromhex(secret_hex),
payload.encode("utf-8"),
hashlib.sha256
).hexdigest()
Verification steps
- Parse header — extract
tandv1; reject malformed (401) - Replay window —
abs(now_unix - timestamp) <= 300; reject stale (401) - Dual-slot verify:
- Try
connector.webhook_secret_current - If fail AND within 30 days of rotation → try
webhook_secret_previous - If both fail → 401
- Try
- Apply
response_transformJSONata - Evaluate
success_conditionJSONata against body - Derive final resolution
13. Common Scenarios
Scenario: Sync 5xx, then success on retry
pending → attempting → 503 → failed_transient → pending (30s)
→ attempting → 503 → failed_transient → pending (2m)
→ attempting → 200 → succeeded
Scenario: Callback succeeds normally
pending → attempting → 202 → awaiting_callback
→ webhook arrives → success → succeeded
Scenario: Callback timeout with P4 upgrade to poll
pending → attempting → 202 → awaiting_callback
→ timeout_check fires → P4 status GET → in_progress
→ upgrade_to_poll → awaiting_poll
→ poll_tick → in_progress (schedule next)
→ poll_tick → completed → success → succeeded
Scenario: Callback timeout, no fallback
pending → attempting → 202 → awaiting_callback
→ timeout_check fires → no P4 fallback → timeout
→ reconcile Rule 4 → failed_transient (retry) or failed_terminal
Scenario: Poll timeout (unconditional terminal)
pending → attempting → 202 → awaiting_poll
→ poll_tick → in_progress (schedule next)
→ poll_tick → in_progress (schedule next)
→ poll_timeout_check fires → poll_timeout
→ reconcile Rule 5a → failed_terminal
Scenario: Circuit breaker trips during sync
pending → attempting → 503 (breaker records failure)
→ attempting → 503 (breaker records failure)
… ×10 → breaker OPEN
→ attempting → breaker open → revert to pending, next_retry_at = now + 30s
→ 30s later → attempting → breaker half-open → allow one probe
→ 200 → breaker closed → succeeded
14. Further Reading
docs/specs/2026-04-14-smartlink-phase2c-async-execution-design.md— Phase 2C design specdocs/runbooks/smartlink-phase2b.md— Phase 2B operational runbooksrc/opengov/platform/integration_events/dispatch.py— Dispatcher implementationsrc/opengov/platform/integration_events/jobs.py— Deferred job handlerssrc/opengov/platform/integration_events/reconciliation.py— State derivation rulessrc/opengov/smartlink/webhooks.py— Webhook receiversrc/opengov/smartlink/executor.py— HTTP execution enginesrc/opengov/platform/circuit_breaker.py— Circuit breaker logic