how-to integrator

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:

ModeWhen to useHTTP semantics
SyncReal-time lookup or validationSingle request/response; outcome is final when HTTP returns
CallbackLong-running external jobPOST initiates work; recipient calls webhook when done
PollLong-running job without webhook supportPOST 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
StateMeaning
pendingNot yet leased by a dispatcher
attemptingLeased; HTTP in progress
succeededTerminal — success
failed_terminalTerminal — exhausted retries or hard failure
failed_transientRetryable — will be re-leased after backoff
awaiting_callbackWaiting for webhook
awaiting_pollWaiting for next poll tick
resolved_manuallyTerminal — admin override

2.2 IntegrationEventAttempt resolutions

Each outbound HTTP call creates one attempt row:

ResolutionMeaning
pendingCall in flight or awaiting webhook/poll
successCompleted successfully
late_successWebhook arrived after event already terminal
timeoutCallback budget expired
poll_timeoutPoll budget expired
failed_transientRetryable failure (5xx, timeout, etc.)
failed_terminalHard failure (4xx, exhausted retries)
staleAttempt rejected by CAS guard
admin_overrideAdmin forced resolution
admin_override_revokedAdmin override reversed

2.3 Attempt kinds

KindWhen created
initialFirst dispatch of the event
poll_tickScheduled poll status check
retryRe-dispatch after transient failure
mode_upgradeCallback timed out, upgrading to poll
status_fallbackP4 status check after callback timeout
admin_override / admin_override_revokedAdmin 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

  1. Enqueue — emit_events_for_transition creates row: state=pending, attempt_count=0
  2. Lease — dispatch_pending_batch locks row with SELECT … FOR UPDATE SKIP LOCKED:
    • state=attempting
    • attempt_count += 1
    • lease_until = NOW() + 300s
  3. Execute — SmartLinkService.execute_for_field runs the HTTP call
  4. Map outcome:
    • 200-299 → succeeded (terminal)
    • 400-499 → failed_terminal (terminal)
    • 500-599, 0 (network error), 429 → failed_transient
  5. Retry — failed_transient rows are re-leased after exponential backoff
  6. Terminal — after 6 attempts or if recipient_idempotency ∈ {not_supported, unknown}, escalate to failed_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, set next_retry_at = now + 30s, decrement attempt_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 10 consecutive failures
  • Cooldown: 30 seconds

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

  1. Allocate IntegrationEventAttempt with kind="initial", mode_at_attempt="callback", fresh correlation_id
  2. Inject callback_url into payload:
    {settings.public_url}/api/v1/smartlink/webhooks/{correlation_id}
    
  3. Call execute_for_field
  4. On 2xx:
    • circuit_breaker.record_success
    • Extract recipient_reference from body (ticket_id / reference / id / job_id / external_id)
    • Enter awaiting_callback:
      • state = awaiting_callback
      • awaiting_until = now + callback_timeout_seconds (default 3600)
      • Schedule deferred callback_timeout_check at awaiting_until
  5. On non-2xx → failed_transient or failed_terminal, then reconcile

4.2 Webhook arrival

When the external system calls the callback URL:

  1. Lookup by correlation_id
  2. Soft-trap — reject with 400 if success_condition is missing (prevents untrusted webhooks from auto-completing)
  3. Parse signature (X-OpenGov-Signature: t=<unix>,v1=<hex>)
  4. Replay window — abs(now_unix - timestamp) <= 300 seconds
  5. 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
  6. Derive resolution from body using response_transform + success_condition
  7. Late-success guard — if event already terminal and resolution would be success, write late_success instead of overwriting
  8. Idempotent update — UPDATE … WHERE resolution='pending'
    • If rowcount == 0 → already resolved; increment webhook_duplicate_count; return duplicate_ignored
  9. Reconcile event state via apply_state_transition

4.3 Callback timeout

Fired at awaiting_until by deferred job:

  1. No-op if attempt already resolved (webhook won the race)
  2. If no poll_status_operation_id:
    • attempt.resolution = "timeout"
    • Reconcile → Rule 4 (may become failed_transient or failed_terminal)
  3. If P4 fallback exists:
    • Fire one status GET with payload {"recipient_reference": …}
    • completed → success → succeeded
    • failed → failed_terminal → failed_terminal
    • in_progress / unknown → failed_transient → upgrade to poll

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_url injected
  • state = awaiting_poll
  • awaiting_until = now + poll_timeout_seconds (default 3600)
  • Schedule first poll_tick at now + poll_interval_seconds (default 60)
  • Schedule poll_timeout_check at awaiting_until

5.2 Poll tick

Fired at each interval by deferred job:

  1. No-op if event.state != "awaiting_poll" or awaiting_until < now
  2. If circuit breaker is open → skip tick (no HTTP, no attempt row), reschedule next tick at standard interval
  3. No-op if poll_status_operation_id is missing
  4. Create poll_tick attempt row (kind="poll_tick", tick_sequence incremented)
  5. Call status endpoint with {"recipient_reference": initial_attempt.recipient_reference}
  6. In-tick backoff: up to 3 retries with delays (1, 2, 4) seconds. Only the last result is recorded.
  7. On 200-299:
    • Extract body.status
    • completed → tick_attempt.resolution="success" → reconcile → succeeded
    • failed → tick_attempt.resolution="failed_terminal" → reconcile → failed_terminal
    • in_progress / unknown → tick attempt stays pending; schedule next poll_tick if budget remains; reconcile keeps event in awaiting_poll
  8. On non-2xx after backoff → failed_transient → reconcile

5.3 Poll timeout

Fired at awaiting_until by deferred job:

  1. No-op if attempt already resolved
  2. attempt.resolution = "poll_timeout"
  3. Reconcile → Rule 5a → failed_terminal unconditionally

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):

  1. Insert mode_upgrade attempt with mode_at_attempt="poll", resolution="pending"
  2. Reconcile → state="awaiting_poll", set mode_upgraded_from="callback"
  3. Preserve original awaiting_until — poll inherits the remaining wall-clock budget; does NOT extend the deadline
  4. Schedule first poll_tick at after_status + interval (if budget remains)
  5. Schedule poll_timeout_check at original awaiting_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):

RuleConditionResult
0Admin override exists AND not revokedresolved_manually
1Any attempt has resolution="success"succeeded
2Event already terminal AND any attempt has resolution="late_success"Preserve terminal state; stamp late_success_at
3Latest 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"
4Latest 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]
5Latest resolution="failed_terminal"failed_terminal
5aLatest resolution="poll_timeout"failed_terminal unconditionally
StaleNone of the abovePreserve current state

CAS guard

Incoming attempt # vs event.last_attempt_numberAction
<Reject (stale replay)
==Allow (timeout jobs / webhooks reconciling same attempt)
>Allow (normal forward progress)

8. Circuit Breaker Interaction

PhaseBreaker open behavior
Sync dispatchRevert to pending, next_retry_at = now + 30s, decrement attempt_count
Callback initialSame as sync
Poll tickSkip tick entirely (no HTTP, no attempt row), reschedule at standard interval
P4 fallbackrecord_failure on exceptions; record_success on 2xx
Sync 2xxrecord_success
Sync 4xxNothing — client error, recipient is healthy
Sync 5xx/0/429record_failure

Breaker parameters:

  • Trip after 10 consecutive failures
  • Cooldown: 30 seconds
  • 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_key
  • SmartLinkService.execute_for_field(idempotency_key=…)
  • HTTP Idempotency-Key header

9.2 QueryLog dedup

SmartLinkService checks existing QueryLog rows by (operation_id, idempotency_key):

  • Terminal COMPLETED → return stored response immediately
  • Terminal PENDING → raise IdempotencyConflict
  • Only failed/timed out → allow retry

9.3 Retry eligibility gate

An event is never retried if:

  • recipient_idempotency ∈ {not_supported, unknown} → immediate failed_terminal
  • attempt_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 in duplicate_ignored
  • Timeout jobs no-op if resolution != 'pending'
  • apply_state_transition CAS on last_attempt_number prevents stale overwrites

10. Timeout & Interval Reference

ConstantValueWhere definedPurpose
LEASE_TTL_SECONDS300 (5 min)dispatch.pyWorker lease expiry
callback_timeout_seconds3600 (1 hr)Operation modelCallback budget
poll_timeout_seconds3600 (1 hr)Operation modelPoll budget
poll_interval_seconds60 (1 min)Operation modelPoll tick spacing
COOLDOWN_SECONDS30circuit_breaker.pyBreaker cooldown
SWEEP_GRACE_MINUTES15jobs.pyStalled event detection
MAX_REPLAY_WINDOW_SECONDS300 (±5 min)webhooks.pyWebhook timestamp tolerance
ROTATION_OVERLAP_DAYS30webhooks.pyPrevious key acceptance window
_POLL_TICK_STATUS_BACKOFF_SECONDS(1, 2, 4)jobs.pyIn-tick retry delays
BACKOFF_SECONDS[30, 120, 600, 3600, 21600]reconciliation.pyRetry delays
MAX_ATTEMPTS6reconciliation.pyMax dispatch attempts
FAILURE_THRESHOLD10circuit_breaker.pyBreaker trip threshold

11. Deferred Job Scheduling

JobTriggerScheduleHandler
dispatch_batch_jobPeriodic cronEvery 60s_dispatch_batch_impl
heartbeat_dispatcherPeriodic cronEvery 60s_heartbeat_impl
callback_timeout_checkDeferredevent.awaiting_until_callback_timeout_impl
poll_tickDeferredSelf-rescheduling at interval_poll_tick_impl
poll_timeout_checkDeferredevent.awaiting_until_poll_timeout_impl
sweep_awaiting_eventsPeriodic cronEvery 5 min_sweep_impl
rotation_expiry_alertDeferredT-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

  1. Parse header — extract t and v1; reject malformed (401)
  2. Replay window — abs(now_unix - timestamp) <= 300; reject stale (401)
  3. Dual-slot verify:
    • Try connector.webhook_secret_current
    • If fail AND within 30 days of rotation → try webhook_secret_previous
    • If both fail → 401
  4. Apply response_transform JSONata
  5. Evaluate success_condition JSONata against body
  6. 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 spec
  • docs/runbooks/smartlink-phase2b.md — Phase 2B operational runbook
  • src/opengov/platform/integration_events/dispatch.py — Dispatcher implementation
  • src/opengov/platform/integration_events/jobs.py — Deferred job handlers
  • src/opengov/platform/integration_events/reconciliation.py — State derivation rules
  • src/opengov/smartlink/webhooks.py — Webhook receiver
  • src/opengov/smartlink/executor.py — HTTP execution engine
  • src/opengov/platform/circuit_breaker.py — Circuit breaker logic