Current state and bounded telemetry history
This implements the simulation/isolated-adapter scope of #37 under ADR-0005. The telemetry service uses the enrolled edge identity, current site/account authorization, PostgreSQL and transactional realtime hints. Host evidence is separate from live provider provisioning, mobile measurements and physical validation.
Composition and authority
Protected server composition calls createTelemetryServer and configureTelemetry with the same database, realm, Gredice identity/resource resolver, current-authority resolver and approved browser origins as cloud jobs. The resolver must read current session, membership, account/site and capability state and honor cancellation; returning a persisted context is insufficient. Humans are authorized and audited by the existing HTTP boundary, then checked again under the inventory lock before and after the protected query. Missing composition returns a redacted private/no-store 503. Production realms, hardware scopes and service principals are denied.
Only a currently enrolled, active edge with current applied configuration and an unexpired/unrevoked Ed25519 credential can upload. The proof binds all envelope fields, including the configuration revision. Boot/session identities are adopted by enrollment, never by a telemetry message. Old boots, revoked credentials, foreign sites/realms and unnegotiated capabilities are denied. Telemetry needs a current-source/configuration state.snapshot with matching advertised capabilities, admitted either through this service or the jobs snapshot route. Pico/pod physical inventory remains in the enrollment registry; the edge owns this cloud upload boundary.
Ingestion, retention and reads share the inventory-first transaction order with enrollment, jobs and realtime. Current state, raw history, both aggregate tiers and the realtime head/outbox commit atomically. Failed storage or hint admission returns unavailable and rolls back all changes. These observational tables are mutable and distinct from immutable audit/job evidence. Historical deletion never deletes those records or grants execution permission.
Apply additive 0006-telemetry.sql after migrations 0001–0005 with pnpm --filter @arbi/dashboard db:migrate:telemetry. Supply ARBI_TELEMETRY_DATABASE_URL privately to the operator process. Runtime roles require SELECT/INSERT/UPDATE/DELETE on the three telemetry tables and USAGE/SELECT on their identity sequence, registry SELECT/row locking, job site SELECT/INSERT/UPDATE, job receiver SELECT, existing authorization audit grants and realtime trigger table grants. PUBLIC receives no rights. Migration ownership and DDL rights must not be the runtime role. Configure finite pool acquisition/connect deadlines; SQL uses a 1.5-second statement deadline, a one-second lock deadline and the existing four-second transaction clock guard.
Ingestion and truthful current state
POST /api/sites/:siteId/telemetry/device accepts exactly version, realm, siteId, deviceId, credentialId, identity, configRevision, issuedAtMs, expiresAtMs, action, payload, signature. Version is arbi.telemetry/1.0; the signed proof uses the existing enrollment canonical proof bytes. Its lifetime is at most ten seconds. Requests have no browser Origin or bearer header. JSON is capped at 60,000 bytes with the existing five-second body-read deadline. No private key crosses the API.
For action: ingest, payload is one validated arbi/1.0 telemetry or event envelope, with null client ingest time and simulation execution mode. Source UTC/uncertainty, boot/session, uint64 sequence, monotonic sample times, units, frames, quality and configuration/capability context are retained. The receiver supplies receive time and ingest time with its configured uncertainty. Protocol events retain full body detail, including fault ID, raised/cleared state, severity and error code. Copied command outcomes are historical observations only; the jobs outcome API still owns job reconciliation and audit effects.
Each device has independent telemetry/event high-water marks. A higher sequence with regressing source/sample monotonic time is rejected. Exact current duplicates return duplicate; contradictory current or retained stream sequences and retained event IDs return conflict. Canonical stream/group hashes are independent of JSON property order. Lower sequences are retained as late raw/event detail without replacing current state, fault state or aggregate counts. Retained late keys deduplicate; contradictory retained keys conflict. Once raw/detail retention expires, an old replay can be retained again as late detail, still without changing current state or aggregates. Advancing gaps report the missing sequence count. A negotiated boot/session change clears incompatible readings/snapshot/fault projections and increments a persisted reset count. Cumulative gaps remain visible even if later backfill arrives: they describe what the current-state stream missed at admission. coverage.startKnown: false explicitly avoids claiming complete pre-attachment history.
Partial telemetry updates preserve other metrics with their own source/receive provenance and age. A numeric zero remains numeric zero. An unavailable measurement retains null value and its reason; it never contributes a numeric zero to aggregates. Current freshness uses conservative source-to-receiver delay plus elapsed receive time and sample age, with a five-second maximum. Unknown/inconsistent UTC uncertainty makes numeric readings stale. Stale readings preserve their origin quality. Current identity/configuration mismatch or a newer negotiated capabilities revision invalidates freshness. Current reads consider both telemetry-service and job-receiver snapshots; a capabilities change clears incompatible partial readings on the next advancing telemetry message. Event snapshot freshness is separate from the latest event’s freshness, so a fresh fault update cannot make an old Ready snapshot current. Callers must continue aging data after observedAtMs; absent readings and stale/unknown coverage supply no measurement or operating permission.
Enforced retention and downsampling
These are upper bounds per site across all devices, configurations, boots and qualities. Age and row limits both apply; high cardinality can evict data before its maximum age. No complete history is promised.
| Tier | Maximum age | Maximum rows | Meaning |
|---|---|---|---|
raw |
24 hours | 4,096 | One detailed sample/provenance row per metric, including explicitly late data |
minute |
7 days | 8,192 | 60-second receive-time buckets for advancing samples |
hour |
90 days | 8,192 | 3,600-second receive-time buckets for advancing samples |
event |
90 days | 4,096 | Full protocol event detail; searchable faults and late observations |
trace |
7 days | 32 | Explicit small diagnostic attachments linked to a retained event |
Both aggregate tiers are updated directly at ingestion, independently of raw retention. Grouping separates source boot/session, configuration/capabilities revision, metric, unit, frame, effective quality, origin quality and reason. Counts, numeric counts, sum/mean/min/max, reported uncertainty maximum, unknown uncertainty/age counts, first/last source and receive times and gap counts are retained. Unavailable-only groups have null numeric statistics. Commanded, estimated, measured and stale data are never silently averaged together. Aggregate quality records freshness at admission; it is not a live sensor assertion. Bucket age is measured from the receive-time bucket start, so a bucket can expire up to one bucket width before its last sample. Row eviction uses creation order, not device clocks.
Every successful ingest prunes expired/excess rows before and after admission. Current heads are capped at 64 streams (32 device pairs); obsolete device heads are removed by pruning. A fault projection retains up to 64 IDs per device, evicting the oldest cleared fault before refusing excess active faults. Detailed fault history retains its separate event policy. Read predicates exclude expired history even when a site is idle. For physical expiry on idle sites, an operator invokes pnpm --filter @arbi/dashboard telemetry:maintain for one known site with private ARBI_TELEMETRY_DATABASE_URL and explicit ARBI_TELEMETRY_ENVIRONMENT (test or preview), ARBI_TELEMETRY_NAMESPACE, ARBI_TELEMETRY_SITE_ID. Provision a once-per-hour site invocation when enabling the service; no all-site scan, scheduler or provider resources are installed by this change. An idle database can retain expired rows until that invocation, while query access still enforces expiry and row growth remains capped.
For action: trace, payload is exactly traceId, eventId, messages. The linked event must be retained and match the current source/configuration. Attachments have at most 128 validated telemetry messages, 512 samples and ten seconds of source monotonic duration within the 60,000-byte request budget. Sequences and sample times advance inside the attachment. A trace does not update current state or statistical history. It is stored as private bounded JSON in PostgreSQL, without a public object URL or arbitrary file upload. An identical retained trace is idempotent; a contradictory ID conflicts. This small attachment budget avoids an unbounded high-frequency recorder.
Filtered and paginated APIs
All reads use /api/sites/:siteId/telemetry/:action, current ARBI bearer authorization and private/no-store responses. Numeric query strings must be nonnegative decimal integers; duplicate or unknown parameters are rejected. Responses carry an observation time, explicit provenance and coverage. No credentials, provider exception or identity directory internals are returned.
| Action | Permission | Query and result |
|---|---|---|
current GET |
state.read |
Optional deviceId, limit (default 8, maximum 32 streams), after. Returns states/readings with source times, units, qualities, age bounds, identity/config compatibility, gaps/resets and next cursor. |
inventory GET |
diagnostics.read |
Optional assemblyId, after, limit (default 25, maximum 100). Returns canonical configured assembly/hardware IDs and revisions, signal ownership/availability/units and redacted enrolled device status/software/config/freshness. This is configured inventory, not a new BOM or installed-inspection claim. |
history GET |
history.read; diagnostics.read for traces |
Required tier, fromMs inclusive, toMs exclusive, limit (1–100). Optional cursor, deviceId, configRevision; raw/aggregate filters metric, quality; event filters faultId, severity, eventType; trace filter traceId. |
History range cannot exceed the selected tier’s retention horizon and is clamped to the current age cutoff. next is an opaque versioned keyset cursor bound to the realm/site and exact filters/page size. It bounds the initial admission ID and excludes later new rows; there are no offsets or unbounded exports. Pages are newest admission/aggregate-creation first, not chronological source time. Aggregate values can evolve and retention can remove rows between pages; this is a bounded observational view, not a frozen export. Current/inventory next feeds their after parameter; callers retain the original filters and treat inventory configuration changes as a reason to restart pagination.
Every site has persisted fixed-minute successful request budgets: 600 ingestion, 10 trace and 120 protected reads. Invalid/rejected transactions roll back their mutation; accepted calls consume the shared budget across processes and principals. Capacity returns 429; oversized successful response candidates are capped at 256,000 bytes and require a smaller page. These application budgets and byte counts are not measured mobile traffic or provider billing. History scans are bounded by hard table caps and SQL deadlines; no public SQL or cursor value supplies authorization.
Validate with pnpm docs:check, dashboard lint/typecheck/test/build, test:postgres and test:http; existing browser checks cover the surrounding authenticated shell/recovery foundation. This API foundation does not add a telemetry chart to the shell or automatically activate a live provider.