Data and persistence
This page describes where Reeve keeps its state, how the schema is created and changed, how time series are stored and read, how data is retained and deleted, and how the alert registry and the System status page are built on top of it. The rules every change must follow are in constraints: Data and persistence.
Stores
PostgreSQL with the TimescaleDB extension is the system of record: devices, accounts, roles, workflows, scenes, dashboards, integration metadata, runtime settings, the audit trail and all time-series history (rule). Redis holds ephemeral cache, sessions, queues and coordination state only, and broker retained messages are advisory. Blob-shaped state goes to the namespaced object storage, whose default backend is the same database.
- A database backup is a complete backup while object storage stays on the database; losing Redis costs a restart and no data. Anything that must survive a Redis flush lives in a table. With a filesystem or S3 object-storage provider active, its directory or bucket belongs to the backup too.
- PostgreSQL 18 is the minimum. The schema relies on features of that release, such as the builtin
pg_c_utf8collation behind case-insensitive room names andold.*in an upsert'sRETURNING. - Redis 8.4 is the minimum, and the backend refuses to start against an older server. The telemetry
last-value store uses the native compare-and-set commands of that release (
SET … IFEQ,DELEX … IFEQ); Redis runs no server-side code (rule). The Redis startup validator performs the version check. - Npgsql auto-prepare is off. The backend sets no
Max Auto Prepare, so Npgsql keeps its default of 0. With auto-prepare on, a statement whose first execution fails or is cancelled between parse and row description stays marked as prepared, the connection returns to the pool looking healthy, and the next use of the same SQL on it throws "Received unexpected backend message DataRow" (upstream Npgsql issue 6391), so an arbitrary later request answers 500. An operator who writesMax Auto PrepareandAuto Prepare Min Usagesinto the connection string gets exactly those values; the pool bounds the host applies leave both untouched.
Schema and migrations
The host's schema is one migration, InitialSchema, in backend/src/Reeve.Infrastructure/Migrations with one
model snapshot. It creates the tables, the hypertables, the continuous aggregate, and the refresh, compression
and retention policies. The workflow, workloads and cluster libraries own their tables and histories, and boot
migrates them in a fixed order: the cluster runner, the workflow library's migrator, the host's migration, then
the workloads migrator. The host's keys and indexes point at library tables, so the library goes first
(rule).
Migrations apply at boot, followed by reference-data seeders, the bootstrap administrator and repository seeds.
In a fleet one replica takes the boot lock (BootLock, a PostgreSQL session advisory lock on
its own unpooled connection) and initialises while the others retry every two seconds. After 60 attempts a final
unguarded attempt relies on the migration provider's own lock to serialise the DDL. An operator who wants schema
applied separately from serving traffic runs the API with --migrate-only, which initialises and exits.
ReeveDatabaseInitializer refuses to boot a database whose migration history holds an id this build does not
know.
A schema rollback is never a downgrade command. It is a restore from backup, or a hand-written procedure that reverses the specific object. During such surgery the migration ledger is left alone, so the database stays knowingly out of step with the model until the object is converted back.
Authoring rules
- Scaffold every migration into the infrastructure project's migrations folder with the pinned
dotnet-eftool. The model snapshot lives there and nowhere else, since a parallel migration namespace only invites a divergent chain. - A model change ships with its migration.
PrimaryModelMatchesMigrationsTestsfails when the primary model has changes no migration describes, andMigrationDesignerSnapshotAgreementTestsfails when the newest migration's embedded model differs from the committed snapshot, or when a script between two migrations would emit a drop that no migration in that range asks for. The workloads context refuses to boot on undescribed model drift. - Do not ship an empty migration as a marker, because it records a name in the ledger that lies about what ran. The exception is a migration whose snapshot is the point: one that stops mapping an object the database must keep because another context owns it or the previous release still reads it. Its class says so.
- A drop, rename or tightening is a contract step and carries its marker (rule). A hot table is never rebuilt in a rolling release (rule).
- No migration builds an index
CONCURRENTLYor records the annotation that makes EF scaffold one. - A seed literal sets every required property and writes the named enum cast, never a bare number. Omitting a property breaks the model's seed validator and fails everything that builds the model at once.
- Rows a migration inserts are not restored by a truncate-and-reseed reset, because the migration is already recorded as applied. A table seeded that way that the initializer does not recreate must be listed in the test reset's snapshot-and-restore set (the API integration factory and the end-to-end reset).
- Raw SQL inside a migration is line-sensitive under idempotent-script generation
(rule). Applying migrations the
normal way runs each body verbatim and is blind to both hazards. Only generating the idempotent script and
running it twice against an empty database (the first run provisions everything, the second is a no-op)
exercises that path, which
IdempotentMigrationScriptTestsdoes.
Time-series storage
Hypertables, the continuous aggregate, its refresh policy and the compression and retention policies are declared on the model and emitted as typed migration operations, not raw SQL bodies, so the model stays the single source of truth and the operations are inspectable (rule). Any context that applies a migration, every test factory and the design-time factory included, registers the TimescaleDB provider.
| Hypertable | Time column | Retention | Compression |
|---|---|---|---|
telemetry.device_telemetry |
RecordedAtUtc |
90 days | none |
telemetry.device_telemetry_hourly (continuous aggregate) |
hour bucket | 1825 days | none |
telemetry.device_state_events |
OccurredAtUtc |
90 days | none |
telemetry.device_event_logs |
OccurredAtUtc |
90 days | none |
telemetry.media_plane_viewer_negotiations |
StartedAt |
62 days | none |
telemetry.integration_events |
OccurredAtUtc |
none | none |
automations.webhook_invocations |
Timestamp |
none | none |
core.user_locations |
RecordedAtUtc |
30 days | none |
- Converting a populated table into a hypertable is irreversible in practice. Reversing it is a manual multi-step procedure (drop the foreign key, decompress chunks, de-register the hypertable, swap the composite key back, reverse the index and table renames, restore the foreign key) with a verified backup taken first and all writers stopped.
- Declare a continuous aggregate with the string-column overload. The generic overload stores the parent as an entity name and rewrites the view mapping during model finalisation, landing the aggregate and its policies in the wrong schema; forcing the schema afterwards scaffolds a null table mapping that throws the next time the model is built.
- A continuous aggregate's retention policy is written by hand in the migration, with the schema named. Every fluent route resolves the schema from the table mapping, which a view mapping leaves unset. Re-add that block if the migration is regenerated.
- Drop a continuous aggregate's policies first, in order: refresh policy, then retention policies, then the view with cascade. The extension creates an internal materialised hypertable and job rows that must be cleaned up together.
- Every policy added in a migration is dropped in its reverse operation, in mirror order, including a policy written by hand outside the generated body.
- A full aggregate refresh runs with the transaction suppressed. The extension rejects it inside a migration's transaction, so the "not in a transaction" warning at apply time is expected.
- A per-device read with
ORDER BY … LIMITneeds an index that delivers its whole order. With the limit known, TimescaleDB costs an ordered scan across chunks by its first chunk only, so an index needing even an incremental sort loses to a walk of the time-keyed primary key that filters every other device's rows. The device index is(logical_device_id, "MetricName", "RecordedAtUtc", "Id"), matching the keyset order ofGetSamplesAsync; location history pages by(RecordedAtUtc, Id)for the same reason. Compare bothplan_cache_modevariants withtools/sql-plan-comparewhen adding such a read. - No history hypertable has a compression policy. Adding one to telemetry means re-verifying the
idempotent insert below against compressed chunks on the deployed extension version, and
DELETEon compressed chunks (which the history sweep issues) needs TimescaleDB 2.11 or later.
First and last from LINQ
EF.Functions.First/Last come from the TimescaleDB provider (CmdScale.EntityFrameworkCore.TimescaleDB.Query)
and translate TimescaleDB's first(value, time) and last(value, time) inside a GroupBy:
EF.Functions.First(g.Select(x => ValueTuple.Create(x.Value, x.At))). The time may be any type PostgreSQL
can order. A null value stays null, so a nullable column needs a nullable result type; a g.Where becomes
FILTER (WHERE …), and a filter that matches no row gives NULL, so use a nullable result type with Where.
Only a GroupBy grouping is a valid source. OrderBy, or Distinct on a keyless entity, is refused with an
InvalidOperationException rather than translated to null, which would surface as an internal error; on a
keyed entity EF drops Distinct before the translator sees it. UseTimescaleDb() registers the translator, so
every context that runs such a query already has it
(rule). The jsonb helper functions translate only
inside a query or ExecuteUpdate.
Telemetry ingest
Telemetry is stored change-only and is idempotent by its row key.
- Row time. A row is recorded under the source's observation time when it lies within
TelemetryIngest:SourceTimeWindow(two minutes) of capture and of the series' last stored reading, otherwise under capture time. A bridge that republishes a device's state with an unchanged timestamp (Zigbee2MQTT does after a command) therefore stores a changed value under that earlier time. - Row id. The id is a name-based UUID (version 8 over SHA-256) of source, metric, that instant and the
value. Each ingest batch inserts its rows in one statement,
INSERT … ON CONFLICT ("RecordedAtUtc", "Id") DO NOTHING, which the extension accepts because the conflict target is the time-keyed primary key. Nothing extra is indexed per insert. - Change-only storage across replicas. On several replicas, change-only storage compares with the cluster's last stored value per series in Redis, and a reading without a usable source time is stored by the replica that first claims it for three seconds; the claim is keyed on the value and the value before it in that replica's stream, so a series returning to an earlier value is not taken for a copy. De-duplication fails open: with Redis unavailable every claim is granted, so an outage degrades to a row per replica, counted, never to a lost or delayed reading.
- Which replica ingests. Home Assistant discovery ingests on one lease-holding replica and ESPHome on
the connection owner, both timing readings at receipt. Zigbee2MQTT state is sharded across replicas only
when an operator opts in with
last_seenenabled, because the broker reorders a device's burst across replicas and only a device timestamp repairs it. - Batch window. After a batch's first state update arrives the sink keeps it open for
DeviceIngest:BatchWindow(20 ms, at most 500 ms) unless it is already full, so a queue holding 50 or more updates is written without waiting. Every state push, automation trigger and telemetry row is up to one window later than the report; zero gives drain-only batching.reeve_device_ingest_batch_sizeshows whether the window collects anything. - Source health and resolution. Unchanged source health skips writes for five minutes, then reasserts with a conditional write that changes the row only if the stored health drifted; a real flip takes the normal write and notification path, and an availability callback that did not change health emits no event or snapshot. Unknown source ids are cached for 15 seconds with a fixed entry bound, and adoption invalidates the key on every replica.
- Device state ordering. Device state rows carry the device-reported observed-at that the sink's monotonic guard reads, so round-robin reordering across replicas cannot write older state over newer.
- Limits. A series name is the series key and a
varchar(100), so an over-long name is refused (shortening would merge two series); an over-long value is truncated, because one bad value must never fail the save its batch shares. The device-event log is append-only observability written beside the realtime publish, never on its hot path, so a failure cannot break delivery; device-reported labels (class, zone, chime, plate) are bounded, and an over-long licence plate is dropped at ingest.
Analytics and charts
Each analytics query picks its backing store from the requested range: a window up to
Analytics:RoutingThresholdDays (7 days, inclusive) reads the raw hypertable, a wider one reads the hourly
continuous aggregate, a keyless entity. Bucket intervals finer than one hour therefore never reach the
aggregate. The aggregate is materialised-only and is not refreshed for the most recent hour, which keeps
the refresh job off the chunks where inserts land; realtime aggregation stays off
(rule).
- Statistics the aggregate cannot recompute are null for aggregate-sourced ranges: standard deviation,
median, percentiles, first and last. Callers needing exact values narrow the window. Count, sum, minimum and
maximum are grouped per series in the database, and the average is the sum over the count (weighted by
samples, not the mean of the hourly averages); the sum is computed in the database, so repeated requests can
differ in the last digits. Percentiles stay hand-written SQL, because
percentile_cont … WITHIN GROUPhas no EF Core translation. - Buckets use the database's
time_bucket, UTC-midnight aligned for divisors of a day. From the aggregate, a 6-hour or 1-day bucket is formed in the chart's own statement over the hourly rows (sum over count) on the UTC grid; a 1-hour chart reads the hourly averages as stored. - The series filter is one expression tree of OR'd (device, metric) clauses. Narrowing by device in SQL and rechecking pairs in memory would pull every metric of every listed device.
- Analytics honour a token's narrowed device scope; out-of-scope devices are dropped silently, since a single-device token could otherwise enumerate every device and numeric capability.
- Reads go to the read replica when one is configured and fall back to the primary.
What a chart series means
The chart response owns each series' semantics; the client does not rebuild it. Storage is change-only, so a setpoint has a few points and a quiet device has none, and no client-side rule can supply the missing rows.
- A reading the device declares controllable is
step: it is read from the raw rows whatever the window (the aggregate has no last value), each point is the last value of its bucket stamped at that report's own time, andcarryInis the last value before the window, stamped at its start. A device last heard before the window gets nocarryIn, and a step series older than raw retention is not drawn. The carried-in value is no reading: nothing that states a reading or its time uses it. - Every other series is
linearand keeps the bucket average. heldUntilUtcis the earlier of the window end and the newest report from any source of the device; it is null when the device has none, and always for an energy counter.bucketIntervalnames the aggregation grid in the database's own interval text (15 minutes); no client computes with it. The response carries no gap rule.
Three limits are known. The newest report is per device and over every source, not the active source's "last seen" the pages show, so the two differ only while a source that owns a metric is dead. A measured series is held at its last bucket average, not its last raw value. At 30 days the buckets are six hours, so a step series that changed twice inside one bucket keeps only the later report.
Counters
The server computes a counter's use once, and every consumer reads it. A series stored in an energy unit
is a cumulative counter, in any spelling the meter unit table knows (watt_hour, Wh, kilowatt_hour,
kWh). ChartSeriesSemantics.WattHoursPerUnit is the one test, and it gives the factor too: each reading is
converted to watt-hours before the arithmetic, so a series that mixes spellings is read correctly and use is
always in watt-hours. One function, CounterUse, holds the arithmetic, and its readings come from one feed,
CounterReadingFeed, for every consumer: the chart's use per bucket, the statistics row's use, the
consumption total behind the utility meters, the utility aggregation buckets and the usage that tariff
evaluation prices. The SPA decides nothing.
- Steps. The series is read from its raw rows with the last reading at or before the window start as the baseline. Each step between consecutive readings belongs to the bucket of the later one, so the use of a silence lands on the reading that ends it, and a window's total is the sum of its buckets.
- Resets. A fall to under half the previous reading is a meter reset, and the new reading is the use since
it restarted (a
CounterResetDetectedevent is raised). Any smaller fall, exactly half included, is rounding or a restated value: it counts no use and becomes the baseline. A negative reading counts no use and is not a baseline. - No gap. No step between rows, however long, breaks the line or is dropped. The spacing of a counter's rows is how long its value took to change, not how often the device reported, so an idle device and an unheard one leave identical rows; after an outage the whole use of the silence is drawn at the reading that ends it, and the total stays right. A gap break at twice the bucket would break at idle and drop the use at the reading that ends it, often the largest of a cycle; a server "unheard" signal has nothing to derive from, because the device's presence history is not stored. A real outage of a metering device is rare and is not modelled.
- A boundary reading closes its period. Counter windows and buckets are end-inclusive,
(from, to]: a reading stamped exactly at a boundary closes the period it ends (the meter reading at the end of a billing period belongs to that period) and is the baseline of the next. Adjacent windows(a, b]and(b, c]add up to(a, c]with no step counted twice. Chart buckets sit on the UTC grid. Other series (power, delta meters) and the statisticsmin,max,avgandcountkeep[from, to), so a statistics row'suseand itscountcover windows that differ by their edge readings. - Past raw retention. For a series with no raw reading at or before the window start, the hours before
its first raw reading come from the hourly aggregate's per-hour maximum. The row of hour
hholds the maximum over[h, h+1), which for a counter is the value as that hour closes, so it is read as a reading stamped ath+1. The baseline is the newest row withh+1 <= from; the window's readings are the rows after it up to the first raw reading or the window end, so adjacent windows meet on the same row and the hour holding the first raw reading is not counted twice. That is good to an hour at each edge; a reset inside one of those hours is not seen, and a reading exactly on an hour line closes the next hour. - Wide windows. A chart or statistics window wider than
Analytics:RoutingThresholdDays, whose points come from the hourly aggregate, reads itsusefrom the aggregate too: every whole hour the aggregate holds is one reading stamped at the hour's end, and raw rows are read only before the first whole hour and after the last aggregated one. A chart whose buckets are not whole hours reads raw rows. The same one-hour edge applies: a reading exactly on an hour line closes the next hour, and a reset inside an hour is not seen. - One connection. A feed reads raw rows and hourly rows from one database connection, never the primary for one and a replica for the other.
- A statistics
useis null when the readings cannot state one (fewer than two), not 0. The chart'suseand the statisticsuseare additive contract fields,initproperties rather than record parameters.
Limits that are not reconciled: two readings of one counter with the same timestamp are ordered by row id,
which is a hash, so the use between them is not defined; a fall to just over half, from a real restart late in
a counter's life, counts no use until the next rise. A utility meter follows its configured measurement kind,
whatever the unit, while the chart and the statistics follow the unit. Chart buckets sit on the UTC epoch grid
and utility buckets start at the request's from, so totals over one window agree and per-day bars need not.
Retention
Every daily-growing table sits in one of two regimes: a hypertable with a retention policy, or a relational table with a scheduled bulk-delete service. Two hypertables sit in neither (integration events and webhook invocations, see the table) and grow until an operator adds a policy. The workflow library owns the retention of its own execution tables.
Retention and compression intervals live in the migration. The matching application settings
(Analytics:RawRetentionDays, Analytics:HourlyRetentionDays) are descriptive only; nothing at runtime reads
them to enforce retention, the database job does. Change the policy in the database and update the setting to
match, or the configuration lies to the next operator. A retention window that the application does enforce
is range-validated at start-up (rule).
Audit retention is a scheduled bulk delete, not chunk dropping. The audit trail is a regular relational table with a composite index on timestamp and event type, queried by arbitrary filter combinations and exported, which suits an indexed table; chunk dropping would buy little at these volumes. A background service deletes entries past the configured retention once a day, starting at boot, so retention cost shows up as write load and table bloat: reindex and vacuum after shortening it. Exports stream rows straight to the response body and paginate by keyset on the composite ordering pair. Erasing one subject's entries has no product surface; it is a database operation.
Command cleanup (pending command timeouts and the old command-log purge) runs each minute on the replica that owns it.
Deletion and cascade semantics
Telemetry hypertables carry the logical-device identifier as a plain indexed column with no foreign key
(rule). Removing a device aggregate means hand-removing every
key-less dependent (current state rows, capabilities, command logs, cloud exposures, access overrides and their
time windows, scene device actions), then removing the aggregate and letting the real foreign keys cascade. The
device's history is the exception: the history sweep deletes it. A logical device is
hard-deleted only through LogicalDeviceRemoval
(rule).
- Foreign keys encode lifetime on purpose. A command log's source reference is nullable and set to null on delete, so command history survives the removal of one source and cascades away only with the logical device. Scene actions have no foreign key to devices, so an action outlives its device and the scene can show what it lost. A camera profile survives a deleted camera so the operator sees why it cannot run. A location fix has no foreign key to the reporting user, so it outlives the account. The logical device is the key of a location subject, so concurrent per-replica creation is safe: the loser's insert throws.
- Removing an aggregate cascades in memory to every tracked dependent. Eagerly including a child collection you did not intend to delete deletes it; rows that must survive are detached from the change tracker or recreated before the save.
- Removing the last source cascades to the device itself, and the response says which of the two happened.
- A capability sweep never deletes name-override rows. The only path that removes capabilities while the device survives is the stale-key loop after rediscovery, and an override for a currently absent channel is the intended steady state, not an orphan.
- Merge-suggestion rows have no foreign key to devices; they are deleted for both sides of the reference inside the same transaction as the device removal, or a suggestion could resurface pointing at a deleted device.
- Merging re-parents the sources and deletes the source aggregate. Per-channel names are keyed by the device, so they are removed and recreated under the target inside the same unit of work; the target wins any collision by construction, and a concurrent colliding write becomes a conflict response.
- Deleting a plugin instance hard-deletes every logical device whose sources all belong to that instance, with its command logs, scene actions, cloud exposures and per-device access overrides, and signals the history sweep. A device that also has a source from another plugin only loses that source. Removing the last instance of a plugin type also drops the recorded consent grant, so a re-install asks again and a hijacked plugin cannot reuse an old grant.
- Uninstalling the plugin type cascades none of this. It is refused while any instance exists, and removes only the installation record, the grant, the recorded consent, the artifact and the registry entry, so the destruction above stays behind the explicit per-instance delete.
- The platform-owned system instance is excluded from ordinary instance deletion: deleting it would take every manually created or service-reported device with it while the row itself is re-seeded on the next boot.
Device history sweep
Removing a device never deletes its history; a sweep does. A hard device delete (an instance delete, a plugin reporting its last source removed, or the operator removing the device)
commits the device, its merge suggestions and its small per-device sets in one transaction, signals the sweep and
returns. DeviceHistoryOrphanSweepJob is the only code that deletes telemetry, state-event and event-log history and
the hourly aggregate's buckets for a removed device.
Removal must cost time bounded by the device's configuration, not by the size of its history. These histories have no foreign key and can be millions of rows, so a delete on the removal's call path would either outlive the command timeout or hold the plugin's per-device lock, or the update lock during an uninstall, for as long as the history is long.
- The sweep wakes on the signal (a one-slot coalescing signal, relayed to peers over the cluster bus) and every ten
minutes, starting one minute after boot. One replica sweeps: the owner of the
device-history-orphan-sweepkind. - It finds devices with history but no device row by walking the device-id index. The hourly aggregate is a source of its own, walked through its materialisation hypertable, so a device whose raw rows have aged out still has its buckets deleted; buckets are deleted from the materialisation hypertable, not the view, and a later refresh does not bring them back because the raw rows are gone.
- It deletes in batches of a few thousand rows, each its own short statement outside any transaction, holding no
device or plugin lock. Limits are per table per pass so one backlog cannot hold up others. It checks cancellation
between batches and logs and skips an orphan whose delete fails. Batches are raw SQL: EF's
Take().ExecuteDelete()rendersDELETE … WHERE EXISTS, which PostgreSQL plans with an extra aggregate, so a batch is chosen through the device index and deleted by key, one device at a time. - A removed device's history is normally gone within seconds, not when the call returns. A wake sent while no replica owns the kind, or a replica that dies between the commit and the sweep, waits for the new owner's first pass, one minute after its tenure starts. Rows written for a device after its removal are orphans too. A failed removal signals nothing, and a live device's history is never an orphan's.
Refusals
| Operation | Refused when |
|---|---|
| Delete a device | It backs a utility meter, the only restricting reference to the device table. A raw constraint violation is caught as a backstop, so a newly added restricting reference cannot surface as a server error. |
| Delete a workflow | An automation binds it, a blueprint installation references it, or any execution state is non-terminal. Terminal execution state and suspensions are purged first, inside one transaction. |
| Delete a role | It is still assigned; the conflict names the affected user count. |
| Delete a user | They own a scene, automation, helper, workflow or workflow version. The first three are backed by a restricting foreign key; the two workflow counts are not (see below). Their automation folders, the fourth restricting reference, never refuse it: a folder is private to its creator, so the deletion deletes the user's folders as a folder deletion does, moving the automations and workflows filed in them to the root. |
| Delete, disable or demote the last administrator | Always. |
| Delete your own account | Always. |
A conflict pre-check is taken inside the transaction that acts on it (rule). A destructive host action requires an explicit confirmation field rather than defaulting to proceed.
The workflow tables are the deliberate exception. They carry no foreign key into auth.users: the owner and
author columns are plain uuids, because those tables belong to a library that must not know Reeve's identity schema.
For workflows and workflow versions the pre-check in AdministrationService is the entire refusal, and it is
check-then-delete, so a workflow created between the count and the commit outlives its owner. Such a row breaks no
read: every workflow query filters by owner, so an orphaned workflow becomes invisible rather than erroring. Closing the
window would mean serialising the whole workflow write path against user deletion. Debug sessions are removed
explicitly in the user-deletion path; their snapshots cascade, and neither removes the stored blobs.
Transaction and query rules
- Bulk delete and bulk update open and commit their own transaction and do not join a pending save. When such a statement must be atomic with a later save, wrap both in one explicit transaction; they enlist in an ambient one (rule).
- A claim that advances a state machine does not move past the state whose work is still running. Snapshot-then-copy pipelines need a distinct snapshotting state and a re-entrant claim, or a crash mid-snapshot resumes treating an incomplete set as complete.
- Check-then-insert is serialised by an advisory lock or backed by a unique index. Workflow names act as a natural key for demo seeding, so the seeder takes a transaction-scoped advisory lock before creating workflows. Advisory locks go through the package (rule).
- A unique-constraint violation that escapes a save is translated into a conflict response; without that arm it
lands on the generic server-error branch. Business logic is not retried; on the delete side, detach the failed
entries and re-issue the save once. A lost race is recognised only through
DatabaseContention(rule). - Pagination offsets go through the shared paging helper. A hand-rolled page-times-size expression overflows into a negative offset, which the database rejects as a server error and an in-memory path silently answers with the wrong page. A genuinely non-pagination skip opts out with a written marker.
- Batched exports paginate by keyset on the composite ordering pair, not by offset, so concurrent inserts and deletes cannot make a batch skip or repeat rows.
- A read filter never doubles as the persistence filter for a user-curated list. See user preferences.
- Hand-written SQL needs a stated reason (rule).
Model integrity rules
- Enums are stored as string names, never ordinals, so a reorder cannot change meaning. Where an ordinal is the
on-disk format (the canonical command value
kind, enum values inside a JSON column), it is pinned with explicit values and an append-only guard comment and covered by a literal round-trip test through the real serializer options; a reflective shape check is a tautology. A retired member stays reserved. - Some JSON columns carry no schema-version discriminator. A structural change to one of those types is silent, has no migration that can be written for it, and surfaces as null reads. Add a version field before changing such a shape.
- Case-insensitive uniqueness EF cannot express is raw SQL in the migration: room names
lower(Name COLLATE pg_c_utf8)per home, plugin type ids and auto-update subscriptionslower(PluginTypeId). The model carries the plain case-sensitive unique index only for EF's benefit and must not be "corrected" to match. Two partial unique indexes treat the NULL device-id scope as its own scope. - Columns arrive with defaults so builds in a window keep working. A column a newer build appends arrives with a default, and a migration re-snapshots existing rows. A retired column stays mapped and unread until a contract step drops it, so a replica of the previous build still works (rule). Domain entities may gain defaulted appended constructor members because they are built only in this solution; the mirrored plugin contract is closed.
- Onboarding and durable command rows carry a domain-controlled concurrency version, so two writers of one row cannot both win.
- Derived values are never stored as a column that could disagree with their source (revocation-derived state,
key-pair status). The consented deployment profile is stored verbatim as jsonb. Plugin update intents are written
only by guarded single statements, never
SaveChanges. - Bearer secrets are stored hashed only: workload gateway tokens and personal access tokens are SHA-256 hashes.
- Media-plane viewer negotiation rows hold flags only; table check constraints refuse an address.
- A helper that evaluates to no value stores why. A null result leaves the stored value, and the helper would otherwise silently serve its last good value.
The read replica
A second, read-only context (ReeveReadDbContext) may be bound to a lagging replica. It is registered without a
migrations assembly, so it can never drive schema changes, it inherits the same model, so drift between the two is
impossible, and it reuses the primary's model instance through a shared model cache key, so the process holds one
model. A save on it is refused. Every migrated service takes it as an optional trailing constructor parameter and falls
back to the primary when it is absent: unset the replica connection and everything works with no code change.
Routing is decided at the context type, not per query: one context per request cannot route individual queries, and authentication handlers write then re-read inside the same request, so a per-request switch is unsafe.
| On the replica | On the primary |
|---|---|
| analytics and hourly aggregate queries | everything else |
| device and location history, automation execution history | every get-by-id and detail read |
| utility aggregation, preview, meter and tariff reads | personal dashboards and tab configuration |
| browse-style collection lists: devices, scenes, rooms, shared dashboards | the automation list, the household home read |
Read-only is not replica-safe. Token revocation, one-time-code replay protection and session role sync are read-only, but a stale answer is a security defect, not a stale read; authentication, authorization, security and rate-limiting reads always go to the primary (rule). A feature service that performs an authorization lookup keeps that read on the primary too, since analytics take their access decisions through the access context, which reads the primary, while their reporting reads use the replica.
Every read-after-create target stays on the primary, which is why no read-your-writes stickiness is needed. Classify by semantics, not by HTTP verb: several replica-safe analytics endpoints are writes in shape only. The replica gets its own, smaller connection pool, and its health check is degraded-tagged and asserts the endpoint is in recovery.
A replica's copy of access data is derived from one state, not bounded by time. Access checks read the access
state of the cluster library, which a reconciler rebuilds in full after any access change, and a write is acknowledged
once every serving replica has applied it or fenced, so a revoked grant is honoured as soon as the write is
acknowledged (rule). A user's access context is cached
under a key that carries the state's version; AccessContextTtl (5 s) bounds only how long a context of a superseded
version stays in memory. A replica that does not serve refuses an access check with ReplicaNotServingException. The
push audience of a device is part of the same state; see authorization.
Object storage
Plugins and core subsystems get a namespaced object store instead of bespoke tables. This keeps plugin-owned SQL schemas out of the deployment's migrations, and opaque blobs out of relational tables nothing queries by content.
The surface is small and has no cross-key transactions, no secondary indexes and no content-aware queries: exists, get metadata, get and put bytes, open and put a stream, delete, list keys by prefix, and read the backend's limits. Concurrency is last-write-wins with no version precondition; pair it with a lease when mutual exclusion matters.
- Objects are addressed by (namespace, key). A plugin type's namespace is its raw
PluginTypeId, so deleting and re-adding an instance preserves its data. Plugins are trusted in-process code, so there is no hashing and no namespace authorisation in the store. Core subsystems use acore:prefix, which cannot collide because an install refuses a plugin type id containing:or made of one or two dots, and WASM registration refuses it again. - A key is at most 512 characters matching
^[A-Za-z0-9._/\-]+$, with slashes as logical paths. Key by the plugin's own logical identifiers, never by a plugin instance row id. - Sensitive objects are encrypted at rest with the data-protection key ring (database-backed, so replicas share root key material) under a purpose string that never changes once payloads exist (rule). The blob is opaque framing (version, key id, IV, ciphertext, tag) that callers round-trip through decrypt. A backend returns plaintext and a target re-encrypts when sensitive, so the sensitive flag travels with a cross-backend copy; losing it would silently strip encryption. A streaming size hint is passed only for non-sensitive objects, since sensitive ones are buffered whole.
- The streaming API is the right choice above roughly 256 KB.
Backends and providers
Object storage is a list of named providers. A provider has a name, a kind and that kind's settings; the active provider is state, not configuration. The kinds are:
| Kind | Default cap | Notes |
|---|---|---|
| Database (default) | 50 MB | Stores bytea in one buffer, so streaming is parity only; the read loop enforces the cap while reading. Bounded by large-object write latency and replication lag. |
| Local filesystem | 5 GB | Writes payload and sidecar to fsync'd temp files and renames them, payload first, so a failure leaves a stale temp file but never a half-written object or a desynchronised sidecar. Only a missing file reads as a missing object: a sidecar that cannot be opened or parsed fails the read, the listing and so a migration, and a write over a corrupt sidecar replaces it. |
| S3-compatible | 5 GB | The cap is where multipart upload becomes mandatory. The secret key is stored encrypted next to the provider. |
- The list.
dbis built in: always listed, with no settings, never edited or removed, and its name is reserved. Any other provider takes a name matching^[a-z0-9][a-z0-9-]{0,62}$, so two buckets or two paths coexist; a backend instance belongs to a provider name, not to a kind. Providers live incore.object_storage_providers(name, kind, settings without the secret, the secret encrypted under the runtime-settings purpose). The table is the change-log aggregateobject-storage: a list edit reaches every replica through the change log, and the singleton the gate and the backends read is installed by the reconciler's deferred step (and by the boot check). The gate and the backends read that singleton, the admin page and the refusals read the table under the migration mutex, andIFeatureConfig<ObjectStorageConfig>(feature keyobject-storage) servesEnsureWritable()and, when the feature is managed, the managed list. - Managed list. When the deployment declares
Managed:ObjectStoragethe list comes from that section alone: the table is neither read nor written, the reconciler publishes nothing, and the same singleton is installed from the section at boot and on every valid reload, so the gate and the backends read the managed list live (a changed credential, region or plain secret key applies on the next call, with no change entry). Add, edit and remove are refused withfeature_managed; switching, the migration and purge stay state and work on the managed list. The list must hold the active provider, the target of a running migration and the source of a finished migration that is not purged yet. The check needs the database: at boot, once it is readable, a list that fails it stops the host. The location of each provider that holds data (the active one, a running migration's source and target, the unpurged source) is recorded incore.runtime_settings(object_storage/provider_locations; kind, root path, endpoint, bucket, prefix and path style, no secret). The switch writes it in the transaction that creates the migration, the purge in the one that marks the migration purged, and the first start of a release that has no record writes it from the declared list or the stored rows. One function compares the declared list with that record, at boot in both modes and on every managed reload, and runs the same edit and remove rules as the API (the active provider's location, the target of a running migration, the unpurged source), so a location moved while the host was down stops the boot. A record that cannot be read stops the boot and refuses a reload too (storage_provider_location_record_corrupt); it is never rebuilt from the declaration. A reload reads the state from the database inside the migration mutex that switch, purge and the provider edits take, so a switch cannot commit between the check and the install. A change that fails is an invalid change that keeps the last list and raisesconfiguration.invalid, naming the provider and the rule and never a value. A change that meets a held mutex or a database that does not answer is retried on a timer with a bounded backoff until it applies or the files change. A provider that holds no data may change location or kind freely. Replicas converge file by file: while one replica has the new file and another the old, a switch committed on one is checked against that replica's list. A provider'sSecretKeytakes the three secret forms underManaged:ObjectStorage:Providers:<n>:: a plain value follows the file's reloads,SecretKey_FILEandSecretKey_REFare resolved at start. - State outside the list. The active provider (
active_backendincore.runtime_settings, a provider name), the migration rows (source and target are provider names) and the per-provider size caps (backend_caps). - Boot. An installation whose active provider has no definition does not start; the message names the provider.
- Location, not name, identifies data. A provider's objects live at its location: the filesystem root path, or the
endpoint and bucket with a prefix. Every rule that protects data compares locations. Two providers may not overlap:
the same endpoint and bucket with equal or nested prefixes (an empty prefix overlaps every prefix), or the same or
nested root paths after normalisation. Add and edit refuse an overlap (
storage_provider_location_in_use), switch refuses a target that overlaps the active provider, the migration engine fails a migration whose source and target overlap, and purge refuses a source that overlaps the active provider. Endpoints compare after normalisation: an empty endpoint and anyamazonaws.comhost are one endpoint, and the scheme case, the default port and a trailing slash are ignored. Spelling cannot see aliases (an IP address and a DNS name, a symlink, a bind mount), so the two destructive points also probe identity: before a migration copies (the engine, after the snapshot) and before a purge, a uniquely named object is written through the target (the active provider for a purge) and read through the source; when it is visible the operation is refused withstorage_provider_same_storage(a failed migration carries it in its error) and the probe object is deleted either way. The database is never probed. The source of the last completed migration keeps its location and cannot be removed or added again (storage_provider_purge_pending) until it is purged, but its credentials and region may be edited so a purge can be fixed; a purge marks that migration purged, and a second purge has nothing to do. The namesfsands3belong to the filesystem and S3 kinds (storage_provider_name_kind_mismatch), because the default size caps are keyed by name. - Refusals. Removing
db, the active provider, the target of a running migration or the source of a migration awaiting purge; editing the target of a running migration, the source of a migration awaiting purge, or the location (bucket, endpoint, prefix, path style, root path) of the active provider, while credentials and region may change; switching to an unknown provider, to the active one, or while a migration runs; aborting when no migration runs (storage_abort_nothing_running); adding, editing or removing any provider, any switch and any abort, while the replicas run more than one build (storage_mixed_fleet, decided withIHostBuildConsensus, failing closed when the fleet cannot be read). One pure decision function holds these rules. Every state conflict is a409with anerrorCodenaming the reason (storage_provider_active,storage_provider_in_migration,storage_provider_location_locked,storage_provider_migration_target,storage_provider_built_in,storage_switch_migration_running,storage_purge_nothing_to_purge,storage_busywhile another change or a purge holds the migration mutex, and the others in the same family); only a malformed request (a missing target,migrateExistingData: false) is a400. - API.
api/admin/storage(permissionhome.manage):GETanswers the active provider, the provider list (a secret is reported assecretKeySet, never returned) and a health probe;POST providers,PUT providers/{name}(an omitted secret is kept) andDELETE providers/{name};POST switchtakes{ targetProvider, migrateExistingData };GET migrationanswers the latest migration andPOST migration/abortaborts it, answering its new state. Add, edit and remove callEnsureWritable(); switching and aborting do not.
Caps are overridable per backend through the runtime settings store. An unknown backend name has an unknown cap, which callers read as "refuse", never as "no cap". Only the caps are cached per replica: they are invalidated when the migration history or the active provider changes and when the engine starts a run, and a malformed caps blob falls back to the defaults. Provider settings are read from the installed list on every call.
Every operation reads the backend from the database
Which backend serves a call, and whether a write may run, is read from the database by every storage operation (active backend and latest migration row in one snapshot), never from a replica's memory, so a lagging replica cannot write to the old backend after a cutover. The cached state is a hint used only for the synchronous size cap.
- Calls hold shared gate leases for the operation lifetime. General admission is held only while a call enters; writes also take write admission while entering and hold a shared write lease for the operation. Claim closes write admission and drains write leases; cutover closes general admission and drains every lease.
- Each admission hold is capped at half the storage-call wait timeout. A postponed claim or cutover is scanned again after a 3, 6, 12, 24, 48, then 60 second backoff, reset to 3 seconds after a completed attempt. Reads continue from the source while a claim waits on write leases.
- A joined transaction re-enters without admission through its transaction marker, and nested calls through an ambient marker; a joined lease reached from another context without that transaction may still wait for admission. A failed admission statement on a joined application connection is not recovered by the owned-connection cleanup.
- For the database backend the gate joins the caller's transaction, so object and lease commit or vanish together. Outside a caller's own transaction a call holds the gate on a connection from a pool reserved for storage.
- No statement waits on a lock: both sides try and retry, so PostgreSQL never queues a shared request behind an exclusive waiter, and a dead host's locks are freed once PostgreSQL drops its connection. The gate is one of the two places a session advisory lock may be taken (rule).
- Key listing runs under the lease but yields after releasing it, so a caller's own storage calls in the loop never wait on a backend switch.
Switching backend
A backend switch snapshots the source, validates every object fits the target's cap before a single byte moves (naming the first offending namespace, key, size and cap), then copies, verifies and flips in a single transaction. The copy step ends by deleting from the target every object the snapshot does not hold, so a target that still has objects from a previous migration (a provider switched back to without a purge, or one a failed migration left a partial copy on) mirrors the source at cutover and nothing deleted in the meantime comes back. Writes throw a defined migration-in-progress error while a migration runs; reads continue from the source. The old backend is retained until an operator explicitly purges it.
- A switch is refused when
MigrateExistingDatais false (data is never silently lost), when the target is not registered, when it re-points the same backend, or when a non-terminal migration exists. The migration row and the target configuration commit together, and each backend's configuration lives under its own key, so source and target coexist for the whole migration and resume and rollback still resolve the source. - The migration is a resumable state machine stored as text: pending, snapshotting, resnapshotting, copying, verifying, cutover, done, failed. Only done and failed are terminal, and any unrecognised value is non-terminal (fail closed). The snapshot is destructive, so entry uses compare-and-sets that change the value: a self-assigning compare-and-set gives no exclusion under READ COMMITTED, so snapshotting to resnapshotting is a value change exactly one racer wins.
- The owner's writes are fenced; its claim and cutover stay compare-and-sets. The owner of
object-storage-migrationwrites the snapshot's delete (in chunks of 5000 rows), each batch of 500 objects, each progress flush and every status save as a fenced transaction of its own, committing only while it holds the tenure, so a paused former owner cannot overwrite what the new owner snapshotted. The claim and the cutover hold the storage drain (admission locks for up to 30 seconds), which a fence bounded at 5 seconds cannot, so they are ordinary transactions guarded by a compare-and-set on the migration's status. The cutover marks the migration done and updates the runtime settings in one transaction, its status write before the flip: operations that resolved the source finish first, and every later one on any replica sees the target. A refused tenure ends the pass without a failure write; an unknown commit outcome ends it too, and the retry re-reads the row. - Fenced transactions need
transaction_timeout0 for the role, the database and the session; the cluster library refuses a connection with a non-zero value, which fails the boot migration. - An operator can abort a running migration from any replica, though only the owner drives it. The abort is one
conditional write that marks the latest migration failed (
Aborted by an operator.) only while it is unfinished, together with astorage.migration.abortedaudit entry naming source and target. It does not take the migration mutex, which a claim holds while it waits on the drain, and it is refused in a mixed fleet, because an older engine would overwrite the failed row. A migration that finished first is left alone and the abort answersstorage_abort_nothing_running; a cutover that is committing holds the row, so the abort waits for it and then finds it done. Every status save and progress flush of the owner, and the step before verification deletes anything (checked under the fence before each batch of deletes), is conditional on the row being unfinished, and the first one that finds it failed ends the pass without writing, so an owner that wakes up late cannot undo the abort or cut over. The owner also reads the row every 5 seconds while a pass runs and cancels the pass when it finds it failed, so a pass stuck in a storage call ends without waiting for that call. Writes resume on the source as soon as the row is failed. What was copied stays in the target until a later migration to it deletes it before verifying. - Verification that may be incomplete refuses cutover and leaves the rewind to an operator. Failures are recorded by a fenced write that never overwrites a finished migration. Purge deletes the source only after a done cutover. Starting a switch, claiming it and purging share a mutex, so a purge never runs beside a new copy.
- Each migrated object has a progress row holding its captured sensitive flag and plaintext size, so a non-sensitive object streams. Migration rows carry a database identity sequence, independent of replica clocks.
- The job drives the oldest unfinished migration on the owning replica, and a new owner resumes from the status it finds. A hosted service on every replica polls (up to 60 seconds) to warm the hint, invalidates the three per-replica configuration readers when the backend changed (a stale S3 reader misbehaves), and relays triggers to the owner.
What stays relational: structured per-field integration configuration surfaced in the admin interface, live workflow execution state (it needs transactional guarantees with other tables), helper configuration whose dependency tracking is relational by design, token scope documents queried with JSON operators, refresh-token families, the boot-state rows, and the hypertables.
Runtime settings store
System-level settings that are not deployment configuration (the active object storage provider and its cap overrides, alert
delivery) live in core.runtime_settings, a generic store keyed by category and key, rather than in
dedicated tables.
- A sensitive value is wrapped. It is JSON-encoded, encrypted with a data-protection sub-protector, base64-encoded
and stored as
{"$enc":"..."}. The blob is opaque, so callers round-trip it through the store's typed read; the whole-category read returns raw wrapped values without decrypting. The data-protection namespace separator never changes once payloads are persisted. - Writes are single upserts, so there is no select-then-write race; the last write wins. A malformed stored value is returned as-is rather than thrown.
- Nothing the boot needs is stored here. Recovery means changing environment variables, and a value saved from a page the boot reads could stop the next start; there is no in-app editor for configuration overrides.
User preferences
- The serialised custom-properties blob has its own size ceiling, because the string-bounds guard inspects only string properties and cannot see a dictionary.
- Favourites are pruned to what the user may see permanently, never with time windows. The client PUTs back what GET returned, so a favourite outside its access window would vanish from the read and the next save would erase it for good. A read filter therefore never doubles as the persistence filter for a user-curated list.
Onboarding and demo content
- Only the first member to finish onboarding sets the home. Home-level settings (name, time zone, locale, currency) are global to every member, so a second member must not re-stamp them and shift everyone's schedules.
- A member joining a configured household is stamped as having nothing to onboard, and the skip is stored, not re-derived: the derivation asks whether some other user completed onboarding, so deleting that account would bring the wizard back on an established household. The write is a convenience, so a vanished row does not turn a plain GET into a 500.
- The onboarding time zone is the client's own (IANA) and is persisted, so cron triggers resolve wall-clock
schedules in the user's zone; a blank value resets to
Etc/UTC. Language says nothing about location. - Demo content is seeded by a durable cluster command. Completing onboarding with demo content, and the Home
settings "Seed demo content" button, send a command of the kind
demo-content-seedand answer at once with its run id; the kind's owner runs the seeder. Installing the plugin and waiting on the simulator can take minutes, longer than a proxy timeout. A run whose owner is lost is run again (InDoubtPolicy.ReRun), every seeder step resumes from what the first attempt left, and one key serialises runs per owner. Any replica reads a run's state (queued, running, succeeded or failed, with the seeder's outcome and reason) from the command row, long-polling up to two seconds. Progress has no stage between running and the outcome. - Completion starts the run only after home and room edits are saved, so the run sees them. The onboarding run id
is derived from the user, so a repeated completion finds the same run; a Home settings run gets a fresh id. The Home
settings reseed is gated by
home.manage, not by onboarding state, so an operator who onboarded against a down simulator can recover; with no home there is nothing to attach demo content to. - The household's latest run is named by the newest audit row a start wrote (
home.demo-content.requested, oruser.onboarding.completedwith demo chosen), because the command store cannot list runs. A run is considered only for the command retention (24 hours) after its start, which keeps the read a short range of thecreated_at_utcindex; a run still in progress after that reads as none. "Newest" is the audit row's time, written from each replica's clock, then its id, so two starts on two replicas within their clock skew may resolve to either. A start whose audit write failed is not found until the next run. - Demo devices come from a plugin's own sync, never from database-only device rows, which would have no live integration source and fail telemetry and command paths silently.
Alerts and system status
Alerts are rows in the database, written under a lock and delivered through an outbox. The full contract (fingerprints, transitions, delivery fields, the System status page) is in reference: alerts.
Alert registry
An alert write takes the fingerprint's advisory lock. Every write to a fingerprint (raise, clear, acknowledge, snooze, silence, their reversals, snooze expiry and purge) runs in one transaction that takes the transaction-scoped advisory lock on the fingerprint, reads the row and its suppressions only after taking it, applies the domain transition function and saves the result. Two replicas raising one fingerprint at once produce one row and both increments, and the function stays plain C# that the unit tests and the store share. The change tracker is cleared once the lock is held, so the context is never shared.
- Only high-rate events are buffered. A kind marks itself
HighRatein the catalogue (events only: egress denials, certificate rejections). Only those raises wait in a per-replica buffer, merged per fingerprint into the highest severity, the newest payload and the summed count, and flushed every 10 seconds and at shutdown. Every other raise is written when it is made: a buffered condition raise could be overtaken by a clear on another replica and reopen an ended condition, and coalescing two severities would hide a rise above an acknowledgement. An event only loses time when it waits. - A count is a lower bound: a crash drops the buffered increments. An explicit operation first writes the buffered raises of its own fingerprint and no other; a transient failure of that write fails the operation, a permanent one is logged and dropped. A buffered raise that keeps failing transiently is dropped after five writes. Data and integrity errors (SQLSTATE classes 22 and 23, except a unique race) and rejected arguments fail identically on every retry, so they are dropped, not retried.
- A raise is validated when it is made, so a producer sees an error for a message that is too long or metadata that is not JSON instead of the buffer failing later.
- An alert naming a deleted plugin instance can never be raised again; sink ids naming instances are read under a lock, otherwise a deletion before commit would fail the caller's foreign key.
- A suppression covers its severity and every level below, for its fingerprint. It is stored at the alert's severity when it is set; a silence at Warning does not cover the same alert raised at Error, which needs attention again, moves its epoch and is delivered, and silencing again at a higher level raises the stored level. By silencing a problem at its worst the operator accepted it, so a milder form of it is no news. One suppression row per fingerprint and mode is enough. The Snoozed and Silenced lists are narrowed by the server, never on the client, so a page and its total agree.
- Maintenance runs on one replica. Snooze expiry and the purge of old inactive rows are the
alert-maintenancejob, run by the owner of that kind, each re-checked under the fingerprint's lock.
Alert delivery
Delivery is an edge test plus a delivery mark on the alert row. The raise that writes an alert also decides whether
to send it. A raise sends only when it is an edge (a new row, a higher occurrence, or a higher severity than the row had),
the alert is open, no suppression covers its severity, it reaches the operator's threshold (Warning, Error or Critical),
and the row's delivery mark (delivered_occurrence, delivered_severity) does not already cover it. Sending enqueues one
outbox row per selected sink in the raise's transaction, under the fingerprint's lock, and sets the mark.
A condition is raised again by every poll, so without the edge, turning delivery on, lowering the threshold or lifting a suppression would send every standing alert at the next poll. The mark keeps one occurrence from sending the same severity twice after an Error, Warning, Error sequence, which the edge alone cannot see. Delivery does not key on the attention epoch, which also moves when a suppression lifts or an acknowledgement ends, and it does not rely on the outbox key alone, since a standing alert has no row yet when delivery is turned on and a row purged after seven days would be created again. The unique index on (alert, occurrence, severity, sink) is a backstop.
- Only a raise enqueues. Lifting a suppression, a snooze expiry, an acknowledgement and a settings change send nothing; an alert suppressed when raised stays unsent until it rises or starts a new occurrence. The bubble already brings back an alert a suppression held, and a backfill would flood the sink the moment an operator turns it on.
- One replica sends. The owner of the
alert-deliverykind claims a batch and sends row by row. Each send first counts the attempt and extends the claim (a null answer means the claim was lost or the row is no longer pending, so it is not sent), and the dispatcher checks its tenure before every send, so a replica whose stop has begun sends nothing; a refused tenure ends the pass without counting as a sink failure. Delivery is at least once. - The dispatcher re-checks suppression just before sending and marks the row
Skipped. A condition that resolved before dispatch is still sent, with no damping of flapping; flapping is a known risk, not handled. - A failed send is retried and capped. It is tried five times, after 30 seconds, 2, 10 and 30 minutes, then marked
Failed; failed rows are kept seven days, and the Delivery box shows the time of the last failure. No alert kind is raised for a delivery failure. The sinks are third-party, so a failure is retried, and capped so an unreachable sink cannot keep a row alive. A sink not running on the owner ofalert-deliveryonly gets retries and then fails. - The text attributes plugin-written text to the instance: the title is the kind's display name, with the plugin
instance's name first for a plugin alert, and the message is capped before the page path is appended, so the path is
never truncated. The selectable sinks are the notification sinks running on the answering replica plus those already
selected, so a
home.manageholder sees sink display names without holdingintegrations.manage. A change writes the audit rowalerts.delivery_changed. There is no test-send button; the plugin page has "Send test".
Who sees an alert
Nothing a viewer cannot open is counted, listed or fetched. An alert of a kind filtered by a device, an automation
or a workflow is pushed as AlertsChanged to the alerts_user:{id} groups of the users who may see that subject, not to the group of
the kind's view permission, which would tell every holder that an alert about a device they cannot open exists.
- Device alerts use the viewer's device grants, then the personal access token's scope; a token that limits devices, or lacks the view permission of every such kind, never joins its user group and reads the list instead. A scene alert follows the scene read's rules.
- An automation alert is visible to the automation's creator, the rule every automation read applies. An alert whose automation was deleted, or whose creator is disabled or no longer holds the kind's view permission, is visible to every holder of that permission, so it can be acknowledged and purged. A workflow alert follows the same rule with the workflow's owner, matched by fingerprint.
- Resolving the audience costs queries per candidate user after every write of a subject kind. The purge of an old inactive alert and the cascade delete with a plugin instance send no push; an open list reconciles on its next read.
- Dismiss for now is per user. It hides the alert from the user's own bubble at its current attention epoch, in
core.alert_user_dismissals, and needs no permission beyond seeing the alert; a global acknowledgement would take it out of every user's count. An alert that comes back (a new occurrence, a severity rise past its acknowledgement, a snooze running out) gets a new epoch and shows again. Dismiss forever is the global silence and needs the act permission and a confirmation.
System status
System status is gated per box, with no page-level permission. Each tab and box shows to a holder of the permission
that guards its data over REST, and the navigation entry shows when the viewer may see at least one tab. A page-level code
would be a second authority that either shows a box the data endpoint refuses or repeats every per-box check. Acting
needs the kind's act permission; a viewer without it sees the item and no button. Two operators can therefore see
different partial pages. The devices box needs devices.manage, the key ring secrets.bind, and the Delivery box,
which is on the Alerts tab only, home.manage. A viewer with neither alert permission is told so rather than that none
exist.
- Each box derives Attention from the alerts filed under it plus, for some boxes, a fact of its own (unreachable
devices of an enabled plugin, a self-reported offline replica, a version split). A count is its own read, so a down
alert store shows as an unavailable box, not as "none awaiting"; the summary names silent replicas or failed boxes as
status incomplete. - The status line counts conditions that hold, not only alerts. It counts the alerts that need attention plus every
box in
Attentionon its own facts, at the severity of the worst open alert filed under the box (acknowledged, snoozed or silenced alike) and at least Warning, unless an alert needing attention under it already counts that much; if those severities cannot be read, such a box counts at Warning. It names the boxes inAttention. Acknowledging an alert stops its notifications, not the condition, and a version split raises no alert, so the only way to quiet the line for such a box is to fix its cause. The badge, tab counts and bubble count alerts only, so the line can count more than the Alerts badge. - The Version box lists versions and replica counts, never a replica name. A missing claim on a paused or observe-only workload needs attention, because the reconciler never recreates it. The Matter bridge has a gateway session but no workload row, so it is never linked.
- The page shows what needs attention within five seconds, and nothing else about storage. It reports workload volume capacity only. Database size, free disk, object storage and backups belong to the operator's monitoring layer, and a per-device availability list would bury what matters.
- An open Critical alert, or a replica in safe mode, shows a banner on every page for a user who may see it. In Advanced it carries the message (for safe mode the reason and the replicas) and a link; in Basic it is one line, "Reeve needs an administrator's attention", linking to System status, so Basic stays free of technical detail while an administrator still learns that the home is in trouble. The page's routes are not hidden in Basic, since view mode is presentation only and every endpoint checks its permission.
- An alert row links documentation only for a plugin's own https
DocsUrl. The catalogue's repository-relativedocsPathis kept but not linked, because the deployed image serves no documentation; the fix hint and the message carry what the operator needs. /health/detailsstays anonymous, reduced to statuses. It answers every caller with 200, or 503 when unhealthy (which includes a replica in safe mode): overall and per-check status and asafeModeflag. A caller whose session or token holdshome.managealso gets the safe-mode reason, the unresolved secret reference count and each check's description; a caller without it is never refused. Probes and external monitors read the endpoint without credentials, and a 401 would break them. A credentialed/health/*request takes the global concurrency partition, since it resolves a token.
Diagnostics buffers
The start-up log ring buffer lets the recovery view show why the host failed to boot even when the remote log sink is unreachable. The diagnostics buffer evicts until its entry and byte caps hold, but keeps a single oversized entry, because dropping it would empty the buffer exactly when it matters.
Backup and moving an installation
Backup and restore belong to the infrastructure, not the application (rule): the repository ships backup, restore and verification scripts, and the operator owns frequency, retention and storage. Moving an installation to new hardware is the same database backup restored on the new host; there is no whole-installation export or import. Workflows are shared by the per-workflow or bundle export, and automation patterns by blueprints. See backup and restore.
Verifying a change to the data layer
- The API integration tier boots the real application over containerised PostgreSQL with the extension, Redis and the broker, and the infrastructure tier force-drops and recreates a throwaway database per test and applies the real migration into it (rule).
- The in-memory provider cannot see provider-level breakage. It evaluates LINQ in C# and ignores transactions, foreign keys and column types, so a model-shape change can compile and pass units while breaking the real database. After any change to entity shape, mapping or keys, run the unit project and the integration tiers.
- Time-dependent behaviour is exercised by setting or advancing the injectable clock, never by sleeping. Poll for the transition or for a value only the operation could produce; a poll for a bare status can match the state that existed before it.
Behaviour that looks like a defect
| Symptom | Why |
|---|---|
| The hourly aggregate is empty on a new or restored instance | It is created with no data, and the refresh policy only backfills its offset window. One manual refresh starting a day inside raw retention (now() - INTERVAL '89 days' to NULL for the default 90) is the only refresh that scans the whole raw hypertable. Take the retention from the database, not from Analytics:RawRetentionDays: SELECT config->>'drop_after' FROM timescaledb_information.jobs WHERE proc_name = 'policy_retention' AND hypertable_name = 'device_telemetry'. Never refresh with an open start (NULL, NULL) on an instance that holds history: aggregate buckets older than raw retention have no raw rows left to recompute from, so the refresh deletes them for every device, and the history sweep leaves invalidations over that old range that make an open refresh act on them. An open refresh is safe only on an empty aggregate. A bulk backfill needs the same bounded refresh, and only data inside raw retention can reach the aggregate. |
| The aggregate disagrees with the raw table | The refresh policy excludes the most recent hour. Compare over the identical window with that hour excluded from both. |
| A metric never appears in the hourly aggregate | The aggregate holds rows with a numeric value only; text and boolean metrics are excluded by design. |
| Telemetry timestamps sit up to two minutes before or after the ingestion log line | The row is recorded under the device's own timestamp when it lies within TelemetryIngest:SourceTimeWindow of receipt; a clock further off is recorded at receive time. |
| A reading is stored twice during a Redis outage | Cross-replica de-duplication fails open; each replica stores its copy, and the duplicate is counted. |
| Disk grows without bound on a telemetry table | Two hypertables (integration events and webhook invocations) ship with no retention policy, and the application settings do not enforce retention; the database job does. |
| Audit cleanup spikes CPU rather than dropping chunks | Audit retention is a bulk delete on a regular table, so it bloats. |
| Replicas collide on start-up with duplicate-key errors | Several are applying schema and seed at once without the boot lock; the lock serialises them and the loser re-runs the idempotent initializer. |
| Devices and their history are gone after a plugin was removed | The removal was an instance delete: every source of those devices belonged to that instance, so the aggregates were hard-deleted and the sweep removed their history. Devices with a second source only lost that source. Uninstalling the type cascades nothing and is refused while any instance exists. |
| A removed device's history is still in the database | The sweep runs on the owner of device-history-orphan-sweep; without an owner the rows wait for the next owner's first pass. |
| The instance will not boot | After two consecutive failed boots it engages safe mode, with non-essential subsystems disabled and the Cluster tab of System status for recovery. Boot state is kept only in the database: a boot that fails because the database cannot be reached waits for it first (Database:StartupWaitSeconds), then exits uncounted. |
| The status line shows Attention while the Alerts badge is zero | A box is in Attention on its own facts (for example a version split), which raises no alert. |
See also
- Device model: what device state and telemetry contain.
- Cluster: coordination, unit-kind ownership, fencing and the object-storage contract across replicas.
- Workloads: retained volumes and the topology signal.
- Reference: alerts: the alert catalogue, transitions, delivery and the System status page.
- Operations: backup and restore, observability.