Skip to content

batch/2026-06-23: realtime v2 (WebSocket), scheduler lanes & fairness, discovery, maintenance windows, availability API (41 specs) - #89

Merged
fclairamb merged 459 commits into
mainfrom
batch/2026-06-23
Jul 3, 2026
Merged

fclairamb merged 459 commits into
mainfrom
batch/2026-06-23

Conversation

@fclairamb

@fclairamb fclairamb commented Jul 2, 2026 •

Copy link
Copy Markdown
Owner

Batch integration branch since 2026-06-23 — 41 specs implemented, each merged via a --no-ff feature branch after an independent completeness audit.

Highlights

Realtime updates: SSE → WebSocket v2

  • v1 shipped org-scoped SSE hint events (a connection got every hint for its org)
  • v2 replaces it outright (not yet released, so a clean swap — no deprecation window): a WebSocket transport with per-entity subscriptions — a connection receives nothing until it subscribes to a check (by uid) or a checks/incidents/events/jobs collection scope
  • Handshake: pre-authenticated via header/cookie (CLI/tests/curl) or an in-band {"type":"auth"} message within a grace window (browsers can't set headers on a WS upgrade); explicit close codes (4401/4403/4404/1012)
  • Storm collapse (>64 distinct check uids in one flush window → ["*"]), scope-keyed dirty-set dispatch, subscription caps, dash0 refcounted subscription registry with per-scope poll-stretch gating
  • Fixed post-merge: a stale/mismatched access_token browser cookie (set by the login endpoints for the unrelated OAuth-consent flow, attached automatically to every same-origin request including the WS upgrade) was fail-fast rejected instead of falling through to the client's fresh in-band auth message — silently killing live updates for any browser carrying one
  • Fixed post-merge: a plain result write (the common no-status-transition case) publishes hint kind results only, but the client's query-invalidation map only refreshed the check/checks object on checks/incidents kinds — so "last checked" drifted stale for up to the 5-minute lazy-poll interval instead of resetting each cycle

Scheduler fairness & capacity (the 2026-07-01/02 arc)

  • Check-execution fairness: WFQ-style claim ordering (effective_scheduled_at), per-plan tier credit, cost EWMA
  • Cost-only bounded offset: delay EWMA demoted to pure telemetry after live measurement showed it punished victims and spiralled unbounded (~95 min offsets stranding jobs); offset now cost-only, clamped at 60 s
  • Fast/slow check lanes: lane smallint on check_jobs, hysteresis classifier, partial claim indexes, reservation-style two-SELECT claim with a reserved fast floor (fast_lane_reserved, borrowing allowed), busySlow accounting + lane metrics
  • Heavy-check demand control: server-side MinPeriod validation on create/PATCH (browser 60 s, js 30 s, global 10 s floor; sleep/internal exempt), read-only scheduling block (cost/delay EWMA, duty cycle) on check detail with a ≥50% duty-cycle warning in dash0, cost-aware execution timeout on by default (factor 3, floor 5 s, cold-start fix)
  • Sleep checker + browser-to-sleep harness for scheduler load testing; cost-distribution mgmt endpoint

Discovery

  • Discovery foundation, container discovery, Kubernetes discovery, Kubernetes checker

Maintenance windows

  • dash0 UI, status0 badge, recurrence (backend + frontend), breadcrumbs/timezone polish

Availability correctness

  • Server-side availability-statistics API (real per-period measurements replacing the client-side estimate); status pages exclude lifecycle results; uptime bar data-source parity; 24h hourly history period; dashboard KPI tile removed in favor of the server numbers

Checks & platform

  • NTP checker; configurable password hashing (+ Server Settings UI, rehash-on-change); memory runtime guardrails + consumption analysis; Microsoft OAuth tenant ID setting; adaptive recovery redesigned as capped flapping backoff; confirmation/recovery probe-count estimates; grey status dot for disabled checks; Slack Socket Mode parameter fix; grouped-incident duplicate-resolved-notification fix; fast-relapse incident reopen fix

UX & docs

  • Status pages/status updates empty-state and layout cleanups, badges deep-link fix, docs ASCII→Mermaid, responsive dashboard refresh button

Database

  • Migrations consolidated into a v0.2.0 baseline delta (002_v0_2_0, per engine) covering everything shipped since the released v0.1.0 tag — MCP OAuth, discovery rework, status-page history period, adaptive recovery, scheduling fairness/lanes. Verified with a fresh-DB schema diff (postgres pg_dump, sqlite .schema) against the old incremental migrations: byte-for-byte identical on both engines.
    • Heads-up for anyone with an existing dev/staging DB that already ran migrations 002-009 individually: bun records migrations by numeric prefix (002), so the consolidated 002_v0_2_0 is silently skipped on such a DB (no crash). Content-wise it already has everything except the user_tokens type-check widening below — so on a stale DB the OAuth refresh flow will fail its insert. Fix: reset the DB, or widen the check by hand (Postgres: constraint swap; SQLite: table rebuild, see the migration file).
  • OAuth storage collapsed from three dedicated tables to one (post-review simplification, before any of this shipped anywhere):
    • oauth_auth_codes → generic state_entries records: the issued code embeds the granting org uid as a prefix so redemption — which gets no other org context — can resolve an org-scoped lookup, and DeleteStateEntry now reports whether it consumed a live row so the single-use replay guard still holds.
    • oauth_refresh_tokens → user_tokens rows with a new third type oauth_refresh (client/scope/resource bindings in properties, revocation = the soft delete every user token already has). The frozen v0.1.0 type check is widened in 002_v0_2_0 (constraint swap on Postgres, table rebuild on SQLite), DeleteUserToken became a compare-and-set returning whether it revoked a live row (the rotation replay guard), and each redemption endpoint validates its own type so PATs, session refresh tokens, and OAuth grants can never be exchanged for one another.
    • oauth_clients stays: a client is a registered application shared across users/orgs, not a per-user credential, so folding it into user_tokens would have broken that table's user_uid NOT NULL invariant.

Notable fixes found during QA

  • bench-checks env var SP_SERVER_LISTEN_ADDR never matched the server.listen config key
  • Availability "today" tests broke within ~5h after UTC midnight (tz resolution)
  • Check edit form seeded from a stale react-query cache (flaky E2E, now deterministic)
  • OpenAPI jobUid param mismatch; regenerated the (stale-since-squash) Go client
  • dashboard.spec.ts's activation-feed E2E test hardcoded API_BASE=localhost:4000, silently hitting the wrong server whenever E2E runs against a side-car test server on another port

🤖 Generated with Claude Code

fclairamb and others added 30 commits June 29, 2026 19:47
…sing "+ New" button, and UTC/local timezone clarity
Maintenance Windows: breadcrumbs, collapsing +New button, and UTC/local timezone clarity.
New internal/memlimit package: pure decide* helpers resolve the GOMEMLIMIT
soft cap and GOGC from config, native env vars, and cgroup auto-derivation
(precedence: native env > config > cgroup x ratio > default), applied once at
startup. cgroup_linux reads v2/v1 memory limits; cgroup_other is a no-op.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add RuntimeConfig (memory_limit, auto_memory_limit, memory_limit_ratio,
gc_percent; defaults auto=true ratio=0.9) and DatabaseConfig pool bounds
(max_open_conns 25 / max_idle_conns 10 / conn_max_lifetime 1h). Manual env
readers applyRuntimeEnv / applyDatabasePoolEnv handle the multi-word SP_* keys
koanf cannot bind, with table tests.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
postgres.New takes *Config and applies MaxOpenConns/MaxIdleConns/ConnMaxLifetime
via applyPoolLimits; zero values preserve database/sql defaults so unset config
is a no-op. Bounds peak connection memory under burst load.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
main.go calls memlimit.Apply early (logs effective GOMEMLIMIT/GOGC + source);
server.go and main.go pass the bounded *postgres.Config through to postgres.New.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Surface the effective GOMEMLIMIT (MaxInt64 normalized to 0) and GOMAXPROCS in
the memory snapshot so operators can confirm the runtime guardrail took effect;
assert both fields in the handler test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Mark Postgres-pool suspect fixed; document GOMEMLIMIT/GOGC precedence,
cgroup auto-cap, the /api/mgmt/memory fields, and the measured GOGC trade.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Memory runtime guardrails: cgroup-aware GOMEMLIMIT/GOGC (internal/memlimit),
bounded Postgres connection pool, and /api/mgmt/memory runtime fields.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Split the passwords package into policy/argon2id/bcrypt files. Hash uses
the configured default policy (argon2id default, m=64MiB/t=3/p=4, or
bcrypt). Verify dispatches purely on the stored hash marker so old and new
algorithms coexist with no migration. NeedsRehash reports when a stored
hash's algorithm or cost no longer matches the active policy. bcrypt uses
a base64(sha256(pw)) pre-hash to dodge the 72-byte/NUL limits. All argon2
derivations still route through boundedIDKey (concurrency cap preserved).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
fclairamb added 17 commits July 2, 2026 22:32
…check attribution

- Hint gains checkUids with storm-collapse to ["*"] at 64 distinct uids
- Publisher.Publish/PublishImmediate take a checkUID param, threaded through
  all call sites (incidents, heartbeat; jobs stays org-level)
- Hub.Subscriber gains per-scope subscriptions + dirty state (collection
  scopes: checks/incidents/events/jobs; per-check scope keyed by uid);
  zero-scope subscribers receive nothing (default-silent)
- Rewritten hub/publisher/multireplica tests for v2 semantics
- New handlers/realtimews/ package: WebSocket upgrade with in-handler auth
  (header/cookie pre-auth OR auth message within SP_REALTIME_AUTH_GRACE),
  subscribe/unsubscribe read loop with per-scope validation, write loop,
  ping/pong keepalive, token-expiry timer, close codes 4401/4403/4404/1012
- Route: /orgs/:org/events/ws registered unconditionally, outside
  RequireAuth/RequireOrgAccess (carries v1's timeout/ratelimit exclusions,
  renamed suffix to /events/ws)
- Removed handlers/realtimestream/ (SSE) and its route
- Config: realtime.auth_grace (5s) / realtime.max_subscriptions_per_connection
  (512) + SP_REALTIME_* env overrides
- Metrics: RealtimeSubscriptions gauge, RealtimeMessagesReceived counter
…e, integration

- handlers/realtimews/handler_test.go: default-silent, per-check isolation,
  handshake edge cases (no-auth timeout, subscribe-before-auth, invalid
  pre-auth token, foreign-org, disabled), duplicate-subscribe idempotency,
  subscription cap, token-expiry close, storm-collapse wildcard delivery
- Fixed a real bug found while writing these: awaiting the auth grace window
  via a context deadline passed into conn.Read let coder/websocket close the
  socket with its own code before our explicit 4401, since Read closes the
  conn on ANY error including context expiry. Now races a timer against a
  backgrounded Read instead.
- test/integration/realtime_stream_test.go: rewritten for the WS protocol
  end-to-end through the real router/middleware chain
- Updated ratelimit_test.go/timeout_test.go exclusion-path fixtures to
  /events/ws; incidents/realtime_hints_test.go gains a check-uid-attribution
  assertion
…on registry

- lib/live-socket.ts replaces live-events.ts: WebSocket client with jittered
  capped backoff, token re-read per attempt, waitForApiQuiet gating, auth as
  first message, onOpen/onSubscribed/onUpdate/onResync/onDisconnected/
  onDisabled callbacks, send(subscribe/unsubscribe). Close 4403/4404 -> onDisabled,
  everything else reconnects with backoff.
- contexts/LiveEventsContext.tsx rewritten as a refcounted per-scope
  subscription registry (LiveRegistry, exported for testing): components
  declare interest via useLiveSubscription(scope); 0<->1 refcount transitions
  send subscribe/unsubscribe; every active scope replays after reconnect.
  New useScopeLive(scope) hook gates poll-stretch on that scope's own
  subscribed ack (rejected/unacked scopes keep polling at base rate).
  useLiveStatus()/stretchWhileLive keep their prior signatures for coarse
  consumers. Explicit per-root query-key predicates (checkDetailRoot/
  resultsRoot/orgRoot) replace the old key.includes(uid) guess — results
  queries nest checkUid inside an options object, not a bare key segment.
- Both use useSyncExternalStore (React 19) so a scope's live-flag flip only
  re-renders its own subscribers.
- 29 new unit tests (live-socket.test.ts, LiveEventsContext.test.ts) covering
  backoff, frame parsing/routing, close-code handling, refcounting, replay-
  on-reconnect, scope-accurate invalidation, and poll-stretch gating.
…bs pages

- dashboard-page.tsx: subscribes checks/incidents/events collections, gates
  each poll interval on that scope's own useScopeLive ack (results ride the
  checks scope, matching v2's kind routing)
- checks.$checkUid.index.tsx: subscribes its own check scope + incidents
  collection; poll-stretch now gated on the check scope's ack
- api/hooks.ts jobs section (useJobsStats/useBackgroundJobs/useCheckSchedule):
  each subscribes the jobs collection scope directly so multiple simultaneous
  callers refcount correctly, gates jobsAdaptiveInterval on useScopeLive
  instead of the global useLiveStatus
ws: true on the /api proxy entry so the local dev server forwards the
/events/ws upgrade to the backend. Verified end-to-end against the running
devloop: proxy forwards the upgrade, unauthenticated connections close 4401
after the grace window, and the full auth -> hello -> subscribe -> subscribed
round-trip works. Vite's own HMR client uses a separate /@vite/client path,
unaffected by the /api-scoped proxy.
…rewrite E2E

- web/docs/docs/features/live-updates.md rewritten for the WS protocol:
  handshake, message table, close codes, config knobs, websocat example
  replacing curl
- wiki/api-specification.md: /events/stream entry replaced with /events/ws
- openapi.yaml: removed /events/stream (OpenAPI 3 can't model WebSocket);
  left a pointer comment to the wiki/docs
- e2e/live-updates.spec.ts rewritten for the WS protocol: waits for a
  subscribed ack instead of the old SSE 200 response; adds a third scenario
  proving reconnect-after-close replays subscriptions and stays live (via
  page.routeWebSocket pass-through + forced close). All 3 scenarios verified
  passing (6/6 across a repeat run) against a side-car SP_RUNMODE=test
  server on an alternate port, without disturbing the shared :4000 devloop.
- rg "events/stream" sweep: zero hits outside specs/todos (the plan doc).
- close response bodies from every websocket.Dial() call (bodyclose)
- justify the two lookup-map globals and the wildcard sentinel
  (gochecknoglobals, matches existing repo convention)
- avoid a per-iteration struct copy in the write loop (gocritic)
- drop the unused nolint:mnd directive; name the ping-pong grace constant
- publishHint test helper: drop the always-"org-a" orgUID param (unparam)
- rename a short loop var kinds->kind (varnamelen)
- fix line length in handler_test.go

TestServe_TokenExpiryCloses4401 flaked under full-suite parallel load: an
800ms token TTL raced the dial+hello round-trip, so the token could already
be expired by the time the handler validated it (same class of bug as the
earlier awaitAuthMessage fix, different call site). Switched to the auth-
message path (validates immediately after the WS handshake, not after a full
TCP dial) with a 5s TTL; stable across repeated runs including -race.
…6-06-23

Realtime v2: WebSocket transport with per-entity subscriptions, replacing
the v1 SSE hint stream. See specs/todos/2026-07-02-02-realtime-websocket-per-entity-subscriptions.md
…okie

The login/refresh endpoints set an access_token cookie for the unrelated
OAuth-consent flow, but browsers attach it to every same-origin request
automatically, including the WS upgrade. A stale or mismatched cookie
(older than the token the page currently holds) was treated the same as
an explicit-but-invalid Authorization header — fail fast, never read the
client's auth message — so any browser carrying such a cookie could never
authenticate the socket, and live updates silently never arrived. Only an
explicit header (a deliberate CLI/websocat credential) should fail fast
now; an invalid cookie falls through to the in-band auth message.
A plain result write (no status transition) publishes realtime hint kind
"results" only — KindChecks is published separately, only on an actual
status change. But the checks list and check-detail queries embed
lastResult/lastStatusChange (with=last_result,last_status_change), and
DEFAULT_QUERY_ROOTS only invalidated those on kind "checks"/"incidents".
So on every steady-state run (the common case — no transition), "last
checked" kept ticking up client-side against an increasingly stale
timestamp instead of resetting, for up to the lazy poll interval (5min).

Verified live: a fast 10s-period check's "Last checked" now resets each
cycle (1s -> 7s -> 3s ago) instead of climbing monotonically.
The "recent activity" test hardcoded API_BASE to localhost:4000, so its
check-creation POST silently hit the wrong server whenever E2E runs
against a side-car test server on another port — the dashboard never
saw "Activation feed probe" because the check landed elsewhere.
Introduced in fe003e4; live-updates.spec.ts already has the correct
E2E_BASE_URL-derived pattern, applied here too.

Verified against a side-car SP_RUNMODE=test server on :4400: all 10
dashboard.spec.ts tests pass with a non-default E2E_BASE_URL.
Consolidate incremental migrations 002-009 (MCP OAuth, discovery rework,
status-page history period, adaptive recovery, check scheduling fairness
+ its two follow-ups) into one 002_v0_2_0 migration per engine, per the
sync-pg-to-sqlite convention. v0.1.0 (001) is a released, frozen baseline
and untouched.

Net final DDL only — omitted the three data-backfill UPDATEs (004, 006/008,
009) and the transient idx_check_jobs_effective_scheduled_at index (created
in 006, dropped in 009): all pure no-ops for the fresh installs this
consolidated migration targets. Updated migrations_test.go for the file
removals (TestMigrationEffectiveReanchor and the lane backfill re-run
tested one-time data-repair behavior that no longer exists as an isolated
migration; TestMigrationCheckJobLane trimmed to its still-valid schema
assertions).

Verified: fresh-DB schema dumps (postgres pg_dump, sqlite .schema) from the
old incremental migrations vs. the new consolidated one are byte-for-byte
identical on both engines. make test and make lint-back green.
@fclairamb fclairamb changed the title batch/2026-06-23: scheduler lanes & fairness, discovery, maintenance windows, availability API (38 specs) batch/2026-06-23: realtime v2 (WebSocket), scheduler lanes & fairness, discovery, maintenance windows, availability API (41 specs) Jul 2, 2026
fclairamb added 2 commits July 3, 2026 01:41
…icated table

oauth_auth_codes was a purpose-built table for a single-use, 60s-lived
record — the same shape the existing generic state_entries store (already
used for password resets, invites, OAuth sign-in state) is built for.
Reusing it removes a table and its two indexes for one narrow use case.

Two gaps had to be closed to make this safe (both confirmed with the user
before implementing, since this touches single-use-code replay protection):

- Redemption has no org context (the token endpoint receives only `code`),
  but state_entries lookups need an org upfront. Fix: the issued code now
  embeds the org uid as a prefix (`{orgUID}.{random}`) so ExchangeAuthCode
  can resolve the org-scoped lookup itself.
- DeleteStateEntry discarded the affected-row count, so it couldn't tell a
  genuine first consume from a replay racing a concurrent redemption — the
  exact property ConsumeOAuthAuthCode's compare-and-set provided. Fixed by
  changing DeleteStateEntry to return (bool, error); all ~15 existing
  callers (password reset, invites, OAuth sign-in state cleanup) just
  discard the new bool and are unaffected.

oauth_clients stays a dedicated table: it models a registered application
(many users/orgs authorize the same client), not a per-user credential —
merging it into user_tokens (also considered) would have broken that
table's `user_uid NOT NULL` invariant or conflated a public client_id with
a bearer token, so it was left as-is.

Not yet released (v0.2.0 unreleased), so 002_v0_2_0's migration files are
edited directly rather than layered with a new migration.
…dicated table

Follow-up to the auth-code consolidation: oauth_refresh_tokens was a
per-user credential table nearly congruent with user_tokens (owner,
hashed value, expiry, revocation). It's now a third token type —
'oauth_refresh' — alongside 'pat' and 'refresh': the grant's
client_id/scope/resource bindings ride in the properties JSON, and
revocation is the soft delete every user_token already has.

Mechanics:
- user_tokens type check widened in 002_v0_2_0 (frozen 001 untouched):
  drop/re-add constraint on Postgres, table rebuild on SQLite (which
  cannot alter CHECKs); verified live on both engines.
- DeleteUserToken becomes a compare-and-set on deleted_at IS NULL,
  returning (bool, error) — that bool is the rotation replay guard
  ExchangeRefreshToken relies on (mirrors the DeleteStateEntry change).
- Cross-type confusion is impossible: each redemption endpoint checks
  its own type (PAT auth, session refresh at auth/service.go, and the
  new Type != TokenTypeOAuthRefresh guard in ExchangeRefreshToken), so
  none of the three token kinds can be exchanged for another.
- RevokeOAuthRefreshTokensForUser and its db plumbing are gone; logout
  and PAT-revoke now go through a typed revoke helper in the auth
  service (list-by-type + soft-delete), same as password reset does
  for session tokens.
- Revoked grants vanish from GetUserTokenByToken (deleted_at filter),
  so "already rotated" and "never existed" are indistinguishable to a
  caller — both errInvalidGrant.

The oauth package's rotation tests pass unchanged on the new storage,
and the cross-engine db parity test now proves the widened constraint
accepts the new type on both Postgres and SQLite.
@fclairamb
fclairamb merged commit 73ff047 into main Jul 3, 2026
11 checks passed
@fclairamb
fclairamb deleted the batch/2026-06-23 branch July 3, 2026 00:10
fclairamb added a commit that referenced this pull request Jul 4, 2026
## Summary
- The `batch/2026-06-23` PR (#89, merged 2026-07-03) was squash-merged
with a prose commit message, not Conventional Commits format, so
release-please never recognized any of its `feat:`/`fix:` content.
- The currently open release-please PR only bumps to v0.1.1, based
solely on two later dependency-fix commits — it's silently missing the
entire batch (realtime v2, scheduler lanes & fairness, discovery,
maintenance windows, availability API, migration squash to `002_v0_2_0`,
etc).
- This is release-please's documented override mechanism: a `Release-As:
0.2.0` trailer forces the next release PR to target that version.

## Test plan
- [ ] CI passes
- [ ] release-please regenerates its PR targeting v0.2.0 after this
merges
fclairamb added a commit that referenced this pull request Jul 4, 2026
The batch/2026-06-23 squash-merge (#89) wasn't Conventional Commits
formatted, so release-please's auto-generated changelog only listed the
unrelated dependency-fix commits. Add Features/Bug Fixes entries
summarizing what the batch actually shipped (realtime v2, scheduler
fairness/lanes, discovery, maintenance windows, availability API,
migration consolidation, OAuth storage collapse, and the two realtime
bugs fixed post-merge).
fclairamb added a commit that referenced this pull request Jul 5, 2026
#105)

## Summary

release-please's changelog only sees each squash-merge commit's own
title/body. The v0.1.0 and v0.2.0 batch integration PRs (#73, #78, #85,
#89) each bundled many independently-implemented, independently-audited
specs behind one flattened changelog bullet, hiding most of what
actually shipped.

Expands both releases' changelog entries to list every underlying
feature/fix, sourced from each batch PR's own itemized description
(which already documented them in detail — the changelog just never
surfaced it). No functional/behavioral change, `CHANGELOG.md` only, plus
one unrelated one-line `.gitignore` fix for a local E2E test-server pid
file that kept showing up as untracked.

## Test plan

- [x] Docs-only change, no code touched.
- [x] Cross-checked every expanded bullet against its source PR's own
description (`gh pr view <n>`) rather than reconstructing from raw
commit diffs.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Sonnet 5 <[email protected]>
fclairamb added a commit that referenced this pull request Jul 8, 2026
release-please's first-parent commit traversal only saw the merge
commit for #111 ("Batch 2026-07-06-2: 10 completed specs"), which
isn't conventional-commit-formatted, so none of the 93 squashed
feat:/fix: commits it merged were auto-categorized. Manually adding
entries here, following the same precedent already used for #89's
release (0.2.0) — multiple bullets against a single merge commit sha.
fclairamb added a commit that referenced this pull request Sep 2, 2026
…ed devices (#301)

Batch of four specs from `specs/todos/`, each implemented on its own and
gated on an independent completeness audit before being archived to
`specs/done/2026/09/`.

## Embedded TCP/UDP heartbeat push transport

Heartbeat checks could only be fed over HTTPS, which shuts out the fleet
the primitive fits best — microcontrollers, cellular modems driven by AT
commands, battery sensors, legacy PLCs — because TLS costs tens of KB of
RAM, a CA store and a correct clock. This adds two small listeners (one
port number, **4001**, on both TCP and UDP, **off by default**) speaking
a one-line, netcat-debuggable protocol in two forms:

- **SP1** — `SP1 <org>/<check> <token>` — plaintext token, convenience
default.
- **SP2** — `SP2 <org>/<check> <ts> <ctr> <mac>` — HMAC-SHA256 keyed
with the check's token, no secret on the wire, ~80 bytes.

Replay protection is a strictly-increasing per-check counter enforced by
the database itself (a single conditional upsert), so an old datagram
fails and even the latest datagram cannot be replayed. The new per-check
`require_hmac` option rejects SP1 outright; the dashboard pairs the
toggle with a token-rotation nudge, because a check that ever accepted
SP1 has leaked the key.

Beats carry an optional annotation (a status word plus logfmt
`key=value` pairs). Numeric values land in the result's `metrics` jsonb,
so battery volts and RSSI become first-class time series charted on the
check page. An annotation **never** invalidates a beat — a firmware typo
must not make a healthy device look dead.

Security posture is stated explicitly in the code and the docs: SP1 is
replayable to mask an outage (that is what `require_hmac` closes), SP2
authenticates the message rather than the transport, and UDP source
addresses are spoofable and are never treated as identity. UDP answers
nothing at all on any failure — a nonexistent org is byte-identical to a
bad MAC — and never replies with more bytes than it received.

New docs page: **Embedded / push monitoring**. Enabling the ports is a
deployment decision (k8s Service / LB) and is documented, not automated.

## gRPC checks: real phase breakdown and request metadata

`connection_time_ms` was fiction — `grpc.NewClient` is lazy, so the
metric measured struct construction while the real DNS + TCP + TLS cost
hid inside `rpc_time_ms`. The connection is now established eagerly and
instrumented, reporting genuine `dns_time_ms` / `connect_time_ms` /
`tls_time_ms` / `rpc_time_ms`, with failures classified by the phase
that failed instead of collapsing into one opaque RPC error. Checking a
service the server never registered now says so in words rather than
surfacing a raw `NotFound`.

gRPC checks also gain `metadata` and encrypted `secretMetadata`, so a
health endpoint behind an authenticating proxy can be checked at all —
and the dashboard form is no longer a stub: TLS skip-verify, timeout and
both metadata editors are now reachable.

## Uptime report emails: trends, latency and worst-first ordering

The scheduled report showed one period in isolation. It now carries
period-over-period deltas, a response-time block, average incident
duration, and a check table sorted worst-first with a per-day
availability strip — so a broken check can no longer sit invisibly at
the bottom of a 50-row alphabetical table.

Considerable care went into the degenerate cases, because this is
exactly where a digest starts lying: zero is never green, a missing
baseline omits the delta entirely rather than rendering "±0.00%", a
monitor down all period gets a plain factual sentence instead of a grid
of zeros and a celebrated response-time "improvement" measured on error
responses, and days before a check existed are gray rather than red. No
MTBF, and no plan-upsell content in report emails by explicit product
decision.

## Dashboard polish

The "Getting started" checklist rows had no background of their own, so
the card's tint bled through and completed rows looked identical to
pending ones. Rows now carry an explicit surface with a faint emerald
wash when done.

---

## Changelog entries

feat(heartbeat): add an embedded TCP/UDP push transport so constrained
devices can beat without TLS
feat(heartbeat): add the SP1/SP2 beat wire protocol, annotation parsing
and the per-check require_hmac option
feat(dash0): show the embedded beat examples and the require_hmac toggle
on heartbeat checks
feat(grpc): report a real DNS/connect/TLS/RPC phase breakdown and
classify failures by phase
feat(grpc): support request metadata and encrypted secretMetadata, and
complete the dashboard form
feat(uptimereport): add period-over-period trends, a response-time
summary and a worst-first check table with a per-day strip
feat(heartbeat): expire an SP2 replay counter a week after the last beat
feat(dash0): give the Getting started checklist rows their own
backgrounds and a done state
fix(checks): a heartbeat config PATCH no longer destroys the check's
ping token
fix(uptimereport): render a zero previous-incident count instead of "<no
value>"
fix(dash0): render the TCP beat one-liner's newline escape

## Notes for review

- **Two bugs were found and fixed in passing**, neither in this batch's
own new code: a heartbeat `config` PATCH silently destroyed the check's
ping token (the public patch path is REPLACE, and `Validate`'s
regenerated token was discarded because it ran on a deep copy), and
`Data.PreviousIncidentCount` carried `omitempty`, so the commonest
healthy report — no incidents this month or last — printed `<no value>`
where it meant `0`.
- **No new migration.** The SP2 counter lives in the existing generic
`state_entries` store rather than a dedicated table, matching the
consolidation already made for OAuth storage in #89. Strict monotonicity
stays in the SQL `WHERE` clause on both dialects, never in Go — a
read-modify-write there would reintroduce the replay race under exactly
the concurrency a retried UDP datagram produces. Net DDL for this cycle
is nothing, so there is no `018` file.
- **Counters expire on a sliding 7-day window**, refreshed by every
accepted beat, so a beating device never expires its own counter and a
check that went quiet stops occupying a row forever. That sweep is a
*soft* delete and the guard ignores `deleted_at`, so a swept counter
keeps refusing replays — pinned by a test per dialect. The one thing a
future change should weigh is recorded in the code and the spec: if a
hard purge of soft-deleted state entries is ever added, a clockless
(`ts=0`) device silent for over a week could have an old beat replayed
at it.
- **Dev-database note:** an earlier commit in this branch briefly added
an `018_v0_22_0` migration that was withdrawn. A local dev database that
ran it carries a `bun_migrations` row for a file that no longer exists.
The runner tolerates that and boots normally, but reset any dev DB that
ran it before a future `018` lands, rather than using `migrate repair`.

---------

Co-authored-by: Claude Opus 5 <[email protected]>
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.

1 participant