Reeve Docs

Docs / Architecture

Architectural constraints

These are the rules a change to Reeve must not break. Read the architecture overview first for the shape they protect. Some rules are checked by the build (an MSBuild target, a startup validation, a generated-file comparison) and the text says so. The others are conventions held at review.

Layering and dependencies

Dependency direction

Reeve.Domain references Reeve.Contracts and no other Reeve project. Reeve.Application references Domain, Contracts and the plugin abstractions, never Infrastructure. Reeve.Infrastructure and Reeve.Api sit outermost and may reference inward.

MSBuild targets in backend/Directory.Build.targets fail the build on a forbidden edge. Each constrained layer declares the projects it may reference (REEVE0001) and the full Reeve.* assembly closure it may compile against (REEVE0002). The workload and workflow engines are consumed only as packages, so a project reference to a local copy of either is an error.

Core holds no plugin knowledge

No backend project references a plugin project or package (REEVE0003). Plugins live in separate repositories and reach the host only through the plugin loader. Workflow blocks and alert subscribers are discovered from loaded assemblies, and the workflow engine dispatches by block-type string and references no device, room or scene type.

The plugin reference set

A plugin references only the plugin-abstractions package, the contracts package, the plugin-authoring helpers, the shared adapter wire-protocol contracts and NuGet packages, never the application, infrastructure or domain assemblies. Those are the only assemblies shared with a plugin's load context. Anything else a plugin ships loads isolated, and a shared type whose identity splits fails with a missing-method error at first use.

Hardware-bound integrations run beside the backend

An integration that needs a radio pinned to a host or a heavy native runtime ships as its own container with a thin companion plugin in process. The backend never references adapter-side native libraries, and the sidecar never touches the database: its persistence flows through its plugin. Do not add a sidecar for a protocol that is only a network socket.

Runtime and language floor

The backend, mobile app, in-tree services and plugin SDK target .NET 11. Every project reads its target framework from the root Directory.Build.props:

  • $(ReeveTargetFramework) is the host runtime (backend, its tests and tools, tools/Reeve.PluginDev).
  • $(ReeveSdkTargetFramework) is the plugin SDK framework for every packable library and plugin fixture. It is never newer than the host's.
  • $(ReeveMobileTargetFramework) and $(ReeveAndroidTargetFramework) follow the MAUI workload.

The web client is React with strict TypeScript under Vite, lint allows no warnings, and frontend/src holds no .js files.

The data stack follows the runtime's major

EF Core, Npgsql EF and the EF Core data-protection store carry the runtime's major version (11.x), which the TimescaleDB provider is built for. The version is pinned once in Directory.Packages.props and moves only together with that provider. Migrations are scaffolded with the dotnet-ef that dotnet tool restore pins.

TimescaleDB support is upstream's CmdScale.EntityFrameworkCore.TimescaleDB and .Design. Reeve keeps no fork. A query translation upstream lacks is written host-side against EF's public translator API, and a provider fix goes upstream.

The backend image builds from the repository root

backend/Dockerfile is built with the repository root as its context, because Reeve.Infrastructure references projects under services/adapter-protocol/. The image carries the host alone. Device plugins are installed at runtime as OCI plugins and never built in.

Plugins

Plugins are drivers; the framework never translates

A plugin owns all vendor-to-canonical translation in both directions. It emits canonical state and accepts canonical commands. No framework, API or client code parses a vendor key, coerces a wire value or branches on vendor identity.

A native plugin is trusted code, not a sandbox

For a native plugin the permission model is consent, least privilege and an audit trail, not containment. It can reach past its grants by reflection or its own socket. Only the WebAssembly lane is a capability sandbox, where an ungranted capability is a host import that returns a denial. A native plugin escaping its grants is not a vulnerability in itself, but the sandboxed lane leaking past a denial is.

A facade built from a grant is re-checked against the grant row

A facade resolves the plugin type's grant when it is built. A facade that outlives that moment, such as one held by a running instance, is re-checked against the grant row when the plugin_grant generation is applied and at every dispatch. A facade whose grant no longer matches is not dispatched to and is rebuilt. A capability already handed out through an open socket or handle cannot be recalled.

Granted is clamped to requested, and the code set is closed

Enforcement reads the granted set only, and the factory clamps it to the requested set at build time. Permission codes match case-sensitively against a closed list, and an unknown code fails the manifest parse. A required code must be present when a grant is first created, and removing a granted required code is refused.

Capabilities are present or absent, never nullable

Every gated capability is a sub-interface fetched from a bag and absent when its code is not granted. The root facade exposes no service provider, scope factory, raw data-protection provider or raw HTTP client factory. A plugin probes for a capability and degrades, and never catches an exception to discover a denial.

A running plugin is dispatched to through the checked accessors

Code that passes a running plugin to a request or background work gets it from the instance manager's checked accessors (GetPlugin, GetOutputPlugin(s) and the peer-callable, discovery and HTTP-endpoint lookups). They refuse unless the pinned plugin_instance generation admits the instance. GetLoadedPlugin skips the check and is for diagnostics, management listings and the data-frame router only. A start registers its instance only through IPluginGenerationGuard.TryRegister. This is what makes an acknowledged disable, edit or grant change hold on every path that reaches a plugin.

A component is built from the generation it begins against

An instance start or reload, a WebAssembly trigger arm and an alert-subscriber build read the plugin_instance row, its configuration revision and the type's plugin_grant state from the generation recorded by IPluginGenerationGuard.BeginBuild, not from PostgreSQL. A request that writes one of those rows does not start, restart or re-arm a component itself. The generation that carries the write does, on every replica. A component is published only through TryRegister or TryArm with the generation it began on.

No lock is held across a plugin's StartAsync or StopAsync

A plugin controls how long those calls take. Code that calls them holds no lock or semaphore across the call, and the instance gate is never held across an await, a plugin call or a database read. Instance lifecycle runs as operations on the instance's lane, and a caller that needs the outcome waits for it.

Boot never waits unbounded for one plugin's start

The boot pass starts up to four instances at a time and waits at most 30 seconds for one start before its slot goes to the next. The start keeps running and the replica's status report lists the instance as faulted until it ends. A plugin's StartAsync has its own 30-second budget, after which the host abandons the call and faults the instance.

Plugins hold no device state and lease before connecting

Every in-process plugin loads on every replica, so a plugin keeps no device state in memory. It takes the connection-ownership lease before opening a long-lived connection, polls it, and self-fences when it is lost. A probe failure counts as lease loss. Do not build a leader election on the broker or the distributed cache.

What the host keeps from a load context keeps the context

Host code that creates a PluginLoadContext and keeps something built from it (a factory, a registration, a record naming a plugin type) without keeping the context itself passes that object through PluginLoadContext.KeepAliveWith before storing it. A collectible context nothing references is finalised, and every later assembly load through it throws "AssemblyLoadContext is unloading". Key the host's own object, never a plugin Type, which would pin the context for the life of the process.

Plugin-derived state keeps the plugin id, never the plugin

A long-lived host component that holds state derived from a plugin (an observation holder, session, checkpointer, timer, cache or subscription) keeps the plugin instance id and load number and resolves the live plugin on every call through IPluginDataFrameRouter. It never stores the plugin object or any object, delegate or Type from the plugin's load context, and a resolve that finds the instance stopped or reloaded ends its work. A stored reference keeps the context reachable after the instance stops; operators see that as reeve_plugin_alc_retained_total (see the plugin host).

A plugin's entry, hash, signature and floor come from one resolver

Everything the host reads off a release manifest goes through PluginEntryResolver: the hash, signature and compatibility floor for every manifest kind, and the entry file for a native manifest. No other code reads dllAssetName, signature or minBackendVersion, so no two gates disagree. A release's build is chosen at load time by PluginBuildSelector from the declared builds, the running runtime and the host version.

The install order is fixed and non-bypassable

Hash verification, then the signature check, then anomaly acknowledgement, in that order. An acknowledgement satisfies only the last step, is bound to one release and one anomaly set, and triggers a full re-verification. There are no blanket acknowledgements. An unattended update that resolves an anomalous candidate parks and installs nothing. Every transition writes an audit row.

Only the vended HTTP client is gated

The egress guard covers the vended HTTP facade alone. A raw socket or a self-constructed client is ungated.

  • An empty host list denies all outbound HTTP. An empty device-type list means all device types.
  • Every resolved address is checked at connect. Loopback, link-local, carrier-grade NAT, multicast and unspecified addresses are always closed to plugins, and only an exact address on the operator's allowlist opens one. RFC 1918 and unique-local addresses are open for any granted host unless Plugins:Egress:LanOnlyThroughOwnerAddresses limits them to addresses the owner typed.
  • The same address rule covers plugin broker connections under mqtt.outbound. Reeve runs no broker of its own, and a connection that names no broker is refused.
  • Nothing recorded about a plugin call (call log, trace span, issue, blocked-egress row) carries text from the path or query, because webhook APIs put credentials there. Records name the host and either the template the plugin set or a keyed fingerprint.
  • Every refusal of the vended HTTP client is written to the blocked-egress log. An MQTT broker refusal is logged but writes no blocked-egress row.

A plugin cannot steer its own allowlist

A config field that a plugin's config: host token reads is set only by the owner, because the token grants whatever host the field holds.

  • The plugin's settings facade refuses, whole, a write that would add, change, empty or drop the field.
  • A config or options flow's value counts only when it equals what the owner typed into a same-named Text (or default-less Password) step field.
  • The host never fills the field from a declared default, and a token resolves only inside a running instance against that instance's own config.

A plugin contributes no frontend code

A plugin ships a configuration schema plus server-driven views rendered generically. Core handlers key on capability or kind, never on plugin identity. Author-supplied text is rendered quarantined and attributed to the author, never as product copy.

Published packages open their internals only to the host

A library package published for outside code grants InternalsVisibleTo only to the host assemblies declared in ReevePackageInternalsVisibleTo (Reeve.PluginAbstractions to Reeve.Infrastructure), never to a test assembly. REEVE0006 fails dotnet pack for an undeclared name.

Plugin contracts are append-only and move in lockstep

Never widen a compiled contract by appending to a positional record's primary constructor, which breaks every built plugin. Add init-only properties, and add a new facade query as a default-implemented member rather than a new sub-facade.

Widening a manifest vocabulary updates the parser, the enum-to-wire mappings, the spec hasher and its fixtures, the published schema, the consent axis, the client mirror and both path enforcers, with existing hashes unchanged. Raising the manifest contract line moves three values together: the backend version property, the shipped-component floor and the chart's application version. The stamp committed in Directory.Build.props must be a release version, never a prerelease.

Sidecars talk to the backend, never to the broker

A managed workload's control plane is a backend-terminated WebSocket session at wss://<host>/ws/workloads/{instanceId}, authenticated by a per-instance bearer token in the header. Sidecars hold no broker credentials and need one egress, to the backend. The manifest extension validator refuses a broker key on any workload. Reeve never creates or deletes a network or volume it did not make. It lists, inspects and connects only.

Wire contracts serialize through generated metadata

Every SDK package a plugin or workload ships with (plugin SDK, contracts, discovery, BLE decoding and the adapter-protocol packages) is IsAotCompatible and adds $(ReeveAotAnalyzerErrors) to WarningsAsErrors, so NativeAOT adapters work.

  • A contract bounds a string with [StringLength] and a collection with [MaxItems], never [MaxLength] or [MinLength].
  • Every record on the wire is listed in the package's source-generated JSON context.
  • A generic seam that binds by reflection carries [RequiresUnreferencedCode] and [RequiresDynamicCode] next to a JsonTypeInfo<T> overload.

Reeve owns what its workloads see, and the workload library composes only its two keys

The gateway URL, backend base URL, workload token, REEVE_API_SCHEMA, the reeve manifest extension and the adapter-session health mode belong to Reeve.

  • The bootstrap source never answers instanceId or specHash, which the workloads library composes, nor workloadHost:<id>.

  • The workload token's credential id is gateway-token and the env name is REEVE_WORKLOAD_TOKEN. Neither changes, or every instance mints a new token.

  • The trustedCaCertificates answer stays an UnhashedLiteral, so a CA list change does not roll every declaring workload.

Retained workload data is matched by label, never by name

Adoption, drift detection and teardown key on the workload-instance label, never on a reconstructed name. Critical retained data is never auto-deleted, and purge is a manual operator action. An adopted claim must exist or fail, so no path provisions a fresh empty volume in its place, and a retained name has at most one owner.

The workload settings are Reeve's rows

The orchestrator settings are read from integration.workload_settings (one jsonb document per feature) and the pause from core.runtime_settings. Every write takes the advisory lock WorkloadGatewaySettings_Writers, writes the rows and the pause, and appends the workload_settings change entry in the same transaction.

Devices and canonical contracts

The canonical vocabulary is closed and core-owned

Device types, capabilities, value kinds, enum tokens and units are a closed set of typed records in the shared contracts package. A plugin maps its vendor vocabulary onto it and cannot invent a capability. Never hand-edit the generated backend catalogue or client mirror. Regenerate both with dotnet run --project backend/contracts-codegen -- generate and commit them. The contracts-codegen CI job runs check and fails when a committed file differs.

Canonical device contracts are append-only

Canonical records grow by addition only. The capability-kind enumeration is stored by numeric ordinal in descriptors and scene actions, so never insert, reorder or reuse a member. A retired ordinal stays reserved. Never add a write-only capability key with nowhere to route.

The same holds for every enum stored by ordinal (CapabilityKind, DeviceType and others). Storage stays numeric even where the HTTP surface uses strings. Reads accept both forms and refuse an undefined value. An ordinal this build does not know is skipped and the rest of the device stays usable. Other persisted identity strings are frozen the same way, such as an alert fingerprint and the JSON naming policy of stored backup-code rows. Where no safe default exists the producer chooses explicitly: a cover position is required, and null means unknown, never 0 as closed.

Capability keys are contract identifiers

A capability key is a dotted path rooted at the lowercase device-type name, and a channel member is <type>.channels[<number>].<leaf>. The plugin assigns each channel an opaque integer number and a stable SourceId. Numbers are unique within a device, stable for the channel's lifetime, never reused for another SourceId and never derived from list position. Keys are persisted by scenes, automations and workflow blocks, so a rename is a contract-versioned change. Never make the bare channel-list key settable. A command against an index the descriptor does not declare is refused.

The availability descriptor is the only statement of what an instance exposes

Presence, controllability, render label and value domain come from the per-instance availability descriptor. Never infer support from a non-null typed member, since null can mean the device has not reported yet. A capability absent from the descriptor is neither rendered nor commandable. A re-declaration carries the whole descriptor, because the stored snapshot is replaced wholesale. The server validates commands against the declared domain, and clients render strictly from it.

A control that must hide diagnostics asks the capability's catalogue role (capabilityRole(key) in the SPA, CanonicalCapabilityRoles.Resolve in C#), never vendor property names.

Values cross the driver boundary already canonical

Every numeric value is in its canonical unit and every enum value is a canonical token from a catalogue-validated map. Vendor scales (millivolts, centi-degrees, mireds) are converted inside the driver. A canonical value with no declared wire form throws rather than being guessed. A state parser that cannot type a message returns nothing so the raw path takes it. A plugin-declared range outside the canonical range is dropped.

Unmapped vendor properties are an escape hatch, not a promotion path

A vendor field with no canonical capability surfaces as a structured unmapped property (vendor key, value type, value), readable and writable from raw-property paths and never consumed by typed features, scenes, triggers, dashboards or bridges. A reusable capability gets a proper contract change instead.

There are two ways to write to a device

POST /api/devices/{id}/canonical-commands carries a device type plus an ordered list of canonical capability assignments and is the primary path. POST /api/devices/{id}/raw-properties is the untranslated hatch for unmapped vendor properties. There is no free-form command endpoint. A plugin that has not opted in to typed commands makes the canonical path refuse the request.

Logical devices are the addressing layer

Automations, scenes, widget bindings, helpers, per-user grants, favourites, telemetry, history, device events, bridge exposure and mobile all key on the logical device. A device source is one feed from one plugin instance, addressable for naming, health and diagnosis. A logical device owns one or more sources and a failover policy. Merging is allowed only between sources of the same device type, duplicate suggestions are advisory, and nothing merges on a heuristic, because a wrong merge breaks every scene, automation and grant that pointed at the device. Merge and detach are operator actions that name their blast radius first. A command sent to a source bypasses failover.

State is stored per source

Each source's current-state row holds the canonical typed state (the only state non-plugin code reads), the raw vendor payload verbatim and that source's capability descriptor. Reading the raw payload above the source boundary is a layering violation.

A camera event's source does not matter

Host code that consumes camera events or motion never branches on which plugin, plugin type or instance produced them. Camera motion is decided only at the motion gate. camera.motionStarted and camera.motionStopped are published only by the gate, and only for a stretch recorded open in Redis, so every start has exactly one stop decision.

Realtime ordering rules

  • Ingestion is serialised per source. A state report older than the stored one does not publish its value to the realtime notification or either state feed, though telemetry still appends. The guard is a source-time monotonic conditional upsert under a row lock, so it also rejects an older write from another replica. A consumer that orders one device's state across replicas uses the per-source state version, never a capture time.
  • A plugin instance hands every realtime push for a device to the instance's realtime queue after the write commits. It never awaits a send or sends inline beside the queue. The queue is bounded, drops its oldest push when full and counts the drop, since a push is a hint the client can recover from and a reading is not.

A bridged cluster is declared before it is written

A Matter mapper that writes a cluster must have declared it on the endpoint plan, because an endpoint rejects a payload block for an undeclared behaviour and rolls back the whole frame. The two mapping directions cover the same attribute set, and an observer for an attribute the other direction also writes needs an echo guard. services/matter-bridge/test/mappingCoverage.test.ts requires the mappers to cover the canonical catalogue.

Data and persistence

One database holds everything

PostgreSQL with the TimescaleDB extension is the only persistent store: devices, accounts, permissions, workflows, scenes, dashboards, integration metadata, the audit trail and all time-series history. Redis holds ephemeral cache, sessions and queues only, and broker retained messages are advisory. Losing Redis costs a restart and no data. Any new high-write table is a hypertable, never a plain table.

Telemetry carries no foreign key

Telemetry hypertables hold the logical-device identifier as a plain indexed column with no foreign key, since a foreign key onto a hypertable is not viable at these volumes. Nothing cascades from a device to its telemetry, samples, state events or event logs. Removing a device aggregate means removing every key-less dependent first and then letting the real foreign keys cascade. A constraint violation is translated into a conflict response, not a server error.

A hypertable's key includes its time column

Every hypertable's primary key is the time column plus the surrogate id, because the extension rejects a unique index that omits the partitioning column. Hypertables, the continuous aggregate, its refresh policy and the compression and retention policies are declared on the model and emitted as typed operations, so any context that applies a migration registers the TimescaleDB provider. Realtime aggregation on the continuous aggregate stays off.

The schema is one migration, applied at boot under a lock

The host's schema is one migration, InitialSchema, in backend/src/Reeve.Infrastructure/Migrations with one model snapshot. It holds the operations EF Core cannot express: lower() indexes, the retention policy, workflow foreign keys and indexes, and the dashboards.view grant. The cluster, workflow and workloads libraries own their tables and histories. A host migration neither creates nor alters a library table, though it may add a key or an index on one, so the library chain runs first. The boot order is the cluster runner, the workflow migrator, the host migration, then the workloads migrator.

The API applies pending migrations at startup, then runs seeders. One replica takes the boot lock (BootLock, a session advisory lock) while the others wait and retry, so operators need no separate migration step. ReeveDatabaseInitializer refuses a database whose migration history holds an id this build does not know.

Raw SQL inside a migration is line-sensitive. The idempotent script rewrites any line whose first token is SELECT into PERFORM, unless the body starts with CREATE, ALTER or DROP. A SELECT that belongs to a larger statement (INSERT … SELECT, a CTE, a subquery) must not begin its own line, and a standalone SELECT some_function(…) must not share a body with leading DDL.

Hand-written SQL needs a reason LINQ cannot meet

EF Core is the only query translator. A statement is written in LINQ unless EF cannot express it:

  • advisory-lock statements and row locks (FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, FOR KEY SHARE, SKIP LOCKED);
  • INSERT … ON CONFLICT upserts, including the unnest batch insert, and UPDATE … RETURNING queue claims;
  • recursive and data-modifying CTEs, window functions and ordered-set aggregates;
  • a FROM-less read of the database clock and jsonb merges over jsonb_object_agg/jsonb_each;
  • statements against tables outside the context's model, ADO.NET that runs before the service provider exists, and catalogue queries, DDL and DML on TimescaleDB internals.

Such a statement stays SQL text, read through FromSql or Database.SqlQuery<T>. LINQ never moves work out of the database: no client evaluation and no load-modify-save of what one statement did, because a split compare-and-set is a race. An upsert never lowers to MERGE. Converting a statement to LINQ keeps its rows, lock mode and single-statement atomicity, and tools/sql-plan-compare compares both plans. A new sequential scan on a large table, more chunks touched, more round trips or a slower median means the statement stays.

Advisory locks

The host takes an advisory lock through Reeve.EntityFrameworkCore.AdvisoryLocks (AdvisoryXactLockAsync on the context's transaction, AdvisorySessionLock in BootLock), never a hand-written pg_advisory_* statement. The package throws outside a transaction, so a call site that may run on the in-memory provider keeps its provider guard. ObjectStorageGate stays raw.

The host passes its own keys explicitly: a SHA-256 name hash (BootLock.KeyOf, the *AdvisoryLock.Key classes) through FromRaw, and a prefixed text name through FromHashedText. A key already in use is never moved to a namespace. Namespace ids are part of the lock identity and are never reused or renumbered. A new namespaced key registers its namespace in the composition root.

Id Name Owner
1 reeve.host this repository
2 reeve.cluster the cluster library
3 reeve.workflow the workflow library
4 reeve.workloads the workloads library
21061 reeve.cluster.raw-keys the cluster library (its raw ASCII keys REEVCLOG and REEVMIGR)

No code takes a session advisory lock outside BootLock and the object-storage admission gate. A session lock outlives the work that took it and knows nothing of a fence or a drain, so a fenced replica would keep exclusive work while a peer takes it over. Owned work takes a cluster mutex (IClusterMutexProvider), and a short critical section takes the transaction-scoped form.

A lost race is told apart from contention only by DatabaseContention

Code that reads a failed save as "another writer got there first" decides it with DatabaseContention (Reeve.Infrastructure.Persistence): IsLostOptimisticRace for a concurrency-token loss and IsSerializationFailureOrDeadlock for SQLSTATE 40001 or 40P01 anywhere in the exception chain. A serialization failure or deadlock is not a lost race: retry loops do not retry it and the API answers 500. A catch of InvalidOperationException around database work excludes IsDatabaseFault, so an outage does not read as a domain refusal.

Device names change only through change tracking

A logical device is renamed or deleted by loading it and calling SaveChanges. That rules out a bulk ExecuteUpdate/ExecuteDelete on the set and raw SQL that updates, deletes from or truncates logical_devices. A write that must bypass tracking appends device:{id} to the change log in the same transaction. Only a captured or appended change reaches every replica, and a rename wakes the dependents that reference ${device.<oldName>.*}. A logical device is hard-deleted only through LogicalDeviceRemoval.

Backup is the infrastructure's job

There is no in-application backup, restore or whole-installation transfer. The operator backs up the database with their own tooling, and moving an installation is a database restore on the new host. See backup and restore.

Retention and destructive steps fail closed

Any retention window read from configuration is range-validated at startup, since a zero or negative value would erase the table at the next tick. A retention sweep repeats its expiry predicate in the final delete, so a row renewed after the candidate scan is kept. A destructive delete-and-swap is gated on an explicit changed signal, never on a row count, and an unresolvable upstream leaves the live data untouched.

A gate in front of a user-visible or safety-relevant effect (viewer slots, trigger cooldowns, window claims, baby-monitor alert checks, state freshness) admits on any answer it cannot act on and logs once. A step that deletes or rewrites durable data (the blueprint catalogue swap, the object-storage migration, the media-plane sweep, device-model rewrites) refuses on anything unconfirmed. Duplicates are preferred to silence, and inaction to loss.

Non-rollbackable side effects happen after the commit

An external side effect that cannot be rolled back, such as an object-storage write or a bulk statement that commits its own transaction, happens after the owning transaction commits. Where a bulk statement must be atomic with a later save, wrap both in one explicit transaction. A conflict pre-check is taken inside the transaction that acts on it.

Security-sensitive reads stay on the primary

The read-only context bound to a lagging replica is injected only into services classified replica-safe: analytics, device and location history, utility aggregation and high-volume browse listings. Authentication, authorization, security and rate-limiting reads, and every read-after-create, go to the primary. A revoked token or stale permission served from a lagging replica is a security defect.

Secrets at rest use purpose-isolated protectors

Each subsystem encrypts through its own data-protection purpose over a database-backed key ring shared by every replica. A purpose string is part of the data format, so changing one invalidates every ciphertext under it. The per-plugin purpose embeds the plugin type and instance. Never derive an at-rest key from the token signing key or by protecting a fixed value.

Only the key bootstrapper calls CreateNewKey with immediate activation, under its advisory lock, so two replicas never create keys neither can read. The application discriminator is the content root (/app/ in the image) and is never set explicitly, because changing it makes every ciphertext unreadable.

Every commit that changes a device ingest view reaches the cache

A device ingest view outlives a batch, so every commit that changes one is pushed to the ingest-view cache when the batch is flushed, not when the context is disposed, because the --migrate-only job has no Redis. Change-only telemetry is judged against the cluster's last values, never one replica's memory.

Host composition

Boot validates options before it migrates

Every ValidateOnStart registration and every other IAsyncStartupValidator runs before the first schema step, so a misconfigured host fails before it touches the database. A provider with no startup validator is refused, and so is one registered only under the synchronous IStartupValidator, which would make the host skip the asynchronous ones.

The migration job, a replica that migrates at start and the sweep run the same schema path in one order: the window check, then the cluster library's schema, then its version floor where one is raised, then the remaining chains in the order given in the schema section. The cluster schema comes first because the host's seeds are captured into its change log, and a seed written before those tables exist is lost to every peer.

One clock

The host registers one TimeProvider, the workflow clock, and code that schedules or ages anything reads it. A concern that must follow real time, such as the camera motion gate or media tickets, names the wall clock explicitly.

Hosted services stop in reverse registration order

A plugin-roll turn in flight releases its row while the cluster bus is still up, and requests the replica took finish before the cluster library publishes its draining row for peers to adopt. A hosted service that must finish before peers adopt the replica's work registers after the library's (ClusterHostRegistration).

Replica-local singletons are deliberate

A singleton that outlives requests on one replica does so by design. The accepted cases are the camera codec memory, the media plane's hardware probe and decorator, the repairs orchestrator and the helper coalescer's pending state. Anything else kept in one replica's memory is a multi-replica hazard. A mutable per-process coordination dictionary in the infrastructure layer is either propagated through the cluster or marked [SingleNodeState("<justification>")] with the reason it is safe on one replica.

The host never replaces the static logger

The host configures Serilog with preserveStaticLogger: true, so each host's pipeline is scoped to that host. A host that overwrites the static logger disconnects the sink of the host that started it.

Concurrency and multi-replica operation

No correctness-critical state in one replica's memory

Persist correctness-critical state to shared infrastructure. A local cache is fine only if it can be rebuilt from the shared store and tolerates a cold start. Never derive a cross-replica idempotency key from a per-replica stamp such as a capture time or a new row id: use the device-reported timestamp, or a hash of the raw payload, so the same event looks the same on every replica. Fleet-wide settings written at runtime go to the shared settings table, never to a file, because each pod has its own volume.

Access data is read from the access state

What a user may see or do is decided from the access state of the generation the action reads, through IConfigView<AccessState>. Device access goes through DeviceAccessContextProvider, and a feature service keeps no copy. The cached context is keyed by the state's version, so a change is visible as soon as the replica applies it. Entries also expire after Authorization:Cache:AccessContextTtl (default 5 s, at most 5 min), which only bounds how long a superseded entry stays in memory. The household time zone is the one input read live, from the home feature. A replica that does not serve refuses an access check and skips a push.

Exclusive work is placed by the cluster library

Every replica, a single replica included, is a member of the cluster library. Reeve keeps no membership table, elects no coordinator and keeps no assignment map. Work that must run on one replica is a unit kind registered with the library, which places it on one serving replica. Every kind needs an eligibility filter: a kind that skips in safe mode or needs a running plugin forbids the safe-mode capability (SafeModeCapability.NotInSafeMode), and a database-only kind takes SafeModeCapability.Anywhere. A periodic driver that must run once per cluster is a unit kind. Placement churn may cause a brief gap or a repeated attempt, never double execution. A unit with an effect outside the cluster checks its tenure before the effect.

Membership, liveness and each replica's build come only from the library's members. Anything that must tell one process of a replica from the next keys on ReplicaProcessIdentity.Local.ProcessId, never on the library's epoch, which also changes on an in-process fence and rejoin.

A per-key mutex is a held slot that its holder checks

IClusterMutexProvider is the per-key mutex. It lives for ClusterMutex:TimeToLive (default 30 s) and renews every ClusterMutex:RenewInterval (default 10 s). TryAcquireAsync answers null when the key is held or the replica is not serving, and a database error throws. Treat both as transient and retry. There is no re-entry.

Lost is final and never re-arms. It fires at fence step 0, at drain start, on a renewal answered Ended or NotServing, when the validity deadline passes, and on disposal. Code that holds a mutex checks Lost or IsValidAsync before each effect and releases when Lost fires. A mutex that read invalid stays invalid, so the holder acquires a new one. A crashed holder's key frees at its time to live.

The tenure contract

A tenure is a unit kind's ownership with its fencing token, or a held mutex. A holder cannot learn from the database in time that it lost a tenure, so the work is bound to the tenure and not the other way round.

  1. Lost is final and fires early: at fence step 0 and at drain start for a unit and a mutex alike. Every validity check includes it.
  2. Readmission takes a new tenure: a new placement and token for a unit, a new acquire for a mutex.
  3. A fenced member's tenures end at fence step 3. Nothing extends them.
  4. A draining member's slot stays held, and peers stay excluded, until its holder releases it or its renewal lapses.
  5. Database effects are fenced writes or compare-and-sets, so they never overlap. An external effect may overlap a peer's by at most its holder's bound, and every new holder states that bound where it acts.
Event Tenure ends A peer may take it
Fence step 0 (stalled renewal or fault) not yet, but Lost is already set no
Fence step 3 yes, at most 3 s after step 0, or within 30 s if the lease release goes unanswered a unit at the next placement pass, a mutex at its next acquire
Drain start a unit once its stop returned or after StopBudget, a mutex when its holder releases it after the release
Crash a unit at lease expiry (failover within 41 s), a mutex at its time to live yes
Pause, then resume the mutex reads invalid at once and the member fences as for a crash

How each kind of holder learns of the loss:

  • A unit with an external effect (the Matter bridge link, the OAuth refresh, alert delivery, the secret fetch) calls EnsureOwner() immediately before each effect. It can overlap a peer by one call in flight.
  • The applied snapshot executor, the plugin grant restore, the trusted keys revalidation and the object-storage migration use fenced transactions or compare-and-sets, plus EnsureOwner() before each effect. At worst one effect, reconcile or revalidation repeats.
  • Idempotent units and the trigger host rely on the stop token.
  • Workflow run locks and run slots are checked by the workflow heartbeat every 10 s. A run can overlap by 10 s of non-dispatch steps, and dispatch is refused from step 4.
  • Camera viewer and event-media slots renew every 10 s. A fenced replica is refused, and the fence aborts the socket at step 4.
  • The OIDC refresh lease is held for one provider call, at most IdpTimeout (10 s).
  • Plugin connections either observe Lost or poll IsStillOwnedAsync.
  • Plugin flows are not a tenure. Every step write and end is conditioned on the recorded owner and refused with FLOW_OWNER_BUSY otherwise.

Exclusive work stops while the replica is fenced

The cluster library stops every unit kind at fence step 0, and every held mutex fires Lost there. Everything else that acts for the fleet observes the singleton ReplicaEligibility, which is turned off at fence step 4. That covers plugin dispatch, the flow submit router and its relayed handlers, the device-model job worker and the trigger fire path. While it is off the replica runs no flow step, adopts no flow, claims no job or trigger fire, and hands no running plugin instance to a caller. Only ReplicaReadmissionHostedService turns it on again, after a Serving read of the cluster phase taken after the latest fence. Readiness is not an input.

A new periodic job is a unit kind (AddReeveJob). A new per-key exclusion is a held mutex. Any other new loop reads the eligibility flag before it acquires and stops when EligibleToken is cancelled.

A request from a peer over the member ask still reaches a fenced replica, and its handler decides: a flow step answers FLOW_OWNER_BUSY, a plugin holder call answers not-holder, and the recovery restart and the replica logs run. The Matter bridge's inbound-frame and live-state relays on the cluster bus have no fenced path.

A request that stays open ends when the host stops

An endpoint that holds a request open until its client leaves (a WebSocket, a live stream) ends on IHostApplicationLifetime.ApplicationStopping, not on RequestAborted alone. Kestrel waits for open requests before any hosted service stops, so one that ignores the stop holds the whole shutdown timeout on every rollout. Send a WebSocket a going-away close first and cancel its loops afterwards. A bounded response such as a download is not ended early, and a body cut for any reason other than the client leaving aborts the connection. ShutdownAwareRequest in Reeve.Api/Http is the shared helper. It is internal to Reeve.Api, so an endpoint mapped from a plugin or library follows the rule only by being written to it.

Postgres arbitrates ownership; windows are Redis claims

Every ownership and liveness decision goes through PostgreSQL, judged on the database's clock. A unit kind's owner is its row in reeve_cluster.owned with a fencing token, and a held mutex is its row in reeve_cluster.slot. A new at-most-once or concurrency-limit decision uses one of the cluster library's primitives, and each use states its store and what it does when the store does not answer.

Held slots on PostgreSQL are the workflow run slots, the camera viewer and event-media slots (they admit when the database does not answer) and the OIDC refresh lease (it refuses then).

Window claims (fire de-duplication, trigger cooldowns, the baby monitor's sound and test-alert claims) use the library's Redis claims with the Grant policy. They are taken per matching event, which does not justify a database write, and a silent automation during a Redis outage is worse than a repeated one. While Redis does not answer, every replica that sees an event runs it. A replica that is not serving wins no claim and takes no slot.

Some short-lived state lives only in Redis and expires by itself. The baby monitor keeps its sessions, claims, command stream and episode state there (see the baby monitor), and a loss makes the phone alarm rather than treat the evaluator as alive. The camera motion gate keeps its motion stretches and pan-tilt-zoom quiet windows there and reports no motion while Redis is unreachable. A plugin flow's state, owner and end are Redis state: a step write and the end it causes commit in one transaction conditioned on the stored owner, and SET … NX claims on configflow:tombstone:{flowId} and configflow:hookinvoked:{flowId} decide which end wins and who calls the plugin.

Coordination:Clustered alone switches on coordination only a fleet needs (the Matter live-state relay, the plugin roll's census, the host-build comparison, the observation-replication default, the device-model job recovery scope and the replica-id conflict check). Unset means off, and no declared replica count implies it.

Rate limits are not a cluster primitive. The named policies and the failed-login gate count in Redis on every replica count and fail closed. The workload handshake limiter is per replica. The workflow engine library is told it has peers at every replica count, so a host that leaves its run budget, fire de-duplication or run lock unfilled refuses to start.

A request to another replica goes through the relay port, sealed

A request one replica sends another (a flow step or end, a redescribe, the replica logs, the recovery restart, a plugin's holder call) goes through IReplicaRequestRelay. No caller asks a member directly. A request for a unit kind's holder goes through the library's keyed ask.

The library writes requests and answers to Redis in plain text, so they are sealed with ASP.NET Data Protection under the purpose Reeve.ReplicaRequestRelay before they reach Redis. A handler's failure reaches the library with no text.

ReplicaRunning alone decides whether a replica runs, because the library never deletes a member row. A target that is not running is not asked. A process-addressed send names its process, and the target answers gone if its own process differs. A flow is adopted only when its owner's process is gone, never on a roster fault or an unanswered ask, because a fenced replica is readmitted and its flows wait. Code that a unit or job handler can reach takes IClusterAsk lazily, because an eager one creates a dependency cycle that deadlocks host start without an exception.

Every process has one replica id and a role that can read replication

Every process, the migrate-only job included, resolves one replica id (REPLICA_ID, then Workflow:Engine:ReplicaId) and refuses to start without it. No component generates a fallback, since recovery, MQTT, the cluster library and the workflow store must name the same replica. The database is PostgreSQL 18 or newer, and the migration runner refuses an older server. The database role must be able to read replication state. Otherwise the library's replication check reports the view unreadable, /health/ready stays unhealthy and the probes restart the pod.

Configuration saves are captured into the change log

Configuration saves through the primary context are written to the cluster change log by the capture interceptor (UseReeveClusterCapture), which is registered after the other interceptors. ClusterCaptureMapping names every mapped entity with its aggregate type, key and counted columns. An entity or column not in it is not configuration. The host registers the capture through AddReeveClusterHost, and a hand-built test container adds AddClusterCapture(configuration) after AddInfrastructure.

Three rules apply to writes the capture cannot see:

  • A write that skips the change tracker (raw SQL, ExecuteUpdate, a setting stored as a blob row) appends its own entry through ConfigWrite, in the transaction that commits it, as the last statement before the commit. A write that joins an open transaction hands its entries to the committer. The append fails closed: its exception rolls the write back.
  • An ExecuteUpdate on a mapped type carries .AppendedToChangeLog() and appends its entry when it writes a counted column, a key, or any column of an all-columns type. Every ExecuteDelete on a mapped type does too. An update of runtime columns only (health, timestamps, values) needs neither. A context with the capture refuses an unmarked call.
  • A workflow write that creates, deletes or moves the current version of a workflow is a tracked save on WorkflowDbContext or runs in the editor's owned scope, which appends one keyless workflow entry before its commit.

Every hard delete of a logical device goes through LogicalDeviceRemoval.RemoveAsync, so the capture names the attached helpers beside the device.

Configuration-derived state is read through a generation

A request reads configuration-derived state through IConfigView<TState>, or IFeatureConfig<TConfig> for feature configuration, which answers the request's pinned generation. A write service calls EnsureWritable() right after its permission check. The trusted signing keys are the exception: every verification reads them from the table, outside any generation.

  • Background code that acts on that state runs one action per IConfigActionRunner.TryRunAsync call, which pins a generation and skips the action when the replica does not serve.
  • Readers that cannot skip, such as the ingest sink or the egress guard, read a singleton installed through TryActivate. Inside TryActivate only a reference swap or a dictionary write runs, and a view read there throws.
  • A view read outside every scope (workflow blocks, scripting, plugin facades) is an action of its own, so two such reads may answer different generations.
  • A component built from several state types takes one pin, builds from it, installs through DeferredActivation.ActivateAcrossTypes and rebuilds on a new generation of any input type. A deferred walk covers every key of its type, never only the changed ones.
  • Reconcilers read the database only through ReconcileDbContextFactory, which binds the pass's snapshot and refuses saves. A reconciler's constructor graph never reaches IClusterGenerations: it takes no IConfigView<>, IFeatureConfig<> or IConfigActionRunner, because the library builds its generation store from the reconcilers and a cycle deadlocks start.
  • GetInputPlugin and GetOutputPlugin answer the ambient scope's pin, so they do not tell whether an instance runs. Use IsInstanceRunning, or the start's own answer (StartInstanceWithResultAsync).

A configuration write is answered once every serving replica has applied it

A request that writes configuration is answered after every serving replica has applied the generation holding the write. Controllers get the acknowledgement filter from the library, and a minimal-API group that writes configuration carries AcknowledgeWrites(). Do not wait for a component a generation converges (an instance start, a trigger arm) inside a request or a reconciler, because a reconciler that waits for a slow component stalls the applier and fences the replica. The library refuses to start unless ReadIndexTimeout + ActionTimeBudget + AckTimeout < ProxyReadTimeout.

Plugin type registry writes happen inside the swap, under the type's gate

A registry write made by a generation's deferred work happens only inside TryActivate, through the RegistryCommit it was given. Everything that can fail or wait (the pull, the manifest gate, the module build) is prepared before. Every activation of a type takes PluginTypeActivationGate first, then its replica-local database lock, then the shared install gate. Nothing under WasmRegistrar's write lock or a lane gate calls the generation store. A native plugin's workflow block write goes through the activation's RegistryCommit after the instance starts, so new block code never runs against the old instance.

A WebAssembly install is hot-registered on peers through the cluster bus, and an uninstall deletes the replica's copy on disk so the boot scan cannot bring it back.

The plugin roll

stage.host.plugin-roll keeps its id, its placement after the library's version commit with ordinal 0, its reversibility (irreversible once entered) and its failing Down. Change its Up, never these. The library journals an update by stage id and reads that journal on whichever build leads next, so a build that does not register the id an update stands at cannot continue it.

Inside a plugin-roll turn, the reload guard and the WebAssembly installer ask IPluginRollFenceCheck before they raise a registration fence or replace the registry. The check refuses when the claim's renewal came too late (later than the lease minus one renewal interval), and a refusal ends the turn. The claim keeps two replicas from fencing at once.

Redis is mandatory on every deployment

Every host that serves requests needs a reachable Redis, whatever the replica count. Sessions, sign-in challenges, rate-limit counters, cluster coordination and the realtime backplane live there. Redis:ConnectionString has no production default. The process refuses to start when it is blank or when Redis does not answer a PING within Redis:StartupWaitSeconds (default 90). The minimum Redis version is 8.4, checked at start-up. No code path treats Redis as optional or keeps a per-process copy of Redis-backed state.

--migrate-only composes the host without Redis. Nothing it resolves may read the Redis options.

Redis keys can hold bearer secrets such as session ids. Redis diagnostics expose no keys, but Exception.Data["Redis-Message"] can contain one, so log sinks and enrichers must not capture Exception.Data unless they drop that entry.

Redis runs no server-side code

An operation that must be atomic in Redis uses one native command (GETDEL, SET … NX, SET … IFEQ, DELEX … IFEQ, EXPIRE … NX, ZADD XX) or a MULTI/EXEC transaction, with WATCH where a read value decides the write. Never use a Lua script or a Redis function, including through the raw-command escape hatch. A script is logic in a string the compiler and tests cannot see, it blocks the server while it runs, and it needs a script cache to recover.

  • A conditional transaction reports a lost race as false and does not retry. Retry in a bounded loop.
  • A condition check blocks a thread-pool thread, and a timed-out check reads as false. A path that admits on a Redis error, or runs per reading or per frame, must not decide with a condition. Use SET … IFEQ or DELEX … IFEQ for a compare-and-set on one key, and decide from what an unconditional transaction returns otherwise.
  • A write a retry may repeat must be idempotent. Keep a budget a retry touches as a set of ids, not a counter (ZADD NX to take, ZREM to release).
  • A native compare-and-set that replies "not written" means that only while no command retry (WithRetry) wraps the database.
  • Observation replication appends with a single unconditioned MULTI and no MINID or age-based retention, because stream ids carry no time and age-based trimming would drop a live long session.

The worker thread pool has a floor of sixteen threads

At start-up the backend raises the .NET worker pool minimum to ThreadPool:MinWorkerThreads (default 16, valid 1 to 1024) and keeps a higher minimum the runtime already chose. An out-of-range value refuses the start. The runtime sizes the floor from the CPU limit, one thread on a one-CPU pod, and adds threads only slowly. A few blocking waits at once, such as Redis condition checks, would otherwise stall every awaited Redis reply while the CPU idles.

Waiting for a dependency is not a failed boot

A failed boot counts toward safe mode, which starts no plugin. A dependency that comes up late, such as Redis loading its data or Postgres restarting, is not the build's fault, so waiting for it must not count. The start-up watchdog (Bootstrap:MaxStartupSeconds) measures only the backend's own start. A boot step that waits for an external dependency either runs before the watchdog starts or runs in the StartingAsync of a hosted lifecycle service registered between PauseStartupWatchdog and ResumeStartupWatchdog in ClusterHostRegistration. Hosted services start one at a time.

  • The cluster join is bounded only by Hosting:StartupTimeoutSeconds (default 300, range 30 to 3600). Start-up refuses a Redis:StartupWaitSeconds not at least 10 s below it.
  • The Postgres wait (Database:StartupWaitSeconds) runs before the host is built. It retries only transient failures (a refused, reset or timed-out connection, SQLSTATE class 08, 57P01-57P03, 53300). A wrong password or a TLS failure ends it at once. Its expiry exits 75 and is not counted. The operator commands do not wait.
  • Expiry of the other waits is a counted failed boot.
  • The chart's startupProbe covers the Postgres wait, the steps before the host starts and that timeout. The chart refuses a backend.postgresStartupWaitSeconds that does not fit.

Only a boot failure the database records counts

A replica's boot-failure streak lives only in its bootstrap.replica_boot_state row. A failure counts toward safe mode only when that row records it, as an increment of the stored count. A failure the database cannot take (unreachable, or not yet migrated) is logged as not counted, and the process exits 75 all the same, because safe mode withholds only plugins and cannot cure a database problem. No file, volume or other store may hold the streak instead. Nothing decides whether to count from the exception type.

A boot fails only before ApplicationStarted or by the watchdog. A fault after it records nothing and exits 0, because counting a crash of a replica that had served would engage safe mode for a fault a restart may cure. The streak is reset once every hosted service has started.

Readiness reflects hard dependencies and whether the replica serves

/health/live answers as long as the process runs. /health/ready is gated on the primary database, the safe-mode check and the cluster library's readiness check, which is healthy while the replica serves. Readiness reports loading.failed or activation.failing when a full load or an activation keeps failing. Cache, discovery and the read replica are degraded-tagged: they appear in /health/details but never pull the instance out of rotation. Alert on the details endpoint, not on readiness. Code that must react to the replica serving or not reads IReplicaPhase, never the readiness status.

Transport and proxies

Nothing in a deployment may depend on which replica a client reaches.

Transport identity is per replica, and nothing may depend on affinity

Every hub client opens its WebSocket without a negotiate call, so any replica can take the connection and the Redis backplane carries messages to the one that holds it. Nothing requires session affinity at the load balancer. Route messages by deserialised type, not per channel. Every broker client id is replica-unique, because the broker disconnects the older of two connections sharing one. Anything that depends on a retained snapshot stays broadcast, and a correlated request/response stream is never sharded.

Proxies resend only a 503 and read for at least ProxyReadTimeout

A balancer or proxy in front of the backend resends a request only after a connection error or a 503, only for an idempotent method, and never after a read timeout, because a request that timed out may have committed. Its read timeout on /api is at least Cluster:ProxyReadTimeout (120 s), otherwise a committed write is cut off with no 202 write_unconfirmed. The termination grace period exceeds StopBudget + ProxyReadTimeout + 2 × RenewTimeout (131 s), and Hosting:ShutdownTimeoutSeconds (default 204, range 5 to 600) is at least that. The chart's render guards check these, and deploy/scripts/balancer-retry-check.sh checks the shipped deploy/balancer/nginx.conf when run by hand.

Each replica owns its plugin install root

The directory Plugins:CustomPluginsDirectory names belongs to one replica, and no other process reads or writes it. A deployment gives each replica its own volume (a per-pod PVC or an emptyDir). The host does not coordinate disk writes between replicas. Object storage is shared and keeps cluster locks.

Rolling upgrades

A release rolls inside its window, and a full stop is kept for the rest

A release is installed by a rolling update when every build in the fleet is inside its window. A full-stop release, and a jump from a build below the release's ReeveRollFrom, stop every replica of the previous release before any replica of the new one starts. A replica refuses to start while a member outside its window holds a lease.

The window is the exact build unless the build stamps ReeveRollFrom in backend/Directory.Build.props. That widens it to every build at or above that version by SemVer precedence, build metadata ignored. ReeveRollFrom is a plain X.Y.Z without leading zeros and not above <Version>, or Reeve.Api.csproj fails the build. Rolling is supported only while the cluster library's mixed-version harness and the host roll harness are green for the window, and the rules in this section are followed.

The check runs before the first migration, in the migration job too. A refusal exits with code 76 and records its reason in the replica's boot-state row behind the prefix [window] without counting a failure.

The chart's cluster.fullStopUpgrade (default off) renders RollingUpdate on the StatefulSet and on a clustered Deployment. On, it renders Recreate on the Deployment and OnDelete on the StatefulSet. The migration Job is a hook that runs before the pods are replaced, so with the Job on the operator scales the backend to 0 first. Known gaps of the exact window are in upgrading. Compose or a custom manifest is the operator's procedure.

A change is measured against every build in the window

Every build in a window shares the database, Redis and the cluster, so a change to the schema or to a cross-replica surface (the frozen names, change-log types, status sections and REST responses; see the cluster) is judged against all of them, not only the previous build.

Class Examples Rule
Additive a table, a nullable column, a column with a database default, an optional message or response field, a new unit kind or change-log type ships as is
Gated a unique index, check constraint or foreign key an older writer does not satisfy, a new value in a column or enum older builds read, a new Ask kind, a replacement for an existing unit kind or claim formula reader and writer ship in release X, the writer turns on behind RequireVersionAsync(X)
Contract step a removal two releases
Full-stop release an index built on or a rewrite of a hot table, a renamed frozen name, the cluster timings in ClusterHostRegistration, a library bump the library's notes do not say rolls ReeveRollFrom set to the release's own core

A rewrite of data older builds read, and boot-time work in ReeveDatabaseInitializer (it runs on every new replica while older ones serve), need review. The reasons are concrete: an older replica acknowledges a change-log type it has no reconciler for and serves stale state, a reconciler that reads a dropped column stalls and fences its replica, and a key formula or channel name that differs between builds lets two builds win one event or hear none.

A contract step waits two releases and carries a marker

A contract step is a step of a host migration's Up, or of boot-time DDL, after which a build that predates it fails or reads or writes wrongly. These count:

  • a drop or rename of a table, column, unique index, unique constraint, primary key, schema, sequence or continuous aggregate
  • an AlterColumn that makes a column required, drops a required column's default, changes its type, narrows its length or changes its collation
  • the same written in migrationBuilder.Sql() (DROP, RENAME, ALTER COLUMN … TYPE, SET NOT NULL, SET SCHEMA), and any Sql() call that is not a chain of string literals

Additions, relaxations (DROP NOT NULL, a wider column), Down, and EF's own DropForeignKey and DropCheckConstraint do not count. A rename is an add, a copy and a later drop.

A contract step expands first: a build stops using the object (the expand, shipped in the build whose core is E), and the removal ships in a release whose ReeveRollFrom is above E. The migration carries one line comment // CONTRACT (expand X.Y.Z) with E as a plain core. While ReeveRollFrom is unset every upgrade is a full stop and the marker is only required to be present. Once it is set, E must be strictly below ReeveRollFrom. A removal in the release that stops using the object would break the build one release back, which still reads and writes the old shape.

A hot table is never rebuilt in a rolling release

A release that builds an index on, or rewrites, one of these tables is a full-stop release: the telemetry hypertables (telemetry.device_telemetry, device_event_logs, device_state_events, integration_events, media_plane_viewer_negotiations), telemetry.device_telemetry_hourly, core.user_locations, automations.webhook_invocations, the workflow journal tables and reeve_cluster.change_log. The build locks writes from every replica. A migration never builds an index CONCURRENTLY, because a concurrent build waits on every open transaction, a peer's wait for the migration lock included, and neither replica migrates.

A frozen name is renamed only by a full-stop release

These are shared between builds by name and are never renamed or reshaped outside a full-stop release:

  • change-log types and their key formats
  • owned-unit kinds, capability names and eligibility filters
  • Redis claim key formulas (cooldown:, fire:, babymonitor-sound:, babymonitor-test:) and held-slot keys
  • Ask kinds (including device.redescribe, recovery.restart, plugin.holder-call) and sealing purposes
  • the plugin connection lease key plugin-conn:<type>:<instance>:<resource>
  • the plugin.holder-call payload, including the typed DeviceCommand inside it. A holder refuses a field or enum value it does not know, so an addition reaches a holder only once its build knows it.
  • bus channels, hub types and method names, MQTT $share group names
  • the required fields of the reeve status section, the process-identity keys and the Data Protection purposes

A replacement is a new name, gated, and the old one goes by a contract step. A renamed unit kind runs twice, a renamed slot key excludes nothing, and a renamed hub type splits the backplane. Nothing compares the names automatically. The host roll harness (see end-to-end testing) covers a mixed fleet.

Releases and libraries

The SemVer core of a host build is <Version> in backend/Directory.Build.props. A release build takes its version from the tag without the v, and the release commit raises the core. Builds that share a core must be able to roll among themselves, so a change that is not additive lands in a release commit and is tagged. A hotfix release is cut from main, never from an older tag. A deployment names one released chart version from OCI, which fixes the chart and every image.

The cluster library keeps one release of overlap, so a window spans at most two adjacent releases of it. A library bump is measured against the library version of the build ReeveRollFrom names. When the library's notes do not say that jump rolls, the host release sets ReeveRollFrom to its own core. A bump of the workflow or workloads library inside a window needs the host roll harness green across that window, otherwise the release is a full stop.

Testing conventions

  • Integration tests run against real PostgreSQL/TimescaleDB, Redis and MQTT in containers. Never use SQLite or an in-memory provider for persistence or sessions there. A change to entity shape, mapping or keys runs against the integration tier.
  • A test asserts behaviour (a call returns, refuses, routes or converges), not a version pin, a naming convention or a constant's literal. A test that asserts a refusal pins the specific failure (error code or exception type), not just "it failed".
  • Unit tests use fake time (FakeTimeProvider, vi.useFakeTimers) or await a signal, never a fixed sleep.
  • Tests do not hard-code /tmp. Use a per-test temporary directory.
  • A latency or throughput bound carries [PerformanceFact] and runs only with REEVE_RUN_PERFORMANCE_TESTS=1.
  • End-to-end specs run serially against a reset database and an injectable clock, serve a built bundle and run without retries. See end-to-end testing.

Security

Permission codes are a closed core contract enforced in the service

Authorization is checked against string codes in backend/src/Reeve.Domain/Permissions/PermissionCodes.cs. A new code means editing the catalogue and its All collection, seeding a row and, if a controller names it in a policy attribute, registering the policy (an unregistered policy name answers 500 instead of 403). A code describes a platform capability and is never named after one plugin's protocol. The authoritative check is an imperative permission assertion inside the service, so a background runner or a second controller cannot reach the operation ungated. Policy attributes are defence in depth, and anonymous endpoints are a closed, deliberate set. A denial names the missing code in the server log and never in the response body.

Access is filtered in SQL, and an inaccessible resource is not found

Every read path over device- or scene-scoped data applies the accessible filter as a SQL predicate before counting and paging, because filtering in memory gives wrong totals and empty pages. A resource the caller cannot reach answers not-found, not forbidden, so no endpoint is an existence oracle. Sources inherit access from their logical device. One evaluator is shared by the domain check, the database-side filter and the point check, so list, detail and command cannot disagree.

A token can never exceed its owner

A personal access token's effective permissions are the intersection of a capability ceiling, the token's own scope and the owner's current permissions, computed once and never widened elsewhere. The ceiling (PatCapabilityCeiling) is a source constant in Reeve.Domain and must never read configuration. Interactive-only surfaces refuse any inbound bearer before the permission check.

Sign-in creates a server-side session record and an opaque HttpOnly, SameSite cookie, secure over HTTPS. There is no refresh endpoint and no client-held bearer token, so sign-out and password change revoke immediately by deleting the record. A token signing key and an initial administrator password must be supplied before first start. The backend checks the signing keys for presence and a length of 32 characters and the administrator password for presence only; no example values ship. The bootstrap credential is flagged must-change and issues a single-purpose change token instead of a session.

Every new session, PAT or user-status revocation path publishes the hub-revocation cluster hint after its durable change. Each hub connection and live camera stream records its credential and user in a replica-local index, and periodic revalidation is the backstop for lost hints.

Every outbound client is guarded

Register every new outbound HTTP client with the shared guarded handler, or it opts out of every egress control. The guard rejects non-HTTP schemes and embedded credentials and refuses loopback, link-local, metadata, carrier-grade-NAT and private ranges at TCP connect time, after DNS resolution, which defeats DNS rebinding. The inner handler never follows redirects, and the safe wrapper follows GET redirects only and re-checks the allowlist at every hop. The handler keeps no cookie jar, so a Set-Cookie is never replayed. Every refusal is written to the operator-visible block log with host, port and reason. A plugin's OAuth code exchange uses the plugin's own egress chain and grant.

Outbound TLS clients do not resume sessions

The backend sets System.Net.Security.DisableTlsResume (in Reeve.Api.csproj), so no TLS client in the process resumes a session. Every client the host builds that validates the peer's certificate also builds its SslClientAuthenticationOptions through WithoutSessionResumption(). A resumed session would hand the validation a cached certificate, and a server that reloads a short-lived leaf would be refused with NotTimeValid once the cached one expires.

Scripting is unsandboxed and the permission is the control

The workflow scripting block compiles and runs user code in process with full host privileges. It needs a dedicated permission held by administrators alone, checked at author time and again at execution against the workflow owner. In-process sandboxing is not achievable, so treat that permission as equivalent to deploy access to the host and never feed untrusted input into a script. Managed:Capabilities:CSharpScripting turns the block off. Any other user-authored expression surface (the tariff formula, for example) gets a hand-written parser, never a script host.

Sign-in rules

  • A passkey is never the only way in. The rule that every account keeps a way in counts passwords and live provider links only, because a passkey is bound to one handset. A sensitive ceremony needs a purpose-bound step-up token, plus the current password when the account has one.
  • Failed password sign-ins are counted in the rate-limit storage by source address, never on the account, because an account lock lets anyone lock anyone out. Wrong authenticator codes are the one count kept on the account, and backup codes and passkeys are never refused by it. The address is HttpContext.Connection.RemoteIpAddress after the forwarded-headers middleware, never a header or body field. A forwarded-header trust-list entry that does not parse fails the boot.
  • An operation that changes what an account can do or how it signs in writes its audit row in the same save. Audit metadata and logs never carry a plaintext secret: no challenge tokens, raw credential ids, session ids, setup passcodes, pairing codes or private keys. A line that must correlate a session across replicas carries a short non-reversible fingerprint.
  • Write roles through User.AssignRole and User.ReplaceRoles and status through User.SetStatus. The entity refuses to take the built-in administrator out of Active or give it a role set without Administrator, and BuiltInAdministratorGuardInterceptor enforces this at save (409 with built_in_administrator, and 403 for deleting the Administrator role). Writes that skip the change tracker (ExecuteUpdate, ExecuteDelete, raw SQL) bypass it, so do not use them on user, role and user-role tables.

Responses and headers

  • Only GET and HEAD responses of host controller actions outside /api/auth are compressed. A GET whose body can hold a secret (a token, a key, a pairing code, a raw configuration document, echoed request data, log or plugin-authored text) carries [NoResponseCompression], because compression leaks such a body through its length (BREACH). A reverse proxy in front of the API adds no compression.
  • Every backend response carries content-type-options, frame-options, referrer-policy, permissions-policy and a strict content-security policy, plus transport security in production. The static front end repeats them on the files it serves and adds none to a response it proxies. In the front-end nginx configuration a header directive is not inherited into a location block that declares any header of its own, so repeat every header in each such block. CORS origins are enumerated per environment, and credentials are enabled only with explicit origins.
  • API errors are RFC 7807 problem documents carrying the request path and a trace identifier. Destructive administration refuses with 409 and a machine-readable code (deleting yourself, deleting or demoting the last active administrator, deleting a role still in use). Cluster refusals (replica_not_serving, replica_fenced, replica_behind, write_refused, write_unconfirmed) use the same envelope with a top-level errorCode.

Whether a workload update escalates anything is computed server-side by comparing the recorded consented profile with one derived from the release manifest and the resubmitted parameters. The check fails closed on a fresh install, a missing profile, an added workload or any derivation error. Approving a privileged deployment, changing provider settings, force-adoption, revealing or rotating a workload token, and any parameter edit that widens a resolved host or device path all require the dedicated approve permission, which is close to node-root authority and is not implied by ordinary integration management. Every escalating mutation and live-credential return fails closed on a missing context, an unresolved principal or a thrown check.

Backend API and clients

OpenAPI

Every type reachable from a published route takes its OpenAPI schema id from its short name alone. Two published types with the same short name must not coexist: rename the one this repository owns. One collision aborts generation of the whole document, so /swagger/reeve/swagger.json answers 500 for every endpoint.

Request contracts are positional records with their DataAnnotations bounds on the constructor parameter, which MVC reads and Swashbuckle does not. RecordParameterValidationSchemaFilter copies them onto the schemas. SwaggerCliStartup registers what Program.cs registers for the document and must not drift from it. An endpoint moved to a minimal-API route keeps its URL and gets its refusals reattached by the host, because minimal APIs run no DataAnnotations.

Frontend contract mirrors are generated

Every frontend zod schema that mirrors a C# contract is generated by backend/contracts-codegen into frontend/src/contracts/generated/. A contract change regenerates the mirrors in the same commit, and no generated file is edited by hand. A tolerance (an optional or defaulted member, a loose enum) is a per-member override with its reason in the area file under backend/contracts-codegen/Areas/. A hand-written schema exists only where the frontend deliberately narrows a generated one, and it extends the generated schema. The contracts-codegen CI job fails when a committed generated file differs from a fresh run.

The backend writes a nullable member as null, never omitted, unless it carries an ignore-when-null attribute. The client mirror accepts the literal null, and the generator derives this from the C# member.

Web and mobile client rules

  • All web API traffic goes through the shared HTTP instance, and responses are parsed through schema validation. On mobile, every call and the realtime hub connection use one shared cookie-carrying client, because a second client has its own cookie jar and fails every call as unauthorized. Session material is held in memory or platform secure storage, never in plain text.
  • One teardown function clears the query cache, the view-mode cache and store, the dashboard draft and the editor canvas. It runs on sign-out, on any session-ending 401, on a failed bootstrap and on an identity swap. Any new session-scoped singleton or client cache that can name a device or a person joins it. An endpoint answering 401 about a credential inside an authenticated session is flagged as a credential re-check, so it does not sign the user out mid-dialog.
  • A value domain, unit spelling, failure message, availability verdict or capability ordering has exactly one implementation, imported by every consumer.
  • View mode is UX only. No authorization decision keys off it, and no client gates an affordance on a role name, since roles are renameable data. Gate on permission codes.
  • A live state push patches the existing collection item in place. On reconnect, invalidate the cached device-detail entries and refetch a device list at most once, at a random moment within a few seconds. Missed pushes are not replayed, and refetching per device or all at once is a thundering herd on a large inventory.
  • The frontend image serves nothing outside /assets/ as immutable or with a positive max-age. Cache-Control is written once, in frontend/nginx.conf. frontend/public/sw.js keeps the __BUILD_ID__ placeholder in its cache name, which the build replaces with a hash of the emitted files.
  • In frontend/nginx.conf and deploy/balancer/nginx.conf, every proxy_pass names an upstream (or an address literal), every named upstream server carries resolve, a lone server also carries max_fails=0, and the file declares a resolver. Otherwise nginx resolves a name once at start and a recreated backend answers 502 until nginx restarts.
  • The production frontend build, not a bare no-emit type check, is what proves the tree compiles.

Reachability is read from availability, not from the freshness label

A consumer decides whether a device is reachable from the availability field, plus the silent flag for a sensor or presence reporter. The freshness label is display only and is not an outage signal, and no client ages a reading itself. A device that reports on change is quiet when nothing happens.

Mobile

The mobile app is a read-oriented companion, split into a framework-free core and a thin platform head.

The mobile core carries no UI framework, and the head is proved on a device

The mobile core holds every view model, service and projection and references no UI framework assembly. The platform head holds markup and platform services only. Markup and platform defects compile clean and pass the machine suite, so run a mobile change on a device or emulator from a build that compiles its markup. Manifest attribute values and permission strings are verified on a real image.

Mobile is read-oriented, and critical actuation is confirmed

The phone monitors the house and sends simple commands. What it may change is a closed list: friendly name, favourites, room, scene activation, per-capability actuation and pairing. Complex authoring stays in the web client. Every actuation of a capability an administrator marked critical goes through the single confirm gate and shows a visible confirmation. The armed confirm stores the capability key and value, and the second tap dispatches the stored value. The critical flag is server-side data, never a name heuristic.