The canonical device model
Reeve models every device in a household through one closed vocabulary owned by the core. A plugin translates its vendor's protocol into that vocabulary and back. Nothing above the plugin sees a vendor key, token or unit.
This page describes the model and the rules of the device area. How a driver produces the model is in device-drivers.md. Rules shared with the rest of the system are in constraints.md.
Layers
| Layer | What it is | Addressable |
|---|---|---|
| Logical device | The thing the household owns, names and automates | Yes: the primary identity (api/logical-devices/{id}, api/devices/{id}) |
| Device source (physical device) | One feed of that device as reported by one plugin instance | Yes: own name, health, descriptor, state, commands, rename and removal (api/devices/sources/{sourceId}) |
| Driver | The plugin that owns the vendor translation | As a plugin instance |
| Vendor | The protocol on the wire | Never |
Anything a human or an automation targets stays logical. Anything that describes a feed is physical. Automations, scenes, widget bindings, helpers, per-user grants, favourites, telemetry, history, device events, the Matter bridge and the phone are keyed by logical device (constraints). A command sent to a source bypasses failover and is validated against that source's own descriptor.
Logical devices and sources
A logical device owns one or more sources and a failover policy. Each source owns its own current-state row, so two sources of one device never overwrite each other. Commands go to the active source only.
Failover reads the stored health value. The read-time presentation described under freshness never moves it. Active-source election has one implementation shared by every projection: equal priorities keep the earlier source, and a device with no active source reads as offline. A failover to another source of the same device is not a model change.
Merging and detaching
- Merge only within one device type. Two different concrete types conflict and the merge is refused.
Unknownon either side is the absence of a classification, so it stays mergeable. - Nothing merges by itself. Duplicate suggestions come from exact strong-identifier matches and are advisory.
- A merge deletes the merged-away device and everything keyed to it: scenes, grants, helpers, exposure and history. Merge into the device that carries the configuration. The target keeps its name and pin and wins every slot collision. The merged-in sources join after the target's own in failover priority, in their previous order.
- Detaching keeps the original id on the remainder and creates a new logical device for the detached source. The new device is named "(detached)" until the next discovery of its source, and inherits the pin when the original was pinned.
Removing a source or a device
- Removing the last source removes the logical device. An active device always has a source. Only a retired device has none, and it is removed without the one-source rule. The confirmation dialog and the response say which happened.
- "Is this the last source?" is decided under a
FOR UPDATElock on the parent logical device, so two parallel removals cannot leave a device with no source. A source a peer removed meanwhile answers like a secondDELETE. - After the delete commits, a plugin that implements the optional removal handler learns which of its sources an operator removed, once and best effort. Both removal dialogs show the plugin's own notice about what else the source stands for. See device-drivers.md.
- Removal never deletes history inline. Telemetry carries no foreign key (constraints), and a sweep removes it (data.md).
A down plugin instance holds its sources Offline
When a plugin instance is disabled, or fails to start on a single-node host, the host records each of its sources that is
not Offline as Offline and sets OfflineByHost on it. The instance's next successful start returns exactly the marked
sources to Online. Any health report, discovery or state update from the driver clears the mark first, so the host never
overwrites what the driver itself reported. A source held over a Degraded comes back Online.
- Session plugins. For a plugin whose workload declares
health.mode: adapter-session, the presence sweep marks the sources once the session has read absent on every tick for 180 s (InstallFenceMaxHoldSeconds+ 30 s +PresenceSweepSeconds). It skips any source reported on since that tick's read. A replica that takes the sweep unit over starts the grace afresh. A start lifts marks only while the session is up, and only for sources reported on at or after the live session connected. The reconnect snapshot lifts the rest, so a session plugin must report every device it knows when it connects. A device goes Offline within 210 s of a clean stop and 300 s of a crash. - Clustered fleets record an outage on a disable only. A peer may still run an instance whose start failed here, so an
instance that fails to start on every replica keeps its sources' last health. Several replicas with
Coordination:Clusteredunset or false is a misconfiguration the peer monitor reports. There, one replica's failed start takes the sources Offline for every replica. - A stop records nothing. A stop for a reload, an update or a host shutdown leaves health alone. A disable counts only once the instance's event sink is disposed. A read the sweep cannot make (a Redis fault, an unreadable manifest) writes nothing and ends the count.
Naming
Three tiers
A name has three tiers: what the driver reports, what an administrator set on the physical device, and what an administrator set on the logical device. Each page shows its own layer, and the pencil beside a device or channel name writes to that layer.
- The physical page shows
DeviceSource.FriendlyNamewhen set, else the driver's reported name, else the external id, plus the source's own channel names (DeviceSource.ChannelLabelsJson, keyed by canonical channel key). - The logical page shows the logical device's name and its per-channel labels.
- A physical rename shows wherever the physical device itself is shown and never as the logical device's name. To rename a device everywhere (Start, dashboards, automations, the phone, the Matter bridge), rename the logical device.
- The driver's reported name is never overwritten. It is listed as "Reported name" under the physical page's identifiers, and clearing a name restores it.
Naming a feed's channel does not rename the same channel on the merged device, and the reverse. A driver that renumbers its channels leaves stored names on the old numbers until they are cleared. A name can be set only on a channel the device reports and cleared whether or not it still does. Two administrators saving channel names of one source at the same moment can lose one save. Both writes leave an audit entry.
The logical name follows the primary source until a user renames it
A logical device records whether a user has set its name (friendly_name_user_set). Until one has, every discovery of any
of its sources sets the name to the reported name of its primary source. The primary is the source ranked first, not the
active one, because the active source moves with health and a name must not flap on every failover. A promote, reorder or
detach takes effect at the next discovery.
- A user rename pins the name for good. Resubmitting the current name pins nothing. There is no way to unpin short of the database.
- A stand-in name used when a plugin sends none is not recorded as the reported name. Neither is a name that only repeats the source's identifier. A name equal to the source's key is a real name, because an integration may key its devices by name.
- A plugin must report a device's real name or none. A placeholder it later replaces (a node number before an interview completes) renames a never-renamed device twice.
- A detached device takes its source's name only at the next discovery. For a plugin that announces only on change or restart that can take days, and the remainder can share the name meanwhile.
Area names
A vacuum's area has one name per logical device and area id (core.device_area_labels;
GET/PUT /api/devices/{id}/area-labels, the write needing devices.manage). The physical page reads and writes it
through its logical device, because an area belongs to the vacuum, not to a feed.
A name can be set only on an area the device reports (the allowed tokens of vacuum.selectedAreas) and cleared whether or
not it still does. The area id is the device's own token, matched exactly. A device the caller may not view, or one outside
the token's scope, answers 404 on both routes. A merge or a model collapse drops the replaced device's area names.
How a name is written
- Names change only through change tracking (constraints). One EF interceptor validates every rename the save makes and wakes the helpers a committed rename broke, so a new write site cannot forget either. Cluster change capture is registered after it.
- Device names have one writer. A metadata form that also carried the name would revert a rename behind a success response.
- Per-capability friendly names and critical-capability keys must hold no control characters and fit their column, so a bad value is a 400, not a database 500. The administrator's critical flags are saved in the same unit of work as the rename and its audit entry.
- Only excluding a sensor from a device type is refused when the device no longer has the sensor. Including it stays possible after the device lost it.
Room names are unique regardless of case
The unique index on rooms is ("HomeId", lower("Name" COLLATE pg_c_utf8)), so "Salon" and "salon", or "Łazienka" and
"łazienka", cannot both exist. Create and rename answer 409. Lookups by room name fold the same way (RoomNameFold in the
database, Room.NameComparer in memory). Onboarding's first room treats a unique violation as the room already existing.
A time-zone id is validated against the OS tz database and refused with 400 before it reaches the home aggregate.
The canonical vocabulary
Device types, capabilities, value kinds, enum tokens and units are a closed set expressed as strongly typed records in the contracts package: one record per device type, with nested typed sub-objects for multi-component devices. A plugin maps its vendor vocabulary onto that set and cannot invent a capability or a token. Adding one is a deliberate core change (constraints).
Device types
Switch, Light, Outlet, Sensor, Climate, Cover, Lock, Fan, SmokeCoDetector, GasDetector, Valve,
Coordinator, Siren, Humidifier, WaterHeater, Vacuum, SceneController, MediaPlayer, AlarmControlPanel,
Unknown, Camera, in ordinal order.
SceneControlleris stateless.Unknownis the absence of a classification.- Smoke and carbon monoxide share one record.
- A water heater reports its tank, not the room, so it starts excluded from room and home temperature averages.
Sensor is deliberately wide: one record with the curated set of home-relevant measurements plus one named typed toggle
per binary meaning (contactOpen, leakDetected, occupancyDetected, presenceDetected, motionDetected,
vibrationDetected, tamperDetected, batteryLow and the rest). Occupancy, presence and motion are separate slots and are
never collapsed. A new binary meaning is a contract change, not a free-form string. The long tail stays in
unmapped properties.
Safety detectors are their own types, not sensors. They carry endOfLife, faultDetected, muted, sensitivity and a
unified alarmState beyond a bare detected flag. Route detector notifications to the detector types, because operators,
automations and the UI treat life-safety alarms specially.
Value kinds
Every leaf member has exactly one canonical value kind.
| Kind | Backing shape | Example |
|---|---|---|
Toggle |
bool |
light.isOn |
Enum |
A token from a closed canonical token set | lock.lockState |
Number |
Numeric plus a declared canonical unit, range and optional step | light.brightness |
Text |
Opaque string, no option list | climate.workdaysSchedule |
Color |
Structured colour value | light.color |
Channel |
A list of per-channel sub-records | outlet.channels |
OpenEnum |
A string whose suggested options the driver supplies per instance. Any string is accepted on the wire | light.effect, fan.presetMode |
TokenSet |
A list of driver-supplied tokens, offered per instance like OpenEnum |
vacuum.selectedAreas |
OpenEnum and TokenSet have no canonical token set and no static option list in the generated catalog. Everything else
that looks like a choice is a closed Enum. An empty TokenSet list is a value, not an absent one: an empty
vacuum.selectedAreas means the whole home, so a driver never reports an empty set to mean "none".
The canonical state value is a kind-tagged union carrying one member. Enum, OpenEnum and Text ride the text member,
TokenSet the token list, and Channel carries no scalar value. A present but valueless capability (a light that is off
with no brightness) is null in the map, not absent from it.
Units, tokens, colour and ranges
Canonical units are a closed token set: celsius, percent, kelvin, watt, watt_hour, volt, ampere, lux,
hectopascal, ppm, degree, lqi, minute, day, count, microgram_per_cubic_meter, decibel, index, second,
fps, cubic_meter_per_hour, becquerel_per_cubic_meter.
Canonical enum tokens are lowercase and carry no vendor vocabulary. For example, lock.lockState is
{locked, unlocked, jammed, unknown}, climate.mode is {system_off, heat, cool, auto, dry, fan_only} and cover.state
is {open, close, stop}. Tokens avoid a bare on/off; the canonical spellings are system_off, stay_off and
stopped. Alternative spellings are accepted inbound through a closed alias table.
A colour value is sRGB-canonical: red, green and blue are always populated. Hue/saturation and CIE coordinates are carried only when the vendor reports them natively, with a marker recording which representation the driver treated as authoritative. All colour-space conversion lives in the plugin.
Ranges declared on the record are the type's bounds: percent 0-100, link quality 0-255, kelvin 1000-12000, an angle 0-360. Open-ended measurements (temperature, power, energy, illuminance, pressure) carry a unit and no range. Per-instance bounds come from the availability descriptor.
Capability keys and channels
A capability key is a dotted path rooted at the lowercase device-type name (constraints):
<device-type>.<property> light.brightness, lock.lockState
<device-type>.channels[<number>].<leaf> outlet.channels[1].isOn
The bracketed number is the channel number the plugin assigned, verbatim, with no offset. Do not assume it starts at zero:
channels[0] may not exist. A display that needs an ordinal derives it from the channel's position in the list. The bare
channel-list key is never settable, so command a specific member.
The generated catalog has a single Channel entry with no per-channel leaf keys. A per-channel command key is therefore
validated structurally: the base capability is present and controllable, the kind matches, and the number addresses a
declared channel. Channel identity across re-description is in
device-drivers.md.
Generated artefacts and append-only rules
The typed records are the single source of truth. The backend capability catalog and the frontend TypeScript mirror are generated from them (device-drivers.md). Records and the capability-kind enum are append-only (constraints). In addition:
- On every API and realtime boundary the capability-kind enum serialises as its member name. Only the storage converter is
numeric.
OpenEnumandTokenSetsit at the trailing ordinals for this reason. - Device-type ordinals are on-disk format, so a new type is appended after
Unknown, asCamerais. - Enum values persisted in descriptor-diff deltas are append-only, so a stored delta never changes meaning.
- A new canonical member is an init-only property, never a primary-constructor parameter. C# bakes omitted optional arguments into the caller, so widening a constructor breaks every already-built plugin (constraints).
- Every widening of the published contract or SDK surface is additive. An out-of-tree driver upgrades on its own cadence and simply never lists the new capability until then.
Per-instance availability
The canonical record says what a device of a kind could have. The availability descriptor says what this instance does have. It is the only thing the interface, the pickers and command validation read (constraints). It carries:
- presence: inclusion in the descriptor list;
- controllability: settable or read-only;
- the render label;
- the value domain: instance-narrowed enum tokens, or unit, minimum, maximum and step, or per-channel labels.
Never infer support from a non-null typed member. null does not mean "unsupported", since a device may not have reported
yet. A capability absent from the descriptor is neither rendered nor commandable even when the record field is populated.
Per-instance bounds are enforced server-side. A declared range that escapes the catalog's canonical range is dropped whole, because a vendor-scale range under a canonical unit label would lie.
An enum capability's instance domain is the driver's reported tokens intersected with the canonical set. When the
intersection is empty, the whole canonical set applies, so a driver still reporting vendor spellings gets no narrowing.
Reported tokens pass through the alias table first, as the command validator does. A blank or malformed stored
allowed_values_json means "unknown", not "nothing allowed".
A capability descriptor is replaced wholesale. A driver with a static capability set gets a correct descriptor from an accurate discovery record. Only runtime-conditional availability needs an explicit re-declaration, and it carries the whole descriptor.
Two things are overlaid on the descriptor at the read boundary and are never declared by a driver: the critical-capability flag (a household setting on the logical device) and the operator's per-channel names. Malformed stored JSON counts as no overrides.
Per-channel names on the logical device
An operator can name an individual channel of a multi-gang switch or outlet on the logical device. The override lives in a channel-label table keyed by logical device, root capability key and channel number. Clearing deletes the row. It is written through the device-metadata form and applied at read time over the descriptor's channel labels.
Capability rows cannot hold it, because discovery deletes a row whose key the vendor set no longer carries. Plugin-scoped storage cannot either, because the name would vanish when failover flipped the active source. An override for a number the descriptor no longer declares is kept and inert, and returns if the channel does. Labels are display-only: a channel's identity is its number.
Unmapped properties
A vendor field with no canonical capability is neither promoted into the typed model nor silently dropped. It surfaces as a structured unmapped property (vendor key, value type, value). It is readable and writable from workflow raw-property blocks and from the raw-property endpoint, and forwarded to the plugin untranslated. Typed features, scenes, triggers, dashboards and bridges never consume it (constraints). If a property is a genuine reusable device capability, add it to the canonical model.
Writing to a device
There are two write paths, each available on the logical device and on a single source (constraints):
| Path | Carries |
|---|---|
POST /api/devices/{id}/canonical-commands |
A device type plus an ordered list of canonical capability assignments |
POST /api/devices/{id}/canonical-commands/by-value |
Canonical keys and values. The kind of each value is inferred from the catalog |
POST /api/devices/{id}/raw-properties |
Untranslated vendor key/value pairs for unmapped properties |
POST /api/devices/sources/{sourceId}/... |
The same three, aimed at one source, with no failover |
- The by-value form is the only command surface a widget may reach. Raw-property writes bypass the typed catalog, so they are off-limits to widgets.
- Authorization runs before command-kind inference, so a caller without control access gets a refusal rather than a validation error that would reveal whether a key is a canonical capability. The controller policy on device routes is defence in depth. The service layer is the authoritative per-device gate (overrides, time windows, token scope).
- Scene activation dispatches through a privileged first-party executor that no interface, plugin or scripting code can reach. It skips the user's own per-device permissions and is fail-soft per action: it reports the dispatched count and the reasons for each skip. It uses a fixed refusal message, because that text is stored where scene or run readers may not be allowed to see the device.
- Preflight judges each assignment alone, so a caller who may control some of the targets dispatches those that pass.
Validation, idempotency and the error classes are in device-drivers.md.
Critical capabilities
An administrator can mark a capability of a device critical. Every interactive client asks before it sends a command that writes a critical capability: the web application through one confirmation dialog shared by device controls, tiles, room quick actions and custom widgets, the phone through its confirm gate (constraints). The question names the exact value, and confirming sends that value.
Scenes, automations, scripts, plugin-originated commands and API tokens are not asked, because whoever authored them has already decided. The server does not enforce the confirmation, so a client that does not implement it or a script can actuate a critical capability unasked. Every new interactive surface routes its sends through its client's gate.
State storage
Each source's current-state row carries the canonical typed state (authoritative, and the only state non-plugin code reads), the raw vendor payload retained verbatim, and that source's capability descriptor. The logical device surfaces the active source's typed state. State is per source because keying it per logical device would collapse multi-source reports to last-writer-wins (constraints). Reading the raw payload above the source boundary is a layering violation.
- Canonical state is read through one typed reader. It never navigates stored JSON by key. An unknown key, an absent capability, a kind mismatch or malformed JSON is a clean miss. Scalar accessors resolve scalar kinds only. Structured kinds such as colour are read off the typed graph. One implementation builds the flat capability map for both the HTTP assembler and the realtime sink.
- Camera capabilities are all optional, so an unset member stays absent. Write-only members read as a miss and stay in the catalog. No lock code or PIN is stored.
Ingestion order
Ingestion is serialised per source. The device-reported observed-at instant, not the ingestion time, feeds the monotonic guard, because messages can land on different replicas. A report older than the stored one does not publish its value to the realtime notification or to either state feed (constraints). Telemetry still appends, and availability and descriptor pushes are unaffected.
A telemetry sample is skipped when it repeats the last recorded value for the same source and metric at an instant no earlier than that one, because a delta-usage metric sums its series and one reading landing twice would be billed twice. A strictly older sample still appends, which is the backfill path. Source health writes are deduplicated on a short time to live.
Toggle and Enum changes are state events
An accepted update from the active source writes one DeviceStateEvent for each Toggle, Enum or OpenEnum capability
whose value differs from the state it replaced. Two replicas applying one flip write one row. The table keeps 90 days and
feeds the Basic drawer's Recent activity. A merged device records only its active source's flips. These values are not
written as telemetry.
Availability, health and freshness
- An asserted fault passes through. An explicitly reported Degraded or Offline health is shown unchanged. An Online source is presented as Degraded once the time since it was last heard exceeds its freshness window. This happens at read time only. The stored health and the failover routing that keys off it are untouched.
- Silence counts only for cadence reporters. Sensors, presence reporters, battery-budgeted types and position reporters
have a silence window (
Automations:Freshness:SensorLabelTtlSeconds, default 1800, andPresenceLabelTtlSeconds, default 900). A device that reports on change has none and is marked down only by driver availability. An operator's explicit window on a device overrides the type default. A non-positive window clears the override. The windows pushed to clients with the labels come from these options (null means the built-in defaults). - One label, computed once. The fresh/stale label is computed in one place for REST and SignalR, and the physical and
logical pages use the same last-heard instant, so their badges cannot contradict each other. Offline wins. No observation
reads "unknown". A device that is not Offline reads stale while its source's adapter session is definitely lost. "Silent"
(
SilentAfterSeconds, default one day) is a separate verdict. Clients read reachability from availability, not from this label (constraints). - The automation freshness gate suppresses only the side effect. State is always persisted. A state change whose
source-reported age exceeds
StaleTtlSeconds(default 120; 0 disables) is dropped at the trigger seam. A missing source timestamp is never gated, and the gate fails open on an unknown observed-at or a negative age from a skewed clock. - "Last seen" is the time of the last report. Source DTOs and the physical summary and detail publish the state row's
LastSeenAtUtc(andLastHeardAtUtc), falling back to the source row only for a source with no state yet. - Attention. A device needs attention when its active source's enabled instance lost its session, or no source is up and the host recorded Offline for an enabled instance's outage. A disabled instance's devices count nowhere.
Momentary events
Button presses and scene-controller activations carry no persisted state. They flow on a dedicated device-event channel and are readable from a read-only history endpoint scoped to the caller's accessible devices. A scene-controller button is a channel that exists only so each physical button is addressable and nameable. It has no value, so do not look for it in canonical state. A picker that offers only channels with canonical state is right for commands and wrong for a naming panel, which must reach every declared channel.
A device event goes to its viewers in one call. A replica that does not serve sends nothing. A removed device has no access
rules left, so a holder of devices.manage can read its events even if it was hidden from them while it lived.
Discovery
Providers emit candidates into one table with a stable identifier per source type, a time to live and a dismiss action. A plugin claims candidates by declaring matchers. A matched candidate pre-fills a suggested plugin type so the operator can create the instance in one action. Nothing is auto-instantiated.
- Matchers. Typed matchers for a candidate's type win over typeless ones. Typeless matchers run as a fallback in declaration order, so a plugin can claim candidates from a source the core knows nothing about. A typeless matcher's criteria are case-insensitive equality on metadata keys. A typed matcher ignores criteria keys it does not know. The criteria are listed in reference/discovery.md.
- Privacy. Only an allowlisted set of metadata fields is persisted, in the stored record and in the audit trail alike. Raw mDNS TXT records are never stored (only host, port, name and type). Hardware addresses are hashed or masked.
- Trust. An invalid inbound envelope is dropped and logged with its rejection reason. Node hardware inventory accepts
only absolute
/dev/paths. A workload reports only paths inside a host path it was consented to inspect (the Discovery Host's/dev/serialand/dev/dri). Other records are dropped with a warning. - Freshness. Candidates are deduplicated by type and identifier. Hardware inventory is idempotent on node name and device path. Freshness is stamped from the backend clock, never the publisher's observed-at, because a node running ahead would keep dead devices fresh. A wizard is not offered a vanished path.
- Replicas and cleanup. Workload-session candidates wait in memory until the next scan, at most 1,000. Past that a new candidate is refused and counted in a warning at the next scan. The daily cleanup removes expired candidates after a grace period, so a rediscovered one does not flap.
- Scans are operator actions. Manual scans are rate-limited per user. A scan is not a polling mechanism.
Device onboarding sessions
Onboarding (commissioning a new device through a plugin, for example a Matter pairing started from the phone) runs as a session.
- Sessions live in a durable PostgreSQL store, so any replica can advance a session another created. A session is returned only to its owner. A missing id and another principal's id both answer 404.
- Routing is by the stored kind and plugin instance id. There is no default provider.
- Cancel is legal only from Pending. After Commissioning the device has joined the fabric, so a cancel answers 409, which the phone treats as unrecoverable.
- The service never creates a device row. It records the commissioned node. Device sync creates the device, and the session becomes succeeded when the device row matches.
- The commissioning passcode is never logged or persisted.
- Sweeps fail a session never commissioned past the adapter timeout (Retryable at the soft deadline, Terminal at the hard one) and one commissioned but never correlated. A node that reached the fabric but could not be recorded is Terminal, so clients stop re-pairing paired hardware.
Device model changes
A reported model applies at once
Every descriptor change a plugin reports (by discovery, a capabilities-changed report or a rediscover) is applied immediately. It is recorded as a model event when structural and followed by revalidation of everything that references the device. Nothing is held for approval and there is no preview.
A breaking change holds back the dependent automations, through error findings and the model-disable reason, never the descriptor. An operator repairs the automation and enables it. The device view shows the diff after the fact. Operator procedures are in troubleshooting.
A unit change is judged on canonical spelling: Wh and watt_hour are an alias, not a change. A scan counts only changes
that hurt. An added or newly controllable channel breaks no Home-app routine.
A type change re-homes the source
When a source reports a concrete device type different from its logical device's concrete type, the host detaches that
source into a new logical device of the reported type, even when it was the only source. The new device inherits name, pin
and room but no references. A merged device keeps its other sources and revalidates. Unknown is no type: a single-source
logical device of type Unknown takes the reported type in place, and a multi-source Unknown device is refused as
ambiguous.
A device left with no sources is retired, not deleted. It keeps its id, name, room, history and findings, records its
replacement, stays unavailable and accepts no commands or sources. References to it carry a device.replaced error, so
their automations stay disabled until one of these happens:
- the operator repairs the references;
- the operator deletes the retired device, after a warning that removal lifts the blocks;
- the source returns. A source that reports its previous type again returns to the retired device.
Retention deletes a retired device only once nothing references it and DeviceModel:EventRetention has passed since its
retirement. It never lifts a block by itself.
Collapse and renumber
When a plugin reports a structural model change that replaces sources, the model gate applies the descriptor and, in the same transaction, the collapse it carries: replaced sources are removed and references move to channels of this source's device. A mapping that cannot be carried still removes the source and leaves the references to findings. A bare list of replaced sources names no channels and is acted on only when one device can take their place. A renumber rewrites only vacated numbers and never leaves two labels on one channel.
- The new device inherits the stricter of its predecessors' access restrictions. An exposed row replaces an unexposed one.
- Dashboards follow a collapse only for device widgets. Chart series keep the old device, which holds the history. A helper name clash is left in place, never renamed.
- The capability rows of a retiring device move to the target without overwriting existing keys.
Matter exposure across a collapse or re-home
Matter endpoint ids embed the device id, so a re-home re-identifies every endpoint of the device, and a bridged device
retired by a collapse removes its accessories. The new device's endpoints get new numbers. Google Home and Apple Home show
them as new devices, and the user re-assigns room, name and routines there. The new device inherits the old device's Matter
exposure, so it stays bridged, and the device.exposure_changed alert says it must be re-added in the Home app. A
channel-less switch has the never-commandable default endpoint 0, and Unknown is never exposed. See
integrations.md.
Rewrite rules for contributors
Re-home, collapse, renumber and redescribe run in one gate transaction under advisory and row locks in a fixed order: the revalidation and workflow advisory locks first, then device rows, then automation rows, each ascending by id. Every path that records a source event takes the gate's locks before it locks a logical-device row. The gate never commits the transaction it was handed. A new writer of several workflow or automation rows must take them ascending.
- Row locks are
NO KEY UPDATE, so a scan's finding insert does not wait. - Plans are revalidated under the lock. An automation that gained a reference since the plan was built keeps it and is reported by the scan.
- Rewrites touch only drafts. A published version is immutable. A draft that gains a reference after locking, or one the model no longer reads, is skipped, logged and reported, and never fails the collapse. Rewrites are all-or-nothing per trigger or block and do not touch wired ports.
- Writes that change capture cannot see append their change-log entries once, as the gate's last statement before commit.
- A re-home commits alone. Any collapse it rides on is queued in the same transaction as a job that later runs,
idempotently, against whichever device then owns the source. A deferred collapse that keeps failing raises
device.collapse_stuckper collapse row after five attempts.
Model jobs and retention
- Model jobs (redescribe, collapse, revalidation) are claimed through a lease decided on the database clock. A worker claims
nothing unless its replica is Serving. A job kind written by a newer build stays queued for that build.
DeviceModel:RedescribeCallTimeoutmay not exceedDeviceModel:LeaseDuration. - A job that applied a model event reads pending until its paired revalidation is done. A source whose device link was cleared has nothing to re-describe against.
- Model events and terminal model jobs are kept for
DeviceModel:EventRetention, thirty days by default (1 to 3650 days), and purged each minute in bounded amounts by the owner of thedevice-model-retentionkind. Removing a device or source leaves its model history readable until the period ends. Once purged, the diff behind an older finding is gone and a rediscover job reads404. An operator who needs longer history raises the option.
How findings read references
Scans for automations, scenes and workflows hurt by a model change follow the engine's own reading rules, so a finding never disagrees with what a run would do.
- A workflow input wired to a block's device or key port, or to a target block's
Targetport, is traced through inline branches and static sub-workflows up to the engine's call depth. - Findings on sub-workflow arguments attach to the calling workflow. Camera blocks name a device and no capability, so a reference to one can only be replaced, never "missing a key".
- A finding open for a button reference holds until a source lists the buttons again. Button event indices are resolved
only against
scenecontroller.channels, without requiring controllability. - A gone device is device removal, which never resumes automations. A resume needs the scan itself to have cleared an error on that device.
- Messages name the device and, for a channel, its plugin-assigned number (never a position) and label. They fit the 512-character column.
- An object save preserves the severity of an unchanged finding, because editing an object does not change the device model.
Access control
Per-user device access is inherited: a source is visible exactly when its parent logical device is. There are no per-source grants and no per-source permission codes. A source a caller cannot reach answers "not found", so the per-source endpoints are not an existence oracle. Access filtering is a SQL predicate applied before counting and paging (constraints).
The physical layer's access checks mirror the typed-device query: a caller never sees a physical device whose logical device they cannot view, a one-device token cannot enumerate the home through this layer, and an invisible device answers 404.
Who receives a device's realtime push is read from the access state, which holds the default audience and an audience per
device with an override (constraints). Replacement lookups run
one query per request and name a replacement only if the caller can view it.
Read models
- Logical and physical read models share projection primitives, so the two pages cannot disagree. Canonical values are read canonically, never in vendor units.
- The physical layer projects the source, not the logical device: one row per source, from that source's own state, descriptor, availability and channel names. The merged device's name and room come from the parent, read-only. Operator metadata, unit and value domain that only logical rows carry read null. Recent commands are those aimed at this physical device (failover-resolved commands carry a null source id), newest first, top 20. A plugin this replica does not run reads as unsupported.
GET api/devices?view=leanleaves out the vendor-shaped capability rows, sends raw properties as an empty list and omits every null member. Without the parameter the list is the full summary, andGET api/devices/{id}keeps the full shape. The web application and the phone ask for the lean view and treat an absent member as null or its declared default. Capability-filtered pickers match on the descriptor only, so a device with no descriptor, or whose capability is declared only by a standby source, is not offered.- The vendor-shaped
core.device_capabilitiesrows are derived from the canonical descriptor. OnlyEnum,OpenEnumandTokenSetcarry allowed values. An operator-set friendly name survives. A source's report removes only the rows of keys no source of the device declares, so on a merged device one source's discovery keeps the other sources' rows. - The device reconciler state is one immutable value, so readers never lock. A change in a device's id is always announced, because the Matter bridge rebuilds on every one.
- The per-device exposure document is shared by plugin metadata writes and the Matter bridge. Each writer owns its top-level keys and writes one key at a time with an atomic upsert, so concurrent writers on any replica cannot drop each other's keys. On plugin uninstall, rows lose the instance's keys and keep host-owned ones, or the row is removed.
Other standing rules
- Pickers branch on kind and controllability, never on key names. The controllability filter differs by surface. Triggers and conditions apply no controllability filter, a workflow read filters by kind only, and scene actions and workflow writes apply the full filter. A read-only capability is offered as a trigger and excluded from anything that sets a value.
- Read-only is what remains when the manage and control predicates are both false. It is not a mode flag anyone can read or toggle.
- A client's cache key travels with the command target. A control that commands a source but invalidates the logical device's entry refreshes nothing while appearing to succeed.
Behaviour that looks like a defect
| Symptom | Why |
|---|---|
| A control the device clearly supports is not rendered | The capability is absent from that instance's availability descriptor. The fix is in the driver's descriptor, not in the interface. |
| A slider loses its bounds | A plugin-declared range outside the catalog's canonical range is dropped whole rather than mislabelled. |
| A scene action stops firing | A persisted capability-kind ordinal decoded as a different kind than the action recorded, and the consistency check refuses the mismatched action. This fails closed: no wrong command is sent. |
| A device appears twice, once retired, after its type was corrected | A concrete type change re-homes the source into a new device of the new type. The old device stays retired while references point at it. Repair the references, then delete the retired device. |
| A device kept a "(detached)" name | A detached device takes its source's name only at the next discovery of that source. |
| A source name reverts to the vendor's own name | Reported names refresh on every discovery. A name set on the physical page is a separate override that clearing removes. |
| Two channels of one socket both read "State" | Vendors label channels identically. Name each channel. |
| An automation does not fire from an old reading | Out-of-order and over-age reports are suppressed from the realtime, feed and trigger paths. If an old reading still fires, the report carries a timestamp claiming to be newer than it is. |
| History exists per logical device only | Telemetry is keyed by logical device, and historical rows cannot be attributed to a source retroactively. |
| Merging, or deleting a plugin instance, took scenes, grants and history with it | Device removal cascades. Merge into the device that carries the configuration, and export configuration before deleting an instance. Uninstalling a plugin type cascades nothing and is refused while any instance exists. |
| Devices of a stopped plugin show Offline, then come back without a report | The host held them Offline for the instance's outage and lifted its own marks on the next start. |
See also
- device-drivers.md: the driver contract.
- data.md: how device state, telemetry and cascade deletion are stored.
- integrations.md: how protocol integrations and the Matter bridge reach the model.
- reference/devices.md: the device endpoints and DTOs.
- glossary.md: logical device, device source, descriptor and the other terms.