ARBI
Documents / docs/software/realtime-recovery.md

Outbound realtime and authoritative recovery

Work record: #29, parent #4. This implements the simulation-only source/host slice selected in ADR-0005. Committed host evidence is separate from an Ably account, Neon/Vercel test deployment, mobile-network measurements and physical acceptance. Those external gates remain open.

Composition and authority

createRealtimeServer requires the current Gredice identity, current site/resource resolver, persisted-actor currentAuthority resolver from command jobs, explicit browser origins, migrated PostgreSQL and a broker adapter. Install it explicitly through configureRealtime. Missing composition returns a redacted uncached 503. Production realms and hardware resource scopes are denied; no fixture identity, broker or server is installed by default.

AblyBroker uses supported Ably JavaScript SDK 2.29.0 REST requestToken, channel publish, and revokeTokens. Only a private server receives the API key. Enable revocable tokens on the issuing key before issuing any token, as required by Ably's revocation documentation. The adapter requires an explicit operator assertion of that configuration; it cannot certify an unprovisioned account setting. During key rotation retain up to two previous issuing keys privately until their tokens expire; revocation is attempted through each issuing key. Never send those keys to browsers/devices or commit them.

Each grant persists a unique client ID and a unique exact channel containing realm, site, site-state resource and a hash of the principal/session/device binding plus grant ID. The token capability contains only that channel with subscribe: no wildcard, publishing, presence, history, actuator or store permission. Token TTL is at most 30 seconds, capped by original human authorization freshness/session expiry or enrolled credential expiry, with 250 ms issuance headroom. The issuer verifies the SDK response's client, capability and expiry. Renew/resubscribe requires the same principal/session/membership or exact device credential/boot/session/configuration; it cannot extend the original grant expiry. A new attach is a new audited authorization, subject to persistent reconnect budgets.

Human requests use the existing dedicated ARBI bearer and current membership/resource boundary; POST requires approved Origin and x-arbi-request: 1. Attach/resubscribe admission and its allow observation are durably staged through the existing audit store in the same transaction as the persisted grant, before the token is returned. Generic human authorization denials use the existing durable authorization boundary. A token is subscription authorization only. It proves no state acceptance, watched duration, command acceptance or physical completion.

Device requests use current enrolled edge Ed25519 credentials and exact boot/session/configuration under the inventory lock. Pico/pod credentials cannot subscribe. HTTP recovery and every publication recheck the current resource/account binding; current credential revocation, replacement, boot/session/config change or original expiry fences a grant. Membership revision/session changes fence human grants. Provider revocation uses allowReauthMargin=false, as specified by the SDK authentication API. Provider enforcement is near immediate after successful provider revocation, not after an unobserved external directory change.

An operator must run bounded realtime:maintain invocations at a configured interval (target one second) using private ARBI_REALTIME_COMPOSITION: an absolute server-only module exporting runtime: RealtimeHttp, up to eight siteIds, and optional close. This reauthorizes active subscriptions, publishes pending hints, and retries revocation. It is not an unsupervised background loop inside a Vercel request. No scheduler or live deployment is installed here. Until a successful revocation, short original token expiry is the provider-access upper bound; publishers stop using an invalid grant's unique channel as soon as they observe invalidity. Directory freshness, scheduler delay and provider delay must be measured in the test deployment.

Mounted HTTPS contract

All actions are POST under /api/sites/:siteId/realtime/:action, with no query parameters. Exact JSON keys are required; bodies use the existing 16 KiB/five-second bounded reader. Responses are private/no-store.

Action Input Authority and result
attach {grantId: null} or persisted prior grant ID Current human state.read; audited grant plus SDK TokenDetails
recover {grantId, epoch, cursor} Current human state.read, original grant/session binding; snapshot or bounded replay
device Signed envelope below Current enrolled edge, no browser Origin or Authorization header; attach or recover

The device envelope is version=arbi.realtime/1.0, realm, siteId, deviceId, credentialId, identity, issuedAtMs, expiresAtMs, action, payload, signature. Sign the accepted enrollment proof digest over everything except signature. Request lifetime is at most ten seconds. payload has the exact attach/recover shape above. Body identity claims acquire no authority without the bound current credential proof. Unknown or cross-site resources, stale identity/configuration, revoked credentials and incompatible realms fail closed.

Initial recovery uses epoch=null,cursor=null. A response contains version/realm/site, epoch, decimal uint64 cursor, reset, at most 32 contiguous change records, more, bounded current snapshot when reset or caught up, original grant expiry and a 2.5-second heartbeat interval. Snapshot covers at most 32 device reports/devices and 64 job status summaries, explicitly marked bounded-current-view. Reports retain original authenticated source and receipt time; freshness distinguishes current identity/config/time from stale reports. No report invents measured position or tension. Job summaries separate cloud disposition from nullable device status. No replay/snapshot contains dispatchable commands.

PostgreSQL visibility, outbox and presence

Apply unchanged migrations 0001–0004, then additive 0005-realtime.sql via db:migrate:realtime with privately supplied operator ARBI_REALTIME_DATABASE_URL. Migration can be repeated. No startup/build migration is performed. Existing job/enrollment APIs, migrations and immutable audit history are preserved.

Additive triggers observe inventory, job, receiver-state and control-lease changes inside their existing transaction. They update a per-realm/site head under a transactional row lock, append a small replay marker and coalesce the durable notification outbox to its newest cursor. Existing mutations already acquire the inventory lock first; recovery and maintenance use that same lock order. Cursor allocation rolls back with the mutation. A blocked/late writer cannot commit behind a cursor already acknowledged by a reader: the native test proves recovery blocks until its inventory/head lock is released. An independent SQL sequence would not establish that property.

The head, opaque epoch, bounded contiguous 256-event replay tail, outbox/retry status, exact client/channel routing, grant original authority/expiry, HTTP heartbeat and last client-submitted recovery cursor live in PostgreSQL. Ably presence/history and process memory are not authoritative. Heartbeat/presence conveys no lease or motion authority. A cursor before retention, beyond head, from another epoch or without a matching epoch forces a current snapshot. Triggers intentionally coalesce notification backlog; dropping intermediate broker hints does not drop authoritative state or job history.

The application role needs registry SELECT/row-lock; existing job/audit staging grants; SELECT/INSERT/UPDATE on realtime heads, outbox, grants and budgets; SELECT/INSERT/DELETE on replay markers; DELETE on expired grants/budgets. Triggers run with the caller's ordinary privileges, so existing job/enrollment writer roles also need their narrow realtime head/event/outbox grants after migration. The operator owns migrations. PUBLIC access is revoked. Grant records store public device identity/credential IDs and authorized human context, never bearer tokens or private keys. Runtime roles must not own schema/audit tables or receive broad administration privileges. Restore requires a new epoch when a restored cursor could represent different content; perform provider role/restore drills separately under #47.

Bounded consumer and traffic

There are at most 64 retained grants per site, including recently expired/revoked ones; expired rows are removed after a one-minute grace. A per-principal PostgreSQL budget allows eight attaches per minute across cloud instances. Recovery requests less than 500 ms apart deny with capacity. A heartbeat older than ten seconds fences its grant. Outbox/revocation attempts stop after eight failures, using exponential delay capped at 60 seconds plus jitter; exhausted publication still permits authoritative HTTP recovery. Exhausted revocation is visible in persisted pending/attempt fields and needs operator attention; original token expiry remains binding. New committed changes reset the coalesced outbox's publication budget. Maintenance is bounded by existing database statement/lock/transaction deadlines and a 2.5-second iteration budget.

The separate recovery executable runs with pnpm --filter @arbi/edge-controller recover:cloud after build, with a private absolute ARBI_CLOUD_RECOVERY_CONFIG file (mode 0600). Required fields: realm, siteId, identity, HTTPS origin, credentialId, absolute protected Ed25519 keyPath, absolute spoolPath, explicit metering boundary. It rejects production. No endpoint, real site, key or device identity is supplied in the repository. The normal local runtime/supervisor does not start it. It imports no local jobs executor and exposes no actuator callback.

The supported SDK consumer opens with only TokenDetails/client ID, explicit subscribe channel mode, strict mode and disabled publication queue. It closes on connection loss, channel discontinuity/revocation or original expiry; a new application admission is required. It coalesces duplicate/reordered hints into one dirty flag, recovers dropped hints on HTTPS heartbeat, permits one operation at a time, at most eight admissions and 60 HTTPS calls/minute, four catch-up pages before snapshot reset, 64 KiB responses and 2 MiB attempted JSON application bytes/minute. HTTP attempts have a four-second deadline; broker connection/attach uses SDK deadlines. Reconnect uses exponential backoff/jitter capped at 60 seconds. Budget exhaustion stays visibly degraded until the next bounded window.

Recovery consumes the merged signed command-job poll independently, preserving its current authorization, receiver clock, lease/fence and original-deadline checks. It validates returned realm/site/current target, reports only a count and discards envelopes. It sends no accepted/running/completed receipt and never dispatches work. A reconnect cannot revive stale manual motion. Durable local execution policy is owned by #30.

Edge shutdown aborts the active HTTPS/SDK operation, clears diagnostic state and permanently closes that consumer. Delayed admission, attachment, recovery or job poll results cannot restore it. SDK opening deadlines include channel attachment; the earlier of provider token and original grant expiry closes the subscription. Broker opening failure retains the authorized grant for metered HTTPS heartbeats with visible degraded status. Invalid replay discards its epoch/cursor before the next admission requests a fresh authoritative snapshot. Retry/heartbeat delays start after the operation settles, and callbacks from an old subscription cannot shorten backoff or trigger reads for a replacement grant.

The edge executable shares one application traffic budget between HTTPS and Ably. Original broker payload bytes count before size/JSON filtering, including oversized discarded hints; exhausting 2 MiB/minute closes the discretionary subscription and denies HTTP submission until the next window. The HTTP adapter races submission and streamed reads against cancellation and its four-second deadline. A transport ignoring abort is quarantined until settlement, so repeated reconnects cannot accumulate orphan submissions. Late response bodies are cancelled. These bounds do not classify SDK heartbeat/framing or WAN bytes.

@arbi/traffic counts actual attempted HTTP JSON submissions and received chunks, including failed submissions and oversized/discarded responses. The SDK publisher carries the original bounded JSON hint string; the subscriber meters its decoded original string bytes before parsing. This covers application notification payload, not SDK/WebSocket framing, SDK authentication/heartbeat wire bytes, TLS, DNS, TCP retries or provider billing. Those remain unclassified/separate interface/provider coverage. Every repeated submission is a distinct attempt. Fixture paths are lan; loopback cannot claim garden-sim or cellular billing. No new traffic rollup/sink or recording support is added. Strict accounting capacity can deny this discretionary recovery path; local fault/stop paths do not consult it.

Browser subscription and recovery

The opt-in browser consumer, HTTPS adapter and Ably browser SDK adapter complete the browser transport boundary. They are app-owned libraries, with no Node imports or actuator/job dispatch callback. The dashboard shell does not install a broker or invent a credential. Trusted composition must supply the current dedicated ARBI bearer callback and explicitly configured server above; the existing HttpOnly dashboard session is not exported to browser JavaScript. Cookie/BFF integration and operational presentation remain with the dashboard owner.

Construct one BrowserTraffic, share it between BrowserHttpsRecovery and AblyBrowserSubscription, then pass those adapters and the expected realm/site to BrowserRecoveryConsumer. HTTPS uses only the configured origin, omits cookies, rejects redirects, and retrieves a current bearer for every request. Only explicit test/preview simulation realms are accepted. Local HTTP is allowed only with the adapter's explicit loopback fixture option. Admission validates the exact site/realm/channel/client binding, subscribe-only capability, token expiry and original grant expiry before opening the SDK. The SDK has no issuing key, automatic credential refresh, publishing queue or presence capability.

The caller owns a single timer (a 500 ms step() cadence suffices), page visibility, site/session changes and rendering. step() ignores overlapping callers and honors nextAt; there is one operation and one bounded current snapshot. Call close() and clear the timer on page/site/session teardown. Closing aborts HTTP and SDK opening, releases the subscription and clears the snapshot. Late responses or attachment completion cannot restore a closed page. Share the traffic budget across replacement consumers within the same page; server admission budgets remain authoritative across pages and cloud instances.

Duplicate/reordered hints retain no queue. They request a read after at least 500 ms; a hint arriving during a read is retained as a coalesced dirty signal. Callbacks from retired grants cannot shorten retry/capacity backoff or schedule reads under a replacement grant. The 2.5-second HTTPS heartbeat recovers dropped hints. Replay pages must be contiguous, correctly scoped and consistent with the epoch/cursor. Invalid replay discards the cursor; a server retention/epoch reset supplies a current snapshot. At most four catch-up pages precede a snapshot request. Snapshots contain only the bounded current view; the caller must preserve report provenance/freshness when displaying state. No replay invokes a command API.

The browser permits at most eight admissions and 60 HTTP calls/minute, 64 KiB per response and 2 MiB/minute of attempted application bytes across HTTPS and broker hints. HTTPS has a four-second deadline covering credential acquisition, submission and streamed body reading. Attempted request JSON/bearer bytes and received chunks count even on failure, denial or overflow; broker payload bytes count before parsing. Totals explicitly exclude HTTP/SDK framing, SDK auth and heartbeat wire bytes, TLS, DNS, WAN retransmissions and provider billing. The browser counters do not replace the edge's durable mobile accounting.

Broker opening failure retains the authorized grant for bounded HTTPS recovery, with visible degraded status. Established connection loss/discontinuity, token expiry or original grant expiry requires a new audited admission. Retry delay uses exponential backoff with jitter capped at 60 seconds; capacity exhaustion waits for the next minute window. A 401/403 clears state and enters denied until the caller explicitly creates a newly authorized composition. Short human directory-freshness deadlines can exhaust the existing persistent admission budget even without network churn; limits remain binding and must be measured and reviewed at the external gate, not bypassed by SDK token renewal.

Unit checks run in the ordinary dashboard suite. The Chromium integration check runs under the existing test:browser launcher with native PostgreSQL and the installed browser SDK. Its HTTP/module host, identities and broker transport are test-only fixtures. Dated evidence keeps those checks separate from live provider/mobile acceptance.

External acceptance gate

Before closing #29, provision isolated nonproduction Ably (revocable issuing keys), Neon/PostgreSQL and Vercel/current identity adapters without production credentials; run the maintenance scheduler and at least two cloud instances. Verify original token expiry, provider subscription revocation/rotation, database role/restore/epoch behavior, deployment churn, quotas, broker downtime, slow consumers and repeated reconnects on an actual mobile network. Record application, transport/WAN and provider layers separately and preserve budgets. No secrets are requested in chat. Real Ably account/mobile tests, live deployment, Linux selected-host storage/power-loss, bench/HIL, installed operation and physical safety acceptance remain unverified. #68 recording remains disabled; live media, dashboard UI, local job policy and updates belong to their owners.