Skip to main content

Architecture decisions, and when to revisit them

A log of significant design decisions: what was chosen, what was rejected, and the concrete triggers that should reopen the question. Add new entries at the top. Keep entries honest about trade-offs, the point of this file is that a future session (human or AI) can tell whether the world has changed enough to revisit.


2026-10-31, Camera display order: one admin-set order on the server, not a per-user sort in each client​

Decision. Cameras get a nullable cameras.display_order (migration 0085). An admin drags cameras into order in the web console (Cameras, "Reorder"), which sends the whole list to PUT /config/camera-order (AdminUser). GET /cameras, GET /config/cameras and /status return cameras in that order through db::list_cameras_for_display: placed cameras by position, then unplaced ones in natural name order. Clients already show the server list as-is, so the only client changes are removing the few spots that re-sorted by name (Android Clips and LPR camera filters, the desktop playback legend). The order is folded into config_version, so connected clients re-fetch on their own.

Rejected. A per-user sort setting in each client (name, custom, group, recent motion): three separate implementations and a per-user store, for a need the owner described as one fleet-wide order. Admin default plus per-user override: the same cost on top of this one. Putting the column into v_camera_effective_policy / Camera: that view feeds the recorder, and the order is display only, so it is read in a separate query and db::list_cameras_all (which the recorder's retention sweep calls) is unchanged.

Trade-offs accepted. One order for everyone; a viewer who wants a different arrangement uses a saved view. Unplaced cameras (new ones) land after the placed ones rather than in their name position among them. Saving rewrites every row's position in one statement, which is fine at fleet sizes Crumb targets.

Revisit when. Users ask for a personal order that differs from the admin's (add a per-user override on top, keep this as the default); ordering by group is wanted (sort by group, then position).


2026-10-30, Android light polish pass: transitions, spacing and type roles only, no new structure; wall tile to camera is a scale grow, not a shared-element transform​

Decision. The Android app gets a "light polish" pass (owner brief: same navigation, screens, controls, per-tab colours and fonts; better transitions, cleaner pages, better spacing). It is built from shared tokens rather than per-screen tweaks: a spacing scale (ui/theme/Spacing.kt, 4/8/12/16/24), an explicit shape scale (8 tiles and chips, 12 cards, 28 dialogs), labelMedium / bodySmall type roles plus a mono data style (the already bundled JetBrains Mono), one CrumbFilterChip (Live, Playback wall, Clips and the LPR active-filter strip), one StateMessage for empty and error states, a hand-rolled shimmer skeleton, and small motion helpers (staggerIn, dialogEntrance) in ui/. Navigation uses a fade-through between tabs (scale 0.92 to 1 only when the target is not the Live wall), and a wall tile opens its camera by growing out of the tapped tile and shrinking back on Back (ui/nav/NavMotion.kt). No server change, no new dependency.

Rejected. SharedTransitionLayout / sharedBounds for the tile to camera transform: the live tiles are SurfaceViews and the fullscreen and playback surfaces are separate TextureView players, so there is no single element to share, and moving a SurfaceView through the shared-transition overlay risks blank video during the animation. A scale and fade from the tile's bounds gives most of the feel with no risk to playback. Controls auto-hide with fades on single playback (P7), a swipe-camera AnimatedContent (F5) and fixed GridCells.Fixed(2) on Clips were skipped or reduced because each changes behaviour or structure, which the brief ruled out.

Trade-offs accepted. The grow transform is an approximation (origin from the last tile position, not pixel-exact bounds). The incoming camera slides on swipe but the outgoing one does not (one shared player). The single-camera timeline is taller (88 dp portrait, 56 dp landscape) to host the time chip and the detection band. Reduced motion relies on Compose following the system animation scale; the app has no separate switch.

Revisit when. A shared-element-capable player surface is adopted (for example a single TextureView for wall and fullscreen), or testers report the grow transform stutters on low-end phones (fall back to the plain fade-through).


2026-10-30, Android LPR tab redesign: phone-native (search bar + one filter sheet, two-line rows, pinned-video profile), not the desktop plate desk shrunk​

Decision. The Android LPR tab is rebuilt around the answers 0A 1A 2A 3B from the owner's mockup round (the mockup page itself is not in the repo): registration-blue accent shared with desktop (0A); ONE search bar with a filter icon (count badge) that opens a single bottom sheet holding cameras, time range, "ends at", match mode, view (List / Gallery / Grouped), Hide regulars and Merge duplicates, plus a chip strip that only exists while a filter is off its default, landscape riding inline in the top bar like Clips (1A); 72 dp two-line rows with an aspect-true crop, no row icons, a marquee for long names that never moves the plate, long-press peek for the actions (2A); a distinct full-screen plate profile with the video pinned and Visits / History / Details tabs (3B). No server change: every surface uses GET /plates, POST /lpr/plates/stats, /lpr/plate-labels, /lpr/plate-aliases (+ suggestions), /lpr/watchlist, and the existing scoped-token /play + segment path.

Rejected. 0B (keep plate-red): reads as an alarm and differs from desktop. 1B (chip row) and 1C (bottom bar): taller, and 1C makes LPR look like a different app. 2B (name on its own line + overflow dots): taller rows and a column of dots; kept as the fallback if long-press proves too hidden. 2C (grouped by plate as the default): hides the chronological feed, offered as a view instead. 3A (one scrolling page) and 3C (drag sheet): 3A scrolls the video away when a visit is picked, 3C is fussy to build and buries the charts. The desktop header tiles, split bar, density switch, ledger columns, radial clock, six-fact grid, Benchmark button and the Timeline view were deliberately NOT ported.

Trade-offs accepted. Long-press is invisible until learned (mitigated: every action is also in the profile menu). Whether Hide regulars is on is told by the badge and the chip strip, not a visible toggle. Hide regulars and the NEW tag depend on the stats endpoint, so an older server simply shows neither. The old "LPR thumbnail image" (plate crop vs full image) setting is removed: the list is always the crop and the gallery always shows the frame with the crop inset. The "regular" rule is the desktop one (!isNew && seen_30d >= regular_min_reads_30d, watchlisted plates never hidden).

Revisit when. Testers cannot find the long-press actions (switch to 2B); the second tab strip in the profile feels like too much structure (fall back to 3A); two blues in the tab row confuse people (nudge Live's steel blue, not LPR).


2026-10-29, LPR plate corrections: an admin-managed alias table resolved on the server; raw reads are never rewritten​

Context. Plate OCR sometimes misreads one character, so one car shows up as two plates (the owner's example: GIF2GAB and GIT2GAB). Its history, "regular" status, counts and profile were split in two with no way to tell Crumb they are the same vehicle (issue #673).

Decision.

  • Storage: plate_aliases (migration 0084), alias_plate (primary key) -> canonical_plate, plus created_by and created_at. Both are normalized plates. plate_reads is never rewritten: a read keeps what the engine read, a correction applies when reads are queried, and deleting the row undoes it. Not pruned by plate retention (operator curation, like plate_labels and the watchlist).
  • One level only. A canonical plate is never itself an alias. The write path (db::create_plate_alias, under an advisory lock) flattens: correcting A -> B when B -> C exists stores A -> C; aliases that pointed at A move to its new canonical plate; correcting B -> A when A -> B exists swaps them. Resolution is therefore always a single LEFT JOIN on the alias primary key, never a recursive walk.
  • Resolution rule (every read path, verbatim): a read counts as COALESCE(plate_aliases.canonical_plate, plate_reads.plate).
    • GET /plates: plate is the canonical plate; new nullable corrected_from carries the raw read when it was corrected. Every search mode matches the raw read OR its canonical plate, so an exact search for the canonical plate (the profile's visits) returns its misreads. A search that matches a known misread string returns the whole car: the misread reads and the canonical plate's own reads (amended 2026-11-01, #700; before, searching GIT2 found only the reads stored as GIT2GAB and missed the car's other sightings). The same search text, as typed, also matches plate names and watchlist labels case-insensitively (ILIKE, anchored like the match mode, wildcards escaped), folded onto the whole car the same way. The name resolves as COALESCE(label(canonical), label(raw), watchlist label(canonical), watchlist label(raw)).
    • POST /lpr/plates/stats: a requested misread is answered under its canonical plate, and a canonical plate's numbers include every read stored under its aliases. The SQL still groups by the stored plate through the (plate, ts) index and folds the groups in Rust.
    • GET /lpr/overview: today's unique plates, new plates, regulars and watchlist hits are counted per canonical plate.
    • Ingest: the ignore list and watchlist alert matching also try the read's canonical plate, so a known misread of a watched plate alerts.
    • The A/B engine benchmark does NOT resolve (PlateReadQuery::resolve_aliases = false): it must score the engines on what they read, and a correction would inflate their accuracy.
  • Server-side resolution, not client-side, so every client agrees and the clients that already show reads (Android, iOS, the web console) show corrected plates with no client change.
  • Endpoints and permissions: GET /lpr/plate-aliases[?canonical=] and GET /lpr/plate-alias-suggestions?plate= are view_plates-gated (like the watchlist read) with camera-scoped read counts; suggestions only consider plates seen on cameras the caller may see. POST /lpr/plate-aliases and DELETE /lpr/plate-aliases/:alias are admin-only, the same gate as plate names and watchlist writes: a correction changes what every operator sees.
  • Suggestions reuse the watchlist matcher's distance (db::levenshtein, OCR-confusable pairs such as O/0 cost nothing): plates in scope within 2 edits, folded onto their canonical plates, closest then busiest first. It scans the distinct plates of the right length, which plate retention bounds; it backs an admin dialog, not a hot path.
  • Desktop: "Correct plate..." in the plate profile and the list row menu opens a dialog with likely matches, the effect ("GIT2GAB's 12 reads will count as GIF2GAB"), and Undo; the canonical plate's profile lists its known misreads with Undo.

Rejected.

  • Rewriting plate_reads.plate (a one-shot "merge"): simplest to query, but irreversible, destroys the OCR text needed for audit and for the engine benchmark, and a wrong merge could not be told apart from a real read.
  • Client-side resolution (each client fetches the alias list and re-maps): five clients would have to agree on the rule, server counts (stats, overview) would still be split, and an old client would show split plates forever.
  • Applying corrections to every confusable or fuzzy variant automatically (the plate-names entry, 2026-07-31, deferred naming fuzzy variants for the same reason): it risks merging genuinely different plates. A correction is an explicit, per-string operator decision.
  • A per-read override in this change (correct one read without aliasing the string): deferred. An alias on a one-off misread only affects that string, and the dialog shows how many reads it moves before saving, so the alias covers the reported case. Because resolution is centralized in the COALESCE above, an override column on plate_reads can be added later as the first term.

Trade-offs accepted. Every plate query now carries a LEFT JOIN on a small primary-keyed table (and stats one extra lookup). The alias list is visible to anyone with view_plates, like the watchlist, though its read counts are camera-scoped. Events on the timeline (events.sub_label) still show the raw plate. Android and iOS display corrected plates but cannot make corrections yet. The watchlist-hit tile now counts a watched plate's misreads too.

Revisit if. Operators need to correct single reads (add the per-read override), non-admins should be able to correct (split a capability), the alias table grows large enough that the suggestion scan shows up as slow, or the timeline should show corrected plates.


2026-10-29, Bookmarks whose footage retention deleted: flag at read time, never auto-delete​

Chosen: footage_expired is computed in the bookmark SELECT on every read (no segment covers ts AND ts is earlier than the camera's oldest segment, or the camera has no segments), using two bounded probes of segments (camera_id, start_ts). GET /cameras gains oldest_footage_ts (one per-camera ORDER BY start_ts LIMIT 1 subselect, not a GROUP BY over all segments) and the effective recording_mode, so playback states the actual reason a moment has no footage instead of guessing from loaded coverage. Expired bookmarks are badged and can be removed in bulk by the operator ("Remove expired (N)", confirmed); nothing is deleted automatically. Deletes ask for confirmation (Shift+click skips) and offer Undo, which re-creates the bookmark through POST /bookmarks.

Rejected:

  • Auto-deleting a bookmark when retention removes its footage. The note and the moment can still matter (an incident reference, a plate read) after the video is gone, and silently removing operator data is the wrong default.
  • A stored footage_expired column updated by the retention sweep. It would add a write to the eviction path (recorder correctness) and could drift; the read-time check is cheap and always current.
  • A server-side soft delete / restore endpoint for undo. Re-creating through the existing create API needed no new endpoint or migration; the cost is that a restored bookmark gets a new id and creation time, its creator becomes whoever pressed Undo, and a protection is restored for its remaining time rounded up to whole days (a lapsed one is not restored).

Revisit triggers:

  • Bookmark lists large enough that the per-row probes show up in GET /bookmarks latency.
  • A need for undo to preserve the original id or creator (e.g. bookmarks referenced from elsewhere by id), which would justify soft delete.
  • Operators asking for automatic cleanup, which would then be an explicit, opt-in setting.

2026-10-29, Scrub pre-generation stays OFF by default; documented as the scrubbing knob, with a catch-up cap​

Context. #657 made a grid frame a single keyframe decode and the scrub sprites (entry below) made pre-generation worth more, so the audit asked whether THUMB_PREGEN_ENABLED (one switch for grid frames AND sprites) should now default to on.

Measured (9 real 4 s fixture segments, 1080p to 4K, H.264/HEVC, single-threaded ffmpeg 7.1): grid frame 0.08-0.28 s CPU and 25-44 KB; sprite 0.15-0.55 s CPU and 12-20 KB. Per camera that is one of each per 4 s of footage: about 0.28 s (1080p) to 0.8 s (4K) of CPU per 4 s, i.e. 7-20 % of one core per camera (1080p about 7 %, 4K 13-22 %, fixture mean about 14 %), and ~1.0 GB/day of cache per camera (21 600 segments x ~48 KB). The worker is serial (one ffmpeg in flight), so its total is capped near one core: it keeps up with about 5-7 4K or 14 1080p cameras. The default cache budget (20 GB) holds about 20 camera-days.

Decision. Keep the default OFF, and make the knob prominent instead: the environment reference, the scrubbing page, .env.example, the admin console hint and docs/AI-INSTALL.md now say what it does and what it costs, in numbers. One switch keeps covering both grid frames and sprites.

Also: the worker's per-camera start point is now capped (thumb_pregen::pass_start_ms). A camera whose watermark is older than the lookback window (at least 2 h) skips ahead instead of chasing an ever-growing backlog, so a box with more cameras than one serial worker can serve still gets previews for the most recent footage. Skipped footage keeps the on-demand path.

Why not default on. An always-on cost of 7-20 % of a core and 1 GB/day of writes per camera is paid by every install, including small boxes where the recorder (the component that must never fall behind) shares those cores, and it is paid whether or not anyone ever scrubs. The on-demand path after #657 is already 0.1-0.3 s for a cold 4K cell and instant on revisit, and the clients prefetch around the cursor, so the default experience is good without it.

Rejected.

  • Default on with a lower concurrency limit: the worker is already serial; a lower limit can't go below one ffmpeg, and the per-camera cost is the problem, not a burst.
  • Default on for sprites only: the sprites are the larger CPU share and the smaller user-visible change; splitting the switch would add a second knob for operators to reason about.
  • Auto-enable based on core count: hidden behaviour that changes with hardware is harder to support than one documented switch.

Revisit triggers. Hardware decode available to the api container (would cut the per-picture CPU several-fold); a cheaper source of preview frames (recorded sub stream, see the 2026-07-07 entry); field reports that first-drag latency is the main complaint on default installs.

2026-10-29, Scrub sprites: one keyframe-only sprite strip per segment, made only by the API pre-generation worker​

Context. The scrub overlay's frames come from GET /filmstrip/{cam}/frame, which snaps every request to a fixed 4 s grid so cache keys are shared. That makes a drag across segments step in 4 s jumps, and every new cell is its own request. The 2026-07-07 entry deferred "sprite atlases"; the performance audit behind PRs #655-#657 recommended per-segment sprites for 1 s granularity.

Decision.

  • One sidecar JPEG per recorded main-stream segment: one tile per started second (4 for a 4 s segment, capped at 16), 160 px wide, in a single row, tile i = the segment at start + i s. Cached at {thumb_cache_base}/.thumbs/{camera}/sprites/{segment_id}_w160_t{n}.jpg.
  • Rendered with a keyframe-only decode (-skip_frame nokey, fps=1, tile): every camera in the benchmark fixture set keys once per second, so this gives a distinct frame per tile. A longer GOP repeats the previous keyframe (the frame endpoint's "keyframe at or before" rule). The fps filter holds back its last frame, so the first frame is split off and re-stamped as a sentinel at n s to release the final slot without decoding anything extra.
  • Made ONLY by the API's thumbnail pre-generation worker, behind the same THUMB_PREGEN_ENABLED / console "Scrub previews" switch as the grid frames. There is no on-demand path: GET /filmstrip/{cam}/sprite?ts= returns 404 until the sprite exists, and the desktop and Android clients fall back to the frame endpoint. The layout travels in X-Crumb-Sprite-* response headers, so one GET is enough.
  • Same auth as the frame endpoint (MediaOrFullUser, playback capability, per-camera scope, scoped ?token= from the clients).
  • Lifetime: the serve path resolves the segment from the DB and names the file by its id, so a sprite of a deleted segment is unreachable; the cache sweeper deletes sprites whose segment id is no longer in segments (read-only primary-key lookups, a DB error deletes nothing); the generator re-checks the segment after publishing; and the existing .thumbs age/byte sweep covers sprites too. Sprites live in the api's writable cache, never beside footage, so they cannot delay or block the recorder's deletion of a segment.

Measured (9 real 4 s fixture segments, 1080p to 4K, H.264 and HEVC, single-threaded ffmpeg 7.1): sprite 0.15-0.55 s CPU per segment (mean about 0.36 s), 12.4-19.9 KB (mean about 14.8 KB); for comparison the 480 px grid frame from #657 costs 0.08-0.28 s CPU and 25-44 KB. A full decode of the same segments for the sprite costs 0.34-0.98 s CPU.

Rejected.

  • Full decode for exact 1 s instants: 2-3x the CPU for no visible gain on 1 s-GOP cameras.
  • One ffmpeg input per tile (-ss i x4, hstack): no cheaper (0.16-0.94 s), and slower on H.264.
  • Rendering sprites on demand in the request path: a 4-keyframe decode is too slow for a pointer event, and the frame endpoint already covers the cold case.
  • Rendering in the recorder from the motion decoder's frames: golden rule 2, and the motion frames are grayscale sub-stream (same reasoning as 2026-07-07 option 2).
  • A JSON layout endpoint plus an image endpoint: two round-trips per segment for data that fits in six headers.

Revisit triggers. Cameras with a GOP well above 1 s become common (tiles would repeat; consider a full decode for those); SEGMENT_SECONDS raised past 16 s (the tile cap); the sprite pass measured as the bottleneck that stops the worker keeping up with recording; iOS wants sprites (client work only, the endpoint is ready).

2026-10-29, Playback /play/ resolves are cached briefly on the client, token-less and positive-only​

Context. A scrub release, a frame-step, a re-seek and the adjacent-segment probes on desktop and Android each paid a GET /play/{camera_id} round trip, even though most of them land in a segment the same client resolved moments earlier, and a segment's id and [start, end) window never change once indexed.

Decision. Desktop (lib/api/play_resolve_cache.dart, used by PlaybackApi.resolveSegment) and Android (data/PlayResolveCache.kt, used by CrumbRepository.resolveSegment) keep a bounded (256 segments) in-memory cache of resolves with a 60 s TTL from fetch time. Any instant inside a cached segment's window hits. Only 200 answers are cached (a 404 never is, so new footage appears on the next resolve). The cached value is the token-less /segments/{id} path; the scoped ?token= media claim is still attached from the media-token cache at use time, so a cached resolve can never yield an expired media URL. Keys include the server and session token (one principal's grants never answer another's resolve); sign-out clears it; Android's player-error recovery invalidates the camera first so recovery always asks the server. Callers can pass bypassCache.

Rejected. HTTP caching headers on /play/ (Cache-Control): the desktop and Android HTTP stacks would cache per exact URL, i.e. per ts, so a release a few hundred ms from the last resolve would still miss; it also widens what intermediaries may store for an authenticated endpoint. A longer TTL: a segment retention deletes would stay answerable longer for no real gain, since the hits come from actions seconds apart.

Trade-offs accepted. For up to 60 s a resolve can name a segment that retention or reconcile has just removed; the player then fails to open it, exactly as it would if the deletion had landed right after a fresh resolve.

Revisit if. Segment windows ever become mutable after indexing (e.g. an in-flight segment indexed with a growing end), or iOS gains the same scrub paths (it has no cache yet).

2026-10-29, /timeline merges contiguous segments into spans IN SQL (gaps-and-islands); the Rust merge stays as the test oracle​

Context. GET /timeline fetched every segment row in the window and merged contiguous runs in Rust. The desktop's 30-day coverage fetch (every 5 minutes per client) is ~650k rows per continuously recording camera; the api logged "large /timeline span-merge scan (audit Risk #4)" and shipped tens of MB of rows from Postgres per request only to collapse them into a handful of spans. The 2026-08-07 intensity entry below left this path out of scope as "inherently O(rows)"; the row SCAN is still O(rows), but the transfer, row decoding and per-row allocation in the api need not be.

Decision.

  • db::timeline_merged_spans runs a gaps-and-islands query: a window max(end_ts) over the camera's earlier rows (ordered by start_ts, id) flags a row as a span start when it is the camera's first row or starts more than the 1 s tolerance after that running max; a running sum of the flags numbers the islands; GROUP BY (camera_id, island) returns min(start_ts), max(end_ts), bool_or(has_motion) and the first row's stage. count(*) OVER () gives the total, LIMIT/OFFSET pages in SQL. Response shape, tolerance, first-wins stage, motion OR, ordering and total/has_more semantics are unchanged; no client change, no migration.
  • The first row's stage is carried as max(CASE WHEN is_start = 1 THEN stage END) rather than (array_agg(stage ORDER BY …))[1]: the ordered aggregate forced a second full sort of every row (spilled ~36 MB to disk on 500k rows), the CASE form lets Postgres hash-aggregate the few spans.
  • Ties on start_ts are now broken by id in both the SQL and the timeline_spans row order, so "stage of the first segment" is deterministic (it was planner-dependent before).
  • The old Rust merge moved to db::merge_segments_into_spans and is kept as the executable specification: timeline_sql_merge_edge_cases_match_reference and timeline_sql_merge_random_fixtures_match_reference assert the SQL equals it (unpaginated and across many limit/offset pages, including past the end), on hand-built edges (touching, 999 ms / exactly 1 000 ms / 1 001 ms gaps, a segment contained in a longer one, mixed stages, window-straddling rows, two cameras) and on seeded pseudo-random fixtures with overlaps and ties.

Measured (Postgres 16, one camera, 500k contiguous 4 s rows with 500 gaps, 30-day window, release build, warm cache): old path (fetch rows + Rust merge) ~400 ms and ~500k rows / tens of MB transferred and decoded per request; new path ~245 ms with 500 rows returned. Server-side execution of the old SELECT alone was ~138 ms; the windowed query is ~300 ms of that work but removes the transfer and decode.

Rejected / not done.

  • A covering index (camera_id, start_ts) INCLUDE (end_ts, has_motion, stage) for an index-only scan. Not done: it is a migration on the hottest write table (every recorded segment pays for it), touches recorder-adjacent schema, and the remaining cost is per-row window evaluation, not heap fetches.
  • A maintained span table updated by the recorder. Rejected: it adds a write path in the recorder (recorder correctness is sacred) and a second source of truth that eviction/retention/reconcile would all have to keep in sync.
  • Keep Rust merge, page earlier. Rejected: total needs every span, so the full window must be merged regardless.

Revisit triggers.

  • /timeline still slow at much larger scale (many more cameras × long retention): consider the covering index or a client-side incremental fetch.
  • Any change to merge semantics (tolerance, stage rule, motion rule): update BOTH the SQL and merge_segments_into_spans in lockstep; the equivalence tests will fail otherwise.

2026-10-29, LPR page redesign ("plate desk"): two server aggregates, history buckets in the server time zone, hints computed on the client​

Context. The desktop Plates page listed reads with no sense of history: an operator could not tell a neighbour from a first-time visitor without searching each plate, and the three display menus (Show / Crop size / Crop corner) barely changed anything. The owner approved one combined design from six concepts: a "plate desk" header (today's reads, unique plates, new plates, watchlist hits, and a regulars / returning / first-time split), ledger rows with a history cell and a 30-day sparkline, group-by-plate, one Density control, a contact-sheet grid, and a per-plate profile.

Decision.

  • Two new view_plates-gated, camera-scoped endpoints in plates.rs: GET /lpr/overview?day=&camera_ids= (the header) and POST /lpr/plates/stats {plates} (history for up to 200 plates: total, 7/30-day counts, first / last / previous sighting, per-camera counts, 24 hour-of-day buckets, 30 daily buckets). Only reads from cameras the caller may see are counted, including the history that decides "new" and "regular", so a viewer can never learn about a camera they were not granted through a count.
  • "Regular" = at least 5 reads in the 30 local days ending with the day (db::LPR_REGULAR_MIN_READS_30D, echoed to clients as regular_min_reads_30d). The split is exhaustive: first-time (first seen on the day), regulars, and returning (everything else seen before the day).
  • Days and hours are the server's local time (ApiConfig::server_tz), bucketed in SQL with AT TIME ZONE, because "today" and "usually at 5 PM" only mean something in the site's wall-clock time, and DST makes a fixed offset wrong.
  • New index plate_reads (plate, ts) (migration 0083). Every stats query is driven by plate = ANY($1), so its cost is bounded by the requested plates' history, never the table; it also speeds up exact plate search.
  • Derived hints (NEW, UNUSUAL HOUR, "Nx TODAY"), visit collapsing (reads within 5 minutes on the same camera) and the plain-English profile summary are pure client functions over the stats and the reads the client already holds. They are presentation rules that will be tuned, and keeping them out of the API avoids freezing them into a wire contract.
  • Clients degrade against an older server: a 404 on either endpoint hides the header and renders history cells as "-".

Rejected.

  • A materialized per-plate summary table updated on ingest: faster reads, but a second source of truth that must stay consistent with retention pruning and per-camera grants (a viewer's counts differ from an admin's). The on-demand aggregate over an index is cheap enough for the 200 plates on screen.
  • Computing history on the client from GET /plates: it would mean paging every read of every plate on screen (thousands of rows for a regular).
  • UTC buckets: an evening regular would show up split across two "days".

Trade-offs accepted. Stats are recomputed per request (the desktop caches them for 60 s). The watchlist-hit tile counts exact plate matches against watch entries; fuzzy watchlist matching still drives alerts but not the tile. A server TZ that Postgres does not recognise makes both endpoints fail, and the page then hides the header as it does for an older server.

Revisit if. Stats requests show up as slow in production (move to a summary table), operators want the regular threshold configurable, or Android/iOS adopt the plate desk and need the hint rules shared server-side.


2026-10-29, Batch export: friendly file names, optional zipping, and a server-side size estimate​

Context. Batch export named clips clip01_<8 hex of camera uuid> on disk and clip01_<cam8>_<UTC timestamp> in the zip, and always zipped more than one clip. Operators found the names unreadable and wanted plain files. The desktop size estimate was a flat 10 Mbps guess and came out 2.2x low on a real export (397 MB estimated, 874 MB actual, 4 clips, 3 cameras, copy codec).

Decision.

  • Every clip (disk file and zip entry alike) is named {Camera Name} {YYYY-MM-DD} {HH.MM.SS}-{HH.MM.SS}.{ext} in the server's local zone (server_tz), or {Camera Name} {date time} to {date time} when it crosses local midnight. The name is sanitized for Windows and POSIX (illegal characters and control characters become _, whitespace collapsed, trailing dots and spaces trimmed, camera part capped at 60 chars, Windows reserved device names prefixed _) and de-duplicated with (2), (3).
  • package on POST /export/batch: "zip" (default, unchanged for Android and iOS) or "files". A password forces zip (files + password is a 400). In files mode output_files has one entry per clip.
  • GET /export/:job_id/output/:index downloads an output_files entry by position, because one camera can have several clips and /files/:camera_id cannot address them. The old routes stay. Content-Disposition is RFC 6266 (filename*=UTF-8'' plus an ASCII fallback). The zip is offered as Crumb export {YYYY-MM-DD HH.MM}.zip through a new download_name field (#[serde(default)], so persisted rows still load); the disk name stays crumb_export.zip.
  • POST /export/estimate returns, per clip, the sum over the main segments the export would use of size_bytes * overlap / segment duration (one SQL aggregate, no file I/O) plus the footage seconds. It models a copy-codec export; clients scale it for a re-encode.

Rejected. A flat bitrate guess (what failed: real cameras vary 3x or more, and motion-mode recordings have gaps). Estimating from ffprobe of the files (file I/O per segment, too slow for a live dialog). Naming from the camera uuid (unreadable) or UTC times (wrong for operators reading the file later). Dropping the zip entirely (still the right default for a multi-clip hand-off and for a password).

Accepted trade-offs. The estimate ignores container overhead and burn-in re-encode; the single-camera POST /export path keeps its uuid-based names (one file per camera, no ambiguity) and old URLs.

Revisit when a client needs per-clip re-encode size accuracy beyond a scale factor, or the single-camera POST /export path is retired in favor of batch.


2026-10-08, Eviction under a full or missing disk: the archive tier gets its own floor, failing moves fall back to deleting live footage on the low disk, and sweeps never prune or write on an unconfirmed storage​

Context. Audit findings R2 to R7 against services/recorder/src/archive.rs: a full archive disk on its own filesystem made every move fail and the live eviction loop break, so the live disk filled and recording stopped on every camera of the policy; the retention and eviction sweeps deleted index rows for missing files with no marker or breaker check (the issue #504 failure through a second door); archive moves and the "Change storage" drain wrote into an unmounted mountpoint; the live retention sweep's single shortest-retention cutoff let long-retention footage fill the oldest-first batch, so a short retention was never enforced; protected-bookmark bytes counted toward byte caps they could never be evicted from; and archive-off floor eviction deleted footage on other disks and credited it against a deficit it never freed.

Decision.

  • The archive filesystem has its own free-space floor (global MIN_FREE_* thresholds), run per archive-enabled policy before the cron move: the oldest unprotected archive footage on that filesystem rolls over. With the live floor in deficit and archive moves failing for a systemic reason (or the destination refused), the sweep deletes the oldest live segment on the deficit filesystem rather than stopping; cap-only pressure still keeps the footage. A full or read-only archive destination raises storage_unwritable.
  • Every missing-file row prune in the sweeps goes through one guard (marker present, breaker not latched, a sweep-local breaker with reconcile's thresholds); otherwise the row is kept. A missing file never credits a deficit.
  • Archive moves and drains require a confirmed destination: marker present, or no segment ever indexed under that path (a new disk, which gets the marker after the first committed move).
  • Live retention applies each camera's own cutoff in SQL.
  • Byte caps compare against unprotected bytes, and a cap-driven delete never touches footage younger than one hour.
  • Archive-off floor eviction only considers and credits footage on the deficit filesystem.

Rejected.

  • Stop archive moves while the archive disk is below its floor, without deleting archive footage. Keeps old archive footage, but the live tier then fills with nothing to move into, which is the original failure. Rolling the oldest footage over is what any NVR does on a full disk.
  • A new dedicated alert key for "archive full" and for "protected footage exceeds the cap". Needs a seeded rule plus console and notification surfaces; storage_unwritable already means "the recorder cannot write to this storage". The protected-share condition is a log warning for now.
  • An index on segments(storage_id) for the destination history check. A non-concurrent index build on a large segments table at boot blocks inserts; the check only runs when the marker is absent, which after the first committed move is never.
  • Skip the per-camera SQL cutoff and loop per retention value instead. Same effect with more queries; the view already exposes the retention per camera.

Trade-offs accepted. An archive tier configured with "keep indefinitely" now loses its oldest footage when its disk reaches the floor (before, the disk filled and live recording eventually stopped). On a shared live/archive filesystem the archive floor deletes the oldest archive footage before the live rescue touches live footage. A policy whose protected footage is large can use more disk than its byte cap (the free-space floor still guards the disk). A storage that lost its marker keeps stale rows until an operator restores the marker (an empty file is enough).

Revisit triggers. Operators wanting a "never roll archive footage" mode (would need an explicit, loud stop-recording or stop-archiving choice); a dedicated alert surface for storage health landing in the console; reports of the history check being slow on very large indexes.

2026-10-08, Storage path edits: refuse a path change on a storage that holds segments; refuse overlapping storage roots​

Context. Segment rows store their path relative to the storage root. The console let an operator edit a storage's folder freely, which silently re-resolved every existing recording under the new folder: playback broke at once, the bytes stayed behind in a folder no storage owned, and the recorder's sweeps began deleting the rows as dangling (audit R11). Separately, nothing stopped two storages from overlapping (a storage at the media root, or an archive folder inside the live folder), and reconcile's orphan walk of the outer root then quarantined, and two weeks later deleted, the nested storage's footage (audit R1).

Decision. PUT /config/storages/{id} refuses (409) a path change while the storage has any indexed segments, and points the operator at "Change storage" (the per-policy drain that copies, verifies, flips each row, then deletes the source). A path that differs only lexically (trailing /, .) is not a change and is not written. POST and PUT both refuse a folder that equals, contains, or lies inside another storage's folder, compared on canonical paths. The recorder enforces the same ownership on its side (RECORDER-CORRECTNESS item 35), so rows that predate the api check are safe too.

Rejected:

#OptionVerdict
1Allow the change when the new folder already holds the storage's newest indexed files (the operator moved the data)Rejected: a sample proves only that the sampled files moved. A partial copy passes, and every unsampled row then resolves to nothing and is pruned. Refusing cannot lose footage.
2A force flag on the PUTRejected for now: it re-opens exactly the silent-loss path, and the console would need UI to explain it. The drain covers the legitimate need.
3Rewrite every row's path on a path changeRejected: rows are already relative; the problem is that the BYTES did not move. Only a copy-verify-flip move is safe.
4Allow exact-duplicate storage paths on createRejected: nothing in the product needs a second row for one folder (existing duplicates keep working; the recorder groups them by canonical path).

Trade-offs accepted. An operator who really did move a disk's contents to a new mountpoint must either mount it at the old path or move the footage with the drain. That is slower than a one-field edit, and it is the price of never silently hiding recordings.

Revisit if: operators report a real need to repoint a storage in place (for example after a hardware swap) that mounting at the old path cannot meet; then design an explicit, verified "relocate" action that checks every row, not a sample.


2026-10-08, Motion recovery and persist safety: every session end closes its event, stuck sessions reconnect, unhealthy alerts repeat, failed persists retry, the recording path confirms a root from earlier history​

Context. Three production Motion-mode cameras raised motion_detector_unhealthy ("frame-stall watchdog fired") once each on one night and then kept every segment for 18 days until a recorder restart. The frame-stall watchdog returned out of the frame loop past the synthetic STOP for an in-progress event; the detector reconnected and recovered, but the stranded START kept the recording task's motion union open, so the buffer stayed in Recording. The alert fired once per episode. Separately, a session that keeps delivering frames the detector cannot use is never replaced by the watchdogs. Audit R8: a kept motion segment whose copy into storage failed was dropped from the ring and later deleted by the reconnect sweep. Audit R9: the recording path wrote the storage marker after any committed segment, so recording onto an empty mountpoint confirmed that mountpoint.

Decision.

  • Every pixel session exit (cancel, EOF, either watchdog, read error, stuck guard) emits the STOP for an event in progress. The recording side keeps its no-expiry rule: the source that opened an event closes it.
  • A pixel session connected for 120 s without a verdict is torn down and reconnected; the dwell doubles per consecutive stuck session up to 30 min and resets on the first verdict. Reconnects continue indefinitely.
  • motion_detector_unhealthy re-fires every 4 h while the same episode lasts, stopping on RECOVERED or when the episode's worker is gone. Constant, not a setting.
  • Failed cache persists go into a process-wide per-camera retry queue (backoff 5 s to 5 min, no give-up while the file exists) that the R1 sweep never deletes from.
  • The recording path writes the marker only when the storage has no indexed segments older than this process's start, or one of its 50 newest such segments is present under the root.

Rejected:

#OptionVerdict
0Expire stale open keys in MotionUnion (or clear the union when a source recovers)Rejected: item 25 already rejects a blind expiry (it would cut a second source's genuinely long event); closing at the source fixes the cause instead.
1Reconnect the moment the long-GOP check tripsRejected: a camera whose sub-stream is keyframes-only by design would reconnect-spin; the doubling dwell bounds that to one retry per 30 min.
2Re-alert on every reconnect or at the rule cooldown (15 min)Rejected: noisy for a known-degraded camera; 4 h keeps it visible without paging all night.
3Give up on a failed persist after N attemptsRejected: the cache file is the only copy; a storage outage of any length must not turn into lost footage.
4R9 cutoff "older than the committed segment by a few segment lengths"Rejected: after a few minutes of recording onto the wrong root, those segments become the "history" that confirms it. The process start cutoff holds for the whole process lifetime.

Trade-offs accepted. A genuinely long-GOP camera reconnects every 30 min (seconds of extra decode). The retry queue lives in memory, so a recorder restart with a tmpfs cache still loses queued segments (as before, now with a log line per failed attempt). A disk that is unmounted at recorder start and then recorded onto across a restart can still be confirmed by the previous process's segments; the reconcile breaker remains the backstop there.

Revisit triggers. A stuck-session reconnect loop observed on a healthy camera; operators asking to tune the repeat interval; a persistent retry queue needed because the cache moves off tmpfs; a confirmed false marker from the cross-restart case above.

2026-10-08, server_settings.crumb_rtsp_base is CLIENT-FACING ONLY; the recorder dials its embedded go2rtc over loopback, and the bootstrap no longer seeds either crumb_* base column from the recorder's env​

Context. One column was serving two audiences that need different values (issue #630). The api hands crumb_rtsp_base to native clients, so it has to be an address a phone can dial. The recorder read the same column for its own ffmpeg workers, and go2rtc is embedded in the recorder container, so every camera byte left the container through the host's published RTSP port and came back in through the bridge NAT: measured at roughly 1.74 TB/day of container eth0 against about 1.08 TB/day of real ingest, with lo essentially idle. The shipped go2rtc/go2rtc.yaml already claimed the recorder connected over loopback and rode go2rtc's loopback auth exemption. It did not.

The configuration-only workaround (leave the column empty so each consumer falls back to its own env) held for 25 days and then failed on a host reboot: ensure_server_settings_table runs on every process start in BOTH services and backfills any empty column from that process's env, and the recorder's CRUMB_GO2RTC_RTSP_BASE is rtsp://localhost:8554 in the shipped compose. The recorder therefore wrote loopback into the client-facing column, every camera on every client showed "Reconnecting", and recorded playback kept working, which reads like a client bug.

Decision. Split the two audiences in code, in three parts.

  1. The recorder's base resolution moved to crumb_common::rtsp_base. When go2rtc is embedded (GO2RTC_EMBEDDED is anything but false, the default) the crumb base is rtsp://127.0.0.1:<port> and server_settings.crumb_rtsp_base is ignored entirely, operator-set or not. The port is DEFAULT_EMBEDDED_RTSP_PORT (8554, what the shipped go2rtc.yaml binds), overridable with CRUMB_GO2RTC_LOOPBACK_PORT. With GO2RTC_EMBEDDED=false the existing order stands: the DB column, then CRUMB_GO2RTC_RTSP_BASE, then GO2RTC_RTSP_BASE. The GO2RTC_EMBEDDED parse now lives once, in crumb_common::config::go2rtc_embedded, shared with the supervisor in go2rtc_embed.rs, so the two can never disagree.

  2. That module is the ONLY recorder-side resolver. recording.rs and motion.rs had each grown a copy and they had diverged: the motion copy fell straight back to GO2RTC_RTSP_BASE, the FRIGATE base on a split install, so with the column empty a Crumb-served camera's motion sub-stream was opened against Frigate's go2rtc.

  3. ensure_server_settings_table takes a SettingsSeedRole. The recorder seeds NEITHER crumb_* base column, and for crumb_rtsp_base even an api-role loopback candidate is refused, because a client handed rtsp://localhost:8554 dials itself. Every other column still seeds from either process exactly as before. A fresh install is unaffected: the first-run wizard suggests the value from the Host header (/auth/setup-status → suggested_rtsp_base) and writes it through PUT /config/server.

    crumb_api_base is the same defect in the same upsert, found while auditing this one. It is the go2rtc REST base the api proxies iOS/macOS live (MSE and WebRTC signaling), frame.jpg snapshots and notification images through, and the recorder's compose default was CRUMB_GO2RTC_API_BASE=http://localhost:1984 while nothing in the recorder reads that key at all. If the recorder won the boot race with the column empty, the api ended up dialing localhost:1984 inside its OWN container, where nothing listens: live and snapshots die on those paths, recording keeps working, and the install looks healthy. The recorder's copy is also gone from the stock compose, so the trap has no source there any more. There is deliberately no loopback guard on this column: it is dialed by the api PROCESS, so http://localhost:1984 is legitimate on a single-host install, it is simply never the recorder's value to supply.

The bootstrap upsert also gained updated_at = now() plus a WHERE clause that fires only when the backfill actually changes a column. Before, the row was rewritten on every process start while updated_at stayed put, so a value written minutes ago still showed a timestamp from weeks earlier. Now an untouched row is genuinely untouched and a changed row says when.

Rejected:

#OptionVerdict
1Find one value that works for both audiencesRejected: none exists. An address a phone can reach is never the address the recorder should dial for a restreamer inside its own container.
2A second DB column for the recorder's baseRejected: a schema change, a new admin field, and a new way to misconfigure recording, to express a value that is derivable with certainty whenever go2rtc is embedded.
3Rename the recorder's env var (for example CRUMB_GO2RTC_DIAL_BASE) so the two facts stop sharing a nameRejected for now: after part 1 the recorder ignores that var on the default path entirely, so the collision is moot in practice, and renaming would silently strip the escape hatch from an existing GO2RTC_EMBEDDED=false install that already sets it. If the var ever grows a third meaning, revisit.
4Parse the port out of go2rtc/go2rtc.yaml's rtsp.listenRejected: crumb-common would have to read a recorder-container path and hand-parse YAML whose values can be ${VAR} placeholders, and a parse failure would land on the recording path. A documented constant plus an override cannot fail that way.
5Derive the loopback port from CRUMB_GO2RTC_RTSP_BASE instead of a new varRejected, and it is the dangerous option: the issue recommends operators pin that var to the client-reachable address as a seatbelt, which carries the HOST-published port (18554), and nothing listens on 18554 inside the container. That would stop recording rather than waste bandwidth.
6Change the non-embedded order to env-before-column, as the issue's suggested fix listsNot taken: that is not today's order, and the repo-wide precedence is that an admin-set DB value wins over env with an empty value falling back to env. The escape hatch is intact either way, so the behavior-preserving order was kept.
7Keep the hairpin and only fix the documentationRejected: doubling container network I/O for the whole fleet, continuously, also makes capacity planning from container graphs impossible and leaves recording dependent on the host address staying reachable from inside the container.

Trades knowingly accepted:

  • An install that leaves GO2RTC_EMBEDDED at its default while actually running go2rtc elsewhere now dials loopback and finds nothing. That install was already running a second, Crumb-supervised go2rtc in the recorder container; the fix is the documented GO2RTC_EMBEDDED=false.
  • An operator who changes rtsp.listen in go2rtc.yaml must also set CRUMB_GO2RTC_LOOPBACK_PORT. The default is the shipped port, and both places now say so.
  • On a compose install where the api's CRUMB_GO2RTC_RTSP_BASE is empty, the client-facing column is no longer pre-seeded with anything, so it stays empty until the wizard (or PUT /config/server) sets it. It used to be pre-seeded with the recorder's loopback value, which was worse than empty.
  • crumb_api_base on a stock compose install is likewise no longer pre-seeded by whichever process booted first. Empty falls back to the api's own CRUMB_GO2RTC_API_BASE, which compose sets to http://recorder:1984, so the effective value is unchanged and it is now the api's env that decides it.
  • The recorder's RTSP connection to its own go2rtc is now exempt from auth (go2rtc exempts true loopback peers). Credential injection is unchanged on that path, the credentials are simply ignored, and nothing about how clients authenticate moved.

Revisit if: go2rtc gains a way to express "this listener is internal only" that Crumb could consume directly, or the recorder ever needs to reach a restreamer in a sibling container on the compose network while GO2RTC_EMBEDDED is still true (then the posture needs a third state, not a reinterpretation of the column).

2026-10-08, The recorder creates its own recording streams in the embedded go2rtc when they are missing; the api stays the owner of everything else​

Context. go2rtc keeps streams in memory only, and the api's reconcile loop was their only writer. A go2rtc or recorder restart while the api was down, crash-looping or still booting left go2rtc empty, so no Crumb-served camera recorded until the api came back (audit finding R10). An api that refuses to boot on a bad secret makes that window longer, not shorter.

Decision. When the recorder runs the embedded go2rtc (GO2RTC_EMBEDDED not false and the child was spawned), its stream_registry module creates each camera's recording streams (main and <name>_sub) that go2rtc does not have: once before the camera workers start (bounded at 10 s) and every 5 s after. The definitions come from crumb_common::go2rtc_streams::recording_streams, which the api's reconcile now calls too, so both writers send byte-identical name and source. The recorder is create-only: it never re-PUTs or PATCHes an existing stream, never touches derived streams (_subv, _mainv, _mobile), and only deletes a stream it created in the same pass whose camera row vanished on a re-read (so a camera delete is not undone). In steady state a name must be missing on two reads 2 s apart before it is created, which lets a healthy api win.

Rejected:

  • Falling back to the camera's own RTSP (source_url) after N "stream not found" failures: a second camera session per camera (session-capped cameras refuse it), a different code path to keep correct, and Frigate and live clients would still be dark.
  • Moving all stream management into the recorder: the derived client streams, rejection alerts and source-edit reconnects need api state and are not recording-critical; moving them is a larger change with no recording benefit.
  • Having the recorder PATCH existing streams too: two writers updating the same stream is exactly the fight to avoid.

Trades knowingly accepted:

  • Two writers can both create the same missing name; they send the same definition, so the worst case is one replaced object before any consumer attached.
  • A source edit landing in the few milliseconds between the recorder's row read and its PUT can briefly re-create the old source; the api's next reconcile PATCHes it to the new one.
  • After a recorder-only restart the api's cheap count check may see the main streams already present and leave _mobile/_subv to its 60 s periodic pass instead of its 5 s shortfall path.

Revisit if: go2rtc gains persistent runtime streams or a writable config we can safely use, or stream management moves wholly into the recorder.


2026-09-08, Notification times are rendered PER PROVIDER: client-localized markup for Discord and Slack, the server's TZ for everyone else​

Context. Every channel message formatted the event timestamp in UTC with a literal "UTC" suffix, in ChannelMessage::token_map/text. On a phone hours away from UTC the alert reads as the wrong time at a glance (issue #628). Stored timestamps are UTC and stay that way; the question was only what the outbound text should say.

Decision. The timestamp style is chosen from the destination's kind (channel_notify::TimeStyle, picked by time_style_for). Discord gets <t:UNIX:f> / <t:UNIX:t> / <t:UNIX:d>, Slack gets <!date^UNIX^{tokens}|fallback> with a server-zone fallback string; both are markup those providers' own clients resolve against the viewer's zone, so one alert reads correctly for every recipient regardless of where they are. ntfy, Pushover, Telegram, the generic webhook, and any future kind render %Y-%m-%d %H:%M:%S %Z in the server's TZ (resolved once at startup into ApiConfig::server_tz via crumb_common::config::server_tz, threaded into the notification engine the same way the go2rtc credentials already are). The %date%/%time%/%datetime% template tokens follow the same style, so a custom template needs no per-provider variants. The generic webhook's JSON ts stays a raw UTC instant: it is a machine contract.

Rejected:

#OptionVerdict
1Keep UTC everywhereRejected: the reported bug.
2Server TZ for every provider, no markupRejected: correct for the operator at home, still wrong for anyone reading in another zone, and Discord/Slack already solve that for free.
3A per-user or per-channel timezone settingRejected for now: a new setting, a new column, and new console UI to reproduce what the two markup-capable providers do by themselves, for the providers where it would matter least.
4Convert the stored ts on writeRejected outright: the database stays UTC. Recorder and retention correctness depend on it.

Trades knowingly accepted:

  • The Discord and Slack messages now contain provider-specific markup, so the raw text is less readable if it is ever inspected outside those clients (Slack's fallback covers this; Discord's does not).
  • The admin console's alert-text preview can only show one style; it shows the server-zone rendering and says so.
  • An operator who never sets TZ gets UTC, matching the documented .env.example contract ("if unset the default is UTC, NOT any local zone").

Revisit if: operators in mixed-zone households ask for per-recipient times on the non-markup providers (then option 3, hung off the notification rule, not off ChannelMessage), or a new channel kind arrives that has its own client-side timestamp markup (add a TimeStyle variant; do not special-case it in a dispatcher).

2026-09-07, The app-switcher cover is unconditional on mobile, and Android hides the recents snapshot without a permanently secure window​

Context. The operating system takes a picture of the app as it leaves the foreground and shows it on the task switcher, so whatever camera was on screen stays visible to whoever picks the device up next. iOS already had an opaque cover for this (RootView.privacyShieldVisible), but it was drawn only when the opt-in biometric lock was on, and that setting defaults to off. Android had nothing.

Decision, iOS. The cover is now drawn for any signed-in session whenever the scene stops being .active, independent of biometricLockEnabled. The two concerns are separate: the cover is about what the system snapshot records, the lock is about who may resume the session. The lock keeps gating only the Face ID / passcode challenge, and .inactive still never triggers that challenge, since .inactive also fires on harmless momentary interruptions (Control Center, an incoming-call banner, a system alert).

Decision, Android. API 33+ calls Activity.setRecentsScreenshotEnabled(false) once in onCreate. Below 33 the window is made secure in onPause and cleared again in onResume, so it is secure only across the transition during which the snapshot is taken. Picture-in-Picture is exempt from the pre-33 path (a secure window would render the floating video window blank), and the flag is cleared again in onPictureInPictureModeChanged because entering PiP is asynchronous and onPause can run before the activity reports itself as being in PiP. The per-API-level decision lives in RecentsPrivacy so it is unit-testable.

Rejected: a permanently secure Android window (FLAG_SECURE set once in onCreate). It is the simplest and strongest option and it is what most guidance suggests, but it also disables ordinary screenshots and screen recording of the app. The maintainer records screenshots and screen captures of the Android client for documentation and for the site, and an operator photographing an incident off their own phone is a legitimate use. Blocking that to protect a preview the operator can also protect by closing the app was judged the wrong trade.

Rejected: a macOS occlusion or resign-active cover. macOS has no task switcher preview of this kind, and a video wall on a second monitor is meant to stay readable while another app has focus. macOS behavior is unchanged.

Trades knowingly accepted:

  • Below API 33 the flag toggles on every pause, which includes pauses that are not "leaving the app" (a system permission dialog, the biometric prompt). The effect is invisible: the flag is cleared again on the next resume.
  • Below API 33, leaving the app straight into PiP can still put a video frame on the recents card, because that path is deliberately exempt. API 33+ devices use the dedicated switch and are unaffected.
  • The iOS cover now appears for users who never asked for a lock. It is a plain opaque background with no interaction, so the only cost is a brief flat colour during multitasking.

Revisit if: Android ever gains a pre-33-compatible recents-only switch (it will not, but a support library shim would count), or if the minimum supported API rises to 33, at which point the FLAG_SECURE fallback and RecentsPrivacy can both be deleted. Also revisit if operators report that the PiP exemption matters on old devices, in which case the pre-33 path can drop PiP entirely (auto-enter off below 33) instead of exempting it.

2026-09-07, Session validity is a positive cached lookup per jti, not a cached revoked-set alone; per-user camera grants are read from the user row​

Context. sessions (migration 0033) made a token revocable, and the AuthUser extractor checked it against an in-memory set of REVOKED jtis refreshed on write. That set answers "was this session signed out". It cannot answer "was this ever a session at all", and sessions.user_id is ON DELETE CASCADE, so removing an account made its rows disappear rather than be flagged. A token for a removed account therefore read as "not revoked" and kept working for the rest of its exp, which for a remembered mobile login is years. Separately, a user's per-user camera grants were baked into the token at login and unioned with the role's cameras at request time, so editing them did nothing until that user signed in again.

Decision. The extractor now resolves each jti POSITIVELY: a small AppState cache maps jti to "session row present and not revoked, plus the owning user's users.camera_ids", populated by one joined query on a miss and cleared on any user change. An unknown jti is resolved against the DB then and there, never assumed either way, and the resolved grants replace claims.camera_ids in the role-union. A login token with no jti is refused outright (the table predates the first public release, so no supported client holds one). The existing revoked-set cache is kept as the fast path for revocation; the new cache answers existence.

Rejected:

  • Caching the LIVE set instead. A session minted a millisecond ago on another API replica would not be in this replica's set until the TTL lapsed, so a user who just signed in would be spuriously signed out. A false 401 right after login is worse than a revoke that lands a few seconds late.
  • Querying sessions on every request. Correct but puts a DB round trip on the hot path of every authenticated request, including the media reads a video wall issues continuously. The repo's established pattern (roles_cache, revoked_jtis) is cache-the-truth, refresh-on-write.
  • Also ending sessions when only the extra-cameras list changes. Once the grants are read from the row on each request, the new set is in force on that user's very next request, so signing them out adds nothing but disruption (a viewer loses their wall because an admin granted them one more camera). A password or role change still ends every session: those replace the credential or what the account may do.
  • Keeping the opt-in "reject legacy jti-less tokens" switch the 0033 migration sketched. There are no legacy tokens to keep working, and a configurable switch for "accept credentials that can never be signed out" is a setting nobody should choose.

Trades knowingly accepted:

  • A cold jti costs one query, so a burst of first-time-seen sessions (an API restart with many clients reconnecting) costs one query each, once.
  • Across replicas, a user edit made on another replica lands within the cache TTL rather than instantly; a revoke still lands within the shorter revocation TTL. Single-process installs (the norm) see both immediately.
  • A scoped media token minted just before an account was removed keeps working for the rest of its short life. It is one camera, media bytes only, minutes, which is the property the media token was designed around.
  • A supplied password always counts as a change, even if it is the same string: hashes are salted, so old and new are never comparable.

Revisit if: an install runs enough distinct concurrent sessions that the per-jti cache is a memory or miss-rate problem (then key the cache by user and carry a session generation counter), or Crumb grows a real multi-replica deployment story where cache TTLs are too coarse (then push invalidation between replicas, for example over the existing DB with a notify channel).

2026-09-07, Opening the web console in an external browser uses a single-use handoff code, not the desktop client's session token​

Context. The desktop client can show the server's web admin console two ways: embedded in its own WebView, and "Open in browser", which hands the URL to whatever browser the OS launches. Both used the same URL shape, /admin#token=<session token>&embed=1, which admin.html's bootSSO reads and persists like a login. That is fine for the embedded WebView, which is this client's own process, but "Open in browser" crosses a process boundary: the token then lives in a browser's history, its profile storage, and within reach of whatever extensions the operator has installed, for as long as the session lasts.

Decision. The embedded WebView keeps #token=. "Open in browser" instead calls POST /auth/handoff (full session required, a scoped media token is refused), gets back a single-use code that expires in about a minute, and opens /admin#handoff=<code>. The console posts the code to POST /auth/handoff/exchange, which consumes it exactly once and mints the browser its OWN session: its own jti, its own sessions row, normal (not "remember me") expiry, so it is listed under "your sessions" and every sign-out path reaches it. Codes are held in memory only, bound to the issuing user and session; an expired, unknown, reused, or signed-out code is a 401 and the console falls through to its normal login form.

Rejected:

  • Keep passing the session token in the fragment. Cheapest, and the fragment never reaches the server, but the credential still lands in browser history and profile storage under a different security boundary than the client that owns it.
  • Open the console with no credential at all. Safest and free, but the operator is asked to type their password again to reach a console they are already signed in to on the same machine, which is exactly the friction the handoff exists to remove.
  • Persist codes in Postgres. Rejected as unnecessary machinery: a code lives for seconds, and losing the map on a restart only costs a second click.

Trades knowingly accepted: codes are per-process, so an install running several API replicas behind a load balancer can have the exchange land on a replica that never saw the code (the operator clicks again, or the browser shows the login form). The browser's session is not the client's session, so signing out in one does not sign out the other; both are visible and revocable under "your sessions".

Revisit if: Crumb starts supporting multiple API replicas behind a shared load balancer as a documented deployment, at which point the code store moves to Postgres (or a shared cache) with the same single-use semantics.

2026-09-07, Media routes: bounded waits answering 503, not unbounded queues​

Context. Every expensive media path (clip and low-bitrate transcodes, the filmstrip's single-frame extractions, and now the live-still proxy) gates its work behind a shared semaphore. Those acquires were plain acquire_owned().await, an unbounded queue: once the permits were gone, further requests parked indefinitely, holding a connection and never answering. The media router also carried neither a request timeout nor a rate limit, both of which the JSON routes have had since #17.

Decision. Every media semaphore acquire goes through one helper (services/api/src/media_limits.rs::acquire_bounded) that gives up after a per-call-site budget and returns 503 plus Retry-After. The media router gains its own, much larger rate-limit bucket (burst 1200, 240/s sustained, roughly 6x the busiest real client) and a 180 s time-to-response bound.

Why a timeout is safe over streaming media. tower_http's TimeoutLayer bounds only the handler future; response bodies have a separate ResponseBodyTimeoutLayer that is deliberately not used. Segment downloads, export archives, and the open-ended live stream.mp4 all return headers immediately and stream afterwards, so none of them can be cut. The one route that legitimately produces for minutes before answering, the on-demand DB-vs-disk size verification walk, is mounted outside the timeout for exactly that reason.

Rejected: making the clients wait longer. Raising the permit counts or the wait budgets keeps the failure mode (a request that never answers) and only moves the threshold. The clients already treat a failed media fetch as "keep the placeholder, poll again", so "busy, retry shortly" is both truthful and the behaviour they already handle.

Rejected: a per-user or per-camera semaphore instead of a global one. It would give fairer degradation, but it multiplies the tuning surface and the memory footprint for a system whose realistic worst case is a handful of operators. Revisit if a deployment reports one client starving others despite the bounded waits.

Trades knowingly accepted. Under genuine saturation a scrub thumbnail or a wall tile now fails fast instead of eventually arriving; that is the intended swap. A camera whose full still-fetch ladder failed is latched for 10 s so subsequent polls make a single attempt instead of the cold-start retry ladder (a failed single attempt never extends the latch, and the first request after the window runs the full ladder again as a probe), which means a camera coming back can be up to 10 s late to serve its first still.

Revisit if: operators report 503s on the media routes during normal use (the budgets or permit counts are too tight), or a deployment large enough to need per-principal fairness appears.


2026-09-07, Filmstrip widths snap to a fixed ladder; export requests are capped​

Context. The thumbnail width was clamped to 48..640 but otherwise free, and it is part of the on-disk cache key, so 593 distinct widths for one instant meant 593 ffmpeg runs and 593 cache files for what is visually one frame. Separately, POST /export validated only start < end: nothing capped the window, the camera count, or duplicates in the camera list, and filter_camera_ids is a scope filter rather than a de-duplicator (for an admin it returns the list verbatim), so [X, X, X, ...] ran N sequential full-range encodes all writing the same output file with -y, counted as one job against EXPORT_MAX_CONCURRENT.

Decision.

  • Widths clamp and then snap to 80/160/320/480/640 (nearest, ties down). The buckets are chosen so every width the shipped clients ask for lands on itself: 160 (Android and desktop scrub lists), 320 (the Android playback wall), 480 (the iOS scrub still, the desktop preview frame, and the THUMB_PREGEN_WIDTH default), so no existing or pre-generated cache entry is invalidated.
  • POST /export sorts and de-duplicates the camera list, caps it at 50 distinct cameras (the same ceiling /export/batch puts on clips, since both fan out to one sequential encode per unit of work), and caps the window with a new EXPORT_MAX_RANGE_SECONDS (default 86400, a full day of one camera).
  • Each per-camera encode gets a wall-clock budget derived from the range (4x realtime, floored at 10 minutes, capped at 24 hours) and kill_on_drop. A child that wedges now fails the job with a stored error instead of leaving it Running forever, which used to consume an EXPORT_MAX_CONCURRENT slot permanently until the api was restarted.

Rejected: quantizing by rounding to a multiple (say 32 px). It bounds the key space too, but it does not guarantee the clients' existing widths are fixed points, so the whole warm thumbnail cache (including anything pre-generated at 480) would be re-rendered at neighbouring keys on upgrade.

Rejected: de-duplicating inside filter_camera_ids. That function is the RBAC scope filter used by several handlers, including ones that rely on comparing the filtered length to the input length to detect a partial-scope request. Making it also dedup would silently change those comparisons.

Rejected: a stall watchdog on ffmpeg progress instead of a wall-clock budget. More precise (it would catch a wedged child in seconds rather than hours) and the progress parsing already exists, but it is a larger change to the export worker than the failure mode warrants right now.

Revisit if: a deployment genuinely exports multi-day ranges and finds the default cap or the derived encode budget too tight (both are configurable; the budget is not), or if per-camera export throughput makes the 4x realtime factor the binding constraint, at which point the stall watchdog becomes the better mechanism.

2026-09-07, The api refuses to start on the placeholder database password, and every _FILE twin wins over its plain variable​

Context. Three inconsistencies in how secrets were read and documented:

  • db.rs's ha_env read HA_TOKEN first and only fell back to HA_TOKEN_FILE, the reverse of config::secret_env, which every other secret goes through. An operator who mounted a Docker secret while a stale plain value sat in .env silently got the stale one, and the docs-site already said HA_TOKEN_FILE was "read in preference to HA_TOKEN".
  • The docs-site said GO2RTC_USER/GO2RTC_PASS "don't support _FILE". The api routes both through require_secret, which does read the _FILE twin. What is actually true is narrower: the embedded go2rtc restreamer expands the plain variables from the process environment, so the plain form has to be set regardless.
  • .env.example and docker-compose.yml ship POSTGRES_PASSWORD=change-me and a matching DATABASE_URL. JWT_SECRET and GO2RTC_PASS both refuse their documented placeholder at startup; the database password did not.

Decision. ha_env calls secret_env("HA_TOKEN"), so the file wins like everywhere else. The two docs pages now describe the GO2RTC_* situation accurately. And ApiConfig::from_env refuses to start when DATABASE_URL's userinfo password is one of the documented placeholders (change-me, changeme, case-insensitively), with an error naming the fix, including the part that trips people up: a changed POSTGRES_PASSWORD does not re-initialize an existing Postgres data volume, so the password has to be changed in the database too.

Trade-off accepted: this is a startup-breaking change for an install that is currently running on the placeholder. That is the point, and it matches what JWT_SECRET and GO2RTC_PASS have always done; the error says exactly what to do. Only exact placeholder matches are refused, so a real password that happens to begin with change-me still starts.

Rejected: warning instead of refusing (a warning in a log nobody reads is how the value survives to production, and the two adjacent secrets already set the refuse precedent); a generic weak-password check (arbitrary, and Crumb has no business grading operator passwords, only rejecting the one it shipped itself).

Revisit if: a deployment shape appears where the api legitimately cannot know the real password, e.g. an external connection broker, in which case the check should key on the password being absent rather than a value list.


2026-09-07, Camera source URLs mask their password on read; sending the mask back means "keep it"​

Context. A camera's source_url / source_sub_url carry the camera's own user:pass@ credentials inline, because that is what go2rtc dials. onvif_password has been write-only since the distributability work (never copied into a DTO, blank on PUT keeps the stored value), but the two source URLs were returned verbatim by GET /config/cameras, so every admin session, and anything that logged or cached that response, held the camera passwords in clear.

Decision. camera_to_dto masks the userinfo password with a fixed string (crumb_common::redact::CREDENTIAL_MASK, ********) and adds source_has_credentials / source_sub_has_credentials so a client can say "there is a stored password" without holding it. PUT /config/cameras/{id} resolves a submitted URL against the stored one: a password equal to the mask means keep the stored credential, anything else is taken literally and replaces it. The rest of the submitted URL always wins, so an operator can change the host or path while leaving the masked password alone. The masking and unmasking live in services/common/src/redact.rs next to the log-redaction helpers, which already own the scheme://user:pass@host parsing rule.

Why a mask inside the URL rather than a separate password field. The URL is one text field the operator types, pastes and edits as a whole; splitting the credential out would mean a different editing model in the console and a migration of the stored shape. The mask keeps the field a URL, keeps copy-paste-and-edit working, and reuses the read/write contract onvif_password already established.

Trade-offs accepted: a camera whose real password is literally ******** cannot be distinguished from the mask, so a PUT would keep the stored value rather than set that password. The API also cannot tell "keep" from "set to the same value", which is the same limitation the blank-keeps-it ONVIF password field has. The console shows a hint under the stream fields when credentials are stored.

Unaffected by design: the recorder and the go2rtc reconcile loop read source_url from the database (db::list_camera_streams), never from a DTO, so the restream keeps dialling the real credentials.

Rejected: omitting the URLs entirely from the DTO (the console needs to show and edit them); returning them only to a narrower role (there is no role above admin); a per-request "reveal" endpoint (adds a way to read the password back out, which is the thing being removed).

Revisit if: a client ever needs the real source URL for something other than editing, or the console moves to a structured stream editor with its own password field, at which point the mask can be dropped in favour of a write-only field.


2026-09-07, Login backoff is keyed on (account, client), not on the account alone​

Context. Issue #127 added a repeated-failure backoff to POST /auth/login: five consecutive failures for a username, then 429 + Retry-After with an exponential window capped at 15 minutes. The counter was keyed on the username only, so anyone who could reach the login endpoint and knew (or guessed) a username could keep its owner out for as long as they kept failing, from anywhere.

Decision. The counter key is now username + \u{1f} + client, where client comes from rate_limit::client_key — the same derivation the per-client request bucket uses, so both honour TRUST_PROXY identically and can never drift. Thresholds, the exponential schedule, the cap, the map-pruning bound and the 429 + Retry-After shape are all unchanged. A success clears only the client that succeeded. The per-client request bucket stays the global limiter on top, unchanged.

Two further rules keep the per-client key from being something a client can choose:

  • Proxy trust is per peer. With TRUST_PROXY on, X-Forwarded-For is read only when the TCP peer is in TRUSTED_PROXIES (IPs, CIDRs or hostnames, default caddy, re-resolved every 30 s). The client is the right-most hop that is not itself a trusted proxy, i.e. the entry the proxy appended, never the client-supplied left-most one. Anything that reaches the published :8080 directly is keyed on its TCP peer whatever it sends. Previously the first hop was taken from any peer, so a direct client could pick a new key per request.
  • An account-wide ceiling sits on top. 30 failures for one username within a sliding 15 minutes, from any mix of clients, put the whole account into a backoff of 30 s that doubles per further failure up to the same 15-minute cap, until 30 minutes pass with no failure. One client cannot reach it alone: its own backoff (5 free, then 2, 4, 8, ... s) admits at most 13 failures in 15 minutes. A success does not clear the account count.

Trade-off accepted: someone able to fail from three or more addresses at full speed can still make the owner wait (up to 15 minutes per failure while they keep going). That is the price of a brake that address rotation cannot dodge, and it takes far more than one noisy client to trigger.

Rejected (proxy trust): trusting the Docker bridge range by default (on some setups host-local and published-port traffic arrives from the bridge gateway, so it would trust direct clients); a fixed Caddy address in compose (needs a pinned subnet that can collide with existing networks); honouring the left-most hop (client-controlled).

ConnectInfo is extracted as an Option in the login handler, so a router driven without into_make_service_with_connect_info (a test harness) still serves logins, with every such request sharing one "unknown-peer" key.

Rejected: keeping the account-wide key with an operator allowlist (more configuration, same failure mode by default); dropping the per-account counter entirely and relying on the request bucket (loses the per-account signal, and the bucket is deliberately generous for normal JSON traffic).

Revisit if: Crumb ever grows an account-lockout policy an operator actually asks for (compliance-driven), in which case it should be an explicit, opt-in setting with an admin unlock, not an implicit side effect of failure counting.


2026-09-07, Response headers: two site-wide headers everywhere, a Content-Security-Policy on the /admin document only​

Context. The api sent no X-Content-Type-Options, no Referrer-Policy, and no Content-Security-Policy on any response. The admin console (services/api/src/admin.html) is one include_str!-embedded page whose entire network surface is same-origin: every fetch() is a relative path, the icon set is inline SVG (Lucide path data embedded, not hotlinked), and the only non-'self' image sources are data: (inline placeholder glyphs) and blob: (snapshot frames from URL.createObjectURL). It has no <iframe>, no <base>, no <form>, no WebSocket/EventSource/Worker, and one inline <script>.

Decision. X-Content-Type-Options: nosniff and Referrer-Policy: no-referrer are set on every response by a tower_http::set_header layer applied outermost in main.rs (so it also covers the /auth subtree, which is merged outside the CORS layer). The Content-Security-Policy is attached to the /admin route only, not to JSON or media responses, whose consumers are native clients and for which a document policy means nothing. The policy and both helpers live in services/api/src/response_headers.rs with a test that asserts the wiring.

Trade-off accepted: the policy carries 'unsafe-inline' for script-src and style-src, because the console is deliberately a single self-contained file with one inline script and inline style= attributes throughout. Nonces or hashes would mean changing how the page is assembled and served, which is a much larger change than this one; the policy still pins every load origin to 'self' (plus data:/blob: images) and sets base-uri 'none', object-src 'none', form-action 'self', frame-ancestors 'self'.

frame-ancestors 'self' is safe for the desktop client: it navigates a native WebView2 to /admin as a top-level document (apps/desktop-flutter/lib/ui/ admin_console/admin_console_screen.dart), not in an <iframe> as the retired Tauri client did.

Also noted, deliberately unchanged: admin.html keeps its bearer token in localStorage. Moving it to a cookie or in-memory-only store changes the whole sign-in/refresh flow and every client that deep-links into the console with #token=; it is out of scope here.

Rejected: a single global CSP covering the JSON/media routes (meaningless for native clients, and one more thing to keep in step with the media surface); nonce/hash-based script-src (needs the console to stop being one static include_str! file).

Revisit if: the console ever gains an external asset, an <iframe>, a WebSocket, or a cross-origin fetch() (all four would need a directive widened, and the widening should be argued here first), or if the console is split into separate served assets, at which point 'unsafe-inline' can go.


2026-08-10, Home Assistant climate (thermostat/HVAC setpoint) control is out of scope​

Context. #442 introduced value-setting HA controls. Light dimming (set_brightness), cover position (set_position), and fan speed (set_speed) shipped in v0.2.0 and actuate from the on-video badge, gated by the actuators capability. The issue also listed a thermostat/climate setpoint (climate.set_temperature).

Decision. The climate domain is deliberately NOT in the action allowlist (HA_ACTION_ALLOWLIST, services/api/src/ha.rs); a unit test asserts climate.set_temperature stays rejected. A camera view is a security-monitoring surface, not a thermostat UI, and setpoint control would add a per-entity min/max/step/unit contract across every client for something the operator can already do in Home Assistant itself. #442 was closed as complete on the three delivered value controls.

Rejected: adding climate control (the "Slice 2" once sketched in an HA-management plan). Owner decision, 2026-08-10.

Revisit if: the maintainer wants HVAC control on the video wall and will own the setpoint min/max/step/unit UI across all clients. Until then, keep climate out of the allowlist.


2026-08-08, A main whose SDP lacks fmtp is repaired for Android by an OPT-IN H.265->H.264 transcode (_mainv), not the _subv-style copy — because a copy-remux reintroduces an AP Media3 can't read​

Context. Some cameras (verified: a Uniview H.265 LPR main) publish their main over RTSP with an SDP whose video track carries no a=fmtp / no sprop-parameter-sets — the parameter sets ship only in-band. Android's Media3 RTSP client requires fmtp and rejects the DESCRIBE outright with IllegalArgumentException: missing attribute fmtp, so the main never brings up a frame. CrumbLiveFallback logging (#561) captured exactly this on the LPR main: errorCode=2000/retryable ... detail="... IllegalArgumentException: missing attribute fmtp <- RtspPlaybackException: missing attribute fmtp". Recording, motion, desktop (libmpv) and web are all unaffected — ffmpeg recovers the in-band sets. This is the same failure class as the H.264 _subv repair (#483/#501), now seen on an H.265 MAIN.

The obvious fix was to mirror _subv: register ffmpeg:<name>#video=copy as a <name>_mainv and hand Android that. Empirically it does not work for H.265, and the reason is the whole point of this entry.

Empirical finding (2026-08-08, against the real LPR stream via the recorder's embedded go2rtc; ffprobe + tshark RTP capture over loopback).

  • The raw lpr main SDP has a=rtpmap:96 H265/90000 and no a=fmtp — the confirmed Media3 blocker. Its native go2rtc packetization is AP-free (399 FU fragments + single-NAL parameter sets, zero aggregation packets), i.e. it would be Media3-playable if only it had fmtp.
  • A known-good 4K H.265 main (driveway, which plays full-HD on the same phone) is likewise AP-free — confirming native restreams don't aggregate.
  • A copy-remux (ffmpeg:lpr#video=copy) DOES restore a=fmtp:96 sprop-vps/sps/pps=... — but go2rtc then emits, at every keyframe, an HEVC RTP Aggregation Packet (payload type 48) bundling VPS+SPS+PPS+SEI (measured: 2 APs across 2 keyframes, alongside 1824 FU). Media3's RtpH265Reader has never implemented AP depacketization (androidx/media#1008) and throws processAggregationPacket on the first one — which is the keyframe it needs to start. So the copy-remux only trades the missing attribute fmtp rejection for a processAggregationPacket crash. The AP is introduced by the ffmpeg: republish path, not present in the native restream.

Conclusion: for H.265, an SDP-only repair is not achievable through go2rtc's copy-remux idiom. The only repair that yields a main Media3 can decode is a re-encode to H.264 (H.264 RTP from go2rtc uses STAP-A/FU-A that Media3 fully supports).

Decision.

  • Two independent fixes, in one change:
    1. Client (ships on, free): add missing attribute fmtp to LiveStreamFallback's deterministic step-down signatures (next to processAggregationPacket). The error is identical on every retry, so the LPR main now steps down to the H.264 sub (SD) on the FIRST failure instead of waiting out ~5 IO-coded retries (~30 s). Narrow by design — matched on the exception-chain message, not by widening any error code to step down (that would reintroduce #560's eager-SD).
    2. Server (opt-in, default OFF): a per-camera, detection-driven repaired main <name>_mainv, advertised as rtsp_mainv_url and tried by Android right after the raw main (main -> mainv -> subv -> sub -> mobile). It is a full-res H.265->H.264 transcode, gated behind MAIN_REPAIR_TRANSCODE_ENABLED because it costs real recorder CPU (a libx264 encode) for as long as an Android fullscreen viewer is attached (go2rtc spawns it lazily, so idle cost is zero). Detection reuses sdp_video_lacks_fmtp on the MAIN producer (always warm — the recorder consumes the main through go2rtc), sticky across an unknown verdict, exactly like _subv.
  • The recommended fix for an operator who can reach the camera remains the free one: set the camera's main to H.264 in its own UI. The transcode is for cameras that can't, and the client fast-step-down means even with everything off the camera is watchable in SD immediately.

Rejected:

  • Mirror _subv with ffmpeg:<name>#video=copy for the main (cheap, no CPU). This is what a reader of the _subv code would reach for first. Proven not to work for H.265 above: the copy-remux reintroduces a parameter-set Aggregation Packet Media3 can't depacketize. Kept off the table with an empirical citation so the next session doesn't re-try it.
  • Enable the transcode by default / for every fmtp-less main. A full-res libx264 encode is not free; silently turning it on would tax the recorder for a minority of cameras. Opt-in + per-camera detection keeps the cost where the operator chose to pay it.
  • A hardware (NVENC/VAAPI) transcode to cut CPU. Attractive on this host (it has an iGPU + an RTX 4000) but out of scope here, and VAAPI on this deployment is already fragile (render-node reorder incidents). Left as a future option below.
  • Do nothing server-side, rely on the client fast-step-down alone. Enough for "watchable" (instant SD), but the maintainer specifically wanted an HD path that isn't "nuclear"; this provides it without imposing the cost.

Trades knowingly accepted.

  • With the repair off (default), an fmtp-less H.265 main is SD on Android (the H.264 sub) — same as before, only now instant.
  • With it on, that camera's fullscreen Android view costs one full-res libx264 process on the recorder while watched.
  • _mainv is a TRANSCODE while _subv is a COPY, an intentional asymmetry the code and tests call out (mainv_src_is_a_transcode_not_a_copy).

Revisit triggers.

  • Media3 shipping HEVC RTP Aggregation-Packet support (androidx/media#1008) ⇒ the cheap #video=copy _mainv would then work; switch to it and drop the transcode.
  • go2rtc gaining a way to republish a native (single-NAL/FU, AP-free) HEVC restream with a synthesized fmtp ⇒ same, an SDP-only repair becomes possible.
  • Operators enabling the transcode at scale and hitting recorder CPU limits ⇒ wire a hardware-encoder path (#hardware/NVENC) behind the same flag.
  • The server growing per-stream codec metadata (already a trigger on the ladder entry) ⇒ the client could pick mainv proactively instead of after a failure.

Correction (2026-08-08, later — on prod, live LPR). The detection in the Decision above (reuse sdp_video_lacks_fmtp on the MAIN producer SDP) is WRONG for this camera and the repair never fired. Directly querying the running go2rtc showed the LPR main's producer SDP DOES carry an a=fmtp:108 — but only sprop-sps + sprop-pps, no sprop-vps. go2rtc, unable to assemble a complete HEVC parameter set, then serves consumers an SDP with no a=fmtp at all (confirmed: the RTSP consumer SDP is a=rtpmap:96 H265/90000 with no fmtp). So the producer verdict is Some(false) ("has fmtp") while the SERVED SDP is what actually breaks Media3. The three other H.265 mains (frontyard/driveway/garage) serve a complete a=fmtp with sprop-vps, which is why they play. Earlier notes calling the raw main "no a=fmtp" were reading the served side; the producer side is the incomplete-fmtp case. Fix: detection now reads the SDP go2rtc SERVES to RTSP consumers (stream_served_video_lacks_fmtp → StreamIndex::video_lacks_fmtp_served), used for _mainv only; _subv stays producer-based (it demonstrably works for the known #483 H.264 class, and switching it risks the un-consumed-sub case). Under the default record-from-main policy the recorder is a persistent RTSP consumer of the main, so its served SDP is reliably present; a record-from-sub camera (or an idle main) has no RTSP consumer and stays unknown/unrepaired — a reconcile debug log flags "enabled but no served verdict" so that case is not silent. Follow-ups tracked separately: record-from-sub main-repair blindness, and the sub-side incomplete-fmtp class (an a=fmtp present but missing its parameter sets). The transcode decision itself is unchanged.

Correction (#594, later). The Decision above has Android try mainv right after the raw main (main -> mainv -> subv -> sub -> mobile). That order cost every LPR camera a doomed connect to the raw main on each fullscreen open (the startup lag called out elsewhere in this entry). LiveStreamFallback.kt now tries mainv FIRST when the server has published it: fullscreen mainv -> main -> subv -> sub -> mobile, wall no-sub mainv -> main -> mobile. A camera with no repair published has no mainv rung and is unaffected, main -> ... exactly as before. docs/COMPONENT-MAP.md's ladder entries are kept in step with this reorder.


2026-08-08, Boot storage seeding is PATH-idempotent (skip a name whose directory is already covered) + runtime name lookups fall back to path — supersedes #557's "detect, never fix"​

Context. db::upsert_storage is idempotent by NAME only (INSERT … ON CONFLICT (name) DO UPDATE SET path). The recorder seeds the two configured storages (LIVE_STORAGE_NAME / ARCHIVE_STORAGE_NAME, defaulting to the compose values Live / Archive) on every boot, and the seed binary does the same at container start. When an operator renames a storage in the console (PUT /config/storages/{id} — e.g. Live → 2TB NVMe), no row carries the configured name any more, so the next boot's upsert-by-name INSERTs a SECOND, empty row for the same directory. On prod this produced two ghost rows (Live → /data/live, Archive → /data/archive) sitting next to the real 2TB NVMe / 16TB Spinner rows.

PR #557 (b70a311, 2026-08-07) added db::duplicate_path_under_other_name as a detector: it WARNed at seed time and deliberately did nothing else, on the reasoning that a boot-time adopt-by-rename would undo a deliberate operator rename, and duplicate rows were "tolerated" because reconcile keys duplicates by root path. That entry's revisit trigger — "the duplicates actually materialize and confuse the operator" — has now fired. The ghost rows are also not fully inert: the recorder resolves several runtime defaults by config NAME (archive.rs free-space-floor fallback when a policy's live_storage_id is NULL; reconcile.rs live/archive stage labelling), so once the real rows are renamed those lookups miss and the code silently degrades (byte-cap floor, fewer disks labelled).

Decision.

  • Seed by path-idempotence, not by name alone. Boot seeding (main.rs::seed_storages) and bin/seed.rs now share ONE decision function, db::seed_storage_path_idempotent(pool, known, name, path):
    1. a row named name exists → upsert_storage (retarget its path — the supported "repoint a named storage via env" behavior, unchanged);
    2. else a row already covers path under a DIFFERENT name → SKIP the insert (log info!, never create a second row) and return the covering row;
    3. else → insert (fresh install, unchanged). The resolved row is folded into the in-pass known set, so a shared live == archive directory now resolves to ONE row instead of two. The operator's row is NEVER renamed or deleted (that could undo a deliberate rename, or orphan real footage).
  • Runtime name lookups fall back to path. New db::get_storage_by_path (deterministic: OLDEST created_at wins when a path is shared) and db::get_storage_by_name_or_path (name first, then path). The two runtime sites — archive.rs free-floor fallback and reconcile.rs live/archive labelling — call the name-or-path variant, so a renamed install keeps full behavior, and once the empty ghost rows are cleaned up the configured paths still resolve to the real renamed rows.
  • duplicate_path_under_other_name is kept and promoted from detector to gate; path comparison normalizes trailing slashes (normalize_storage_path).
  • No migration, no UNIQUE(path) — see rejected.

Rejected / not done.

  • Boot-time adopt-by-rename. Still rejected, for #557's original reason: PUT /config/storages/{id} is a deliberate operator action, and silently renaming their row back on the next boot would fight them. Skipping the duplicate insert achieves the goal (one row per directory) without mutating their row.
  • A UNIQUE(path) constraint. Rejected: existing prod DBs already carry duplicate paths (the very rows this fixes), so the migration would fail to apply; and a shared live == archive layout expressed as two rows is legal (seed.rs §6.5). The gate prevents NEW duplicates without breaking old DBs.
  • Deleting the existing ghost rows in code. Out of scope and unsafe to do at boot. A referenced row can't be deleted anyway (segments.storage_id FK is ON DELETE RESTRICT); the one-time cleanup of the two already-present empty rows is a maintainer DB action, sequenced AFTER this deploys.

Tests. seed_is_path_idempotent_against_renamed_rows (the exact #557 scenario, run twice → still 2 rows, operator names untouched, no growth); seed_fresh_db_creates_both_defaults; seed_retargets_existing_name_in_place; seed_shared_layout_yields_one_row; get_storage_by_path_prefers_oldest (determinism + trailing-slash); get_storage_by_name_or_path_falls_back_to_path (the free-floor/labelling fallback); plus pure-function tests for normalize_storage_path and the trailing-slash-aware detector.

Revisit triggers.

  • If a future need arises to actively MERGE duplicate storage rows (reassign segments off a ghost row so it can be deleted), that belongs in an explicit, guarded admin/maintenance operation — not the boot seed — and would get its own entry.
  • If storages ever gain a real path-uniqueness requirement (e.g. per-path accounting that duplicates would corrupt), reconsider UNIQUE(path) behind a data-cleanup migration.

2026-08-08, Notifications pane: inline per-alert ✎ icon opens the alert-text editor in place, whole-hour quiet-hours pickers validated 0..=23 server-side, admins see every channel​

Context. A Notifications-pane UX pass surfaced four issues. (1) The engine fans out to every enabled channel regardless of owner (db::list_enabled_channels), but the console's Destinations list called list_notification_channels scoped to the caller's own + global channels, so a channel created under a different account was invisible even to an admin — and two round-trip defects made the "global" checkbox cosmetic (ChannelResponse had no global field; UpdateChannelRequest silently dropped global). (2) The system-alerts table rendered a full per-row <details> "Customize alert text" block for all ~13 alerts — a wall of collapsibles. (3) Quiet hours were raw type=number inputs; a value like 2200 was stored verbatim and only clamped at read time (in_quiet_hours clamp(0,23)) to the zero-width window 23..23, so quiet hours silently never fired — no server-side validation existed. (4) The Title field showed for every provider though only Pushover/ntfy consume a rendered title.

Decisions.

  • Admins list ALL channels with owner attribution. list_notification_channels now returns every channel for an admin (via list_all_notification_channels, a LEFT JOIN users), each with owner_username; non-admin scope (own only) is unchanged. ChannelResponse gained global: bool and owner_username, and UpdateChannelRequest/UpdateChannelParams gained an admin-only owner toggle (global → user_id = NULL/claim). A non-admin supplying global on update is rejected (403), not silently ignored. Rejected: filtering the engine fan-out by owner instead (that fan-out is correct — a global/foreign channel is a real destination); leaving the console blind to foreign channels (the reported bug).

  • A small inline ✎ icon per alert opens the editor in place (no modal). Each system-alert row carries a compact pencil icon on its control row, inline right next to "Bypass quiet hours"; clicking it expands the editor as a panel directly under that row (_sysAlertEditorBody rendered into a colspan row by _renderSystemAlertsSection; toggled via sysAlertToggleEditor, only one open at a time). The icon itself carries the "customized" state (accent border + a dot) when a template override is set, so no separate chip is needed and the list reads as a clean list with a tiny icon per row. The panel holds the same message textarea, conditional Title field, per-alert token legend (click-to-insert, with sample values), live preview (ONE generic notification-card, not per-provider chrome), Restore default, and it saves via the existing per-alert PUT, decoupled from the row-toggle bulk save. Rejected: a shared .modal-overlay dialog (the maintainer found a labeled "Customize" button opening a separate modal too heavy for "just a little icon to click"); the earlier status-quo inline <details> "Customize alert text" row per alert (13× noise, a wall of collapsibles); a floating anchored popover (positioning/collision math, and it clips inside the table's overflow-x wrap). Inline expansion needs no anchoring and works identically in the desktop WebView2 embed and any Android WebView. NOTE: this replaces the modal affordance that the first cut of this PR shipped — do not "restore" the modal.

  • Whole-hour <select> quiet-hours pickers + server-side 0..=23 validation. Both quiet-hours pairs (per-user rules and system alerts) are now native selects (— off — + 24 friendly 12-hour options), so an out-of-range or minute value is unrepresentable, and the sections collapse into details.detail-section with a live-state summary. The server rejects any quiet-hours value outside 0..=23 (do_upsert_rule, put_notification_settings) instead of storing junk; the engine-side clamp stays as defense for any legacy rows, which the console renders as — off — with a one-line "out of range, pick an hour" warning. Rejected: a data-migration to scrub existing bad values (the clamp keeps them harmless and the picker can't write a new bad one); free-text/military-time input (the original bug surface).

  • Title field only when a configured destination consumes it (Pushover or ntfy present), with the helper naming the actual destinations. A stored title is left untouched when the field is hidden (the PUT omits title_template = keep).

Trade-offs accepted. The console now issues one extra GET /auth/me on the Notifications pane load to know the session's user id + admin flag (for owner attribution and gating the global checkbox). Quiet hours are whole-hour only (minutes were never representable in the old 0–23 inputs either). owner_username is display-only and populated solely by the admin listing's join, so every other channel query path leaves it None.

Revisit triggers. A hosted/multi-tenant mode where "all channels" is too broad for an admin (scope the listing per tenant). Demand for sub-hour quiet windows (the picker + validation + in_quiet_hours would need a minute component). A second event type that carries an image (the preview's image-slot gate — currently plate_watchlist_hit only — generalizes).


2026-08-08, Home Assistant entity role labels in the camera editor are mode-aware (copy only)​

Context. The per-camera HA link editor (admin.html, renderHaLinks &c.) labeled the motion role "Motion (triggers recording)". That is only true on a camera whose recording policy is Motion-triggered. On a Continuous (24/7) camera a linked motion binary sensor never starts a recording — it feeds the additive multi-source motion stream (timeline events + notifications) only. The static label read as a contradiction on a 24/7 camera and confused the maintainer about how to add an HA entity at all.

Decision.

  • The motion role's label and the picker/helper copy are derived from the open camera's effective policy mode (profileById(cam.policy_id) || cam.policy, the same source the storage tab and banner use), surfaced as HA_CAM_MOTION_MODE. Motion-mode ⇒ "Motion sensor (triggers recording + marks the timeline)"; Continuous ⇒ "Motion sensor (marks the timeline, can notify)". The sensor/actuator labels are mode-independent.
  • This is presentation only. The stored roles remain motion|sensor|actuator, device_class and the whole-list PUT /cameras/:id/ha/links contract are unchanged; no migration, no schema, no server change. The same rework moved the device_class box into the icon & style panel, replaced the three add buttons with one "+ Add Home Assistant entity" + a role segment toggle, grouped rows by role, and added a Save-links "Unsaved changes" indicator.

Rejected. A single static label for all cameras (the status quo) — rejected because "triggers recording" is factually wrong on a Continuous camera and was the reported source of confusion. Encoding the behavior difference in the schema (e.g. a per-link "notify" flag) — rejected as out of scope; it is genuinely new data, flagged in the PR for a future decision, not built here.

Revisit if. The motion role's server-side behavior stops depending on the camera's record mode (e.g. motion links always trigger recording, or never do), or a per-link notify/behavior toggle is added — at which point the copy should follow the new behavior and this entry is superseded.


2026-08-07, Timeline motion-intensity is bucketed in SQL (GROUP BY over a generate_series-expanded range), not by fetching every segment to Rust​

Context. The desktop Playback/clip timeline "intensity ribbon" took roughly a minute to populate for a wide (30-day) window. db::motion_intensity_buckets and motion_intensity_buckets_multi fetched every segments row overlapping the window and bucketed them in a Rust loop; prod logged a single-camera 30-day request scanning ~302k rows. The value behind each bucket is the MAX motion_score (0..1 real) of any segment whose in-window overlap touches that bucket; because a segment can span several buckets, each row contributes to a half-open bucket range [b0, b1), not a single bucket. The timeline.rs doc comment already named "future SQL-side bucketing" as the intended fix.

Decision.

  • Bucket in Postgres. A CTE computes each segment's integer-millisecond in-window offsets [s_off, e_off), derives the bucket range [b0, b1), expands it with LATERAL generate_series(b0, b1 - 1), and takes MAX(motion_score) per bucket (single-camera) or per (camera_id, bucket) (batch). The DB returns at most n (default 240, clamped 1..4096) rows instead of hundreds of thousands; Rust fills the sparse result into a zero-initialised vec, so empty buckets stay 0.0. The response shape (IntensityResponse { buckets } and the batch map) is unchanged — no client change.
  • span_ms and n are passed as bound parameters (not recomputed in SQL) so the divide/multiply/floor/ceil math is bit-identical to the former Rust loop. Millisecond offsets are computed as floor(round(extract(epoch …) * 1e6)/1000) — micros-then-round avoids the float dust that a naive epoch*1000 floor hits exactly on bucket boundaries.
  • No new index or migration: segments (camera_id, start_ts) (migration 0001, segments_camera_start) already serves the sargable WHERE, and the existing start - MAX_SEGMENT_LEN lower bound keeps the scan O(window).

Rejected / not done.

  • Keeping the Rust loop but capping rows / windowing on the client. Rejected: it moves the cost around rather than removing it, and the doc comment already committed to SQL-side bucketing. The client already sends the right request.
  • A precomputed per-bucket rollup table. Rejected as premature: the indexed index-range scan + aggregate is fast enough and adds no write-path surface (no recorder-correctness risk). Revisit if intensity is still slow at much larger scales.
  • Touching the /timeline span-merge path. Out of scope: merging contiguous segments into spans is a different operation and inherently O(rows); its large-scan WARN was rescoped, not removed.

Equivalence proof. motion_intensity_sql_matches_reference keeps the old algorithm as an in-memory oracle and asserts the SQL output equals it, across bucket counts {1,7,100,240,4096}, for a fixture that hits: empty buckets, a segment starting exactly on a bucket boundary, a segment ending exactly at the window end (end-exclusive last bucket), multiple segments sharing one bucket (MAX wins), a before-window overlap, a sub-bucket segment, and a segment spanning many buckets — plus the multi-camera grouping. Hand-computed edge asserts pin the boundaries independently of the oracle.

Revisit triggers.

  • Intensity latency regressions at far larger scale (many more cameras or far longer retention) → consider a precomputed per-bucket rollup table.
  • If bucket semantics change (e.g. average instead of MAX, or event-count instead of motion_score), update BOTH the SQL aggregate and the oracle in lockstep.

2026-08-07, Per-channel snapshot MODE with a capability gate; the plate crop is derived SERVER-SIDE via ffmpeg for notification delivery​

Context. A notification channel had a single include_snapshot bool that attached the full vehicle frame, and only three providers actually sent an image. The ask (the second half of the customizable-alert feature): let each channel choose to attach the plate, the vehicle frame, both, or nothing, and extend image support to more providers where their transport genuinely allows it. PR #568 had just started writing plate_bbox (normalized [x,y,w,h]) and plate_read_id into system_events.meta for a watchlist hit, which makes a server-side crop of the vehicle frame possible for ALL plate reads (Frigate reads have no stored tight crop; only crumb-alpr does, in plate_reads.crop).

Decision.

  • notification_channels.snapshot_mode ('none'|'plate'|'vehicle'|'both', migration 0080, db::SnapshotMode) is the single source of truth. The legacy include_snapshot bool is kept as a synced mirror (mode != 'none', written on every create/update) for rollback/older-reader safety but is no longer read by the engine. The 0080 backfill (true→'vehicle', false→'none', guarded by WHERE snapshot_mode IS NULL so a re-apply cannot clobber an operator's choice) makes the upgrade behaviour-neutral.
  • The mode is capped by a per-provider capability the operator cannot override (channel_notify::provider_image_capability, mirrored by admin.html's NOTIF_IMG_CAP): Discord and Telegram carry two images (both = vehicle frame + plate crop, via multipart file[N] / sendMediaGroup); Pushover and ntfy carry one (both degrades to the plate crop — the more informative single image); Slack and the generic webhook carry none.
  • The tight plate crop is produced server-side: prefer a crumb-alpr read's stored plate_reads.crop, else crop the already-fetched vehicle frame by the meta plate_bbox with ffmpeg (crop=iw*…:ih*…, no pixel dims needed), derived at most once per event and only when some enabled channel wants plate/both. No new image crate: the api already shells out to jellyfin-ffmpeg for thumbnails (filmstrip.rs); there is no in-process image crate in the tree, so adding one would have needed an issue (golden rule 6).

Rejected / not done.

  • Slack image attachment. A Slack incoming webhook takes only an image_url its own servers must fetch; Crumb is LAN-only, so a LAN web_url is unreachable and there is no raw-byte path. A real file upload needs a bot token + files.upload — out of scope. Slack stays text + link, honestly labelled in the console (no image modes offered).
  • Bytes over the generic webhook. It is a JSON contract by design; it now carries the channel's snapshot_mode so a consumer can go fetch an image itself, but never raw bytes.
  • Adding the image crate for the crop. No such crate exists in the tree (the filmstrip thumbnailer is an ffmpeg subprocess, not a crate), and it would be a heavyweight new dependency. ffmpeg is already a hard runtime dependency and the codebase's established image tool.

Not a contradiction of the 2026-08-07 "fix the client's decode, not the payload" entry (server-side derivatives for the Plates UI). That decision rejected server-side crop derivatives for the client Plates report, where the bottleneck was the client's pure-Dart decode and the LAN transfer was already ~1-2 ms — the client can decode natively, so a cold ffmpeg spawn per image lost. The notification path has no client to decode: an external provider needs the actual cropped bytes produced somewhere, and the only place is the server. It is derived once per event (not per row, not per channel) on a background, best-effort path, so the ~40 ms spawn is paid rarely and never blocks or drops an alert (any crop failure falls back to the vehicle frame).

Revisit if: a provider gains a real multi-image or byte path we don't use (e.g. a first-class Slack bot integration with files.upload — then Slack could attach images); or plate crops are wanted on motion/detection alerts (today only plate_watchlist_hit carries a plate_bbox, so motion/detection channels set to plate/both fall back to the vehicle frame); or the per-event ffmpeg spawn shows up as load under a flood of watchlist hits (cache the crop on the system_event, or move it into the detection ingester at emit time).

2026-08-07, Alert-text templates: a %token% engine over per-event_key columns, NULL = built-in default, structured tokens via system_events.meta​

Context. Every system-alert notification was composed by one hardcoded format! in channel_notify::ChannelMessage::text(). Operators asked to customize the wording (date/time placement, plate/free-space facts, their own phrasing) per alert type. The structured facts (plate, confidence, free %) were baked into the free-text detail string only, so a template could not reference them by name.

Decision.

  • A small pure engine (crumb_common::alert_template) with %token% syntax. An UNKNOWN token renders LITERALLY (%typo% stays visible) rather than blank, so a mistake is obvious. No expression evaluation, no recursion into replacement values, substitution from a fixed map only.
  • Templates live as nullable message_template/title_template columns on the existing system_alert_rules (keyed by event_key), migration 0079. NULL means "use the built-in default" — so "Restore default" is simply clearing the column to NULL. Built-in defaults are expressed as templates and rendered through the same engine.
  • Structured tokens flow through a new nullable system_events.meta (jsonb), populated at the emit sites (db::insert_system_event_full). Always-available built-ins (%camera%, %event%, %detail%, %date%/%time%/%datetime%) work for every alert type even when meta is NULL.
  • Rendered text is JSON-escaped for free: every provider body is built with serde_json::json!, so quotes/newlines/braces in a template can never break or inject into a payload (proven by a test). The ntfy title (an HTTP header) additionally strips CR/LF.
  • Timezone: date/time render in UTC, matching the ts formatting the notification path already used. No per-user timezone is invented here.

Rejected.

  • A general expression/handlebars-style language. Overkill and an injection surface; operators want placeholders, not logic.
  • A single global template for all alert types. Loses the per-type structured tokens (a plate token is meaningless to a storage alert) and the per-type default wording.
  • Bypassing the engine for the default (keep the old format! when unset). Would mean the "default" shown to operators and the actual default could drift; expressing the default AS a template keeps the editor's placeholder honest. The one wrinkle accepted: the default message template reproduces the legacy wording verbatim, INCLUDING its em-dash separator, to keep every existing alert byte-identical by default (changing that separator is a wording change the operator can now make, not one this change imposes).
  • Rendering a custom title for every provider by default. Pushover and ntfy build different default titles today; a NULL title_template keeps each provider's existing title so defaults never change. A set title applies to both.

Revisit if: per-user/local timezone lands (date/time tokens should honor it); motion/detection camera notifications (the separate notification_rules path) also need templating (they are out of scope here — this covers system_events only); or a provider needs structured (non-string) payload fields from tokens.

2026-08-07, The HA placement PUT stays a whole-object REPLACE, against the PUT /config/server merge convention (issue #552)​

Context. The v0.2.0 release-prep API audit flagged PUT /cameras/:id/ha/links/:link_id/placement as inconsistent with the merge semantics #533 had just given PUT /config/server (issue #472). PlacementInput carries #[serde(default)] on every optional field, so an omitted key and an explicit null are the same request, and both write "no override". A body that names only the position therefore resets the badge's saved color, icon, shape, backgrounds, pill width, alignment, opacity, size, outline and pinned captions.

Before deciding, every caller on all four surfaces was read:

SurfaceWrites placements?Body
Web console (admin.html haSaveStyle)yescomplete — all 13 style keys plus x/y, each explicitly null when unset, round-tripped through haMapLinkFromServer
Desktop Flutter (ha_api.dart → ha_overlay_controller.dart endEditAndSave)yescomplete — HaOverlayBadgeItem seeds every style field from the link at beginEdit and the whole set is PUT once at end-of-session; there is no per-drag or per-popover instant-apply PUT
AndroidnoGET /cameras/:id/ha/links only
iOSnoGET /cameras/:id/ha/links only

So nothing is currently biting: no shipped client sends a partial body.

Decision. Keep replace semantics. Document the contract on the DTO, on the handler, and in docs/COMPONENT-MAP.md, and pin it end to end with services/api/tests/ha_placement_replace_semantics.rs so it cannot drift silently in either direction. Three facts drove this, and any one of them alone would have been enough:

  • There is no "" state to clear a style field. #533's three-state table works because Crumb's config precedence makes an empty string mean "fall back to env". These columns are '#RRGGBB' hex and closed vocabularies (auto/narrow/medium/wide, start/center/end) validated at the PUT, so "" is a 400. Under merge semantics, null would mean "leave alone" and an operator would have NO way to undo an override through the API. Restoring one would need Option<Option<_>> (double_option), i.e. a second, different mechanism for the same problem — not the consistency the finding was after.
  • A shipped client depends on reset-by-omission. The desktop badge popover's "Reset style" is HaOverlayBadgeItem.resetStyle(), which nulls the style fields; ha_api.dart then drops null keys from the body. Under merge semantics that button would silently do nothing. The admin console is compiled INTO the api binary so it can never skew, but the desktop client is released independently — a v0.1.x desktop against a v0.2.0 server is normal, and the failure mode would be silent-wrong, not an error. #533 had no such skew surface, which is the substantive difference between the two endpoints.
  • The body is a resource representation, not a settings patch. A body-level null already means "clear the placement", so the object form is naturally "this is the badge's complete appearance". x/y are required, so a style-only partial body is refused (422) before it can reset anything; a partial body has to deliberately name a position.

Rejected:

OptionWhy not
Option<Option<_>> merge on the five nullable string fieldsLeaves size/opacity/show_state/show_age/outline still resetting on omission — a half-merge whose contract is harder to state than either pure rule.
Full merge: Option<Option<_>> on the strings AND Option<_> on the numerics/bools, with per-column COALESCE in update_ha_link_placementThe honest version of the above, and it is what a future change should look like — but it breaks old desktop clients silently (see skew above) for zero known benefit today, and rewrites the DB write path on an admin route in a release-prep window.
Copy #533 literally (Option<T>, omitted/null ⇒ leave alone, "" ⇒ clear)"" is not a legal value for any of these columns; it would 400 at validation. The convention does not transfer.
Add a separate PATCH .../placementDoubles the surface for a route with two GUI callers and no scripted ones, and leaves the PUT exactly as it is anyway.
Change nothing and write nothing downThe behavior is currently an accident of #[serde(default)]. The next audit finds it again, or a refactor flips it and no test notices.

Trades knowingly accepted:

  • The API now has two documented answers to "what does an omitted key mean", which a script author has to look up per endpoint. Accepted, and made cheap: both answers are stated in the DTO doc comment where the reader already is.
  • A third-party script doing {"x": 0.2, "y": 0.3} to nudge a badge still wipes its appearance. That is now the documented contract rather than a surprise, but it is still a sharp edge; the 422 on a missing position is the only guard.
  • label remains the one merge-semantics field on this body (omitted ⇒ unchanged, "" ⇒ clear), because the console's link editor writes it too. An exception inside an otherwise uniform rule, kept because the alternative is the two writers clobbering each other.

Revisit triggers:

  • A non-GUI caller appears (a script, an integration, an openapi-generated client) that wants to change one property of a badge ⇒ do the full merge, and ship the desktop client change that always sends explicit nulls in the same release.
  • Any style field gains a meaningful "" value ⇒ the replace rule and the label exception stop being separable and the whole body needs one contract.
  • The generated OpenAPI spec (ROADMAP initiative 4) lands ⇒ the two conventions become visible side by side in one document, which is the point at which "consistent" stops being a preference and starts being a doc-quality bug.


2026-08-07, Plate-crop images: fix the client's decode (engine codec), not the payload (server-side derivatives)​

Context. The LPR Engine Benchmark's pass images loaded slowly (issue #391). The first diagnosis blamed the ~148 KB stored frames and produced server-side downscale/tight-crop derivatives (PR #394); live measurement then falsified the premise — the API answers the report in 3 ms and a full frame in 8 ms, so on a LAN the bytes cost ~1-2 ms and #394 was closed unmerged. A client-side measurement pass (real dialog mounted against an in-process server, plus micro-benchmarks of plate_crop.dart) found the actual cost: package:image's pure-Dart JPEG decode of the full frame, run per newly-mounted row to derive the plate crop — ~130 ms per 1080p frame (~260 ms at 4 MP) vs ~18 ms for the engine's native codec. A 10-row screenful spent 478 ms wall on images, only 43 ms of it fetch.

Decision. Fix the decode where it happens (PR #545): cropPlateToBbox decodes with the engine codec and rasterizes only the bbox region, so the full decoded frame never crosses into Dart; package:image handles just the small crop (near-black guard + JPEG re-encode). The pure-Dart path stays as the reference implementation and decode fallback. Screenful: 478 → 156 ms. The list itself was already lazy (ListView.separated, ~7 rows mounted, ~10 fetches) — the other #391 candidates (eager 165-row build, client fetch stampede) were measured and refuted.

Rejected.

  • Server-side derivatives as the fix (#394's framing). Attacks transfer size, which is ~43 ms of a ~478 ms problem on a LAN, and trades a ~1 ms transfer saving for a 40 ms cold ffmpeg spawn per image server-side.
  • Bounding client fetch concurrency / restructuring the list. Measured fast already; nothing to fix.
  • Keeping the whole crop in package:image but skipping the isolate. The decode itself is the cost; where it runs doesn't change it.

Revisit if: remote viewing over VPN/cellular becomes a priority — then #394's derivatives become a genuine transfer-cost win (its closing comment has the details, including the ?tight=1 serde-bool trap) and they compose fine with the engine-decode path; or the engine codec proves unable to decode some camera's snapshots in the field (the fallback logs nothing today — it would just be slow again for that camera).

2026-08-06, HA badge pill layout: a four-value width mode in units of the badge HEIGHT (not free pixels, not a max-width)​

Context. Live testing of the v0.2.0 overlay editor (issue #497) turned up two gaps in the pill badge. Operators want several pills to be the SAME width so a column of them lines up down a door frame, and they want to move the label off the leading edge once a pill is wider than its content. The shrink-to-content work already landed, so auto is the right default; what was missing was any way to say something other than auto.

Decision. Two additive nullable columns (migration 0078), each a small closed vocabulary, applying only to shape = 'pill':

  • overlay_pill_width = auto | narrow | medium | wide. NULL means auto, which is today's measured hug-the-content width, byte for byte. The three fixed modes are EXACT widths, expressed as multiples of the pill's own HEIGHT: 4x, 6x, 8x.
  • overlay_text_align = start | center | end. NULL means start, the leading-edge layout every renderer already draws. It governs the icon + label group as a unit, and is only observable once a fixed width has left the pill some slack.

Resolution rule, identical in every renderer: width auto/NULL/unrecognized ⇒ measure the content; narrow/medium/wide ⇒ 4/6/8 x height. Align start/NULL/unrecognized ⇒ leading; center ⇒ centred; end ⇒ trailing. A dot ignores both. On the wire the fields are additive on HaLinkDto (overlay_pill_width/overlay_text_align) and PlacementInput (pill_width/text_align, #[serde(default)]), validated against the same lists the migration CHECKs enforce; a field-level null inside the placement object is the reset back to the default, matching bg_color_on.

Why height is the unit. The badge height is the one length all four renderers already derive identically, from overlay_size and the pane scale. A pixel width would resolve differently on a phone pane, a wall tile and a maximized pane, so "make these three the same width" would be true on exactly one surface.

Rejected:

  • A free pixel (or fractional) width field. The obvious ask, and the one thing four renderers cannot agree on: there is no shared pixel space (see above), and it hands the operator a control whose result varies by client. It also invites values that make the badge unusable, which then needs its own clamp vocabulary anyway.
  • A MAX-width (clamp) instead of an exact width. Safer sounding, but it does not solve the actual ask: under a max-width, two pills with different labels still render different widths, so nothing lines up. Exact-plus-ellipsis loses a few characters on an over-long label, which every renderer already handles, and delivers the alignment the exact mode exists for.
  • Deriving the width from a character count (width = N chars). Font metrics differ per platform (Android already ships a glyph-advance estimate where desktop measures), so the same N would be a different pill on each client. Multiples of height are metric-free.
  • A per-badge "align to this other badge" / layout-group concept. The general answer to lining badges up, and much bigger: the placement model has no group that survives a session (see OverlayItem.groupId), so it would need a new persisted relation, plus reflow rules, plus an editor for it. A shared width mode gets most of the value for two nullable columns.
  • Folding both into an overlay_style jsonb blob. Same reasoning as the 2026-08-06 per-state-background entry: it discards the per-column CHECKs and retypes the field in four clients. Still the eventual answer, still not now.

Trades knowingly accepted:

  • Three fixed widths is a coarse ladder. An operator who wants 5x cannot have it; they pick narrow or medium and live with it. That coarseness is what buys identical rendering across four independent implementations.
  • A fixed width narrower than the label truncates. Deliberate: the pill already ellipsizes, and the alternative (silently widening) is exactly the "nothing lines up" failure the mode exists to fix.
  • overlay_text_align does nothing on an auto pill. It is presented directly under the width control in every editor so the relationship is visible, but a puzzled operator setting align-only is a real possibility.
  • Android's auto width is still its char-count estimate widened to fit its content (PR #499), while desktop measures the text; those two can disagree by a few px. Untouched here on purpose — the fixed modes are exact everywhere, and re-litigating auto parity belongs with whatever revisits #499.

Revisit when: operators ask for a fourth or fifth fixed width (then either extend the ladder or reopen free values with a per-renderer normalization), when a real layout-group/alignment-guide feature lands in the overlay editor (which would subsume the "make them line up" use case), or when a renderer is added that cannot express an exact width in units of height.


2026-08-06, PUT /config/server MERGES: omitted key = leave alone, "" = clear (issue #472)​

Context. PUT /config/server was a whole-row replace whose DTO carried #[serde(default)] on most fields. A programmatic caller sending a partial body ({"motion_hwaccel": "vaapi"}) got every unmentioned field deserialized to "" and written, silently resetting the Frigate bases, the stream bases and the VAAPI device to their env fallbacks. The console and first-run wizard were safe only by convention: they use a full-body stash pattern that round-trips every key. The exposure was scripts and third-party integrations, and docs/AI-INSTALL.md step 7 was literally instructing agents to work around it.

PR #518 had already solved this for exactly one field: frigate_api_base became Option<String> so an omitted key could mean "leave the stored legacy column alone" rather than "wipe the value a pre-0014 install still resolves from".

Decision. Generalize #518's semantics to the whole DTO. Every settable field is Option<String> with #[serde(default)], and the three states are distinct:

BodyMeaning
key omitted / null ⇒ Noneleave the stored column alone
"value" ⇒ Some(v)set it (trimmed)
"" ⇒ Some("")clear it ⇒ falls back to the container env

Some("") is deliberately NOT collapsed into "omitted". Crumb's config precedence is admin-set DB value wins over env; EMPTY DB value falls back to env, so an empty string is the operator's way of saying "go back to the env default". Merging it away would remove the only way to undo a setting through the API.

The DB layer expresses it directly: COALESCE($n::text, column), one parameter per field, None binding SQL NULL. version is still bumped on every call, so a no-op merge still tells the recorder and clients to re-read.

Rejected:

  • Drop #[serde(default)] so a partial body 422s loudly (the issue's other option). Honest, but it makes the endpoint harder to use correctly rather than easier — every caller must fetch-then-echo nine fields to change one, and a fetch/PUT race then clobbers a concurrent edit with stale values. It also contradicts the direction #518 already set for frigate_api_base, leaving one field with merge semantics and eight without.
  • PATCH as a separate route, leaving PUT a replace. Strictly correct REST, but it doubles the surface and leaves the footgun armed on the route every existing caller uses. Nothing in the codebase relies on PUT's replace semantics: the only clients that call it send full rows.
  • Rewrite the console/wizard to send minimal per-pane bodies. Tempting now that merging works, and it would honor "wizard/console code must only ever write the specific fields it edits" more literally. Deliberately NOT done in this change: a full body means the same thing under both semantics, so keeping the stash pattern makes this a pure server-side fix with zero console behavior change to re-verify. Doing both at once would make a console regression indistinguishable from a DTO regression.
  • Treat "" as "leave alone" too (i.e. only non-empty values write). Would make "reset this back to the env default" unreachable through the API and quietly break the console's existing "clear the field" behavior.

Trades knowingly accepted:

  • Four fields that were structurally required (server_address, crumb_rtsp_base, crumb_api_base, frigate_rtsp_base) are now optional, so a body that omits them succeeds instead of 422ing. That is the point, but it does mean a caller with a typo'd key name now silently no-ops that field instead of erroring. Accepted: the same is already true of every #[serde(default)] field on every other config route, and the alternative costs the merge.
  • The frigate_go2rtc_api_base seeding rule gets one more state to reason about. Some("") still falls back to a legacy value in the same body (the pre-0014 client contract, unchanged); only a fully absent key means "leave alone". Both branches are unit-tested.
  • The legacy column's "clear the old console's go2rtc duplicate" cleanup only fires when the body actually decides the go2rtc base. A PUT that mentions neither column can't tell a duplicate from operator intent, so it touches neither — a stale duplicate now survives such a request instead of being cleaned up as a side effect.

Revisit triggers:

  • A field where "" becomes a meaningful value rather than "fall back to env" ⇒ that field needs Option<Option<String>> (or a sentinel) and this three-state table stops being sufficient.
  • The generated OpenAPI spec (ROADMAP initiative 4) landing ⇒ the three states must be expressible in it, or the endpoint's contract goes back to living only in doc comments.
  • Any second config route growing the same partial-body hazard ⇒ factor the Option<String> + COALESCE pattern into a shared helper instead of hand-rolling it a third time.

2026-08-06, The storage preflight infers recorder writability from the folder's OWNERSHIP when its own write probe is inconclusive, rather than asking the recorder​

Context. POST /config/fs/check is the wizard's gate on "this disk will actually record". The api mounts /data read-only by design (the recorder holds the RW mount), so its throwaway write probe fails on every stock install and the endpoint returned status:"warn" with "can't confirm the recorder can write here" for a perfectly healthy disk. A genuinely unwritable folder (a root-owned chmod 555 media directory, the single most common first-run failure) produced the identical amber warning, and the wizard only blocks on status:"error", so the one check that exists to stop a silently-non-recording install could not stop one. Found by a hostile first-run pass (#517 §1.3).

Decision. When the write probe is inconclusive because the api's own mount is read-only, derive the verdict from the directory's stat instead: both service images pin their container user to uid 1001, so "would uid 1001 be allowed to create a file here" has a real answer that the api can read without being able to write. Ownership + mode says writable ⇒ ok (with the honest caveat that the write itself is confirmed by the recorder on first write); says not writable ⇒ error naming the owning uid, the mode, and the chown that fixes it; metadata unreadable ⇒ the old warn, which is now the rare case rather than the default.

Rejected:

  • Have the api ask the recorder to probe writability (the issue's own suggestion). It is the more correct answer and stays the long-term target, but it needs a new recorder-side endpoint or a DB-mediated request/response with its own liveness, timeout, and "recorder is restarting" semantics, on the service that must never be destabilised (golden rule 2). Out of proportion for a message-quality pass, and the ownership read gets the same verdict for every failure shape seen in practice.
  • Keep returning warn and only reword it. The wizard would still walk past an unwritable disk, which is the actual bug.
  • Green-light on free space alone. That is the P0-1 regression: a root-owned media directory reports plenty of free space and records nothing.

Trades knowingly accepted:

  • The uid is a constant (1001), not configuration. An install that overrides the recorder's container user to root would see a false error on a root-owned folder it can in fact write. That override is not a supported path, the message names the exact uid it assumed, and the operator can still set the path through POST /config/storages with a path that passes.
  • Ownership is necessary, not sufficient: an exotic mount (NFS with root_squash, an ACL, a full disk) can still refuse the write. The ok copy says so rather than promising success.

Revisit when: the recorder publishes a storage-writability signal (a health row or heartbeat field per storage). At that point prefer it here and demote the ownership read to the fallback, or when an install path that legitimately runs the recorder as another uid becomes supported, at which point the constant has to become configuration.


2026-08-06, MQTT stays plaintext-only: mqtts:// is REJECTED loudly, not implemented (issue #477)​

Context. Both MQTT clients (the API's Frigate detection ingester, services/api/src/detection/frigate.rs, and the recorder's Frigate-as-motion loop, services/recorder/src/frigate_motion.rs) accepted an mqtts:// URL, stripped the scheme, and connected in cleartext. MqttOptions::new + no set_transport is a plaintext socket. An operator who typed mqtts:// believed their broker credentials were encrypted; they were on the wire in the clear. That is a silent security downgrade, which is worse than an unsupported feature.

The obvious fix, "just turn TLS on", is not cheap here. Three days earlier, PR #476 deliberately set rumqttc = { version = "0.24", default-features = false } precisely to drop the crate's use-rustls tree, which cleared four rustls-webpki 0.102.8 certificate-verification advisories (RUSTSEC-2026-0049 / 0098 / 0099 / 0104) and the unmaintained rustls-pemfile warning. rumqttc's TLS feature is pinned to rustls-webpki ^0.102.2 (0.25 requires ^0.102.8), i.e. the vulnerable semver line — it cannot resolve to the patched 0.103.13 that reqwest already uses on Crumb's outbound-TLS path. So enabling it does not reuse the rustls stack Crumb already compiles; it adds a SECOND, older, advisory-carrying one.

Decision. Ship the loud rejection, not TLS. One shared guard, crumb_common::mqtt::check_plaintext_scheme, refuses mqtts://, ssl://, mqtt+ssl://, tls:// and wss:// at three layers:

  • PUT /config/frigate 400s with the operator-facing message (config time, regardless of enabled, so a URL stored while disabled cannot downgrade when it is switched on later).
  • POST /config/frigate/test reports it instead of TCP-connecting to :8883 and cheerfully answering "Reachable" for a link Crumb will refuse to make.
  • Both parse_mqtt_url() helpers Err at connect time, which covers the env-seeded (FRIGATE_MQTT_URL) path that never passes through the HTTP route.

Rejected:

  • Enable rumqttc 0.24 use-rustls. Reintroduces the exact four cert-verification advisories PR #476 removed, plus a duplicate rustls 0.22 / tokio-rustls 0.25 tree alongside the rustls 0.23 that reqwest already pulls. Shipping TLS on a known-vulnerable certificate verifier is not "secure by default", it is the same lie in a different font.
  • Bump to rumqttc 0.25. Same rustls-webpki ^0.102.8 floor, and its tokio-rustls 0.26 defaults to aws-lc-rs: a C/assembly crypto build (cmake + nasm) in the Docker builder. Golden rule 6, a heavyweight dependency and new build-time toolchain, needs its own discussion, not a bug-fix PR.
  • use-native-tls. Pulls openssl-sys, which means OpenSSL dev headers in the builder image and a system-OpenSSL runtime dependency. Same objection, different tree.
  • Silently keep accepting mqtts:// (the status quo) or downgrade with a warning log. Golden rule 1: a misconfiguration on a security recorder is a privacy hazard. A warning nobody reads is indistinguishable from silence.
  • Reject every non-mqtt:// scheme. Deliberately narrower: only the schemes that imply encryption are refused, so no URL form that works today breaks.

Trades knowingly accepted:

  • MQTT is plaintext-only, period. Crumb's posture already assumes a trusted LAN for the broker (the bundled mosquitto binds 127.0.0.1:1883), and the docs now say so explicitly instead of implying mqtts:// works.
  • An operator whose stored row already contains mqtts:// (env-seeded, or saved before this change) now gets a 400 on their next /config/frigate save, even when editing an unrelated field. That is the intended forcing function: the message names the problem and the fix.
  • The guard is a new crumb_common::mqtt module rather than the full shared MQTT helper docs/ROADMAP.md still wants. Factoring the two duplicated parse_mqtt_url() + connect/back-off skeletons together stays that item's job.

Revisit triggers:

  • rumqttc publishing a release whose TLS feature resolves to a patched rustls-webpki (0.103+) on the rustls stack Crumb already compiles, with no aws-lc-rs default ⇒ implement mqtts:// for real and delete the guard.
  • Any deployment story where the broker is NOT on a trusted LAN (a hosted or cross-site broker, MQTT over a WAN link) ⇒ TLS stops being optional and the dependency cost has to be paid.
  • A shared crumb_common::mqtt client landing (ROADMAP "MQTT publisher") ⇒ fold this guard into it rather than keeping a standalone module.

2026-08-06, MOTION_HWACCEL=auto is decided by a RUNTIME device probe, and a hardware backend that cannot decode is latched off per camera​

Context. Issue #479, found by the v0.1.1 → v0.2.0 upgrade test. auto resolved through nvdec_available(), which runs ffmpeg -hwaccels and looks for cuda — a build-time capability. The bundled ffmpeg has cuda compiled in on every host, so auto selected cuda on a machine with no NVIDIA device at all. Each per-camera motion ffmpeg then died before its first frame (Cannot load libcuda.so.1 / Device creation failed), the EOF/reconnect watchdog relaunched it with the same flags, and motion detection stayed down forever. Fail-open did its job — every camera recorded continuously — so nothing was lost, but a Motion policy silently behaved like Continuous and storage filled at the Continuous rate. #513 changed the shipped default to cpu, which protects fresh installs only: an upgrader's generated .env pins MOTION_HWACCEL=auto explicitly, so auto itself had to start working.

Decision.

  • Resolve auto from a runtime probe. decode_probe::cuda_runtime_available() runs ffmpeg -init_hw_device cuda=… -f lavfi -i nullsrc -frames:v 1 -f null - once per process (cached, 15 s deadline) and only reports true when ffmpeg actually created the device. HwAccel::resolve_auto (pure, in common) maps the result to Cuda/Cpu; every explicit choice passes through untouched. Spawn failure, non-zero exit, and timeout all resolve to cpu — the backend that works everywhere.
  • Latch a failing accelerator off, per camera, for the worker's life. After a motion ffmpeg that was launched with cuda/vaapi exits having decoded zero frames, the camera is demoted to CPU decode when either ffmpeg logged a recognised hardware-init failure (immediately — the signature is unambiguous) or three consecutive attempts decoded nothing. The latch lives in run_one_source, so it survives the reconnect back-off that was re-arming the failure; a recorder restart, a camera-config change, or a supervisor respawn all give the hardware another try.
  • Name the cause on the existing surfaces, following the 2026-08-04 (#523) pattern rather than adding a channel: the demotion reason becomes decode_status.fallback_reason and is recorded on the source's UnhealthyAlertGate so fail_open_reason prefers it over the generic "not delivering frames". Because a source that is broken from its first connection never transitions, the health aggregator now also re-persists motion_health_reason when the cause changes within an unhealthy episode (one write per distinct cause), instead of pinning the vaguest wording the run will ever produce.

Rejected:

  • Glob /dev/nvidia* and call that the probe. Cheap and no spawn, but it answers a different question: nodes can be present while the driver libraries are missing (the classic post-driver-upgrade state), and a future container runtime could expose the device another way. It stays in the log line for context, not in the decision.
  • Keep the build-time probe and rely on the per-camera fallback alone. It would work, but it spends a failed decode (and a fail-open window) on every camera on every restart to rediscover a fact one process-wide probe answers in milliseconds.
  • Retry the accelerator periodically after demotion. A GPU cannot appear in a running container (Docker never grants a live container new devices), so the retry could only re-break motion on a schedule. Recovery is deliberately tied to an event that CAN change the answer: a restart.
  • Demote globally on the first camera's failure. Faster to converge, but it lets one camera's stream quirk cost every other camera its GPU offload. Per camera keeps the blast radius at the evidence.
  • Count stall-watchdog timeouts as hardware failures too. A stalled child is alive and producing nothing, which is a stream fault the existing watchdogs own; the hardware verdict is scoped to attempts where the decoder actually exited.
  • Thread the reason through the fail-open watch<bool>. Same rejection as #523: that channel is a correctness rail, not a telemetry bus.

Trades knowingly accepted:

  • One extra ffmpeg spawn per recorder process when auto is set (only then).
  • The unsignatured arm can demote a camera that was merely offline for three reconnects. Harmless — CPU decode works for every stream — and it costs the hardware offload only until the worker restarts. The alternative (never demoting without a known signature) leaves an unrecognised failure mode looping forever, which is the bug.
  • The latch is in-memory, so a restart re-tries a still-broken accelerator and re-learns the same thing. Same trade the camera_offline latch makes.

Revisit triggers:

  • A container runtime that can hot-add a GPU to a running container ⇒ revisit the "never retry after demotion" half.
  • A hardware failure mode that produces frames but garbage (the latch keys on ZERO frames, so it would not fire) ⇒ needs a different detector, not a bigger threshold.
  • auto becoming the shipped default again ⇒ re-run the GPU-less upgrade test first; the probe is what makes that safe.

2026-08-06, Android walks a reactive fallback LADDER down to the server transcode; it does not ask the server what codec a stream is​

Context. Media3's RTSP stack cannot bring up H.265: the stream either errors with a decoder/format code or sits in BUFFERING and never produces a frame. The client already downgraded an unplayable MAIN to the sub, which covers the common "H265 main + H264 sub" camera. Cameras that ship H265 on both main and sub exist (some Uniview, Annke, Reolink, a lot of no-name ONVIF units, and any camera whose "smart codec" setting flipped the sub too), and on those the single-step downgrade landed on a second undecodable stream: fullscreen spun forever and the wall tile reconnect-looped, while the very same server was publishing an H.264 <name>_mobile transcode that Media3 plays fine (#524). Recording, motion, desktop and playback were all unaffected — this was purely a live-client stream-selection gap.

Decision.

  • The downgrade becomes a ladder, walked one rung per never-played stream: fullscreen main → subv → sub → mobile (data-saver order on a metered link), wall subv → sub → mobile (or main → mobile on a camera with no sub — the wall never escalates to the main's bitrate when a sub exists). The server's _mobile H.264 transcode is always the LAST rung, never a starting choice: it costs a real ffmpeg process on the server for as long as a consumer is attached.
  • Reactive, from playback evidence only. A rung is abandoned when it never reached a playable frame, or when it fails with a decoder/format PlaybackException code. A stream that played and then dropped still reconnects to the same rung — that is a camera reboot or an AP roam, not a codec.
  • The verdict is remembered per camera, in memory, for the app run, so a wall reload or a fullscreen revisit reattaches straight to a rung that plays instead of re-walking the ladder. It is dropped on relaunch, on a config_version change (a camera edit), on an explicit Retry, and for any camera whose ladder ran out with nothing playable (that is an outage, which is no evidence about codecs).
  • The pure decision logic lives in apps/android/.../feature/live/LiveStreamFallback.kt and is unit-tested on the JVM; the composables only wire it to the player.

Rejected:

  • Have the server advertise each stream's codec (GET /cameras/:id/streams carrying main.codec / sub.codec) so the client picks correctly on the first try. This is the better end state and it is a real follow-up — but it is a wire change that only helps clients talking to a NEW server, so the client still needs the reactive ladder for every older server and every unmanaged/Frigate-served camera. Doing the ladder first keeps this fix client-local and version-skew-proof.
  • Always start Android on the _mobile transcode. Trivially correct, and it makes every Android session pay a server-side re-encode plus a real quality drop for the large majority of cameras that publish a perfectly playable H264 sub.
  • Add a software HEVC decoder to the client. Out of proportion to the problem, and it would burn phone battery decoding what the server can remux for free.
  • Persist the verdict across launches. A codec guess derived from a failure should not outlive the app: the operator can re-encode a camera at any time, and a stale "this camera is H265" would pin it to the transcode forever.

Trades knowingly accepted:

  • The ladder costs one bounded unplayable-stream timeout per rung on the FIRST encounter with such a camera (~6 s on the main, ~10 s on the derived rungs, which are more patient because go2rtc spawns their ffmpeg lazily). After that, the session memory makes revisits immediate.
  • A camera whose sub is merely slow to start (rather than undecodable) can be downgraded to the transcode; the operator gets it back with Retry, a camera edit, or a relaunch.
  • Walking the ladder no longer reports stalls to the wall's low-bandwidth auto-fallback, so a wall of all-H265 cameras can't flip itself into snapshot-polling on what is a codec problem, not a link problem.

Revisit triggers:

  • The server growing per-stream codec metadata ⇒ make the START rung proactive and keep the ladder only as the fallback for old servers / unmanaged cameras.
  • Media3 shipping a working RTSP HEVC depacketizer ⇒ the whole ladder can collapse back to a bandwidth choice.
  • Operators reporting that healthy-but-slow sub streams get transcoded ⇒ raise DERIVED_FIRSTLOAD_BUFFER_MS, or require a decoder/format error (not just a timeout) before leaving a rung.
  • WebRTC live on Android being reconsidered (see the 2026-07-02 verdict) ⇒ its codec negotiation would change this calculus entirely.

2026-08-07 amendment (#560): H.265 was never the discriminator; the ladder is evidence-based, graduated, and no verdict is permanent.

The "healthy-but-slow rungs get downgraded" revisit trigger above fired within a day, on unmetered 5 GHz Wi-Fi with an excellent link, and measurement then undercut the premise of the entry itself.

Measured, 2026-08-07, Media3 1.4.1 on a Galaxy S24. Media3's RTSP stack plays H.265 mains fine, 4K included: with one camera open fullscreen, go2rtc showed a single AndroidXMedia3/1.4.1 consumer attached to the H.265 MAIN, video and audio both negotiated, held for well over twenty seconds, sharp picture, no SD badge. Seven of the operator's eleven cameras are H.265 mains. The claim in the code comments and the issue history — "Media3 can't bring up H.265 over RTSP" — is false as of the version this app ships, and it had already misled one session. It is corrected at the source in LiveStreamFallback.kt, and the comments in the two live composables now point there.

What genuinely fails is per-stream and is about RTP packetization, not the codec: RtpH265Reader has never implemented RFC 7798 §4.4.2 Aggregation Packets (androidx/media#1008) and throws UnsupportedOperationException("need to implement processAggregationPacket") — verified present in the pinned media3-exoplayer-rtsp:1.4.1. Aggregation Packets pack SMALL NALs into one RTP packet, so an LPR camera at 1080p hits that path while the same vendor's 4K streams always fragment (FU, which Media3 does implement) and play fine. Of eleven cameras, exactly one should ever walk the ladder in fullscreen. data/camera-compatibility.json already had this right.

What was wrong. !everReady -> true read any failure before the first frame as "this bitstream is undecodable". Media3 reports a failed or timed-out connection with an IO code that says nothing about the codec, and a camera with a long keyframe interval or a cold go2rtc restream can miss the first-load buffering limit once for entirely ordinary reasons. Worse, the resulting guess was latched in LiveStreamFallbackMemory for the whole app run, so one blip pinned that camera to SD until the app was force-stopped — where the pre-#529 single-step downgrade had at least been per-visit. Seven HD-capable cameras, one bad moment each, and the whole session is in SD: "very eager to go to SD" exactly.

The rule now, in order: a decoder/format error, or a known-deterministic failure signature found in the exception chain (today: processAggregationPacket), steps down immediately — those repeat on every attempt, so retrying is pointless; a rung that has played a video frame stays put; a codec-agnostic failure (the 2000..2999 IO block, ERROR_CODE_TIMEOUT, ERROR_CODE_BEHIND_LIVE_WINDOW, ERROR_CODE_DECODING_RESOURCES_RECLAIMED) needs CODEC_AGNOSTIC_FAILURES_BEFORE_FALLBACK (5) in a row with no frame in between, which is the entire fast-backoff curve (~30 s); anything else before the first frame — the stall watchdog's silent BUFFERING spin — needs PRE_FIRST_FRAME_FAILURES_BEFORE_FALLBACK (2). Verdicts expire after VERDICT_TTL_MS (10 min). In fullscreen the "it played" signal is a RENDERED VIDEO FRAME, not STATE_READY, which can be reached on the audio track alone. Every attach, step-down and held rung is logged under CrumbLiveFallback with the tier, the transition, the error code and a credential-scrubbed exception chain.

Rejected:

  • An IO code never counts as evidence at all. Clean, and it re-strands #524's camera: the aggregation-packet exception is thrown inside the loader, so it reaches the app wrapped in an IOException and arrives looking exactly like a network failure. Hence the graduated threshold instead of a veto.
  • Requiring a decoder/format error before ever leaving a rung. An unbringable stream frequently produces no exception at all, only a BUFFERING spin, so this would restore #524 outright.
  • Raising MAIN_FIRSTLOAD_BUFFER_MS / DERIVED_FIRSTLOAD_BUFFER_MS alone (the first option the original entry suggested). It trades the #524 spinner back in for a slower wrong answer and does nothing about the latch, which is what turned a one-off blip into a session-long complaint.
  • Rendered-frame readiness on the WALL tile too. A tile's surface can legitimately go away underneath it, which would read as "never played" and push toward MORE downgrades — the exact regression being fixed. Fullscreen's surface is always attached, so the stricter signal is safe there and only there.
  • Proactive codec selection. Still the real fix (the parent entry's first revisit trigger), still a server wire change, and now known to be the wrong lever anyway: the codec is not what predicts failure — the packetization is, and nothing advertises that.

Trades accepted: the one genuinely unplayable camera takes up to ~30 s to escape a rung when its failure surfaces only as an IO code (immediate when the signature or a decoder error is present), and every camera re-tests the top of its ladder once every 10 minutes.

Revisit triggers: androidx/media#1008 landing ⇒ the signature list and possibly the whole ladder can go; more deterministic signatures showing up in the field ⇒ add them to UNPLAYABLE_FAILURE_SIGNATURES rather than lowering a threshold; operators reporting a camera takes too long to settle ⇒ lower CODEC_AGNOSTIC_FAILURES_BEFORE_FALLBACK, not the unexplained one.


2026-08-06, A non-success go2rtc PUT is resolved by ASKING go2rtc what it has, not by reading the status code; and a never-yet-seen camera gets a creation grace​

Context. Two bugs found by a hostile-camera compatibility matrix against the v0.2.0 RC, filed separately (#519, #520) but decided together because the second is what made the first invisible.

put_stream failed only on 5xx, on the documented belief that "go2rtc registers the stream even when it answers 400". That is true for some 400s and false for others: go2rtc also answers 400 "streams: source with spaces may be insecure" and registers NOTHING, which is what an operator gets for pasting an RTSP URL out of a camera's own web UI (several brands ship paths like /Streaming Channels/101). Crumb recorded that as a successful apply, so the camera row was created, the console showed it as normal, no warning was logged, and the recorder reconnect-looped forever against a restream that never existed.

Meanwhile camera_offline treated "no liveness signal at all" as offline and suppressed only inside a grace keyed on the RECORDER's boot, so every camera added to a running server alarmed within ~20-40 s of being added. In the matrix run 12 of 12 cameras fired it and 11 were healthy — which is exactly why the one camera that was genuinely dead (the #519 case) was indistinguishable from noise.

Decision.

  • On a non-success PUT /api/streams, read the body (it carries go2rtc's reason) and then confirm against GET /api/streams whether the stream is actually registered. Present ⇒ benign, Ok(()) as before. Absent ⇒ a real rejection. Only a 4xx gets that treatment; a transport error or 5xx stays a server-wide "couldn't ask", logged and never attributed to one camera.
  • A confirmed rejection of a camera's MAIN or SUB stream raises a new camera_stream_rejected system event (migration 0077) carrying go2rtc's own reason, on the accepted→rejected TRANSITION only — an in-memory latch on AppState, mirroring the camera_offline watchdog's latch, because a missing stream reads as a stream-count shortfall and drives a reconcile pass every ~5 s.
  • camera_offline gains a per-camera creation grace: a camera that has NEVER reported any liveness signal is held for max(threshold, boot_grace) after its created_at. A camera that has reported even once is judged by the threshold alone, exactly as before.

Rejected:

  • Treat every non-success status as a failure (the obvious reading of #519). It would fire a false camera_stream_rejected on healthy camera adds: Crumb mounts go2rtc.yaml read-only, so go2rtc's own post-registration config write fails and it answers 4xx for a stream it did register. Trading a silent failure for a false alarm on every install is not a fix, it is #520 again.
  • Pattern-match go2rtc's error body ("spaces may be insecure" ⇒ fatal, anything else ⇒ benign). Couples Crumb to another project's error strings and silently regains the silent-failure bug the first time go2rtc rephrases a message or adds a rejection reason. The confirming GET is version-independent.
  • Validate/normalize source_url at add time instead (reject or percent-encode a URL that Url::parse round-trips differently). Worth doing, but it is a different fix: it catches only the space case, only on the add path, and leaves every other go2rtc refusal as silent as it is today.
  • Replace the recorder-boot grace with a creation grace. The two cover different windows (a restart of an established install vs. a brand-new row); #520 is an additional condition, not a substitute.
  • Suppress purely on row age, regardless of liveness. Would create a real blind spot: a camera that recorded fine and then died 30 s later would be held for the whole window. Gating on age.is_none() means the grace can only ever delay the FIRST alert for a camera that has never worked.

Trades knowingly accepted:

  • A rejection costs one extra HTTP round-trip — on the error path only, against the local go2rtc.
  • If the confirming GET itself fails, put_stream assumes the stream applied. A late alert beats a false one, and the loop retries within seconds.
  • Both latches are in-memory, so a restart re-derives them and a still-broken camera can alert once more. Same trade the camera_offline latch already makes.
  • A genuinely dead NEW camera now alerts after the creation grace (~3 min by default) rather than ~20 s. Nothing was being recorded in either case, and camera_stream_rejected fires within seconds for the subset that is dead because go2rtc refused the stream.

Revisit triggers:

  • go2rtc gaining a response that distinguishes "registered" from "rejected" (a structured error body, or 201 vs 200) ⇒ drop the confirming GET.
  • Add-time source-URL validation landing ⇒ re-check whether the camera_stream_rejected detail should point at the field instead of go2rtc's raw message.
  • Operators reporting that the creation grace hides a real fault for too long ⇒ give it its own env knob instead of borrowing CAMERA_OFFLINE_BOOT_GRACE_SECS.
  • A second consumer needing "is this camera's stream actually registered?" (the console wanting a per-camera health pill) ⇒ promote the latch to a queryable LEVEL signal, the way camera_motion_health did for detector health.

2026-08-06, Motion health: a structurally-disabled detector is unhealthy but NOT alert-worthy​

Context. Issue #523, found on the v0.1.1 → v0.2.0 upgrade test. The startup-armed unhealthy timer added in #411/#413 (so a detector that is dead from boot and never recovers still pages, after a VAAPI decoder died silently for five days) is armed unconditionally in run_one_source. A camera added with a main stream only (source_sub_url unset, which the self-service add flow allows) has its pixel detector deliberately parked by run_pixel_diff_loop ("motion runs on the SUB stream only", correctness item 12) and reports unhealthy forever by design. So the timer fired ~MOTION_UNHEALTHY_ALERT_SECS after every recorder start, forever, on a camera that is working exactly as configured — recurring unactionable noise on the one channel whose whole purpose is to be trusted.

Decision. Split "unhealthy" from "alert-worthy". A source that the camera's configuration makes permanently incapable of becoming healthy is structurally disabled: it keeps its unhealthy state (fail-open recording and the console's degraded-motion badge are both correct and stay exactly as they are — correctness items 19/26 are untouched), but no startup alert timer is armed for it, so no motion_detector_unhealthy event is ever written for that configuration. Today the one such condition is a pixel source on a camera with no sub-stream; Frigate and HA sources on the same camera are unaffected and still alert, because a main-only camera can be perfectly healthy on those.

Second half: the three surfaces that described this state disagreed (fallback_reason said "camera has no sub-stream; motion analysis disabled", motion_health_reason said "pixel motion detection not delivering frames", the alert said "pixel motion detector never became healthy after startup"). The specific cause is now a single shared constant (NO_SUB_STREAM_REASON) used by the decode-status telemetry, the recorder log, and the persisted motion-health reason. More generally, UnhealthyAlertGate now remembers the reason string of the last UNHEALTHY transition and the aggregator prefers it over its generic "not delivering frames" wording — so the keyframes-only/long-GOP fail-open, which always logged an actionable cause, now surfaces that same cause to the operator.

Rejected:

  • Making the no-sub-stream branch report HEALTHY. Directly violates correctness item 26 (a detector is healthy only when it can produce a keep/discard verdict) and would let a Motion-mode policy gate footage on a detector that does not exist. Never.
  • Suppressing the alert only for continuous-mode policies. The alert is noise in motion mode too: fail-open is already handling it correctly and there is nothing the operator can do except add a sub-stream, which the console already shows. Policy mode is also hot-editable, so gating an alert on it would make the alert appear/disappear on an unrelated setting change.
  • A distinct quieter event key (e.g. motion_analysis_disabled). A new event key means a new alert rule, new notification wiring, and a new row every boot for a state that is already visible in the console badge and in /config/decode-status. Nothing to page about; a level, not an edge.
  • Threading a per-source reason through the health watch channel (changing MotionHealthTx from watch<bool> to a struct). That touches the fail-open rail that recording.rs reads every segment, for a telemetry string. Parking the reason on the alert gate (already passed to every report_health call) keeps the safety rail byte-identical.

Revisit if: a second structurally-disabled condition appears that operators do want paged (then structural_disable_reason grows a variant and the suppression becomes per-condition rather than blanket), or if operators report they wanted to be told a camera has no sub-stream at all — in which case the right surface is the camera-health/console list, not the recorder's unhealthy alert.


2026-08-06, Media-token scope on /cameras/:id/streams: gate the endpoint on a full session now, defer per-request RTSP credentials​

Context. A scoped media token (?token=, typ: "media", ~15 min, one camera, media only) exists so that browser elements which cannot set an Authorization header still get something weak instead of the full login JWT. auth.rs documents that property as "a leak grants at most view one camera's media for a few minutes".

That property is about what a token can reach, not just what its claims say, and it is not self-enforcing. It holds only while every endpoint reachable with ?token= returns something no more durable and no broader than the token. GET /cameras/:id/streams was not such an endpoint: it lives in media_routes, and its RTSP URLs embed GO2RTC_USER/GO2RTC_PASS — one server-wide, non-expiring pair covering every stream go2rtc serves. A media-token holder could therefore trade the weak credential for a strictly stronger one, which makes the token's careful scoping decorative on that path. Found in the v0.2.0 release audit (#506).

Decision. Two changes, both minimum-scope for the v0.2.0 tag:

  • A new FullSessionUser extractor in auth_mw.rs, backed by a media_scoped: bool marker on AuthUser set at the two construction sites. It wraps AuthUser and rejects a media-token principal with 403. live_streams takes it instead of AuthUser. The endpoint stays in media_routes — the extractor, not the mount point, is what carries the rule, and it now reads as an explicit property of the handler.
  • /auth is routed as its own subtree so the permissive CORS layer skips it (cors.rs, cors::compose). It keeps the identical rate-limit / timeout / compression stack — the rate limiter in particular is what makes /auth/login expensive to brute-force, and losing it silently would be a worse outcome than the wildcard header.

Client verification before changing the extractor: all four surfaces (apps/desktop-flutter/lib/api/crumb_api.dart, Android CrumbApi.kt via its AuthInterceptor, apps/ios/.../CrumbAPI.swift, and admin.html's api() helper) already call /cameras/:id/streams with the Authorization: Bearer header during session setup. No client change, no version skew.

Rejected:

  • Per-request short-lived RTSP credentials — the structurally correct fix: the response would carry nothing durable and the property would hold by construction instead of by endpoint-by-endpoint review. Deferred to #507, not dismissed. It needs go2rtc's auth model investigated (per-stream credentials may not be expressible without hand-managing go2rtc.yaml, which the reconcile loop owns), and a credential that expires mid-live-view means a renewal path in three clients. That is a design task with its own testing pass, not something to land inside a release-audit fix.
  • Moving the route out of media_routes into json_routes. Equivalent security outcome, but it would silently add the 30 s timeout and the JSON rate limiter to a call every client makes once per camera at session setup, and it leaves the next reader to infer the rule from a mount point. The extractor states it.
  • Dropping the permissive CORS layer everywhere, not just /auth. Probably right — nothing Crumb ships needs CORS at all, since the clients are native and the console is same-origin. Deliberately not done in a security-fix PR bound for a release tag: it could break an operator's own LAN page or script with no warning, and that is a change that deserves its own note in the release notes rather than a footnote in a hardening commit.

Trade-offs accepted. The go2rtc credential is still server-wide and non-expiring; a full login session can still read it, which is exactly the status quo for every client. The media_scoped flag is a marker a future extractor must remember to check — the mitigation is that FullSessionUser exists and is documented as the thing to reach for, rather than each handler re-deriving the rule.

Revisit triggers. Any of: #507 lands (this entry's first half becomes redundant); go2rtc gains a usable per-stream or token auth mechanism; a deployment mode appears where the RTSP endpoint is reachable beyond the LAN; another endpoint turns up returning a credential broader than its caller's proof, which would mean the one-off extractor gate is the wrong shape and a response-side rule is needed; or the permissive CORS layer is dropped from the remaining routes, at which point cors.rs and its control test collapse.

Superseded in part 2026-08-07 — the fourth revisit trigger fired: the media-token reachability rule is now enforced as a CLASS by inverting the AuthUser default. See the entry immediately below.


2026-08-07, Media-token reachability is enforced as a CLASS: AuthUser rejects media tokens by default, media-read endpoints opt in via MediaOrFullUser​

Context. The 2026-08-06 entry above gated exactly one endpoint (/cameras/:id/streams) against scoped media tokens with a bespoke FullSessionUser extractor, and flagged as a revisit trigger "another endpoint turns up returning a credential broader than its caller's proof … a response-side rule is needed." A follow-up audit fired that trigger: the same invariant was violated across a whole class of routes still on the bare AuthUser extractor, which accepted a media-token principal. Confirmed reachable with a media token minted by an already-authenticated session:

  • POST /auth/refresh re-fetched the user by claims.sub and minted a full, normal-privilege login JWT — a media token traded up to a full (admin) session.
  • POST /notifications/channels / POST /notifications/devices created a persistent webhook / registered a device against the minting user, surviving the token's expiry.
  • GET /media-token let a media token mint another (unbounded renewal; media principals are unrevocable, jti: None).
  • GET/DELETE /auth/sessions* let a media token read and revoke the minting user's sessions.

The root cause was structural: the safe posture was applied per endpoint, so any new AuthUser route silently reopened the hole.

Decision. Invert the default so the safe case is the one you get for free:

  • auth_mw::AuthUser — the DEFAULT extractor — now rejects a media-scoped principal with 403. A new endpoint on AuthUser is therefore unreachable by a media token without anyone remembering a rule.
  • A new auth_mw::MediaOrFullUser extractor accepts a media token or a full session, and is applied to the audited single-camera media-read surface only: serve_segment, get_segment_low, serve_frame (filmstrip), get_camera_frame, get_clip_media, get_clip_thumbnail, get_event_snapshot, get_plate_crop, live_stream_mp4, live_webrtc. Each was verified against all four clients' media-URL builders (Android MediaUrls.kt, iOS MediaUrls.swift, desktop *_api.dart, admin.html) as an endpoint a browser/media loader actually fetches with ?token=.
  • FullSessionUser is kept (still on /cameras/:id/streams) as a loud, self-documenting marker; it is now behaviorally identical to AuthUser.

Everything else that was on AuthUser — the entire /auth/*, /media-token, /notifications/*, /config/*, /views, /bookmarks, /ha/*, /ptz, /timeline, /clips (list), /plates (list), /stats, /status surface — is now full-session-only for free. Admin routes (AdminUser) were already safe (a media principal is Viewer).

Why not the response-side rule (a credential-scanner on responses). That is the theoretically-complete fix the prior entry gestured at, but it needs a way to classify "this body contains a credential/long-lived URL" that does not exist, and it would not catch side-effecting mutations (device registration) at all. Reachability-by-extractor is the property that actually generalizes: a media token reaches only endpoints that opted in, and the opt-in list is short, enumerable, and reviewed.

Trade-offs accepted. Missing a genuine media-read endpoint fails SAFE — it returns 403 to media tokens (a visible functional regression: a blank thumbnail), never a silent privilege hole. The client-fetch survey is the mitigation; the media-read opt-in set is asserted working in auth_rbac.rs (media_token_still_reaches_the_media_read_surface). Adding a future MediaOrFullUser endpoint is a security-review event, called out in COMPONENT-MAP.md row G.

Revisit triggers. A new client feature fetches an existing full-session endpoint with ?token= (means either that endpoint is genuinely media-read and should move to MediaOrFullUser, or the client should use a Bearer request); #507 lands per-request RTSP credentials (then /cameras/:id/streams no longer needs the gate at all); or a media-read endpoint is found that returns more than one camera's bytes (it must leave MediaOrFullUser).


2026-08-06, Unmounted-storage guard: a marker FILE plus a circuit breaker, not a mountpoint heuristic​

Context. Reconcile's dangling-row pass stats storage.path / seg.path for every indexed segment and deletes the row when the file is missing. Nothing checked that the storage root was the real storage. A root that is PRESENT but EMPTY — an fstab noauto disk that never mounted, a dropped network mount, a Docker bind source Docker auto-created after a host path moved — makes every row on that storage look dangling, so ONE pass deletes that storage's entire segment index (issue #504). The footage bytes survive, but everything only the index carries does not: has_motion, motion bounding boxes, stage and stream labels, durations, clip and bookmark linkage. Re-adoption after a remount is rate-limited and re-adopts with has_motion = false and no bbox, so the motion history is gone for good. The orphan pass already had a root-exists guard; the dangling pass had none, and that guard cannot see this case anyway because the root does stat fine.

Decision. Two independent layers in services/recorder/src/reconcile.rs, both failing toward "skip and alarm", never toward delete:

  1. A marker file, <storage_root>/.crumb-storage. The dangling pass deletes nothing on a storage whose marker is absent. The marker rides ON the storage, so an unmounted disk (a bare mountpoint directory) simply does not have one — which is exactly the distinction a "does the root exist?" check cannot make. It is written only on positive confirmation: by the recording path the moment the recorder is about to write footage into that root (ensure_storage_marker), and by a boot/heal pass that requires at least one of the storage's newest indexed segment files to actually be present (seed_storage_markers). A storage with no indexed segments at all is indistinguishable from an empty foreign directory and gets no marker from reconcile; the recorder writes it when it records there.
  2. A per-storage circuit breaker. Even with a marker present (a stale marker, a repointed path), deletions halt for a storage once more than 100 of its rows AND more than 50 % of its checked rows come back missing in one pass. It is evaluated before every delete, so a mass-missing event costs at most 100 rows per storage, and the trip LATCHES for the process — otherwise a timer-driven reconcile would simply drain the index 100 rows per pass. Both thresholds must be exceeded, so neither a small storage an operator emptied nor a large one mid-eviction can trip it.

Both raise the existing storage_unwritable system event.

Rejected:

  • Mountpoint-only heuristics (compare st_dev of the root against its parent, parse /proc/self/mountinfo, or require the root to be a mount point). Too weak in both directions: a perfectly valid storage is very often NOT its own mount point (a subdirectory of one big data disk, the default compose layout's /data/live and /data/archive), so this would refuse to prune on healthy installs; and a mount that succeeded onto the WRONG device, or a bind mount of an empty directory, passes the check while being exactly the failure we are guarding against. It also does not survive containers, overlayfs, or network filesystems predictably. A marker written by the recorder answers the question that actually matters — "is this the storage I have been writing to?" — instead of a proxy for it.
  • A count-based-only guard (breaker without the marker). Bounds the damage but does not prevent it: a genuinely unmounted disk would still lose up to 100 rows per storage, and the first 100 rows of an index are just as unrecoverable as the rest. The marker makes the common case cost zero rows.
  • A DB-side "storage last seen healthy" timestamp instead of a file. Lives in the wrong place: the whole question is whether the FILESYSTEM in front of us is the one the index describes, and only something stored on that filesystem can answer it. A DB flag would happily say "healthy" about a disk that is no longer there.
  • Refusing to prune whenever ANY row on a storage is missing. Safe, but it turns off dangling-row cleanup permanently on any real install (retention, crashes, and operator deletions produce dangling rows continuously), letting the index rot instead.

Trades knowingly accepted:

  • A storage whose footage an operator genuinely deleted wholesale, on a disk with no marker, stops being pruned: its stale rows survive and it alarms until the operator re-creates .crumb-storage (an empty file is enough; the marker body says so). Stale rows are a visible, fixable annoyance; a deleted index is not.
  • A latched breaker keeps pruning off for that storage until the recorder restarts, so a genuine mass deletion needs a restart to be cleaned up.
  • One extra dotfile per storage root, and one indexed sample query per storage per pass until its marker exists.

Revisit triggers:

  • Operators hitting the "I really did delete everything" case often enough that re-creating the marker becomes a support burden → add an explicit admin action ("this disk is empty on purpose, re-mark it") instead of documenting a touch.
  • A storage backend where the recorder cannot write a dotfile into the root (a read-only mount used as archive-only storage that another process fills) → the marker would have to be seeded from the API side, or the confirmation rule relaxed to "any indexed segment present" without a marker.
  • Evidence that 100 rows / 50 % is the wrong shape (e.g. a real deployment where a single pass legitimately sees a majority of one storage's rows disappear) → retune DANGLING_BREAKER_MIN_MISSING / DANGLING_BREAKER_MISSING_PCT, which exist as constants for exactly that reason.

2026-08-07 follow-up — the recording-path marker is written post-commit, not at directory creation. The v0.2.0 re-audit found that the recording path defeated its own layer-1 guard: record_camera called ensure_storage_marker right after create_dir_all succeeded, BEFORE any footage existed. On the exact failure this guard is for — a host reboot where the live disk fails to mount and Docker leaves an empty mountpoint directory — create_dir_all succeeds on that empty dir and the marker was planted there, a FALSE confirmation. The next reconcile pass saw marker_ok and pruned the (unmounted) real disk's whole segment index; only the layer-2 breaker bounded the loss, and only above its 100-row floor. The seed_storage_markers boot pass had never had this hole because it refuses to write a marker unless at least one INDEXED segment is actually present under the root. Fix: move the marker write into index_segment, firing only on a genuine commit — a real ≥floor segment fsync'd on disk AND a row in the index for it. That is the same "a real indexed segment is present under the root" signal the seed pass confirms on, so the two writers are now equally trustworthy. A healthy storage still gets its marker the moment it records its first segment (and the seed pass still heals pre-existing installs), so normal pruning is unchanged; a bare mountpoint the recorder writes into no longer earns a marker until footage is genuinely both on disk and indexed there. Rejected (again) the direct mountpoint / st_dev shape check for the recording path, for the same reasons this entry rejected it for reconcile: it is unreliable across bind mounts, overlayfs and network filesystems. "Confirm via a real indexed segment" reuses the mechanism already chosen here rather than adding a second, weaker signal. Trade-off accepted: the marker now appears a few seconds later (after the first indexed segment) than at directory creation — immaterial for a healthy install, and the right direction for safety. Guarded by reconcile::tests::recording_path_marker_written_only_after_a_committed_segment and a_false_marker_below_the_breaker_floor_prunes_the_whole_small_index.


2026-08-06, setup-env.sh fails the install when uid 1001 cannot write to the media dir (tiered probe, deferred exit)​

Context. A media directory the recorder (uid 1001) cannot write is the worst failure mode Crumb has, because it does not present as a failure: live view runs off go2rtc and never touches disk, the first-run wizard shows green (the api mounts /data read-only and so cannot test writing), and footage is silently never saved. setup-env.sh only did a best-effort chown 1001:1001, which on a large share of real hosts reports success while changing nothing the container sees: NFS root_squash, SMB uid mapping, FUSE user shares (Unraid /mnt/user), and the 100000 uid shift of an unprivileged Proxmox LXC.

Decision. Preflight the media directory and exit non-zero on a definite negative, rather than warn. Recording nothing is not a degraded install, it is a non-install, and the operator finds out days later when they go looking for footage. Three supporting choices:

  • Tiered probe, most faithful method that can answer honestly. Impersonate uid 1001 (root, sudo -u '#1001' or setpriv), else a container run as --user 1001, else read the directory's own owner/group/mode. An inconclusive tier never produces a verdict, it falls through; if no tier can answer, the script prints the manual one-liner and exits 0. A false hard failure on a working install would be worse than the warning it replaces.
  • The docker tier never pulls. It runs only against an image already on the host, and discriminates touch's exit 1 (a real EACCES verdict) from docker's own 125/126/127 (an exec problem, not a verdict). setup-env runs before any docker compose pull, and making secret generation depend on registry reachability would break air-gapped installs.
  • The exit is deferred to the end of the run, after the one-time admin password is printed. .env is complete and correct when storage is broken; what failed is the host. Dying mid-script would cost the operator their credential to save them a scroll.

Rejected: warn-only (the status quo that produced the bug, and the reason nobody noticed); probing from the recorder at boot instead of here (it already raises storage_unwritable, but by then the operator has walked away believing the install succeeded, so this is additive, not a replacement); requiring root for setup-env (would break the documented non-root install path).

Trade-off accepted: a plain non-root git clone && ./scripts/setup-env.sh on a host where the media dir is not yet uid-1001-writable now exits 1 where it previously printed a NOTE and exited 0. That is intended, it is exactly the broken install this catches, and the error names the fix. Any automation that treated setup-env's exit code as "secrets generated" needs to read it as "secrets generated AND storage verified".

Revisit when: the probe produces a false negative on a real operator's host (then narrow the tier that got it wrong, do not weaken the exit), or the wizard grows a genuine server-side write test that makes the pre-boot check redundant.


2026-08-06, Per-state HA badge backgrounds: one extra nullable column that inherits from the base (not paired per-state columns)​

Context. Migration 0062 gave a placed HA badge a single solid background (overlay_bg_color). Operators want the background itself to carry the state: dark when the door is shut, red when it is open. One column cannot express two states, and the wall is where a badge earns its keep, so this is wave A of the badge-customization rework: freeze the server contract first, then let the four renderers (admin console, desktop, Android, iOS) follow against a contract that is already merged rather than four clients racing a moving schema.

Decision. One additive nullable column, overlay_bg_color_on (migration 0076), with an inherit-from-base meaning:

  • overlay_bg_color keeps its 0062 meaning and becomes the BASE. It renders for the off state AND for an indeterminate or stale reading (unknown, unavailable, no reading yet). Every existing row therefore renders exactly as it does today.
  • overlay_bg_color_on overrides the base ONLY while the entity reads on (edge_on == true). NULL, which is what every existing row gets, means "inherit the base".

Renderer resolution, identical in every client: on ⇒ bg_color_on ?? bg_color ?? #17171B; any other state ⇒ bg_color ?? default. On the wire the field is additive on HaLinkDto and PlacementInput (bg_color_on, #[serde(default)], validated by the same valid_overlay_color gate as bg_color, 400 on garbage), plus the same '#RRGGBB' CHECK in the migration that 0059 and 0062 use. A field null inside the placement object resets to inherit, following the existing per-badge override convention; a body-level null still clears the whole placement, unchanged.

Rejected:

  • Paired per-state columns (overlay_bg_color_off + overlay_bg_color_on, base retired). Cleaner on paper, but it is a breaking reinterpretation of an already-shipped column: every existing badge would need a data migration, and every client would need a version-aware read during the wave A to wave B window. The gain is symmetry, not capability. Inherit-from-base gets the same expressiveness with zero rows touched and no client flag day.
  • A per-state ACCENT (foreground/icon color) in the same wave. Real demand, but overlay_color has the same base-column shape as overlay_bg_color, so it is the same decision applied twice. Doing it now doubles the client work in wave B for a knob nobody has asked for yet. If it lands, it lands as overlay_color_on by exactly this pattern.
  • A JSON style object (overlay_style jsonb) covering every per-state attribute at once. The right answer eventually, and clearly wrong now: it throws away the per-column CHECK constraints that keep bad hex out of the database, replaces typed Option<String> fields with untyped parsing in four clients, and rewrites a wire contract three of the four renderers already ship against. Not worth it for a third style column.
  • Making the on color required whenever a base is set. Would force a decision on operators who just want one solid background. Optional and inheriting is the smaller surface.

Trades knowingly accepted:

  • The model is asymmetric: off and indeterminate share one color and cannot be told apart by background alone. Staleness is signalled by the existing treatment (the clients grey a badge after missed polls), not by the background.
  • Two hex columns per badge is one more thing an editor has to present. Wave B owns that UX.

Revisit triggers:

  • Operator demand for a per-state ACCENT (icon/text color, not just background) ⇒ add overlay_color_on by this same inherit-from-base pattern, in one change across all four renderers.
  • A demand for a FOURTH distinct style state (a separate unavailable or alarm look, say) ⇒ stop adding columns and move the whole per-badge style block to a single validated JSON style object, migrating the existing columns into it.
  • A mobile badge editor (issue #444, currently deferred) shipping ⇒ re-check that the two-color model is authorable on a phone; if it is not, that is evidence for the JSON style object plus a preset palette instead of free hex entry.

2026-08-06, Only the CAMERAS that publish H264 without sprop-parameter-sets get a <name>_subv repair stream, detected per camera from the producer SDP​

Context. The Android live-wall tile plays a camera's SUB stream over RTSP (Media3/ExoPlayer). For one camera the tile reconnect-looped forever (#483), with IllegalArgumentException: missing attribute fmtp from Media3's RTSP client, which requires an fmtp attribute on the media tracks it builds. Fullscreen was unaffected (WebRTC/main path).

The initial diagnosis blamed the camera's audio tracks (a audio, sendonly, PCMU/8000 two-way-audio backchannel). Surveying every sub restream on a live install disproved that: cameras with PCMA and AAC audio all work, and go2rtc already drops the sendonly backchannel from its restream. The real discriminator is the video track. The failing camera is a Reolink whose own SDP advertises m=video … H264/90000 with no a=fmtp / no sprop-parameter-sets, and go2rtc's plain restream passes that gap straight through — it was the only stream of eleven whose video track had no fmtp. Such a stream has no out-of-band parameter sets at all: ffprobe on it reports "non-existing PPS 0 referenced / decode_slice_header error / no frame!".

Decision — register a dedicated video-only sub restream <name>_subv in the API's go2rtc reconcile loop, sourced ffmpeg:<name>_sub#video=copy, and hand it to clients as its own rtsp_subv_url field alongside the raw rtsp_sub_url. Passing the bitstream through ffmpeg recovers the in-band SPS/PPS, so go2rtc republishes a proper a=fmtp:96 …sprop-parameter-sets=…; omitting #audio makes go2rtc pass -an, so audio is dropped as a bonus (the wall is muted; two-way audio / listen uses WebRTC). #video=copy is a remux, not a re-encode (verified: identical h264/High/640x360 in and out), it reads the existing _sub stream by name so it shares that producer and adds no camera session. rtsp_subv_url is null for cameras reconcile does not manage (Frigate-served, or a legacy row with no source_url), because no _subv exists for those; rtsp_sub_url keeps its original meaning for every camera.

Register it ONLY for the cameras that actually need it, detected per camera. This is the part two earlier revisions got wrong, in the same way twice. _subv is repaired but LAZY: go2rtc spawns its ffmpeg on first consumer connect and reaps it when the last consumer leaves, so a cold one costs a process spawn plus a wait for a keyframe through an extra hop, per consumer. Registering it for every camera and pointing a whole wall at it therefore converts "attach to N always-warm _sub producers" into "cold-spawn N ffmpeg processes", which is a multi-second wall open. On the reference install one camera of eleven is affected. So the reconcile pass decides per camera:

  • It already fetches GET /api/streams every pass to choose PUT vs PATCH. That payload includes each producer's raw SDP, so the detection costs zero extra requests, no RTSP DESCRIBE, and cannot dial a camera.
  • A camera is flagged when its <name>_sub producer SDP has an m=video section with no a=fmtp line. The check walks media sections rather than scanning the whole SDP, because the broken camera's SDP does contain a=fmtp:97 — on its AUDIO track. A naive contains("a=fmtp:") calls the one broken stream healthy.
  • An unknown verdict (no producer attached yet, no SDP, no video section) is sticky: keep the previous answer, so a producer blinking between passes can neither tear down a repair a live session is playing nor invent one. Nothing known at all means not flagged, the fail-safe direction: the client falls back to the always-warm raw sub and is no worse off than before #483.
  • Flagged cameras get _subv registered and rtsp_subv_url advertised. Unflagged ones get any stale _subv deleted in the same pass, so the stream set and what the API advertises never drift apart.
  • The verdict lives in memory only (no DB column, no migration). It is a runtime property of the camera's current firmware, not operator configuration, so a restart re-derives it rather than trusting a stale row; the empty cold-start set means "nobody needs it", again the safe direction.

Which stream a client plays is also the CLIENT's choice, and only Android takes _subv. Android picks rtsp_subv_url ?: rtsp_sub_url; desktop (libmpv) and iOS (AVFoundation) keep rtsp_sub_url untouched, because both already tolerate the missing-fmtp SDP that Media3 rejects. That split is not tidiness, it is the performance budget. go2rtc spawns the remux ffmpeg lazily, on first consumer connect, and reaps it when the last consumer leaves: an idle _subv costs nothing, but a cold one costs a process spawn plus a wait for a keyframe through an extra hop, per consumer. The first cut of this change pointed rtsp_sub_url itself at _subv, so every client got it. On the owner's install a fresh desktop wall then cold-spawned roughly eleven ffmpeg processes on open and took many seconds to fill, where before it attached straight to the always-warm _sub producers that reconcile keeps running. Splitting the field restored the fast open for desktop and kept the Media3 repair — but on its own it was still too coarse, because it moved the same cost onto the Android wall, whose eleven tiles then all cold-spawned. Client scoping and per-camera detection are both needed, and they answer different questions: which player needs a repaired SDP, and which camera actually publishes a broken one.

Rejected — registering _subv for every camera and letting only the client choose (the shipped-then-reverted #485 behaviour). It looked cheap because an unconnected _subv really is free, but the cost is not the registration, it is the first CONNECT — and the Android wall connects to all of them at once. The owner's verdict on the blanket version was the right one: applying a repair to ten working cameras to fix one is nuclear.

Rejected — making _subv eager (an always-running remux per camera so it is warm for everybody, keeping a single rtsp_sub_url field). That is a permanent extra ffmpeg process per camera on every install, paid by operators whose clients never need it, purely to avoid a cost only Media3 incurs on one camera. Lazy plus detected is strictly cheaper and needs no new configuration. (A narrower version of this — pre-warming only the FLAGGED stream — stays available as a revisit trigger below.)

Rejected — an operator toggle ("repair this camera's sub", per camera in the admin console). It makes an operator diagnose an SDP-level fault that the server can see for itself, and it goes stale silently when firmware changes. Detection is not hard here: the evidence is already in a payload reconcile fetches anyway.

Rejected — putting the media filter in the CLIENT URL (rtsp://…/<name>_sub?video). This was tried first and falsified on-device: it broke playback of every camera. ffprobe accepts a query-string RTSP URL, but Media3 derives per-track SETUP URLs by appending /trackID=N to the base URI, so …?video produces malformed SETUP URLs. It also would not have fixed the reported camera anyway — the filtered SDP still had no fmtp on the video track — and its single-segment rtsp path collides with a managed stream name, forcing reconcile onto the PUT path (object replacement) every pass. Lesson recorded: prove a client-facing streaming fix with the client's own stack, not just ffprobe.

Rejected — fixing it inside the client (each client selecting only the video track itself, or tolerating a missing fmtp). Media3 offers no clean "skip an unparseable track" hook, and every future client would re-hit the trap. The repair therefore stays server-side and is built once; what is per-client is only the one-line choice of which of two published URLs to open, which is exactly where the knowledge of "my player needs fmtp" lives. An old client that never learns about rtsp_subv_url keeps working on the raw sub, unchanged.

Revisit triggers (any one):

  • The live wall needs audio on the RTSP sub (then request #audio= explicitly and re-verify the SDP, keeping the fmtp repair).
  • go2rtc changes ffmpeg: source semantics, drops #video=copy, or stops emitting -an when no #audio is given — re-verify the _subv SDP.
  • Cameras stop shipping H264 without sprop-parameter-sets, or Media3 gains tolerance for a missing fmtp — the copy hop could then be dropped, and with it the second URL field.
  • Even ONE lazy spawn is noticeable on the flagged camera's tile (it is now the only one paying, but it still opens cold). The fix then is to PRE-WARM the flagged _subv — hold a single server-side consumer on it so the remux stays running — which is affordable precisely because the flagged set is tiny. Do not solve it by widening the set again.
  • A large fraction of an install's cameras get flagged. The whole design assumes broken subs are rare (one of eleven on the reference install). If a vendor ships a firmware generation that drops sprop-parameter-sets broadly, the arithmetic behind "targeted" collapses and pre-warming (or a fix further upstream) becomes the right answer.
  • The detection proves unreliable in the field — a camera flapping between flagged and healthy, or a stream whose producer SDP never settles. The sticky unknown handles a blink; sustained flapping would want hysteresis (N passes agreeing) or an operator override, neither of which is worth building on speculation.
  • go2rtc stops including producer SDPs in GET /api/streams, or changes their shape. Detection would silently go quiet (everything "unknown" ⇒ nothing flagged ⇒ the #483 tile reconnect-loops again), so re-verify the parse against a real payload on any go2rtc major bump. This is the one failure mode that is quiet rather than loud.
  • A third client adopts a player that also rejects a missing fmtp. It should take rtsp_subv_url the same way; nothing server-side needs to change.

2026-08-01, Home Assistant value controls (brightness / position / speed) carry one optional server-validated number, discovered via a states control descriptor​

Context. The action model above shipped on/off/toggle/press control. The obvious next step (#442) is value-setting: dim a light, set a cover to 40 percent, pick a fan speed, from the same camera view. That means an action needs to carry a number, and a client needs to know an entity is settable (and its current value) to draw a slider. This is Slice 1: the three already-trusted percent domains only (light.set_brightness, cover.set_position, fan.set_speed). Climate set_temperature is Slice 2, deliberately out of scope here so the non-percent path lands separately.

Decision. POST /cameras/:id/ha/action gains one optional value: f64. The per-domain allowlist becomes a structured spec table (HaActionSpec { action, service, value: Option<ValueKind> &#125;); every existing discrete row migrates in with value: None, and the three value rows carry Some(ValueKind::Percent { param &#125;). The action word is no longer equal to the HA service (set_brightness rides turn_on with brightness_pct; set_position rides set_cover_position; set_speed rides set_percentage) — that invariant is retired, and service plus every value param stay &'static from the table so nothing client-controlled reaches the URL or the service-data keys. A new validate_value step runs AFTER the allowlist and allowed_actions checks and BEFORE HA is contacted: a value on a discrete action, or a missing value on a value action, is a 400; a percent value must be finite and in a HARDCODED 0..=100 (so a cold attribute cache can never block a control), then it is rounded to the nearest integer and sent as a JSON integer. Out-of-range is audited as a rejection like any other. allowed_actions = null still means every domain action INCLUDING the value words (uniform with on/off); a non-null list must name the value word explicitly.

Client capability discovery is an OPTIONAL control descriptor on each GET /ha/states entry, projected from attributes ALREADY in the cached raw snapshot (no extra HA round-trip): {action, kind:"percent", value, min, max, step, unit&#125;, present iff the entity currently exposes a settable value (brightness for a light, current_position for a cover, percentage for a fan). Absent descriptor ⇒ the client shows no slider; an old client ignores the field. The descriptor is kind-agnostic (min/max/step/unit) so Slice 2 temperature reuses it unchanged. audit_actuation records the parsed number (never the raw client string).

Rejected:

  • Overloading turn_on to also mean "set brightness". Ambiguous on the wire and impossible to gate distinctly in allowed_actions; a distinct set_brightness word that happens to ride turn_on server-side keeps the vocabulary explicit while reusing HA's actual service.
  • A separate "value capability" or endpoint. The value path is the same privileged actuation surface with one more validated field; a second endpoint or capability would duplicate every RBAC gate for no security gain.
  • Persisting value ranges in Postgres. Percent is hardcoded 0..=100; richer ranges (temperature) live on the HA entity and reach the client through the control descriptor. No migration is needed: allowed_actions text[] already stores arbitrary vocabulary and range metadata lives on the entity.
  • Per-link value clamps in v1 (e.g. "this dimmer maxes at 60 percent"). Real, but it is a new authoring surface; deferred until asked for. allowed_actions already gates WHETHER the value word is offered at all.

Revisit triggers (any one):

  • A non-percent, non-temperature value kind is needed (a raw 0..255, a named enum): add a ValueKind variant + one validate_value arm + one descriptor arm, and reconsider whether the range still belongs hardcoded in Crumb.
  • Demand for per-link value clamps: split a clamp field from the link config the way allowed_actions was split from the domain allowlist.
  • Slider drag generating a call storm inflates the ha_actuation audit volume: add client-side debounce or a commit-on-release contract before rate-limiting server-side.

Context. The HA integration has been read-only since Phase 1 (config singleton + camera_ha_links + an entity picker that proxies HA so the token never reaches a client). Issue #187 adds the control path: an operator watching the garage on camera should be able to close it from the same view. This is the only endpoint in Crumb that actuates PHYSICAL hardware, and the HA long-lived access token Crumb holds is unscoped, so anything a client can talk Crumb into asking HA for, it gets. The design question is how much of the HA service call a client is allowed to influence.

Decision, POST /cameras/:id/ha/action with a body of exactly {link_id, action}, and nothing else. The client names a camera_ha_links row the operator authored and one action word. The server derives the HA domain from that row's stored entity_id (text before the first .), looks the word up in a static per-domain allowlist, and builds POST <ha_base>/api/services/<domain>/<service> with {"entity_id": <the stored entity>} itself. The allowlist is exhaustive: light/switch/fan/siren (turn_on, turn_off, toggle), cover (open_cover, close_cover, stop_cover), lock (lock, unlock), button/input_button (press), scene/script (turn_on). No domain, service, or entity id is ever accepted from a client. Verification runs in a fixed order and returns before HA is contacted at every step: the new actuators capability, then per-camera scope, then "this link exists on this camera and has role = 'actuator'", then the allowlist. Every attempt that resolves to an actuator link, including allowlist rejections and failed HA calls, writes a system_events row (event_key = 'ha_actuation') naming the user, camera, link, entity, action and outcome, plus a tracing line.

actuators is a role-level boolean, default FALSE in the DB (jsonb capability, migration 0074 makes the key explicit), in the Rust struct, and in serde (a role row that predates the capability deserializes to false, never an error, per the #407 lesson). Admin implies it. It is deliberately NOT a media-token claim: a ?token= credential can end up in URLs and access logs, and it must never be able to work a lock. The same capability will gate the planned Reolink actuators, so an operator grants "may work the devices on their cameras" once.

Rejected:

  • Raw service / entity passthrough (client sends domain, service, entity_id). The obvious, most flexible design, and the reason this needed a decision: it turns any viewer session that holds the capability into arbitrary control of the operator's ENTIRE Home Assistant, homeassistant. restart, shell_command.*, every alarm panel, whether or not the entity is linked to any camera. Crumb's token cannot be scoped down to compensate.
  • Per-camera actuator grants in v1. Genuinely finer-grained, but it means a new grant mechanism (a second table, new admin UI, new resolution path) alongside the role's existing camera list, which already bounds which cameras, and therefore which links, a role can reach. Deferred until someone actually needs "can see 12 cameras, may only work the door on one".
  • Returning the new entity state in the response. Clients already poll GET /ha/states every 3s and converge from it. Returning state here would create a second source of truth that can disagree with the poll (HA applies a service call asynchronously; the state at response time is often still the old one), so the response is just {"ok": true}.
  • A tracing-only audit. Cheaper, but actuations are exactly the events an operator will want to reconstruct later ("who opened the gate at 2am"), and logs rotate. system_events is append-only, is not pruned, and has no system_alert_rules row for this key, so the notification engine consumes and skips it: a durable audit trail with no notification side effects.

Client interaction model (issue #428). The wire contract above is interaction-agnostic, but the clients settled on: single-click actuates the primary action directly for the one-tap "simple" domains (light/switch/fan/siren -> toggle, button/input_button -> press, scene/script -> turn_on), with an optimistic in-flight indicator and no local state flip (the 3s state poll converges); hover surfaces the entity's state/age (desktop has a mouse), so the detail card is no longer the way to read state. The card is reserved for the domains a single tap cannot express: cover (open/stop/close) and lock (which keeps its confirm dialog), plus any future value-setting control (a dimmer / position slider) once the allowlist grows past on/off/toggle. Read-only / non-controllable badges still open the read-only card on click. The simple-vs-card split is derived from the same per-domain table as the server allowlist so the two cannot drift.

Revisit triggers (any one):

  • The Reolink actuators land: confirm they reuse actuators rather than inventing a second capability, and that their action vocabulary gets the same allowlist treatment.
  • Demand for per-camera (or per-link) actuator grants, then split a narrower grant from the role-level boolean, the way view_plates was split from admin.
  • Home Assistant ships a scoped-token mechanism (per-entity or per-domain tokens), which would let Crumb hold a credential that cannot do more than the allowlist and would reopen how much of the allowlist has to live in Crumb.

2026-07-31, Naming a license plate is a first-class plate_labels table, not an extension of the watchlist; resolved via COALESCE with exact-normalized keying​

Context. Issue #363 asks that an operator name a plate once ("Mom's car", "Delivery van") and have every client show the name instead of the raw plate wherever the plate appears: LPR reads, plate detail, the watchlist, and alert text. The plate watchlist (lpr_watchlist, migration 0052) already carries a label column, so the obvious shortcut is to make "naming a plate" just a watchlist entry with a label. The open question the issue raises is whether the name belongs on the watchlist or is its own thing.

Decision, a first-class plate_labels table (migration 0073), keyed on the normalized plate string (plate text PRIMARY KEY, label text NOT NULL). A plate name is display metadata that applies to ALL reads of a plate; the watchlist is an alert / BOLO list, a different concern that a plate need not be on to have a name. Everywhere a plate read is shown, the display name resolves as COALESCE(plate_labels.label, lpr_watchlist.label) on the normalized plate, so a first-class name wins while an existing watchlist label keeps working as a fallback. The watchlist keeps its own label column unchanged (its own alert-list UI still uses it). Resolution is folded into the read path (list_plate_reads and the watchlist read in db.rs) as correlated scalar subqueries and surfaced as display_name: Option<String> on the PlateRead and PlateWatchlistEntry DTOs, so every client gets the name for free; the raw plate is always retained alongside it. Writes (PUT/DELETE /lpr/plate-labels) are admin-only, matching the watchlist write path. Keying is the EXACT normalized plate string (same normalize_plate the matcher uses); a name is not applied to fuzzy / confusable variants.

Rejected:

  • Watchlist-only extension (name = a watchlist label). Conflates naming with the BOLO list: you cannot name a plate without watchlisting it, and clearing a watchlist entry would silently drop the name. Naming should be independent of whether the plate is flagged.
  • Naming fuzzy / confusable variants in v1. The matcher already treats O/0, I/1, etc. as zero-cost for alert matching, so one could argue a name should cover the whole confusable group. Deferred: v1 names the exact normalized string only. Applying a name across a variant group risks a name bleeding onto a genuinely different plate, and there is no demand yet.

Deferred (follow-ups, not part of this change): per-client rendering of the new display_name field, desktop (Flutter), Android, iOS, web, and the PDF export report, each renders the name as its own change.

Revisit triggers (any one):

  • Demand to name a whole confusable-variant group at once (then key the name on a canonicalized plate, or resolve through the same edit-distance matcher).
  • Demand for non-admin operators to name plates (then split a narrower capability from the admin-only write path, like view_plates did for reads).

2026-07-31, No auto-restart watchdog (autoheal) in the default stack; surface unhealthy containers via the notification system instead​

Context. A long-running deployment was found carrying willfarrell/autoheal as a local addition to its compose stack (a leftover from before the stack consolidation). Moving that deployment back to the stock compose removed it, which raised the question of whether an auto-restart watchdog should be stock. restart: unless-stopped only handles a container that EXITS; it does nothing for a container that stays running but goes UNHEALTHY (a recorder wedged on a stalled decode, an api healthy-but-not-serving). Both api and recorder already define Docker healthchecks, so the signal exists. autoheal would watch that health status and restart anything reporting unhealthy. Tracked as issue #396, raised per golden rule 6 (new background services need discussion first).

Decision, do not ship autoheal, in any profile, for now. Rely on the alerting that already exists. The notification system already emits recorder_offline (heartbeat stale) and motion_detector_unhealthy, and the health watchdogs in services/api/src/alerts.rs already turn unhealthy state into operator-facing alerts over the configured channels. For a project whose ethos is "hear about failures and fix the root cause," alert-and-investigate is a better fit than silently restarting. Auto-restart masks bugs (turns a hard failure into a restart loop that never gets reported), and autoheal specifically requires mounting the Docker socket, a meaningful privilege for a default-path service.

Rejected:

  • Shipping autoheal default-on, the Docker-socket privilege on a service nobody asked for is decisive against it.
  • Shipping autoheal as an opt-in profile (like mosquitto/alpr/offsite), still adds a third-party image and a socket-mounting service to the supported surface to solve a problem the alerting path already covers; not worth the standing maintenance and privilege footprint until there is evidence the alert-only path is insufficient.

Revisit triggers (any one):

  • Field evidence that a container goes unhealthy-but-running and the existing alerts are not enough (operator not watching, footage lost for hours) often enough that manual restart is a real reliability gap. Then reconsider the opt-in watchdog profile, with restart events logged AND notified so it heals without hiding the underlying bug.
  • A first-party, socket-free recovery mechanism becomes available (e.g. the recorder self-restarting a wedged internal subsystem, or a healthcheck-driven restart that does not need the Docker socket).

2026-07-31, go2rtc restream auth opt-out is a first-class env choice (GO2RTC_AUTH=off), LAN-RTSP only, secure default preserved​

Decision. The LAN-facing go2rtc RTSP restream (:8554, published :18554) can be run without authentication via a single explicit env var, GO2RTC_AUTH=off (issue #398). It is secure by default: unset, empty, and any unrecognized value all keep auth ON, byte-for-byte unchanged from prior behavior. When set to off: the recorder renders an effective go2rtc config at startup that omits ONLY the rtsp: listener's username/password (the tracked go2rtc/go2rtc.yaml stays read-only and un-edited), the api hands out credential-free rtsp://host:18554/<name> URLs, and the posture is logged loudly by both containers and shown as a red badge on the admin console's Server page. The internal go2rtc REST API (:1984, never host-published) stays authenticated in BOTH postures.

Context. Before this, the only way to run an open restream was to edit the tracked go2rtc/go2rtc.yaml, an invisible fork of a repo-managed file that no fresh checkout reproduces and that makes a deployment stop matching what users run. Turning auth on is a coordination cost paid at one instant by every consumer (a BYO Frigate/NVR pulling the restream, plus every client); on a segmented, trusted LAN an operator may reasonably decline it. The project should let them express that as configuration, not as a patch.

Why LAN-RTSP-only, internal REST always authed. go2rtc auth is per-listener. The :1984 REST API is the stream-management surface (enumerate/PUT/DELETE any camera) and is reachable only over the compose bridge as recorder:1984; the api and reconcile loop depend on its auth as free defense-in-depth. Only the LAN RTSP listener is what an operator wants open, so only its credentials are ever removed.

Why render, not empty-username magic. go2rtc treats a listener with no username/password as open. We render that state explicitly (strip the two rtsp: keys) rather than passing an empty ${GO2RTC_USER} and relying on substitution semantics, because an empty credential is ambiguous (it could break env substitution or silently disable auth in a way that drifts across go2rtc versions). Confidence that an omitted listener credential is go2rtc 1.9.x's "no auth" state: high, it is the documented model and matches the in-repo note that RTSP auth is purely listener-credential-driven with no separate toggle. The render path also fails safe: if reading the template or writing the effective config fails, the recorder falls back to the authenticated template, so a failure can never silently open the restream.

Rejected. (1) Flipping the default to off, explicitly out of scope: a permissive default is paid silently by every operator who never read the docs, whereas the coordination cost is paid once, deliberately, by the operator who opts out. (2) Relying on an empty GO2RTC_USER to disable auth, ambiguous and version-fragile as above. (3) Editing the tracked go2rtc.yaml (the status quo), invisible drift, and the mount is read-only anyway. (4) Also opening the internal :1984 REST listener, no benefit, loses free defense-in-depth on the stream-management surface.

Accepted trade-offs. Opt-out is all-or-nothing across cameras (go2rtc auth is per-listener, not per-stream) and per-deployment, not per-user. The rendered effective config lives at a writable temp path (overridable via GO2RTC_RENDERED_CONFIG), regenerated each boot from the template so it cannot drift. GO2RTC_AUTH must be set on both the recorder (renders the config) and the api (URL construction); compose forwards it to both.

Revisit if: go2rtc gains a per-stream or per-user auth model; go2rtc changes how an omitted listener credential is interpreted (retest the render path); or a demand emerges for a scoped RTSP credential (per-camera / short-lived) rather than the single shared one, which would change the calculus for both the default and the opt-out.

2026-07-29, Media-token capability claims default to false rather than failing to decode​

Decision. The capability claims on MediaClaims (export, playback, clips, view_plates) are #[serde(default)]. A media token minted by a server version that predates one of them still decodes, with that capability false.

Context. They were deliberately NOT defaulted, on the reasoning that a pre-upgrade token lacking a claim should fail to decode and force a clean re-mint. The re-mint half does not exist: no client re-mints on a media-route 401, they only react to a 401 on the mint call itself. So adding a required claim stopped every previously-minted token from decoding, and every warm client lost ALL media (live tiles, thumbnails, filmstrips, segments, clips, admin previews) until its cached token reached exp, up to the full 15-minute TTL. Bearer JSON calls kept working, so nothing prompted a re-auth that would have cleared the caches. Self-healing, but it read as a fleet-wide outage after a routine upgrade.

Why defaulting is the safe direction. An old token still authenticates for basic media but carries no capabilities, so the capability-gated routes deny it exactly as they would for a user who never held those rights. The token is still signed, still typ: "media", and still scoped to one camera by cam. This grants strictly LESS privilege than intended, never more. A short-lived loss of gated features beats a total media blackout.

Rejected: client-side re-mint on a media 401 as the immediate fix. It is the better long-term answer and stays open, but media URLs are consumed by third-party loaders (Coil and ExoPlayer, media_kit, AVFoundation, plain <img> in the admin console), so catching a 401 means per-client interceptor plumbing across four surfaces. Worth doing, but not as the thing standing between an upgrade and a working deployment.

Accepted trade-offs. For the TTL after an upgrade that adds a claim, a warm client silently lacks a capability it should have: exports, clips or plate crops may 403 until the token rotates. That is visible and recoverable, unlike the blackout. Covered by two tests: an old-shape token still authenticates on a capability-free media route, and is refused a plate crop even though the minting user holds view_plates.

Revisit if: clients gain media-401 re-mint, at which point the strict behaviour could return without an outage, though there is little reason to want it back.

2026-07-20, Live-wall quality is managed by measured decode util: a preventive guardrail (75%) gates config, reactive backpressure (85%) sheds at runtime​

The desktop live wall lets a user set the whole wall (or per camera) to the main stream. On a large wall that over-subscribes the client's video decoder (the cameras are shielded by the go2rtc restream; the ceiling is purely local GPU/CPU decode). The client already samples whole-GPU decode util but only displayed it. Decision: manage wall quality from that measured signal with two interlocking stages. A preventive guardrail warns at config time when the projected main-tile load (learned per-main cost x projected count) would exceed 75%; reactive backpressure sheds peripheral tiles to sub when smoothed util exceeds 85% for 4s and restores below 60% for 20s (hysteresis to prevent flapping). The 75 < 85 relationship guarantees the warning always fires before the shedder. The focused/hovered/zoomed tile is never shed. Both features and all thresholds are client-local (per-machine budgets); no server change.

Rejected: a static tile cap (wrong unit: 4K vs 1080p main and 10x machine variance make a fixed count either over-restrict or under-protect); server-side enforcement (the constraint is the client GPU, invisible to the server, and differs per viewer); blocking the all-main action (paternalistic; warn + catch, do not forbid); per-tile cost modeling (the platform exposes only whole-GPU util; deriving avg cost from the global signal is simpler and sufficient).

Revisit triggers: the platform exposes reliable per-tile decode cost (shed the most expensive tile, not by wall-order); multi-monitor / multiple walls make a single global util too coarse (per-window budgeting); operators want a server-persisted quality policy rather than per-machine (reconsider client-local); the 75/85 defaults misfire in practice under a new codec/hwdec path.

2026-07-20, Admin-only outbound probes (stream-test / ONVIF discovery) are not SSRF-guarded; risk accepted under the LAN-only, single-operator trust model​

Context. An API reliability/security audit flagged that POST /config/test-stream, /config/test-frame, /config/discover, and /config/discover/probe let the caller point Crumb's outbound request at an arbitrary host — including 169.254.169.254 (cloud metadata), localhost:<port>, or other internal hosts — a classic SSRF surface. Error text can echo a snippet of the upstream response.

Decision — accept the risk; do not add a URL allowlist or private-IP denylist right now. Every one of these endpoints is AdminUser-gated, and in Crumb's ratified posture the admin is the trust root and owns the LAN. Crumb's whole job is to reach arbitrary RTSP/ONVIF hosts on the operator's own network that the admin types in — a private-IP denylist would break the primary use case (LAN cameras live on exactly the private ranges an SSRF guard blocks). There is no viewer-reachable outbound path: the audit confirmed the only non-admin outbound (PTZ) targets a DB/admin-set host the viewer cannot influence. So this is admin self-targeting, not a privilege-boundary break.

Rejected: an allowlist/denylist on these outbound targets — it fights the LAN camera use case and adds config surface for a threat the trust model already covers. Also rejected: suppressing upstream error snippets — they are genuinely useful for diagnosing why a camera URL failed, and the reader is the admin.

Revisit triggers (any one):

  • Crumb grows a hosted / multi-tenant deployment mode, or any path where a non-admin (or a lower-trust admin) can influence these outbound targets — then a metadata-endpoint / link-local (169.254.0.0/16) denylist and error-snippet suppression become warranted.
  • These probe endpoints are ever exposed to an untrusted network or moved off the AdminUser gate.
  • A credible report of admin-context SSRF being chained with another finding.

Tracked privately as advisory GHSA-v7q8-gj2q-gffw.

Addendum (2026-09-07), notification channels: the first revisit trigger above fired. Notification channels were reachable by any authenticated caller, so the outbound destination was not admin-set the way the probe targets are: any viewer could create a channel and have the server POST alerts, with snapshot images attached, to a host of their choosing. Two changes bring that surface back inside the accepted model.

Channel management is a permission. Creating, updating, deleting and test-firing a channel now needs the manage_channels role capability (migration 0081; admins imply it, it is off by default on every existing and new non-admin role, and a scoped media token never carries it). Listing one's own channels is unchanged, and existing channels keep delivering regardless of their owner's capabilities: only management moved. Rejected: gating on AdminUser alone, which would have been simpler but takes a legitimate operator task away from every non-admin role for good; and gating delivery as well as management, which would silently stop alerts on upgrade.

Destinations are checked syntactically. For a non-admin caller the stored URL must be http/https with a non-empty host, and may not name loopback (127.0.0.0/8, ::1, localhost), link-local (169.254.0.0/16, fe80::/10), the unspecified address, or a compose service name. Admins stay exempt, matching the decision above. Rejected: resolving the host at validation time, which buys little (the name can resolve differently later) and makes saving a channel depend on DNS being up; and blocking RFC1918 / ULA addresses, which would break the primary use case, a self-hosted ntfy or Home Assistant on the operator's own LAN. The test-fire endpoint, the one channel route that sends on demand, is additionally rate-limited per user (429 + Retry-After).

Separately, a provider-supplied snapshot_url (written from a Frigate MQTT payload, not by an operator) is now only fetched when it is a relative path or sits on the configured Frigate base's own origin. Rejected: trusting any absolute URL the provider sends, which was the previous behavior and made the fetch target depend on whatever reaches the broker.

Additional revisit triggers: a provider legitimately needs a destination on a host the syntactic check rejects (then the exemption belongs in the check, not in a bypass); or channel management needs to be delegated more finely than one capability.

2026-07-19, iOS/macOS v0.1.0 parity: HA overlays + LPR are read-only on mobile; client-side logic ported verbatim from the server​

Context. The iOS/macOS SwiftUI client was catching up to a large batch of shipped server/Android/desktop features (Home Assistant on-video overlays, the expanded LPR client, live/playback UX). Two cross-cutting decisions were made.

Decision — HA and LPR mobile surfaces are read-only; the admin/editor halves stay off-device. iOS renders HA entity badges on live video + a per-camera entity sheet, and the LPR Plates tab (reads, collapse, crops, watchlist add/edit/remove). It does NOT ship the HA connection config, the drag-to-place badge editor, the per-camera LPR engine/zone editor, or the A/B benchmark. Rejected: porting those admin editors to mobile — they are large, admin-only, and fully served by the web console (embedded in desktop). This matches Android, which made the same read-only cut. Watchlist writes remain admin-gated server-side (403) with the client hiding the controls for non-admins.

Decision — badge positioning uses the decoded video pixel size, plumbed up from the fMP4 demuxer. HA badges anchor to the letterboxed video frame, so the demuxer now emits the video dimensions (CMVideoFormatDescriptionGetDimensions) up through Fmp4StreamController → Fmp4VideoView.onVideoSize → the overlay's fieldRect math. Rejected: assuming 16:9 (misplaces badges on other aspect ratios) and reading the AVSampleBufferDisplayLayer's rect (not exposed).

Decision — plate-matching logic is a verbatim Swift port of the server, unit tested. normalizePlate, confusable-aware levenshtein, allowedEdits, and the duplicate-read collapse window live in LprMatching.swift, ported exactly from services/common/src/db.rs so the client's fuzzy preview / dedup agree with the server's matching (divergent reimplementations are how parity silently breaks). Same state-honesty rail as the recorder's edge_on: an unavailable/unknown/stale HA state is rendered grey, never "off"/"closed".

Trades accepted. HA live-state and badge placement can't be fully validated without an HA-configured server + device; the logic is unit-tested and matches the desktop/Android contracts. Live-audio-style A/V or PTZ-zoom badge tracking (hiding badges during digital zoom) is deferred (badges position for the unzoomed frame).

Revisit triggers. Demand for on-device HA/LPR admin editing → build the editors gated on is_admin. Badge drift complaints during digital zoom → hide badges while zoomScale > 1. A non-AAC/again-diverging server matcher → re-sync LprMatching.swift.


2026-07-18, Compose forwards code-read env keys explicitly; helpers treat empty as unset​

Status. Implemented. docker-compose.yml now forwards the previously silently-dropped keys (RECORDER_TZ, HA_BASE_URL/HA_TOKEN/HA_TOKEN_FILE, DB_POOL_SIZE, MAINTENANCE_UNTIL, CAMERA_OFFLINE_BOOT_GRACE_SECS, the THUMB_* set) into the api and recorder as ${VAR:-}, and parse_env / parse_tz_env treat an empty-or-whitespace value as "unset → default" (fixes #228, #229).

Context. These keys are read via std::env but the stock compose never forwarded them, so setting them in .env was a silent no-op. Compose materializes a forwarded key even when unset (${VAR:-} → ""), and parse_env previously treated "" as a fatal parse error, so a naive passthrough would have failed boot. Separately, RECORDER_TZ hard-defaulted to America/Los_Angeles for every operator regardless of TZ.

Chosen. Explicit per-service passthrough of the documented keys, plus making the numeric/timezone env helpers empty-safe (mirroring the existing parse_bool_env). RECORDER_TZ now inherits TZ when unset. This keeps the env contract explicit and secure-by-default while making every documented key actually work from .env. Rejected. env_file: .env on the api/recorder services (would pull the entire .env, including secrets meant only for other services, into every container, widening exposure, against golden rule 1). Per-key compose defaults duplicating each code default (e.g. ${DB_POOL_SIZE:-32}) drift from the code defaults over time; the empty-as-unset helper fix removes the need. Leaving the docs to say "add a compose override" (the keys are meant to work from .env). Trade-offs accepted. The api env block grew by the THUMB_* tuning set, which most operators never touch, in exchange for no silent no-ops. An operator who explicitly sets a key to an empty string now gets the default rather than an empty value; for these keys that is the intended reading of "blank = unset". Revisit. If the forwarded-key list grows unwieldy, reconsider a scoped env_file split (a non-secret .env.app forwarded wholesale, secrets kept per-service).

2026-07-18, Desktop release ships the Flutter client, not the retired Tauri app​

Status. Implemented. windows-release-flutter.yml builds apps/desktop-flutter and, on a v* tag, attaches the zip to the GitHub Release; the old Tauri windows-release.yml is deleted and the ci.yml desktop-lint / desktop-linux Tauri jobs are removed. Validated green on windows-latest via workflow_dispatch before the tag trigger was wired. (macos-release.yml builds the native SwiftUI app via XcodeGen and was unaffected.) Two runner-specific fixes were needed and are in the workflow: (1) GitHub's windows-latest moved to VS 2026 / MSVC 14.51, whose STL makes <experimental/coroutine> a hard error (STL1011) that the webview_windows plugin tripped; fixed by defining _SILENCE_EXPERIMENTAL_COROUTINE_DEPRECATION_WARNINGS via the CL env var. The local winbuild box has an older MSVC and never hit it, the CI runner did. (2) github.ref_name is sanitized before use as the zip filename so a / in a branch ref can't break packaging on dispatch runs.

Context. The desktop client was rewritten in Flutter (libmpv over flutter_rust_bridge; see the 2026-07-10 entry). Every desktop feature since, the LPR Plates tab, the Home Assistant on-video overlay, the Data-saver tier, the PTZ panel, and the A/B benchmark, lives only in apps/desktop-flutter. The release path still builds the old Tauri crate, so tagging v0.1.0 today would publish a Windows installer with none of the release's headline features.

Chosen. Repoint the Windows release and drop the Tauri crate from the release path and CI. For the 0.1.0 alpha the Windows artifact is a zip ("unzip and run crumb_desktop.exe"), matching how the macOS release already ships a zip; the docs-site Windows client pages were updated to that flow in the same change. Rejected. Ship the Tauri installer for v0.1.0 (advertises features the shipped app does not have). Hold the desktop client out of v0.1.0 entirely (web console + Android only, a worse story than shipping the real client). Block 0.1.0 on a proper NSIS/MSIX installer (needless delay when a zip is honest for an alpha). Trade-offs accepted. The Windows artifact is an unsigned zip, not an installer: SmartScreen shows "unknown publisher" and updating means unzipping over the top. An installer (Inno Setup or MSIX) and code signing are deferred post-0.1.0 polish, tracked in the workflow's trailing comment. macOS packaging/notarization needs a Mac and the paid Apple Developer account (the same blocker as the iOS app), so the macOS desktop release may lag Windows. The Flutter Linux desktop path is unproven and is not part of the release yet. Revisit. If Flutter desktop packaging proves impractical on a platform, if the zip UX proves too rough and an installer is needed sooner, or if the Tauri app is ever revived.

2026-07-18, First-run admin: seed by default with a memorable passphrase, keep the bootstrap window closed​

Status. Implemented in scripts/setup-env.sh. It generates a memorable two-word-plus-digits passphrase (e.g. IcyApples473) as SEED_ADMIN_PASSWORD, prints it once at the end of the run, and the api seeds the admin user with it at first boot. The browser create-admin wizard is now the opt-in path (blank the seed to use it). Docs updated to "sign in with the printed password."

Context. POST /auth/bootstrap is unauthenticated, gated only by "refuse if an admin already exists" (auth.rs). A blank seed leaves an unauthenticated window on first run where anyone who can reach :8080 on the LAN can claim the admin account; the seed exists specifically to close that window (per the auth.rs comment). But the previous setup-env.sh generated a random base64 password and deliberately did NOT print it, so the docs' "create your admin in the browser" story was false, an operator hit a login screen for a password they were never shown.

Chosen. Keep seeding by default (window stays closed) AND make the password memorable and visible, so the documented "sign in with this password" flow is true. Rejected. Stop seeding by default (reopens the unauthenticated bootstrap window, a secure-by-default regression). Keep seeding but leave the password a random string (usable, but a worse first-run UX and no better on recovery). Trade-offs accepted. A two-word + three-digit passphrase is roughly 21 bits of entropy, weak for a password. It is acceptable only as a LAN-only STARTER credential behind the login rate-limiter, meant to be changed after first login, and is documented as such. Revisit. If the console becomes internet-exposed by default, if login rate-limiting is removed, or if a real first-run pairing/token mechanism replaces the seed.

2026-07-17, Per-camera LPR: the engine dropdown is the single control (none added, lpr_enabled derived, source gate enforced at ingest)​

Status. Built on feat/lpr-admin-console. Migration 0071 widens cameras_lpr_engine_chk to ('none','frigate','crumb-alpr','both') and re-derives the stored lpr_enabled; update_camera_lpr / get_camera_lpr_config derive enabled from the engine; the detection ingester gates each plate read on the camera's engine accepting the read's source; the admin console gained a dedicated LPR section (global knobs + per-camera engine table + zone editor + watchlist/reads) and lost the per-camera "worker should read this camera" checkbox.

Context. Migration 0069 gave each camera TWO LPR controls: lpr_engine ("which plate source feeds this camera") and lpr_enabled ("should the crumb-alpr worker read this camera"). They overlapped and could contradict (engine crumb-alpr with the checkbox off, engine frigate with it on), the UI needed a paragraph to explain the difference, and there was no way to say "LPR off for this camera" at all — the engine semantic was also only half enforced (the crumb-alpr side at POST /lpr/reads, nothing on the Frigate ingest side, so a crumb-alpr-only camera still silently stored Frigate reads).

Decision. The engine dropdown is the SINGLE per-camera control, with none as a first-class value meaning LPR off for that camera. lpr_enabled survives only as a derived back-compat mirror (engine IN ('crumb-alpr','both')): the DB write derives it, the read path computes it in SQL (so the worker's GET /lpr/worker-config poll keys off the engine even against a stale column), and 0071 backfills it. The engine semantic is now enforced symmetrically at the single choke point every read passes through (the detection ingester): a read is stored only when the camera's engine accepts its source, fail-closed on DB errors like the ignore-list, because the per-camera setting is an operator privacy control.

Rejected.

  • Keeping two independent controls (checkbox + engine). Redundant state that can contradict itself; every contradiction is a support question and the checkbox's only non-redundant state (worker-engine camera the worker should skip) is better expressed by switching the engine.
  • Dropping the lpr_enabled column outright. Breaks the deployed worker's cfg.enabled check for zero benefit; a derived column costs one SQL expression and keeps old workers correct.
  • A separate per-camera on/off toggle beside the engine (none not in the enum). Same two-control contradiction with new paint.
  • Gating Frigate-sourced reads in detection/frigate.rs instead of the ingester. Leaves POST /lpr/reads and any future provider to re-implement the same rule; the ingester is the one path every read already crosses.

Trade-offs accepted. One extra cameras lookup per plate-carrying event in the ingester (plates are low-rate; acceptable). Existing crumb-alpr-only cameras stop storing Frigate reads — that is the documented 0069 semantic finally enforced, but it IS a behavior change for anyone relying on the leak. A camera whose engine was both/crumb-alpr with the old checkbox off becomes worker-readable after the 0071 backfill (the engine now wins).

Revisit triggers. A third engine source appears (the accept-rule match in the ingester grows; consider a source→engine capability table). Operators ask for "store reads but never worker-scan" (would need the two-control split back, as an explicit worker toggle). Per-camera LPR config grows past what a table row holds comfortably (dedicated per-camera LPR detail pane).


2026-07-17, LPR A/B benchmark: passes derived at report time (two-phase clustering), truth keyed on (camera_id, bucket_ts)​

Status. Built on feat/lpr-ab-benchmark. Backend: GET /lpr/ab-report + POST /lpr/ab-confirm in plates.rs, pure pairing logic in services/common/src/lpr_ab.rs, lpr_pass_truth table (migration 0070). Desktop: a Benchmark dialog off the Plates screen, visible only when the server reports a lpr_engine = 'both' camera. This is the "engine comparison" item the 2026-07-17 native-engine plan deferred (its §10), now scoped to the two built-in engines.

Context. With lpr_engine = 'both' every physical vehicle pass produces plate_reads rows from BOTH Frigate's native LPR and the crumb-alpr worker — plus Frigate's own self-duplication (it re-emits a read for the same pass as its OCR refines, e.g. 9GXVL98 then 9GXV498 ~5 s apart, under different provider event ids). To score the engines head-to-head (hit rate, agreement, accuracy against operator-confirmed truth) the reads must be grouped into per-vehicle "passes", but no pass entity exists in the schema and the two engines share no join key.

Decision. Passes are derived at report time, never stored: a pure in-memory clustering (lpr_ab.rs, unit-tested without a DB) over the raw reads in the requested range. Two phases: (1) intra-engine collapse — reads chain into a cluster when within the pairing window (default 8 s, query-tunable) of the cluster's latest read AND fuzzy-matching its plate under the same length-scaled Levenshtein model the watchlist uses (levenshtein / allowed_edits, reused not reimplemented; pairing fuzz defaults to 0.25, independent of the operator's alert fuzz which is often 0), keeping one best read (highest confidence) per engine-cluster; (2) cross-engine one-to-one pairing, greedy by fuzzy-plate agreement first, then pure time proximity — so two cars passing close together pair with their own reads, while a wild engine disagreement still lands in ONE pass (a disagreement to surface, not two fake misses). Ground truth (lpr_pass_truth) is keyed on (camera_id, bucket_ts) where bucket_ts is the pass's earliest kept-read timestamp floored to whole seconds — echoed verbatim by the client on confirm.

Rejected.

  • Storing passes (a lpr_passes table maintained at ingest). A stored grouping freezes today's clustering bugs into data, needs migration/backfill churn to tune the window, and adds ingest-path risk for a reporting feature. Derived-on-read costs a few ms over ≤10 k reads and lets the operator re-run the same data under a different window/fuzz instantly.
  • Truth keyed on a representative read id. Simpler-looking, but retention prunes plate_reads (the id dangles) and the "representative" read can change as clustering parameters move; the time-bucket key survives both and degrades benignly (an orphaned truth just shows the pass unconfirmed again).
  • Time-only cross-engine pairing. Merges two cars that pass within the window; the fuzzy-first tier fixes that without splitting genuine disagreements.
  • SQL window-function clustering. The fuzzy-plate chain condition (Levenshtein against the cluster's evolving best) doesn't express cleanly in SQL; in Rust it is trivially unit-testable.

Trade-offs accepted. A pass's bucket_ts can shift if a straggler read arrives after an operator confirms (orphaning that truth row) — benign and rare, since engines finish refining within seconds and operators confirm minutes later. Report stats cap at the newest 10 000 reads per query (truncated flag tells the client to narrow the range). Intra-engine garbage reads far outside the fuzzy budget split into separate passes and inflate "miss" counts slightly.

Revisit triggers. A third engine joins the comparison (the pairing is two-engine-shaped; N-way needs a different pass model). Operators report orphaned confirmations in practice → move truth to a stored-pass model. Cameras with continuous traffic (parking lots) where the >10 k-read cap or the greedy pairing visibly misgroups → revisit stored passes / SQL pre-bucketing.


2026-07-17, Crumb-native LPR engine: fast-alpr sidecar via POST /lpr/reads, keeping plate_reads engine-agnostic​

Status. Building on feat/lpr-native. Backend (ingest endpoint + crop plumbing + per-camera columns + worker-config) done and gated; the crumb-alpr worker and admin/wizard surfaces follow. Fires the revisit trigger of the 2026-07-13 LPR entry below ("a validation month shows Frigate LPR materially under the canceled cloud plan's hit rate → wire the operator's OpenALPR box or a fast-alpr sidecar through POST /lpr/reads").

Context. The 2026-07-13 decision chose Frigate native LPR as the only engine. Validation on Frigate 0.18-beta showed it materially weak on the operator's overview angle. The paid OpenALPR/Rekor engine reads better, but its "Watchman Home" (Basic) license was proven to hard-block all non-cloud data delivery — the agent's own log refuses a local destination and force-restarts — and the Pro tier that unlocks a local webhook is too costly. The open-source OpenALPR C++ engine is 2018-era, worse than current Frigate, and painful to build. So Crumb needs its own free, fully-local, better-than-Frigate engine.

Decision. Add a Crumb-native OCR engine, fast-alpr (a YOLOv9-t ONNX plate detector plus a CCT-xs ONNX OCR), run as an opt-in crumb-alpr Python sidecar (compose alpr profile). It pulls a camera's go2rtc restream, motion-gates, votes across a vehicle pass, and POSTs one read to a new POST /lpr/reads (authenticated by the lpr_config ingest token, not a user JWT). The endpoint builds a crumb-alpr NormalizedEvent and pushes it into the same detection-ingester channel Frigate uses, so dedup, ignore-list, watchlist, alerts, and the timeline mirror are reused verbatim — the only new plumbing is carrying the crop JPEG bytes into plate_reads.crop. plate_reads stays engine-agnostic (already tags each read by source_id). Per-camera lpr_engine (frigate / crumb-alpr / both), lpr_min_confidence, and lpr_zones (include/exclude polygons) columns (migration 0069) drive the worker, which polls GET /lpr/worker-config so admin edits apply without a restart. Benchmarked on real operator footage: 24 of 25 frames correct at ~0.99 char confidence, ~37 ms/frame CPU-only, so ~7 percent of one core motion-gated. No GPU.

Alternatives rejected. (1) OpenALPR Pro (~72 USD/mo/camera) — cost, and still a cloud-license gate. (2) Resurrect OSS OpenALPR — old engine, worse than Frigate, build pain. (3) Rust-native ONNX via the ort crate — deferred: reimplementing the YOLOv9 and CCT pre/post-processing in Rust is real work; the Python sidecar ships now and reuses fast-alpr's CCTV tuning. (4) OpenALPR local 8355 pull API on Basic — its /list needs a diagnostic mode that appears license-gated; unreliable.

Trade-offs accepted. A new optional Python service and image (golden rule 6): justified because it is opt-in, isolated, and only runs when enabled. Model weights are YOLOv9-derived (GPL-3.0) — compatible with Crumb's AGPL-3.0 — and are not vendored: they download at first run, so Crumb never redistributes them (air-gapped installs pre-fetch; see docs/LPR-NATIVE-ENGINE-PLAN.md). The Python sidecar is heavier per-inference than the paid engine's C++, but light enough for a single gated camera. plate_reads.crop now stores bytea for the external path (Frigate still uses snapshot_url).

Revisit triggers. fast-alpr accuracy underperforms in real use → try a different open model, add the CCTV re-detect/upscale tuning, or the Rust-native port. The Python dependency or image size becomes a maintenance burden → port to Rust ort (weights are already ONNX). A maintained permissively-licensed detector appears → swap it to drop the GPL-weight exposure entirely. An operator wants a live three-way crumb-alpr vs frigate vs openalpr comparison → build the deferred stats panel (every read is already source_id-tagged).

2026-07-16, Recording policies: explicit named membership replaces NULL-inherit + anonymous COW forks​

Status. Phase 1 (server-only) landed the origin column + the collapse migration (0067), create_camera joins Default, the deviation-edit semantics, and the reaper predicate. Phase 2 (server-only) landed here: migration 0068 drops the 0020/0021 grouped-camera triggers, pins every inheriting camera to the policy the effective-policy view resolved (grouped → group's policy, else Default), and enforces cameras.policy_id NOT NULL + recording_policies.name NOT NULL + a unique index on name; the boot shim (ensure_named_policies_and_groups) that previously ran ALTER COLUMN policy_id DROP NOT NULL on every boot was inverted to a guarded SET NOT NULL (L4); the group endpoints became write-through (a group pins its members' policy_id directly — no inheritance), camera policy assignment maps the old Some(None) "clear to inherit" to joining Default, and require_assignable_policy reduced to existence. The camera_groups/camera_group_members tables are kept DORMANT for one release (rollback comfort); v_camera_effective_policy is untouched (its COALESCE degenerates to leg 1). Phase 3 (admin UI: policy manager, member lists, bulk assign, group-UI retirement, dropping the "Custom — …" label fallbacks, and the final groups-table drop) is staged per docs/design/POLICY-MODEL.md §8 and NOT yet landed.

Context. A camera's effective recording policy resolved through a three-leg COALESCE (v_camera_effective_policy: own policy_id → group's policy_id → the is_default row), and three code paths minted anonymous (name IS NULL) copy-on-write policy rows: every POST /config/cameras cloned the Default into a fresh fork (config_routes.rs create_camera → clone_default_policy), every save from the admin Motion tab PUT /config/cameras/{id}/policy (the COW fork path) even with unchanged values, and the desktop Motion Tuner used the same endpoint. Result in prod: unnamed policies byte-identical to Default that no UI could see or manage ("ghosts"), exposed when the Storage Advisor started labelling them "Custom — <camera>". The NULL-inherit state also carried a real recorder hazard: an inheriting camera resolves through (SELECT id FROM recording_policies WHERE is_default), so a missing/duplicated default row silently drops the camera from the recorder's inner JOIN — it just stops recording, no error.

Decision. Every camera holds a NOT NULL policy_id to a named policy. (1) Deviation auto-creates: a camera-scoped settings edit on a shared policy mints a new policy auto-named after the camera (renameable), joins it — no naming dialog. (2) De-dup on create: if the edited field-set exactly matches an existing policy (all behavior columns, IS NOT DISTINCT FROM), the camera joins that policy instead; reverting to Default's values rejoins Default. (3) Reap empties, keep templates: a new origin column ('operator'|'deviation') distinguishes auto-created deviation policies (reaped when memberless) from operator-created templates (kept at zero members); renaming a deviation policy promotes it to 'operator'. (4) Default is first-class: new cameras join the Default row (no clone, no NULL); is_default keeps meaning "the policy new cameras join" and stays undeletable. (5) Camera groups retire: a policy's member list is the group; group tables/endpoints are dissolved into direct assignment + a bulk "assign policy to cameras" action (the 0020/0021 triggers already made a group nothing more than an indirection naming one policy assignment). One-shot migration collapses byte-identical forks into Default, names genuinely-distinct ones after their camera, and pins every camera, under the invariant that no camera's effective policy field-values change and no merge may make footage immediately eviction-eligible (byte-cap pools are compared before collapsing; unsafe merges keep the fork as a named policy instead).

Rejected.

  • Keep NULL-inherit + fix the fork leak: keeps the invisible state and the 0-defaults-silently-stops-recording hazard; the DB cannot enforce "every camera has a policy" while NULL means something.
  • Interrogate on deviation (naming dialog before every edit): friction on the most common tuning action; auto-name + rename-later matches VMS convention.
  • Per-camera overlay/deltas on top of a policy (Milestone-style "override flags"): more faithful to "tweak one camera" but reintroduces two sources of truth per knob; revisit if policy-count explosion materializes.
  • Keep groups as a separate assignment layer: a group was already policy-exclusive and authoritative (migrations 0020/0021); two mechanisms for one job is where the confusion came from.

Trade-offs accepted. Collapsing/joining policies pools the shared live_max_bytes/archive_max_bytes budget across the merged membership (that is the intended meaning of "same policy"); a one-time worker respawn per repointed camera (the effective-policy id is in the recorder's change fingerprint); the policy list can grow with one policy per deviating camera (visible and manageable, unlike the ghosts).

Revisit triggers. Operators with large fleets report the policy list becoming noise from many single-camera deviation policies (→ revisit the overlay model). A need re-emerges for camera grouping unrelated to recording (bulk ops, UI folders) (→ reintroduce groups as pure tags with no policy pointer). The recorder gains per-camera knobs that don't belong on a policy (→ keep them on cameras, as motion sources already are).


2026-07-16, Clips are fixed-length event overviews; the timeline owns whole-event viewing; open events are janitor-closed​

Context. GET /clip/{id}/clip.mp4 rendered a detection/motion event's full [start, end) window: the renderer concatenates every overlapping 4 s segment and transcodes it (services/api/src/clips.rs). Event windows are unbounded in practice — Frigate tracks a parked car for hours, and ~123 events rows had end_ts = NULL (never closed; oldest a month old). In prod (2026-07-16) one ~10-hour event made the renderer build a multi-hour transcode; concurrent client retries (each a fresh cache miss, since the cache file never finished) consumed all CLIP_GEN_MAX_CONCURRENCY permits and pinned the API at 600%+ CPU, starving ALL clip playback. A 30 s hard clamp shipped as a stopgap (fix/clip-window-clamp).

Decision — a clip is an overview. A clip is a short, representative snippet of an event, by definition independent of event length. The rendered window is [start − pre_roll, start − pre_roll + overview_len), truncated to the event end (+ post-roll) when the event is shorter. overview_len is an admin-tunable server setting (clip_overview_seconds, default 30, clamped 10–30, same pattern as clip_pre_roll_seconds); a compiled hard ceiling (30 s) remains as the safety floor — a clip is a glance-level overview, and beyond ~30 s it drifts back toward "watch the event". Watching the whole event is the timeline's job — recorded playback streams segments directly with no whole-event transcode — so clients surface event duration + an "ongoing" flag in the feed and make the existing "View on timeline" deep-link the explicit "see the whole event" affordance. q=preview and q=full are two renditions (640p vs source resolution) of the same overview window; both are generated once to the cache and served as files, with a per-clip singleflight so concurrent misses transcode exactly once, and cache keys/ETags that include the window parameters now that they are tunable.

Decision — events must close themselves. end_ts correctness is owned by an API-side event janitor (new background task next to the existing cache sweeper): every open event whose updated_at (new column, stamped on every upsert) is older than a stale timeout (default 30 min) is closed with end_ts = GREATEST(ts, updated_at), lifecycle = 'end'. A late genuine end from the provider self-heals via the existing end_ts = COALESCE(EXCLUDED.end_ts, events.end_ts) upsert. The recorder is deliberately untouched: its events writes are surfacing-only and best-effort by design, and the footage-affecting analogue already exists (MAX_OPEN_SIGNAL_SECS in recording.rs).

Rejected.

  • Clip = full event (status quo): the incident; also unbounded memory in the Frigate proxy path.
  • Peak-anchored clip window: no peak timestamp exists (events.top_score has no peak_ts, and Frigate update messages are mostly filtered out), so it cannot be computed today; onset + pre-roll is where causality lives and matches the thumbnail. Retrofit for motion clips only (via segments.motion_score) is a later polish option.
  • q=full = whole event: recreates the incident and conflates quality with scope; whole-event viewing is the timeline, whole-event files are exports.
  • Bounding events at ingest (cap end_ts − ts): events are ground truth — a car parked 10 h is a 10 h event; the render is what must be bounded.
  • Janitor in the recorder / DB trigger: the recorder must not gain DB lifecycle duties near the footage path (golden rule 2); a trigger hides policy in the schema and can't express "stale" cleanly.
  • 503 on semaphore exhaustion: with singleflight + short (≤30 s) transcodes the queue drains in seconds; bounded awaiting is simpler than teaching four clients a retry-after protocol.

Consequences. New migrations (events.updated_at, server_settings.clip_overview_seconds); /clips descriptors gain ongoing + the response gains overview_seconds; both clip caches (preview and now full) are files under {export_dir}/clips swept by the existing TTL/byte-budget sweeper; clients drop the &_r= cache-bust retry (server files make retries idempotent); the Frigate clip proxy only proxies events short enough to be overviews and falls back to own-footage rendering otherwise. The 123 legacy NULL rows close automatically one janitor period after deploy.

Revisit triggers. Operators demand true whole-event clip downloads (→ route through the export system, not the clip endpoint). A provider starts delivering a reliable peak timestamp (→ revisit peak-anchoring). The clips feed moves to pre-generated/notification-time media (→ revisit on-demand generation entirely). clip_overview_seconds upper clamp proves too small for a real workflow (→ raise ceiling, re-check transcode cost).


2026-07-16, Android recorded-playback seeking: add +global_sidx to the recorder mux (not HLS, not a server index)​

Problem. On the Android client, recorded-playback seeking was completely broken — frame-step (both directions), scrubbing, and datetime-jump all snapped back to the start of the current segment. Desktop (mpv/libmpv) seeks the same footage fine. Reported as "Android frame stepping doesn't work at all, forward and back."

Root cause (proven on-device via logcat + ffprobe across the whole segment fleet). The recorder writes fragmented MP4 (+frag_keyframe+empty_moov+default_base_moof) with no sidx (segment-index) box. Media3/ExoPlayer's FragmentedMp4Extractor builds a seekable SeekMap only from an sidx; absent one it reports the stream unseekable and every seekTo collapses to position 0 (observed as onPositionDiscontinuity reason=2 (SEEK_ADJUSTMENT) -> 0). libmpv scans the byte stream directly and never needed the box, which is why only Android broke. This is a footage-playback defect, not a footage-integrity one, but the fix touches the always-must-work recorder so it went through golden-rule-2 gates (below).

Options considered:

#OptionVerdict
1Add +global_sidx to the recorder's -segment_format_options movflagsCHOSEN. One flag on the existing -c copy remux — no re-encode. Writes one sidx per finished segment (~176 B, into reserved space at finalize, not a rewrite). Makes the same footage seekable by ExoPlayer; desktop is byte-for-byte unaffected in behavior.
2Re-mux/serve recorded playback as HLS (fMP4 segments + a media playlist)REJECTED (Fable adversarial round). Would replace a working native-mp4 seek model in every client with a playlist model, and regress the good desktop mpv in-segment scrub. Frigate's poor H.265 scrubbing is a browser HEVC-decode limitation, not an HLS win — Crumb decodes natively (mpv + ExoPlayer MediaCodec) and doesn't share it. No seek-smoothness upside for the cost.
3Server-side seek index / custom containerREJECTED. Same conclusion as the 2026-07-07 scrub-preview entry (option 4/5): nothing inside a ~2 MB / 4 s segment is worth indexing server-side, and an index cannot create keyframes. The real gap was purely the missing in-container sidx box, which the muxer already knows how to emit.
4Client-only workaround (custom ExoPlayer SeekMap, or force-decode-from-0)REJECTED. Fragile per-client reimplementation of what the container standard already specifies; would have to be rebuilt for every future client. Fix the bytes once, at the source.

Gates run before touching the recorder (golden rule 2 — recorder correctness):

  • Crash safety. A segment killed mid-write is byte-identical with vs. without the flag (786 460 B, same box layout) — the sidx only lands when the muxer finalizes the file, so +global_sidx introduces no new footage-loss mode. This is why it composes with the existing +frag_keyframe+empty_moov crash-safety flags rather than weakening them.
  • Finalize I/O. +176 bytes/segment, filled into reserved space (global_sidx reserves the box up-front); measured no full-file rewrite at close. Negligible.
  • Objective seek proof (Gate 3, headless — no device). A real Media3 FragmentedMp4Extractor unit test (apps/android/.../SidxSeekTest.kt) over two real Crumb HEVC segments (same source, remuxed with vs. without +global_sidx): the +sidx segment yields a seekable SeekMap that seeks to distinct mid-segment frames; the no-sidx segment is not seekable (reproduces the bug). This ships as a permanent regression test so a future mux change that drops the box fails CI instead of silently re-breaking Android.

Trades knowingly accepted. ~176 B/segment (well under 0.01% of a ~2 MB segment). The Android client still needs a step redesign (play-until-next-frame) for smooth per-frame stepping — seekability is necessary but the ms-seek stepping shape is a separate client change; tracked separately. Fix does nothing for, and is independent of, the desktop Driveway frame-step edge (that camera's GOP, handled client-side).

Revisit triggers: a client appears that does want HLS/DASH for adaptive bitrate (re-evaluate option 2 as an additional delivery path, never a replacement for the native-mp4 seek model); segment length grows past minutes (then a coarser index inside a segment could matter); ExoPlayer/Media3 gains the ability to build a SeekMap without an sidx (then the flag is optional, though harmless).


2026-07-16, CI publishes amd64-only Docker images (dropped the arm64 multi-arch leg)​

CI (.github/workflows/ci.yml) built the api + recorder images multi-arch (linux/amd64,linux/arm64) on every push to main. The arm64 leg is a QEMU-emulated Rust release compile that took ~60-70 min, so every backend deploy off a main sha waited well over an hour for an image, versus ~7 min for amd64 alone.

Chosen: build linux/amd64 only (dropped the arm64 platform and the QEMU setup step).

Rejected: amd64 on every push + arm64 only on release tags (v*). Cleaner in theory, but the project has no tagged releases yet and no known ARM operator, so it was ceremony for a hypothetical.

Trade-off accepted: anyone wanting to run the Crumb server (recorder + api) on ARM hardware — a Raspberry Pi / ARM SBC, an ARM cloud instance, or an Apple Silicon Mac via Docker Desktop — no longer gets a native image and would run amd64 under emulation (slow) or build it locally. The clients are unaffected (Android ships its own APK; the desktop app is a separate build).

Revisit when: a real operator wants to self-host the server on ARM, or the project starts cutting tagged public releases for varied hardware — at which point re-add arm64, ideally gated to tags: v* so per-push deploys stay fast.


The desktop client had two drag-to-place editors: the shared apps/desktop-flutter/lib/ui/overlay_editor/ (used only by HA badges) and the PTZ panel builder's own older copy in lib/ui/ptz/. Both had the same unusable UX: aggressive snapping that trapped drags/resizes, and per-pointer- move notifyListeners() rebuilding the whole layer + editor bar + palette (the stutter).

Chosen:

  • One editor. The PTZ builder was ported onto the shared overlay_editor/ (a PtzOverlayButtonItem adapter over PtzPanelButton; view-mode ONVIF dispatch and button visuals stay PTZ-local in ptz_panel_overlay.dart/ptz_panel_palette.dart). The PTZ builder's private drag/snap/bar code was deleted (ptz_panel_editor_bar.dart, plus the never-wired ptz_custom_panel.dart/ptz_interaction_overlay.dart).
  • Raw-tracked snapping. The root cause of "snaps like crazy": the old code applied the snap delta to the already-snapped position every tick, so a snapped item could only escape if one pointer event out-ran the radius. The editor now accumulates the UNSNAPPED gesture position and snaps that — standard editor feel; escape is just moving past the radius. Plus: radius 7→6px, resize snaps to edges only (never centers), hold-Alt bypasses snapping per gesture, and a Snap on/off toggle lives in the bar.
  • Split notifications. The controller notifies structure changes (selection/add/remove/mode) normally, but drag ticks fire only a lightweight geometry ticker that just re-positions each item's Positioned (visual subtrees are prebuilt and wrapped in RepaintBoundary).
  • Selection tooling shared by both hosts: multi-select (click/Shift-Ctrl-toggle/marquee), align/distribute, match-width/height/ size to the last-clicked item, an explicit numeric size field, and group/ungroup (OverlayItem.groupId — persisted in PTZ button JSON; session-only for HA badges, whose placement PUT has no group field).
  • Per-badge HA style on camera_ha_links (migration 0059, mirroring 0058's placement columns): overlay_color ('#RRGGBB'), overlay_icon (curated slug), overlay_show_state/overlay_show_age (pin the live state text / relative age next to the badge). Written by the existing placement PUT (admin), carried over by replace_camera_ha_links, reset when a placement is cleared. The link-level label can also be edited via the placement PUT with the PUT /config/ha token convention (omitted = unchanged, "" = clear). Badge captions/hover/tap-card are all anchored to the badge's placed position (the old tile-corner card collided with the camera-name label and back button).

Rejected:

OptionWhy not
Fix the PTZ editor in place and keep two editorsTwo copies of drag/snap/selection logic to maintain and the HA editor had the same defects; the shared editor was always the plan (issue #170 §3.3 P1).
Snap hysteresis (larger escape threshold once snapped)Treats the symptom; raw-position tracking is how every layout tool behaves and needs no second tunable.
A separate ha_badge_style tableSame wipe/join issues that rejected a separate placements table in 0058; the style is 1:1 with the placement.
Storing HA badge groups server-sideNeeds a schema field for a purely layout-time convenience; revisit if operators ask for persistent badge groups.

Revisit triggers: operators asking for roaming (server-side) PTZ panels (would reuse the placement plumbing precedent); persistent HA badge groups; a second client (Android/web) porting the overlay editor (the geometry/controller layer is Flutter-foundation-only by design).


2026-07-14, Live plate crop boxes: normalize Frigate's pixel-corner MQTT boxes with detect dims fetched from /api/config (issue #157)​

Frigate 0.18 sends the license_plate attribute box in two different conventions by transport, verified live against the same event: the HTTP /api/events data.attributes box is normalized [x, y, w, h], while the live MQTT current_attributes / snapshot.attributes box is pixel corners [x1, y1, x2, y2] at the camera's detect resolution — which is not carried in the MQTT payload. Without the frame dimensions, live reads could never store a crop box at ingest (and there is no periodic HTTP backfill; only an API restart ever filled them in).

Chosen: fetch each camera's detect resolution from Frigate /api/config at provider start and refresh it on the existing 1-minute camera-map reload tick; interpret a pixel box (with dims) as corners first — a real plate always has x2>x1 && y2>y1 — with a defensive origin+size fallback. Also read the box from snapshot.attributes (the emitting frames have empty current_attributes, but Frigate keeps the snapshot frame's attributes on the snapshot sub-object). Best-effort throughout: a missing/failed dims fetch only costs the crop, never the plate text or detection.

Rejected / not chosen:

OptionWhy not
One-shot HTTP GET /api/events/{id} per boxless read (take the normalized HTTP box at emit time)Adds a per-read HTTP round-trip and an availability dependency inside the MQTT hot loop; racy right at end (the event row may not be finalized). The config fetch is one small request a minute with the same self-heal property.
Derive dims from the payload (e.g. snapshot.region)Regions are square crops, not the frame; nothing in the MQTT payload states the detect resolution. Guessing a scale risks silently wrong crops — worse than no crop.
Interpret pixel boxes as [x, y, w, h] (the old speculative rule 4)Disproven by live capture; corners is the observed convention. A pixel plate box read as xywh would produce a garbage crop whenever x2 ≤ 1 − x1 fails etc. The xywh reading is kept only as a fallback for values that cannot be corners.

Revisit triggers: a Frigate release that changes the MQTT attribute-box convention or starts carrying detect dims (or normalized boxes) in the event payload; crop-box support for a second detection provider (would motivate moving dims discovery behind the provider trait).


2026-07-14, Backward wall-clock step: preserve existing footage over the colliding segment (recorder, issue #144 item 2)​

On an RTC-less SBC the wall clock can jump backward after an NTP sync. Since segment filenames are strftime-encoded (%Y%m%dT%H%M%SZ.mp4, second resolution), a backward step makes a new segment's filename/timestamp collide with an already-persisted, already-indexed segment. The DB row key is (camera_id, stream, start_ts), so the two segments are indistinguishable at the index level.

Chosen: when the persist path (Motion-mode cache→storage copy, the step the recorder controls) detects that the destination file already exists, it (a) writes the new segment to a non-colliding -rN sibling name instead of overwriting, and (b) indexes it with a DO-NOTHING insert so the older segment keeps its row. Net: the existing indexed footage always wins; the colliding new segment survives on disk as an un-indexed orphan (never deleted). The partial-cleanup on a failed copy (item 7) only ever removes a destination confirmed absent immediately beforehand, so it can never delete good footage.

Rejected / not chosen:

OptionWhy not
Index BOTH colliding segments (change the conflict key to include path or add a monotonic counter)Requires a schema migration + a filename-scheme change and ripples through reconcile/retention/export. Out of scope for a correctness fix; the safe outcome (keep the older, orphan the newer) loses no footage.
Let the UPSERT repoint the row to the new segmentSteals the row from the older segment, turning its still-present file into an un-adoptable orphan — i.e. drops the older footage from the timeline. Backward from the goal.
Fully prevent the direct-to-storage (Continuous-mode) file truncationffmpeg writes those files itself and O_TRUNCs the colliding name before the recorder ever sees the segment; preventing it needs a filename-uniqueness change (the schema option above). Flagged as a residual: the recorder-controlled cache path — the common SBC/Motion-mode case — is fully protected; the direct path is detected/logged only.

Revisit triggers: reports of clock-step footage loss on Continuous-mode cameras (would justify the monotonic-counter filename scheme), or a decision to support sub-second segment resolution (would change the collision surface).

Addendum (2026-07-20, issue #277): the "stays an on-disk orphan (never deleted)" promise was silently broken when the quarantine-retention prune (#203) landed: an unparseable -rN name is exactly the orphan pass's NotIndexable → quarantine path, and the prune then deleted the file after the retention window. Restored: prune_quarantine now exempts -rN disambiguated files at any age (is_collision_disambiguated), so quarantine is their terminal parking spot and deletion remains a manual operator action — the ratified outcome above holds again. See RECORDER-CORRECTNESS item 29.


2026-07-13, Fuzzy plate matching: length-scaled character tolerance (edit distance), superseding pg_trgm trigram similarity​

The watchlist/ignore "fuzzy match" (from the same-day ignore-list + fuzzy entry below) originally matched a read against a watch/ignore plate with Postgres pg_trgm similarity(read, target) >= 1 - fuzz. In practice this was unusable: trigram similarity for short, word-boundary-free strings like plates is dominated by the padding trigrams, so a single wrong character on a 7-char plate scores ~0.45 — below the tightest reachable threshold (fuzz is clamped to 0.5 → threshold 0.5). The feature therefore could not catch the exact case it exists for (Frigate ALPR misreading one character), and the "%" exposed to the operator mapped to nothing intuitive.

Chosen: match by normalized character edit distance. Normalize both sides (uppercase, keep only A–Z0–9), and accept when levenshtein(read, target) <= floor(fuzz * len(target)). fuzz stays the same stored 0..0.5 float (no migration); its meaning becomes "what fraction of the plate's characters may differ" — 20 % ≈ 1 character on a 6–7 char plate, 0 % = exact. Computed in Rust over the (small) watch/ignore set, so it no longer issues any trigram SQL on these paths. The desktop watchlist panel reproduces the identical rule to render a live preview of the misreads a given fuzz would accept for the plate being typed (truthful only because both sides run the same arithmetic).

Rejected / not chosen:

OptionWhy not
Keep pg_trgm, just lower the floor / relabel the %The metric itself is wrong for plates (padding-trigram dominated); no threshold in the allowed range catches a 1-char misread on a 7-char plate. Relabeling an unusable control is lipstick.
fuzzystrmatch levenshtein() in SQLAdds another Postgres contrib-extension dependency (same BYO-Postgres boot-fragility class as the pg_trgm issue just fixed); the watch/ignore sets are tiny, so Rust-side distance is simpler and dependency-free.
Store an integer edit budget instead of the 0..0.5 floatWould need a migration + DTO/type churn and a length-independent budget (2 edits is lenient on a 3-char plate, strict on an 8-char one). Length-scaling off the existing float avoids the migration and behaves sensibly across plate lengths.
New separate control for the char modelThe existing fuzz field already means "how loose", so reinterpreting it keeps one knob; only the label/preview changed.

pg_trgm is still used (and still guarded by pg_trgm_available()) for the Plates search box's fuzzy q mode — that path is unaffected.

Revisit triggers:

  • A non-Latin / variable-length plate region where character edit distance is a poor similarity notion (e.g. scripts where OCR confusions are visual-radical, not character-substitution).
  • Operators wanting position-weighted tolerance (e.g. "ignore the last digit") — would argue for a richer rule than a flat edit budget.
  • Watch/ignore lists growing large enough (thousands) that per-read full-table distance scans matter; then reintroduce an indexed prefilter.

2026-07-13, License-plate recognition: Frigate native LPR as the engine, engine-agnostic plate_reads + gated "Plates" surface; replaces the paid OpenALPR/Rekor cloud plan​

Context. The operator paid for the Rekor (OpenALPR) cloud plan solely for a searchable plate-reads dashboard. Crumb already ingests Frigate events, and the pipeline is plate-aware at the type level (DetectionLabel::LicensePlate, sub_label, raw JSONB); Frigate's native LPR emits plate strings on the already-consumed frigate/events stream (recognized_license_plate, and a matched-known-plate sub_label). The operator's requirement is moving plates only (they don't want static/parked plates) — which is exactly what Frigate's motion-gated LPR does, and what its "does not run on stationary vehicles" limitation makes it good at.

Decision — engine: Frigate native LPR; Crumb stays engine-agnostic. The api parses the plate from the existing Frigate ingestion (detection/frigate.rs, MQTT + HTTP paths → NormalizedEvent.recognized_plate) and never embeds an OCR engine. A dedicated plate_reads table (normalized plate + plate_raw, confidence, region, vehicle jsonb, bbox, crop bytea, source_id, event_id FK, dedup on (source_id, provider_event_id), gin_trgm_ops index; migration 0051, registered) sits BESIDE the shared events row (each source keeps writing its labeled row, per the additive-motion-sources rule), so plate search / history / hotlists don't contort the shared events schema. Capture is gated on an lpr_config DB singleton (enabled DEFAULT false — a plate database is opt-in), same shape as ha_config. A new view_plates capability gates GET /plates (Crumb's FIRST capability-gated read endpoint; /events is deliberately left camera-scope-only). Clients gate the "Plates" tab on MeResponse.plates_enabled (LPR on AND view_plates); the desktop tab is appended last so existing tab indices don't shift. An engine escape hatch is designed-in (built later only if needed): an authed POST /lpr/reads (generated ingest token) lets an external engine — the operator's existing continuous-scan OpenALPR box, or a MIT fast-alpr sidecar reading a go2rtc _sub stream — write the same plate_reads via source_id='openalpr' etc., with zero Crumb code change.

Rejected. (a) Plate-in-sub_label-only / zero-migration: every UI query (fuzzy search, per-plate history, hotlist join, vehicle attrs) fights the shared events schema and mixed sub_label semantics. (b) OpenALPR OSS as the in-Crumb engine: AGPL-compatible but dormant since 2016, accuracy below the cloud plan — instead the operator's existing OpenALPR box stays an optional external source via the ingest endpoint. (c) CodeProject.AI ALPR: SSPL, (A)GPL-incompatible — never linked, bundled, or documented as an option. (d) Building a sidecar first: pays an engine + service cost for reads Frigate already produces on the existing stream. (e) Crops on the media volume: the api mount is read-only (seam) — crops are bytea in Postgres, retention-pruned api-side.

Trade-offs accepted. Frigate LPR is prosumer (tuning required; no state/region or make/model — the one durable cloud-plan advantage) and reads plates off the lower-res/low-fps detect stream, so fast/distant plates trail a continuous-mainstream scanner — acceptable for the moving-plate use case, and the ingest endpoint keeps OpenALPR available if not. Plate data is privacy-sensitive: default-off, view_plates-gated, retention-pruned. Desktop gains its first feature-gated tab. pg_trgm enters the schema (trusted, in-image).

Revisit triggers. A validation month shows Frigate LPR materially under the canceled cloud plan's hit rate on moving plates → wire the operator's OpenALPR box (or a fast-alpr sidecar) through POST /lpr/reads. A second capability-gated read surface appears → extract a shared client tab-gating helper (the desktop const-tab-list refactor deferred here). Frigate renames the LPR fields → re-verify the ingester parsing. Operator wants vehicle make/model/color search → reopen engine choice (paid add-on vs OSS classifiers).


2026-07-13, LPR alerts: plate watchlist rides the existing system-alerts pipeline (no new notification machinery)​

Context. LPR Phase 0 shipped plate capture + a searchable plate_reads surface. The operator asked for alerts — "tell me when this plate is seen". Crumb already has a mature system-alerts pipeline: system_events rows fanned out over six notification channels (Discord/Slack/Pushover/Telegram/ntfy/webhook) with per-event enable/cooldown/quiet-hours config (system_alert_rules, migration 0032; engine in notifications.rs). The health watchdogs (alerts.rs) already feed it.

Decision — a curated plate watchlist that emits a system_events row. A new lpr_watchlist table (migration 0052; plate normalized + UNIQUE, label, note, color, notify) holds plates the operator cares about. The detection ingester (detection_ingester.rs::maybe_alert_watchlist), right after recording a read, does an exact normalized-plate lookup (match_watchlist, notify = true only) and, on a match, calls insert_system_event("plate_watchlist_hit", camera_id, detail) — reusing the entire existing fan-out, config UI, cooldown, and quiet-hours machinery. A seed row registers the plate_watchlist_hit event_key so it appears in the admin Notifications panel like any other alert. Watchlist CRUD is /lpr/watchlist (GET gated on view_plates; POST/DELETE admin-only). Managed in admin console (Plates → Watchlist) and both clients.

Dedup — alert once per read, on the match TRANSITION. A per-read alerted boolean (plate_reads, migration 0053) latches the alert: the ingester checks the watchlist on every read (insert AND lifecycle-refinement UPDATE) but only while alerted is false, then sets it once fired. This fires exactly once per read AND catches a plate that only becomes the watchlisted value on a later refinement (a misread converging onto the BOLO plate mid-pass) — the original alert-on-INSERT-only (xmax = 0) design silently missed that case (Fable review H1). The rule's 300 s per-camera cooldown still backstops rapid distinct passes.

Rejected. (a) A dedicated plate-alert delivery path (its own channels/config) — pointless duplication of a working six-channel pipeline the operator already configured. (b) Reusing notification_rules (the per-(user, camera) motion pipeline) — it carries owner/presence/object-label dimensions a plate hotlist doesn't have, exactly why system_alert_rules exists separately. (c) Fuzzy / prefix watchlist matching for v1 — trigram-close plates would fire false BOLO alerts; exact-only is the safe default (search already offers fuzzy for humans). (d) A manage_watchlist capability — no non-admin operator use case yet; writes stay admin-only (secure default), reads ride the existing view_plates gate.

Trade-offs accepted. Cooldown is keyed (event_key, camera_id), not per plate, so two different watchlisted plates crossing the same camera inside 300 s can suppress the second alert — acceptable given moving-plate reads are already one-per-pass and rare. Exact match means an OCR misread of a watchlisted plate won't alert (the read is still captured + searchable). Plate-read retention is independent of footage retention (its own daily prune); a watchlist entry never expires.

Revisit triggers. Operators want per-plate cooldown or "alert on the second sighting" semantics → move the latch/cooldown key to include the plate. False misses from OCR variance hurt a real BOLO use case → add opt-in fuzzy matching with a similarity floor. A non-admin "watchlist manager" role is requested → add a manage_watchlist capability rather than widening admin.


2026-07-13, LPR ignore-list + fuzzy matching (two revisit triggers above fired same-day)​

Context. Live use surfaced two gaps the alerts entry above predicted. (1) Frigate zones don't restrict detection — a parked car outside the intended area is still detected + plate-read, and Frigate-side object masking is fiddly, so the plate DB fills with a nuisance plate. (2) Frigate's native ALPR misreads more than the retired OpenALPR cloud, so exact watchlist matching (chosen for v1 to avoid false BOLO alerts) misses real hits — the "OCR variance hurts a real BOLO use case" revisit trigger.

Decision — ignore-list (skip-capture) + a global fuzziness knob (migration 0054). The watchlist gains a kind: watch (alert, unchanged) or ignore. An ignore plate is dropped at ingest — detection_ingester checks is_plate_ignored before upsert and returns, so a nuisance plate is neither stored nor alerted (skip-capture, matching OpenALPR's ignore-list semantics — the operator explicitly wants it gone, not archived). lpr_config.watchlist_fuzz (0..0.5, admin-set) loosens matching: when > 0 the ingester matches reads against watch/ignore entries by pg_trgm similarity >= 1 - fuzz (threshold floored so a stray large fuzz can't match everything), else exact. Fuzz applies to BOTH kinds — a near-misread of an ignored nuisance plate should also be dropped.

Rejected. (a) Capture-but-hide for ignored plates — keeps the DB bloating with the exact nuisance the operator is trying to silence; skip-capture is the direct intent (they can un-ignore to resume capture). (b) Per-entry match mode instead of a global fuzz — more UI for no real gain; one similarity knob is easier to reason about, and Frigate's drift is roughly uniform. (c) Fixing this purely Frigate-side (object masks / required_zones) — correct but fiddly and not always practical; the ignore-list is the operator's own backstop, and both can be used together.

Trade-offs accepted. Fuzzy matching can over-match at high fuzz (a distinct plate near an ignored one gets dropped) — hence the 0.5 cap + the floored threshold, and it's off (0) by default. Skip-capture means an ignored plate has no forensic record while ignored. similarity() on every ingested plate is one extra indexed query per read — negligible at plate-event rates.

Revisit triggers. Over-matching complaints → move fuzz per-entry, or add a "why did this match" debug. Operators want ignored plates still recorded (just un-alerted/hidden) → add a capture-but-hidden third kind rather than changing ignore.


2026-07-13, Recorded audio: ALWAYS re-encode to gap-filled 48 kHz AAC (supersedes the 2026-07-12 copy-when-safe split)​

Context. The 2026-07-12 decision recorded audio with a per-camera split: copy bit-exact when the source rate is "client-safe" (≤ 48 kHz), transcode only the rates Android/web reject (> 48 kHz). Its premise was that a ≤ 48 kHz rate is safe to copy. On-device diagnostics (Media3 1.4.1, SM-S921U) proved that false: recorded playback was silent on Android for a 48 kHz camera on the copy path.

Root cause (measured). A bit-exact -c:a copy preserves the camera's audio timeline verbatim, and cheap camera audio clocks drift ~1 %: the container timestamps promise more time than the AAC frames deliver (measured ~32 ms phantom gap per 4 s segment; 61 of 62 frames non-uniform). ExoPlayer's DefaultAudioSink enforces sample-continuous audio — once accumulated drift crosses ~200 ms it throws UnexpectedDiscontinuityException and, because the audio renderer is the player's master clock, the position lurches, segments "end" early, and the whole player wedges (silent audio, stalled video). libmpv (desktop) and the RTSP live path don't slave to strict sample continuity, which is why only Android fMP4 playback broke.

Decision. The recorder ALWAYS re-encodes audio (when record_audio): -af aresample=async=1:first_pts=0 -c:a aac -ar 48000. Video stays a bit-exact -c copy.

Alternatives considered.

OptionVerdict
Always re-encode + aresample=asyncChosen. aresample=async=1 resamples onto a strictly continuous lattice, filling genuine gaps with silence (preserving A/V alignment). Measured 0/192 discontinuous frames after (vs 61/62 before).
Keep the copy-when-safe splitRejected: its premise is empirically false; timeline continuity — not sample rate — is what matters, and only re-encode guarantees it.
Plain re-encode (-c:a aac without aresample)Rejected: still inherits the input's jittery frame PTS (measured 75/187 discontinuous) — this is why SD/low.mp4 still threw the occasional discontinuity. aresample=async is the load-bearing part.
Client-side (tolerate the discontinuity in a custom AudioSink)Rejected/tested: making the sink swallow the discontinuity turned it into a silent continuous clock lurch that dragged video down too. No correct client-only fix exists (the audio renderer is the master clock).
Per-client serve variant (video-copy + audio-reencode on demand)Rejected: ships a workaround for defective recorded data; bad cache economics (full-segment-sized entries); export/iOS/web still inherit the broken timeline. Fix the data at the source instead.

Trades accepted. A mono/stereo AAC encode is < 1 % of a core per camera (negligible; the CPU-saving that motivated the copy path is not worth silent audio). -copyinkf:a is dropped (it only mattered for the -c copy keyframe gate — RECORDER-CORRECTNESS #23). Existing footage recorded on the copy path (only ~1–2 days, since #103) is not retroactively fixed, but it already plays with audio via Data-saver's on-demand re-encode (/segments/{id}/low.mp4).

Revisit triggers. If the aac encoder ever becomes a measurable CPU problem on a large deployment, revisit selective copy — but only for sources proven sample-continuous, not merely ≤ 48 kHz. If a future ExoPlayer/Media3 gains a "trust sample count over container PTS" mode for progressive sources, the copy path could return.


2026-07-13, Mobile performance: on-demand per-segment low-bitrate transcode (not continuous stream / ABR), Auto default​

Context. Recorded playback and fullscreen live were unusable over poor cellular: GET /segments/{id} served the full main-stream bytes (multi-Mbps H.265) with no downscale option anywhere, and fullscreen live started on HD main. The 2026-07-07 scrub-preview decision listed "WAN/remote scrubbing becomes a first-class target" as an explicit revisit trigger — that trigger fired.

Decision. Add an on-demand, cached, operator-side low-bitrate variant, and an Auto/Full/Data-saver client selector defaulting to Auto:

  • Playback: GET /segments/{id}/low.mp4 transcodes one segment to 640p/15fps/CRF28 H.264 (+ AAC mono), produced on first request and cached ({export_dir}/segcache, LRU, ETag'd). A near-copy of the clips.rs preview machinery — same semaphore, same read-only media mount, same path-traversal guard, same auth (?token=). The recorder is never touched.
  • Live: the reconcile loop registers a per-camera <name>_mobile go2rtc ffmpeg transcode of the sub (or main) stream; go2rtc pulls it only while a consumer is attached (zero idle cost). Gated by MOBILE_STREAM_ENABLED.
  • Client (Android): Auto = Full on unmetered, Low on metered; the on-demand transcode therefore runs ONLY when a client actually asks for Low.

Full write-up: docs/MOBILE-PERFORMANCE.md.

Alternatives considered.

#OptionVerdict
1Per-segment q=low variantChosen. One-line client URL change; cacheable/idempotent per segment (repeat scrubs hit cache); reuses clip machinery wholesale; failure isolation per 4 s unit.
2Continuous time-range transcode (/play/.../low.mp4?start=)Rejected for v1: replaces the whole segment/prefetch/seek client model with a long-lived stream a seek must restart, holds a semaphore permit for the whole session, output not reusable across scrubs. Kept as the v2 shape (it also removes any residual segment-boundary audio seam).
3HLS/DASH ABR ladderRejected: ≥2 encode ladders (double CPU) + playlist generation + a client player-mode change, overkill for a single-operator VMS; a manual/auto two-level selector matches the commercial-app UX at a fraction of the complexity.
4Pre-transcode everything at record timeRejected outright: permanent CPU+storage for footage mostly never watched, and it touches the sacred write path. On-demand + cache is strictly better.
5Cloud/third-party transcode or relayOut of scope — violates the ratified direction (footage never leaves operator hardware).

Trades knowingly accepted.

  • One ffmpeg spawn per 4 s segment on a cache miss (mitigated by cache + the N-deep prefetch; -preset ultrafast at 640p is many-× realtime).
  • The <name>_mobile live transcode runs beside the recorder (go2rtc is embedded in the recorder container). On-demand and bounded to one process per active mobile viewer, disable-able via MOBILE_STREAM_ENABLED=false.
  • Default-on mobile stream doubles the go2rtc stream table; inert until consumed.

Revisit triggers.

  • Measured per-segment spawn overhead dominates on real hosts → switch playback to option 2 (continuous-range transcode), which also subsumes any audio seam.
  • Multi-user remote viewing becomes common → reconsider option 3 (real ABR).
  • ROADMAP dual-stream recording ships → "Low" should prefer a recorded sub segment over an on-the-fly transcode; design the selector so they compose.
  • Recorder-host CPU contention reports → make the live mobile transcode default off, or move go2rtc to a separate restreamer host.

2026-07-12, Recorded audio: copy when client-safe, transcode only the rates Android rejects​

Context. The Android client played recorded footage silent while desktop played the same footage with sound. Device logs showed the segment's audio track present but rejected by the hardware decoder: MediaCodecInfo: NoSupport [sampleRate.support, 64000] [c2.android.aac.decoder]. The camera streams AAC at 64 kHz; Android's/web hardware AAC decoders cap at 48 kHz, while desktop's software ffmpeg decoder handles higher rates — so a bit-exact copy was decodable on desktop only. AAC rates above 48 kHz (64/88.2/96 kHz) are the entire problem set; every standard rate ≤ 48 kHz plays on every client.

Decision — conditional: copy when already client-safe, transcode only the oddballs. At record start the recorder probes the source audio sample rate (probe_audio_sample_rate, a bounded best-effort ffprobe of the go2rtc restream — a local consumer, not a camera connection) and audio_segmenter_args picks per camera:

  • source ≤ 48 kHz → bit-exact copy (-c:a copy -copyinkf:a): zero re-encode, zero added CPU, source fidelity preserved.
  • source > 48 kHz → transcode to 48 kHz AAC (-c:a aac -ar 48000) so it plays on every client.
  • probe failed / go2rtc not ready → transcode (the always-safe default).

The copy path keeps -copyinkf:a (RECORDER-CORRECTNESS #23: RTP-AAC audio is never key-flagged, so a plain -c copy would drop the whole declared audio track). The transcode path re-encodes from decoded PCM, so it has no keyframe gate.

Rejected — always transcode to 48 kHz (blanket). Simplest (no probe), and it was the first cut — but it re-encodes EVERY camera's audio including the majority already at a safe rate: wasted CPU + a tiny generational quality loss for no benefit. The probe is cheap and the copy path is strictly better when the source is already fine.

Rejected — always keep bit-exact copy. Leaves any > 48 kHz camera silent on Android/web.

Rejected — a per-client software decoder (Media3 FFmpeg extension on Android). Heavyweight new dependency, build-from-source, Android-only; normalizing at the source fixes every client.

Trade-offs accepted. A bounded best-effort ffprobe at each (re)connect (falls back to transcode on failure, so it never blocks or breaks recording); for the transcoded oddballs only, tiny quality loss + per-segment AAC encoder priming. Operators see which cameras are transcoding in the admin camera menu, with a hint to set the camera's audio ≤ 48 kHz to avoid it. The EXPORT path (services/api/src/export.rs) still copies audio unconditionally and is NOT yet rate-aware — a known follow-up so shared clips of > 48 kHz cameras play on phones.

Revisit if. The per-connect probe cost matters (→ cache the rate per session); or a lossless requirement emerges for the > 48 kHz cameras (→ copy + document the Android caveat).


2026-07-12, Recorder audit hardening: the free-space floor frees real bytes, fail-open survives every seam, boot-reap tolerates contention​

Context. A two-round adversarial audit of the recorder (issues #70–#84, PR #85) found a class of footage-safety bugs. Fixing them forced several decisions where a plausible alternative was rejected, and the audit iterated (fix → re-audit → fix): a few round-1/round-2 fixes were themselves reverted or reshaped once a later pass proved them unsafe — those reversals are decisions too.

Decision — the free-space (ENOSPC) floor must FREE bytes, not relocate them. When the floor is in deficit and a segment's archive move would land on the SAME filesystem as the live storage (the default compose layout: /data/archive on the live disk) AND that filesystem is the one actually in deficit, the sweep DELETES the oldest live segment instead of archive-moving it in place. This is a deliberate, narrow exception to correctness item #7 (the live sweep normally skips archive-enabled cameras, the archiver owns their deletion), in the exact spirit of item #22 (the max_retention_days ceiling also overrides #7): losing the OLDEST footage beats losing ALL FUTURE footage to a 100%-full disk that ENOSPC-halts recording on every camera. It stays bound by every other safety rule, oldest-first, protected bookmarks excluded, file-then-row (#10), serialized on ARCHIVE_GUARD (#8), and only triggers when a move genuinely cannot free the deficit disk (st_dev identity of segment-fs == archive-fs == floor-fs); a segment on a different disk falls through to the normal lossless move. A loud premature_rollover system event fires so the loss is visible, never silent.

Decision — fail-open is an invariant across EVERY seam, not just steady state (item #19 extended). Concretely: (a) worker-lifetime motion state, the MotionBuffer / MotionUnion / pending_signals are carried across an ffmpeg reconnect (the R1 cache sweep gets a keep-set so it won't delete carried pre-roll, and a flip-guard prevents a cache/storage-flavour mismatch from self-copy- truncating an indexed segment), so a reconnect mid-event no longer drops the event tail; (b) the MotionUnion is kept consistent through an unhealthy (frozen) window, edges are folded and the newest is stashed and replayed on thaw, and a STOP replayed onto an Idle buffer enters PostBuffer (apply_replayed_edge) so an event that ran entirely inside the window still keeps its post-roll; (c) a detector reports HEALTHY only when it can actually produce a verdict, the Frigate source on a granted MQTT SubAck (not ConnAck), the pixel detector after warm-up; (d) a panicked motion-source task is supervised (a JoinSet, the motion-side twin of the service-task watchdog) and immediately reads unhealthy → fail-open; (e) a MotionSignal dropped on a full channel flips the source to fail-open via an interposed health watch rather than being silently lost.

Rejected / not chosen:

OptionVerdict
Free-space floor archive-moves oldest live footage even when the move frees nothing (pre-fix behaviour)Rejected, on the default shared-fs layout it freed 0 bytes every tick, the disk filled to 100%, and ffmpeg ENOSPC-halted recording on every camera. A no-op that reads as success is worse than a bounded, loud deletion.
Free-space floor deletes any same-archive-fs segment without checking it is on the deficit disk (a round-2 fix, reverted in round-3)Rejected, on a repointed-storage config it deleted footage on a disk that frees nothing on the full disk: unbounded loss, zero benefit. The delete now also requires segment-fs == floor(deficit)-fs.
A time-based MotionUnion stale-key expiry to un-wedge a lost STOP (a round-2 fix, reverted in round-3)Rejected, it can't tell a lost STOP from a genuinely-long event (an HA occupancy/contact sensor held on for hours; a pixel event through a storm). On a MULTI-source camera, expiring the long event's key let a second source's STOP close the union and DISCARD footage while a healthy source still asserted motion (golden rule 2). The wedge is covered the footage-safe way (over-record) by the #81 loss-debt fail-open + the motion-source supervision.
Signal a dropped-MotionSignal fail-open by writing false into motion.rs's aggregate_health watchRejected, that watch dedups on last_sent, so a foreign false would never be re-published true: permanent fail-open with no recovery. An interposed second watch (forward_motion_health) folds signal-loss into health and recovers when the channel drains.
Boot index-reap permanently skips any DROP INDEX that hits a lock timeoutRejected, it conflates a real in-progress manual CREATE INDEX CONCURRENTLY (must skip) with transient contention (a busy boot, autovacuum), leaving a droppable INVALID index un-dropped so a later CREATE INDEX IF NOT EXISTS silently no-ops. The reap now re-checks pg_stat_progress_create_index on a timeout: skip only a genuine build, retry transient contention.
Keep the stall watchdog as a per-select!-iteration timeout(read)Rejected, a co-scheduled telemetry tick (45s < 90s) returned from the select and rebuilt the timeout every iteration, so it never fired → silent dead recording on a half-open stream. The watchdog is now a dedicated arm anchored to the last segment receipt.

Cost accepted. The shared-fs floor deletes un-archived live footage of archive-enabled cameras when the disk would otherwise fill, an explicit, loud exception (not silent). Several fail-open paths deliberately OVER-record (a lost STOP over-records until the next event; a warm-up window persists idle footage), disk-waste bounded by retention, never loss, the correct direction per item #19.

Revisit triggers. A source-identity-keyed MotionUnion (each open key tagged by source) lands → the lost-STOP wedge can be closed without over-record, and the "no time-based expiry" rejection can be revisited. Per-GPU decode accounting lands → the floor's single-fs assumption could generalize to multi-disk deficit tracking. A hermetic api-integration-test harness lands (issue #88) → the server_settings-sharing test flakiness surfaced during this work is resolved.


2026-07-11, Admin console: rebuild to a sections-rail + list→detail model (not a reskin)​

Context. The web admin console (services/api/src/admin.html, also embedded by the desktop client per the hybrid-console decision below) used a Milestone Management-Client layout: a left tree with every camera / profile / storage / user nested under collapsible section roots, plus a right-hand editor pane. The operator's repeated complaint was the format/layout itself ("looks like a toy"; wanted a modern sections-rail + content-pane layout like current self-hosted NVR consoles), not just the styling. Two prior attempts restyled the same tree and were rejected for exactly that reason.

Decision — change the information architecture, not just the CSS.

  • The left rail is sections-only, grouped under three eyebrows (Configure / Intelligence / Administer). No items nest in the rail.
  • Each section renders its list in the content pane (Cameras → stat tiles + camera table; Recording → profiles; Users & security → roles + users), and selecting a row opens that item's detail/editor (list→detail) with a "‹ Section" breadcrumb back; the rail keeps the active section highlighted.
  • A visual reskin rode along: cool near-black ground, a single amber accent (the old amber+cyan dual-accent retired), rounder geometry, one consistent card / pill / form component kit, and label-over-input forms.

Rejected.

  • Reskin the existing tree-nested layout (the first two attempts): a "format/layout" complaint is about the IA, not the colors — repainting the same bones does not address it.
  • Keep the Milestone tree-with-children model: familiar to VMS operators, but it was the thing being rejected; the sections-rail + list→detail model is what the operator asked for and approved via a mockup.

Consequences / trade-offs. Cameras/profiles/users sit one extra click away than when nested in the rail (rail → list → item) — accepted; it declutters the rail and matches the operator's approved mockup. Because the desktop client embeds /admin (hybrid-console decision below), it inherits this redesign for free.

Revisit triggers. Operators report list→detail is slower for their workflow than direct tree access; or the desktop client stops embedding /admin (which would change the shared-surface calculus behind investing here).


2026-07-10, Desktop client: rewrite native in Flutter (keep the Rust core), retire the Tauri/WebView2 airspace model​

Context. The desktop client is Tauri 2 + wry/WebView2 with native Win32 child video panes composited above the web chrome (the "airspace" model). Live and playback are fast, but the operator kept hitting a class of jank: panes return to the wrong camera, the on-video PTZ controls feel crude, and the whole thing "feels weird, not native" on Windows, one of the project's golden goals. This reopens the 2026-06-15 KEEP-TAURI decision (golden rule 7). A research spike confirmed the interim "composition-hosted WebView2" fix (option 2b) is a wall in wry 0.55: wry hard-wires HWND-hosted WebView2, and a composition controller you create is an orphan webview carrying none of Tauri's IPC, so sync_panes / pane stats / events all break, getting composition means abandoning Tauri anyway. The deciding input came from asking the operator whether "not native" was the window/video behavior or also the look of the UI itself (buttons, menus, fonts, scroll feel like a website). Answer: also the look. That rules out every option that keeps the 13k-line web UI.

Decision — full native rewrite, toolkit = Flutter, keeping the existing Rust core via flutter_rust_bridge and rendering video through media_kit/libmpv (external-texture). Native compositing makes on-video overlays (PTZ, and the planned Home-Assistant status icons) first-class native widgets, deleting the airspace bug class outright. This is a UI-only rewrite: the tested Rust (mpv management, the client) is preserved behind the FFI bridge, not reimplemented. Flutter replaces the Tauri desktop UI, it does not add a codebase, the surface count is unchanged (web-admin + SwiftUI iOS/macOS + desktop).

Decision — hybrid management console. The settings/users/policies/setup-wizard UI (the largest, least-trafficked slice, already shared with the web admin) stays an embedded web view (system browser on Linux, where Flutter desktop webview is weak); only the daily video surfaces (live wall, playback, on-video overlay) are native. Saves ~2-3 months and keeps those screens auto-synced with the web console. Accepted trade-off: the settings screens keep a web look; the surfaces the operator lives in do not.

Rejected.

  • WinUI 3 / WPF (Windows-only native): permanently forks the on-hold-not-dead Linux desktop against the maintainer's not-over-forking value; its only edges (deepest Windows-Fluent integration, MIT license) don't outweigh a permanent fork. A cross-platform toolkit serves Windows now and Linux later from one codebase.
  • Qt / QML (cross-platform native): credible runner-up, retained as the fallback if Flutter desktop maturity disappoints, but heavier (bundled Chromium via QtWebEngine), LGPL dynamic-link/relink obligations inside an AGPL app, a two-hop Rust↔C++↔QML bridge, and no turnkey mpv-texture equal to media_kit.
  • Path B (custom Win32 + composition-WebView2 shell, keep the web UI) and tighten-in-place on the current airspace model: both keep the web UI, which the "also the look" answer rules out; the spike also showed composition means leaving Tauri regardless.
  • Video into the webview (one web layer): reintroduces browser-video latency/fps limits; never on the table for an NVR.

Consequences. The reconcile "wrong-camera-on-return" fix (~25 slot-keyed sites in apps/desktop) is shelved as throwaway, a native rewrite gets pane identity for free. The SwiftUI iOS/macOS app is not absorbed (it works; don't destabilize live iOS video chasing one-codebase purity). Linux stays on hold, but Flutter makes it near-free when it un-holds. Rough phasing (wide error bars, ~4-6 months with the hybrid console): P0 de-risk spike (Flutter shell + the Rust bridge + media_kit rendering one live camera with one native overlay, proving mpv-texture + Rust-FFI + native compositing hold together before committing) → P1 live wall + HA overlay as first-class native widgets (the headline proof, and the surface the operator complained about) → P2 playback → P3 the rest (clips/export/tuner/bookmarks/views) → P5 Linux target + packaging when un-held.

Revisit triggers. Flutter desktop or media_kit maturity regresses or goes unmaintained (→ Qt fallback). Linux is declared truly dead and deep Windows-native integration becomes a priority (→ reconsider WinUI). flutter_rust_bridge can't keep pace with the Rust core's surface (→ thinner FFI or Qt/cxx). The P0 spike shows mpv-texture + Rust-FFI + native compositing don't hold together acceptably (→ reconsider the rewrite premise before P1).


2026-07-10, Additive multi-source motion: cameras enable N sources at once; fail-open aggregates on residual coverage​

Context. Motion source was an exclusive single pick (cameras.motion_source = pixel|frigate|ha). The operator wants it additive: a camera can enable several sources at once (e.g. pixel + an HA door sensor as a backstop) and record on the union of their triggers. This reopens the motion-source model (golden rule 7). Ratified with a Fable design pass; implemented in increments (schema/plumbing first, recorder core next).

Decision — data model: three boolean columns. Replace the enum with motion_pixel_enabled / motion_frigate_enabled / motion_ha_enabled (NOT NULL DEFAULT false), backfilled from the old value so no existing camera changes behavior (migration 0049). Sub-config already lives elsewhere (motion_algorithm for pixel, frigate_config, camera_ha_links), so the booleans only say which loops run. The motion_source column is kept but deprecated (nothing reads it): dropping it would force re-declaring v_camera_effective_policy (the append-only view trap), so it stays. The view is re-declared to append the three new c_* columns (allowed by CREATE OR REPLACE; existing columns keep name+order). Zero sources enabled on a Motion-mode camera = no detector = fail open (records everything, footage-safe); the admin warns before saving that state. Rejected: a TEXT[]/set column (array-op querying; a typo'd element is a silent no-op) and a join table (over-built for a closed 3-source set, adds a join to every camera load).

Decision — orchestration: N supervised loops + a per-camera SourceMux. One supervised source loop per enabled source (today's per-camera supervisor cloned N ways), but do not point them all at the shared motion_tx and trust recording.rs to union. A per-camera SourceMux sits between the loops and the existing (motion_tx, health_tx): it (1) ORs the per-source open flags into the single-open-event MotionSignal stream recording.rs has always seen (preserving MotionBuffer::apply_signal's single-source invariant), and (2) aggregates per-source health into the one health_tx the buffer reads. Why the mux and not "let recording.rs union": apply_signal was authored single-source (each source's own tracker already unions its events before emitting), so two sources feeding independent started_at START/STOP pairs could have one source's STOP close the buffer while another is still open → a recording gap = footage loss. The mux removes the risk and keeps the recorder core unchanged. (Revisit if a test proves apply_signal unions independent interleaved pairs — the mux's union role could retire, but its health-aggregation role stays.)

Decision — fail-open rule (the crux): aggregate on residual coverage, with an asymmetric grace. The camera fails open (records everything) when (a) ALL enabled sources are unhealthy (immediate, no grace), OR (b) ANY enabled source has been hard-DOWN continuously past motion_source_down_grace (default 60s). Otherwise it is healthy and motion-gated on its working sources. Rationale: a source is added precisely to catch what the others miss, so its silent death must eventually fail open (clause b) — but a still-working source buys a bounded grace so one flaky source doesn't force record-everything on every reconnect. "Hard-down" (loop erroring / in backoff) accrues down-time; a clean config-version exit (the loop returns Ok and re-runs within a tick) is reconfiguring, not down, and never trips clause (b) — this is what stops the flapping. Per-source motion_detector_unhealthy alerts fire by name so a dead added-source is loud, not silent; the operator's release valve is to disable that source (untick it → out of the enabled set → can't force fail-open). This reduces exactly to today for a single-source camera: one source down → clause (a) → immediate fail open. Rejected: fail-open-if-ANY-unhealthy (every added source becomes a permanent disk-filling liability that flaps on reconnect); degrade-to-healthy-only (silently discards exactly the events the operator added a source to catch = footage loss of declared-important events).

Decision — surfacing: each source owns its event row; recording.rs writes none. In the additive model the mux feeds recording.rs a source-blind unioned signal that cannot be labeled, so recording.rs stops writing events rows entirely. Each source loop writes its own labeled row at its transitions: pixel → 'motion' (move upsert_motion_event out of recording.rs's drain_and_persist_motion into run_pixel_diff_loop), HA → 'ha'/device-class (slice 3, unchanged), Frigate → its detection rows (ingester, unchanged). This also fixes an existing double-surface: today a Frigate camera gets both a generic 'motion' row (from recording.rs) and its 'frigate' rows; relocating the write leaves only the richer 'frigate' rows. The slice-3 motion_source=='ha' suppression gate is deleted — it existed only because HA reused the shared motion signal.

Sequencing. PR #55 (exclusive HA) ships as the single-source mechanics (ha_motion.rs/HaTracker/labeled events/poll source are reused verbatim); additive is this follow-up. Also fixes a #55 gap found in passing: the API's normalize_motion_source rejects 'ha', so the exclusive model was not actually settable via the API — additive replaces that validator with the booleans.

Blocking correctness gate (verify on real hardware before merge): (1) SourceMux unit test — interleaved pixel/HA START/STOP with unrelated started_at produce one continuous window; a STOP from one source while another is open does NOT close recording. (2) On a pixel+HA camera: kill HA → after the 60s grace records EVERYTHING; blip HA (< grace) with pixel healthy → NO fail-open flap; disable pixel too (all down) → immediate fail open; a pixel-only camera's fail-open timing is unchanged. (3) cargo test motion:: + full gate.

Revisit triggers. A test proves apply_signal unions independent interleaved pairs → the mux's union role can retire. A 4th+ source arrives → reconsider a set column. Operators find the 60s residual-coverage grace too long/short → make motion_source_down_grace a per-policy knob. A WS HaEventSource lands, changing HA down-vs-reconfiguring semantics → re-verify the grace classification.


2026-07-10, HA motion surfacing: the recorder writes the labeled event row; MotionSignal stays source-agnostic; generic motion row suppressed for HA cameras​

Context. Phase 2 makes a motion_source='ha' camera trigger recording from its linked HA motion/door sensors. The recorder already turns each drained MotionSignal into a generic 'motion'/'motion' row in the shared events table (db::upsert_motion_event, called from drain_and_persist_motion), which is what the notification engine and timeline consume. Slice 3 wants an HA-door event to read as "Door" with its own timeline glyph, not as anonymous motion — the question was who writes the labeled row and where the label lives.

Decision — the recorder writes a LABELED 'ha' event row itself, at the same HaTracker Start/Stop transition where it emits the signal (option b). The linchpin: the recorder already writes these event rows, so this is not new scope in the always-must-work component — it upgrades the existing generic write to a labeled one, done in ha_motion.rs where the linked entities' device_class is already in hand. db::upsert_ha_event mirrors upsert_motion_event (source_id='ha', provider_event_id="ha:{entity}:{start_ms}", same START-inserts/STOP-updates idempotency) and wraps the same upsert_detection_event the Frigate ingester uses, so it renders through the existing labeled-glyph pipeline with no new rendering model. The device_class → label map (crumb_common::ha::label_for_device_class) is one pure, unit-tested fn: door/opening→door, window→window, occupancy/presence→occupancy, garage_door→garage, motion/moving/vibration→motion (reuses the existing dot-row-filtered motion glyph), null/unknown→sensor. The opening sensor fixes the label for the whole event (decided at Start, never relabeled mid-event).

MotionSignal stays byte-for-byte source-agnostic — no device_class, no source tag. The label rides a separate best-effort DB write, never the signal. recording.rs and the pixel/Frigate paths are untouched.

Ordering + best-effort are load-bearing. ha_motion.rs emits the footage-driving MotionSignal first and unconditionally, then writes the labeled row best-effort (a DB error is logged and ignored, exactly like the generic motion write). A failed glyph write can never cost a segment.

Generic motion row suppressed for HA cameras. drain_and_persist_motion takes write_generic_motion_event (false iff motion_source='ha') gating only the upsert_motion_event loop — never the buf.apply_signal loop — so the record/persist decision is byte-identical and only the surfacing row's owner changes. Without this an HA door-open would write both a 'motion' and an 'ha' row and double-fire the 3s-polling notification engine.

/status live badge: reuse the existing recent_motion. HA motion flows through segments.has_motion like any motion, so the "motion now" badge already lights for HA cameras with zero new code. No ha_triggered bool (it would mean the same thing and invite skew). A per-tile "Door"/"Occupancy" caption is presentation, read from the existing labeled events feed; status.rs unchanged.

Rejected. (a) A second api-side poller of the same entities to write labels — reintroduces exactly the region/label skew this avoids (two independent polls, independent failures) for no benefit, since the recorder already writes the row. (c) Carrying device_class through a MotionSignal side channel into recording.rs — spreads HA knowledge into the source-agnostic component and is more plumbing than (b), which quarantines all HA knowledge in ha_motion.rs.

Deferred (honest). The client-side Path2D glyphs for the new keys (door/window/occupancy/garage/sensor) across web/desktop/Android/iOS and docs/DETECTION-ICONS.md are a follow-up presentation slice; until they land an HA event renders with the generic/fallback glyph (no breakage). A DB round-trip / suppression integration test is deferred: crumb-common has no integration-test harness (only the api does), and the write path is a thin wrapper transitively covered by the api ingester tests + the pure unit tests; the runtime fail-open validation covers the recorder path end-to-end.

Revisit triggers. A non-recording role='sensor' status entity (P3) needs surfacing without a recording poll → that is the one case a lightweight api-side read returns; decide it then, not now. If a second consumer ever needs the per-event source/label off the wire, reopen the source-agnostic-MotionSignal choice (today nothing does).


2026-07-10, Home Assistant integration: HA-native transport, REST-polling first (WebSocket deferred), one non-admin token, camera-linked entities​

Context. Home Assistant is the ideal integration for a self-hosted VMS (it IS self-hosted, so it fits "optional integrations must have a self-hosted path, footage never leaves your control"). Goal: HA motion/door sensors surface on the timeline and can trigger recording; HA lights/switches/scenes become on-video controls; and (later) an on-video widget overlay. This entry covers the transport and the Phase-1 foundation (epic #52). Two Fable design passes + a real-hardware spike informed it.

Decision — transport: HA-native APIs on ONE long-lived access token (LLAT), not MQTT. Outbound control uses HA's REST service API (POST /api/services/<domain>/<service>); inbound sensor state will use HA's API too. One credential (a non-admin HA user's LLAT) + base URL, stored like frigate_config (DB singleton ha_config, write-only token, env fallback for empty fields, monotonic version for hot-reload). MQTT is not used for this integration because HA core has no first-class "call an arbitrary service over MQTT" path (control would need a hand-authored per-button automation); MQTT remains the right tool for the separate Crumb→HA MQTT-Discovery roadmap item.

Decision — inbound: REST polling first; WebSocket deferred behind a transport-agnostic source. The spike (live HA 2026.7.1) validated REST control (~30-40ms, non-admin token can call services — no admin rights needed) and WS subscribe_trigger (~30ms), but found a silent WS peer drop took ~39s to detect via a blind send loop. That is a recorder-correctness issue: the fail-open rail flips health only on loop exit, so an undetected-dead WS leaves a motion_source='ha' camera health=true and motion-gated → silently missing footage for the dead window. REST polling makes this property free: a poll is a bounded GET with a timeout, so a dead HA surfaces as a timed-out poll within one interval → the loop errors → fail-open fires in ~1s. Polling also needs no new dependency (tokio-tungstenite, #53, deferred) and no keepalive code; its 1s latency is absorbed by the motion RAM pre-buffer for recording and is nothing for a status chip. Missed sub-second blips don't affect motion/door sensors (they hold state for seconds). So Phase 2's ha_motion.rs consumes an internal HaEventSource trait; HaPollSource (REST) ships first, HaWsSource drops in later, changing no data model, endpoint, or client, gated on a real-TCP-partition retest + WS keepalive (ping/pong).

Decision — model: camera_ha_links table (camera → N entities, role motion/actuator), queried directly (not via v_camera_effective_policy). Controls (Phase 3) reuse the actuators RBAC capability shared with the Reolink plan; the client sends a link_id, never a raw HA entity id.

Rejected. MQTT statestream inbound (YAML-only HA config + broker + no control path); per-action HA automations; WS-first (deferred on the 39s dead-peer finding + the new dependency); requiring an admin HA token (spike proved non-admin works); extending the views model for links (wrong scope).

Entity picker + filtering (Phase 1, decided with the review). The GET /ha/entities endpoint stays dumb: it returns device_class (free from the states call) and does no server-side class whitelist; the client filters and groups. The sensor picker whitelists relevant classes (motion/occupancy/ presence/moving/door/window/opening/garage_door) and buckets the rest under a collapsed "Other sensors" + a show-all toggle, so nothing is unreachable. camera_ha_links.device_class is captured at link time as a snapshot of intent (drives the glyph without re-querying HA); if an operator reclasses the entity in HA later, the link keeps the old class until re-linked — that is correct, do not "fix" it into a live re-query. The role CHECK reserves sensor (status-only overlay widgets, P3) alongside motion/actuator so P2/P3 need no migration. Rejected: server-side class whitelist (server owning a policy list that needs edits); splitting motion vs door roles (device_class carries that; a door that triggers recording is role=motion, device_class=door).

Revisit triggers. The real-TCP-partition WS retest passes and sub-second per-edge fidelity is wanted → promote HaWsSource (with keepalive) via #53. HA ships scoped tokens → the unscoped-LLAT caveat improves. A shared internal event bus lands → the API could relay motion to the recorder over one connection. HA-area filtering wanted (link a camera to its room's entities) → needs the entity/area registry (WS API or a registry helper), lands with the WS phase.


2026-07-10, Camera compatibility database: JSON source, generated docs, PR-curated (and the ratified in-app identify/contribute direction)​

Context. Cameras vary in ways Crumb can't fully paper over (codec quirks, firmware bitstream oddities, ONVIF gaps). The first concrete case: a Uniview LPR whose H265 main uses RTP aggregation packets plus a PPS id out of range bitstream quirk that Android's Media3 RTSP HEVC path can't decode, so phone fullscreen live silently drops to the H264 sub. ffprobe on the go2rtc restream confirmed it is specific to that stream (clean 4K H265 mains from other cameras play full HD on the same phone). That is exactly the kind of hard-won, per-model knowledge a self-hosted VMS community should pool, the way iSpy/Agent DVR and Frigate do.

Decision (built now). A community-curated camera compatibility database:

  • data/camera-compatibility.json is the single source of truth (schema in data/README.md).
  • scripts/gen-camera-compat.mjs (zero-dependency, Node built-ins only, same ethos as sync-arch-docs.mjs) renders it into docs-site/docs/cameras/compatibility.md, which is gitignored and regenerated on every build (local, CI docs.yml, and the Docker image build) so it cannot drift from the data.
  • Contributions are by pull request only. Crumb never auto-collects camera data: no telemetry, no phone-home (project direction).

JSON, not YAML. JSON parses with Node built-ins (keeps the generator zero-dependency, honoring the docs-site CI convention) and is directly readable by the Rust backend (serde_json) for the future in-app hint below, so the same one file serves docs and app. Rejected: YAML (would add a parser dependency and isn't a native Rust read); a hand-maintained markdown table (drifts, no machine-readable form).

Ratified direction (NOT built yet, tracked as a feature). Bundle the JSON in the server image and, in the admin console:

  1. Identify the operator's cameras, primarily via ONVIF GetDeviceInformation (Manufacturer/Model/Firmware; the proven approach used by Scrypted and Home Assistant), with an optional stream fingerprint (codec/profile/full-range/packetization signature, e.g. the LPR's own full-range + PPS out of range signature) as a secondary signal. Crumb does not store make/model today, so capturing it is part of the feature.
  2. If matched, surface "camera identified" + the known quirks and recommended settings inline.
  3. If unmatched, offer a user-initiated "contribute this camera" button that opens a pre-filled GitHub issue in the operator's own browser (detected make/model/codec/fingerprint + their optional notes), which they review and submit under their own account.

Rejected (hard line): the server auto-submitting entries to the repo. It would be outbound data to a third party on the server's own initiative (the phone-home the project forbids), would require a write credential baked into an open-source binary (golden rule 1: no hardcoded secrets, and it would be trivially extracted and abused), and would let unvetted content flow into the repo with no maintainer gate. The browser-redirect-to-prefilled-issue pattern gives the same one-click ease with zero server egress, no bundled secret, and a human PR review, so it is the only sanctioned shape.

Refinements from a design review (2026-07-10), folded in before implementation:

  • The match block is a first-class, machine-first schema concept. Entries carry an explicit normalized match (make + make_aliases + models + *-globs); an entry without a valid match block is documentation-only and never auto-matched. Rejected contributor-supplied regex (review burden + ReDoS); normalized exact strings plus * globs cover the real cases (lens/ region model suffixes). Matching is two-tier: exact make+model = "identified", make/alias-only = "possible match, verify" (never asserts quirks as fact). Firmware never gates matching (vendor-arbitrary formats); it is stored and shown as "reported on firmware X" only.
  • The contribute target is a GitHub issue form (.github/ISSUE_TEMPLATE/camera-report.yml) plus a copy-button modal, not a raw prefilled-body URL. This is a narrowing of "pre-filled GitHub issue", not a reversal: rejected the raw-body URL for its ~8 KB ceiling, confusing logged-out UX, and unstructured triage. The admin console shows the full server-built report in a modal (the operator's review step) with a copy button, then opens the issue form prefilled with only short values.
  • The contribute payload is built server-side from a whitelist (GET /cameras/:id/compat-report, admin-only): make/model/firmware + stream observations + support flags only. Credentials, IP/host, ports, any URL, and the operator's camera name are excluded by construction (camera name is an optional field the user types), because cameras.onvif_password / source_url are one join away and a client-assembled report would eventually leak one.
  • Stream fingerprint demoted to data, not a matcher. Stream observations (codec/profile/pix_fmt/range) are captured and displayed and auto-included in the contribute report, but fingerprint matching stays deferred behind the revisit trigger below (the "PPS id out of range" signal is an ffmpeg log string that shifts across versions, and full-range yuvj420p is common across unrelated models).

Revisit triggers:

  • The compatibility corpus grows large enough that a flat JSON file is unwieldy (split by vendor, or move to per-entry files with a merge step).
  • A contributor pattern emerges where the pre-filled-issue flow is too much friction and a self-hosted, opt-in submission target (never a default, never phone-home) is genuinely wanted, revisit how, not whether, egress happens.
  • ONVIF identification proves unreliable across enough models that the stream fingerprint has to become the primary matcher.

2026-07-09, Update check: re-check every launch + always-present About field (stale-state fix)​

Problem. The first client cut of #7 checked once per client and throttled even the launch check to 24h, and it hid the update field and "Check now" whenever the last response said the feature was disabled. On-device testing surfaced a trap: a client that first checked while the operator had the server switch OFF cached "disabled" and then had no way to discover it was later turned ON — no auto re-check for 24h, and no reachable "Check now" (it was gated behind the stale enabled state). The only recovery was wiping app data.

Chosen. Across all clients (desktop, Android, iOS/macOS):

  • The launch/login check runs on every cold launch, ungated by the 24h timer (guarded per-process against re-spam). The 24h throttle now governs only periodic re-checks while the app stays open.
  • The Settings/About screen carries an always-present update field whenever the server reports the check enabled, and opening it triggers a fresh check, with "Check now" always reachable there. The field hides only on enabled:false/404.

Rejected.

  • Check-once + 24h-throttled launch check (the original): simplest, but strands a client that checked during a disabled window for a full day with no manual recovery.
  • A background/periodic poller to notice enable-flips sooner: heavier than a notify-only nicety warrants; app launch and the About screen are natural, cheap re-check triggers that cover it.

Revisit triggers. Every-launch checks become a measurable server/GitHub load concern (they shouldn't: the api caches ≤6h and the client→server hop is LAN-local); or a client gains a real background presence where a periodic poller becomes worthwhile.


2026-07-09, Scrub-preview tunables: per-tick server_settings re-query; width stays env-only​

Problem. Issue #10 asks to move the thumbnail pre-generation worker's and cache sweeper's runtime tunables from env-only (ApiConfig, read once at boot) to the admin console, following the clip_preroll/update_check_enabled server_settings precedence (DB wins, NULL falls back to env). Unlike those two, the consumers here are background loops, not per-request handlers, so a console change also has to reach an already-running worker without a restart. docs/SCRUB-PREGEN-TUNABLES-PLAN.md is the full design; this entry records the ratified decisions (D1-D5).

Chosen.

  • Five nullable server_settings columns (migration 0046): thumb_pregen_enabled, thumb_pregen_lookback_hours, thumb_pregen_scan_secs, thumb_cache_max_bytes, thumb_cache_ttl_seconds. Same shape as update_check_enabled: DB value wins when set, NULL (never touched) falls back to the matching THUMB_* env default.
  • Live-reload = per-tick direct re-query (D2), not a cached-settings struct. services/api/src/scrub_settings.rs::resolve(pool, cfg) does one query_opt per cycle; both the pre-gen worker (thumb_pregen.rs, one query per scan_secs) and the cache sweeper (main.rs::export_ttl_sweeper, one query per minute) call it fresh. Roughly 2 tiny queries/minute total against a pool that serves every API request, unmeasurable, and mirrors the existing updates.rs::resolve_enabled call-per-use pattern exactly. A resolve failure keeps the last-known-good values and logs a warn! rather than aborting either background loop.
  • Mid-backfill kill switch + watermark clear on disable (D3). The worker never exits when disabled: it idles (one settings SELECT per scan_secs) instead. A console "disable" is honored within seconds even mid-backfill, re-checked between cameras and every 256 extracted slots within one camera. An enabled-to-disabled transition clears the per-camera watermark map, so re-enabling always starts a fresh pregen_lookback_hours backfill rather than grinding through the entire disabled gap (the operator asked for pregen now, not a surprise multi-day catch-up).
  • THUMB_PREGEN_WIDTH stays env-only (D1). Width is part of the thumbnail cache key (.../{ts_ms}_w{width}.jpg); the playback clients pin their requested width (480, matched to the scrub-still tile size). A console width that drifted from that value would make every pre-generated file sit at a cache key nobody ever requests, 100% of the pregen CPU + storage silently wasted while scrubbing quietly degrades to on-demand extraction, with nothing failing loudly. GET /config/scrub-preview still surfaces the effective width, read-only (source: "env-only"), so the operator sees the whole picture in one panel.
  • No "reset to env default" affordance (D4). Matches update_check_enabled shipping without one: plain serde can't distinguish an absent field from an explicit JSON null without a double-Option PATCH helper, and once a knob is touched in the console the DB value wins for good.
  • 100 MiB thumb_cache_max_bytes floor (D5). A near-zero budget would make the sweeper delete every thumbnail every minute, silently defeating the feature; the clamping setter enforces the floor server-side regardless of what the console sends.

Rejected.

  • Shared cached-settings struct with TTL/invalidation (an AppState field refreshed periodically, or invalidated by the PUT handler). No hot-path reader exists to justify the machinery: these are 1-2 reads/minute background loops, and an invalidation seam is a new way to silently go stale (PUT handler forgets to invalidate) that per-tick re-query doesn't have. Revisit if a future hot-path consumer of these settings appears, or a multi-replica API deployment makes per-tick staleness (currently bounded to one tick) visible.
  • Config-file reload / SIGHUP. No precedent anywhere in Crumb; the DB is already the one settings plane (server_settings), and adding a second reload mechanism for one feature would be inconsistent with every other console-editable setting.
  • Exposing THUMB_PREGEN_WIDTH as a sixth column with a warning label (option B in the plan doc). The cache-key-coherence foot-gun above was judged not worth it for v1; revisit if a client ships a different scrub tile size or an operator has a concrete reason to shrink pregen storage via width rather than the cache-budget/TTL knobs that already exist for that.
  • Forced cache regeneration on a width change. Not proposed even under option B: old files can't be safely deleted mid-serve, and a mixed-width cache is already structurally coherent (width is part of the key, so nothing is ever served wrong), just potentially wasteful. Stale-width files age out via the existing TTL sweeper on their own.

Trade-offs accepted. Up to one scan_secs (60s default) of staleness on "enable" (an idle tick just costs one SELECT); up to 256 slots / one camera of in-flight work before a "disable" is fully honored during a large backfill. Both are explicit, bounded costs of the per-tick model, not silent.

Revisit triggers. A hot-path consumer of these settings appears (revisit D2, add the cached-settings struct). A client ships a scrub tile size other than 480px (revisit D1, expose width with per-client negotiation). Operators ask for "reset to env default" (revisit D4, double-Option clear support). Multi-replica API deployments make per-tick staleness visible in practice (revisit D2).


2026-07-09, Update-available check: api-mediated, notify-only, opt-in / OFF BY DEFAULT​

Problem. Issue #7 asks for a non-intrusive "update available → release notes" signal across every client (web console, Windows/Linux/macOS desktop, Android, iOS), so an install doesn't silently drift for months without the operator noticing a new release exists. docs/UPDATE-SYSTEM-PLAN.md is the full design; this entry records the decisions ratified for Phase 1 (server).

Chosen.

  • Notify-only (D1). Version comparison and a release-notes link only. No download, no install, no update channels, and the recorder is never touched by any part of this feature — footage/metadata are structurally uninvolved.
  • Api-mediated, not per-client direct polling (D2). Only services/api (services/api/src/updates.rs) talks to GitHub; every client (including the web console) consumes its own server's GET /updates/latest. One implementation, one cache, one operator off-switch that actually turns the whole thing off site-wide, instead of five client codebases each with their own GitHub HTTP code and their own switch.
  • Opt-in, OFF BY DEFAULT (D3). UPDATE_CHECK_ENABLED defaults to false; the admin-editable server_settings.update_check_enabled (migration 0045_update_check.sql, nullable — DB wins, NULL falls back to env) can turn it on. A fresh install makes zero requests to github.com until the operator explicitly opts in via the admin console or the env var. This is the plan doc's non-default alternative, deliberately chosen over its "recommended enabled" option to keep Crumb's no-phone-home posture intact out of the box — the checker is a value-add an operator turns on, not a default behavior a privacy-conscious install has to notice and turn off.
  • Stable releases only, via releases/latest (D6). That GitHub endpoint already excludes drafts and pre-releases, so channel selection needs no extra code for Phase 1.
  • Manual "Check now" (§2.5), added mid-implementation. ?refresh=1 forces an immediate re-check bypassing the 6h cache TTL, gated to a separate 60s minimum interval between actual forced GitHub hits so a burst of manual clicks can't stampede the 60/h/IP unauthenticated rate limit. The disabled state still wins unconditionally: refresh=1 while disabled makes zero requests, there is no "one-off check while disabled" escape hatch.
  • No Tauri built-in updater (D4). Its value is install/relaunch machinery, which #7 explicitly excludes; using it only for version detection would still require its manifest format and a signing keypair at build time for a job a 20-line fetch + hand-rolled SemVer compare does against one endpoint.

Rejected.

  • Per-client direct GitHub polling as the default. More resilient to a disabled/old server, but five implementations, five off-switches to keep in sync, and every client device (including wall displays) hitting GitHub independently instead of one cached point per site. Not ruled out forever — see revisit triggers.
  • On-by-default (the plan doc's original recommendation). Would surface the feature to exactly the operators it's meant to help without them hunting for a toggle, but costs a fresh install non-zero external egress before the operator has made any choice at all — a worse trade against the project's "operator's hardware is the whole world, no phone-home" direction than the minor discoverability cost of an opt-in switch.
  • A server-hosted artifact/manifest system as the #7 vehicle. Explicitly deferred to the docs/UPDATE-SYSTEM-PLAN.md §6 future extension (real install automation, if ever demanded) — out of scope for a notify-only nicety.
  • Tauri's built-in updater for detection only. See D4 above.

Trade-offs accepted. A client talking to an older server that lacks the route gets a 404 and shows nothing — the accepted cost of server-mediation. Version-level granularity misses an Android intra-version re-ship (workflow_dispatch bumping VERSION_CODE without a new tag). An unparsable own version (a local -dev build) shows no banner rather than guessing.

Revisit triggers. Real operator demand for in-app download/install surfaces (→ design the §6 future extension properly, with signing and scoped tokens). GitHub's REST API terms or rate limits change in a way that makes server-side caching insufficient. A legitimate need emerges for a client to check GitHub directly (e.g. a client that is never paired with a Crumb server) — revisit D2. Enough operators report never noticing the admin console toggle exists that the opt-in default becomes counterproductive — revisit D3 (the plan doc's original recommendation is preserved above as the alternative to fall back to).


2026-07-09, Pin the Rust toolchain (CI + rust-toolchain.toml) instead of tracking stable​

Problem. CI installed Rust via dtolnay/rust-toolchain@stable (unpinned) and runs clippy with -D warnings. When Rust 1.97 released, its clippy began flagging an untouched match in services/recorder/src/resource_stats.rs as clippy::question_mark, turning the gate red on a docs-only merge (#29) with zero relevant code change. Green-this-morning / red-this-afternoon with no code change is exactly the failure mode a floating toolchain + -D warnings invites.

Chosen. Pin the toolchain to an explicit version in two coordinated, cross-referenced places: rust-toolchain.toml at the repo root (governs local builds, so cargo clippy on a Linux build host matches CI and "run the gate before pushing" actually catches what CI catches) and the toolchain: input on the CI dtolnay/rust-toolchain steps (governs CI). Rust is now bumped deliberately by editing both, not surprise-upgraded. First pin: 1.97.0.

Rejected.

  • Keep tracking stable. Zero-maintenance until it isn't: any new stable that adds or tightens a lint can break CI with no code change, and it broke on literally the first run after 1.97 shipped.
  • Drop -D warnings. Removes the fragility but also removes the guard that keeps the tree clippy-clean; trading a real correctness signal for convenience.
  • rust-toolchain.toml alone, CI left on @stable. Works via rustup's auto-switch, but relies on a subtle interaction (CI installs stable, cargo silently switches to the toml version). Explicit pinning in both spots reads clearly to a future maintainer.

Revisit triggers. Bumping the pin becomes frequent toil (wanting the newest stable often), or the two pin sites drift apart in practice — then consolidate to a single source of truth (e.g. an action that reads rust-toolchain.toml, accepting the extra CI dependency).


2026-07-08, macOS/iOS export: adopt the desktop batch-list model (single-shot export retired)​

Problem. The SwiftUI (macOS/iOS) export flow had drifted from the Windows/Linux desktop client: it exported a single time window across N selected cameras (POST /export), while the desktop builds a list of clips (each its own camera + range), with a batch summary, an optional AES-256 ZIP password, and one job for the whole list (POST /export/batch). Issue #22 tracks the parity gap; the maintainer's direction (2026-07-08) is "mimic the Windows client as closely as possible".

Chosen. Port the desktop batch-list model to the SwiftUI client (ExportViewModel holds [ExportClip] + an add/edit-clip builder with a frame-preview scrubber; ExportView renders list ⇄ builder on the left and the global output panel — format, burn-in, audio, password, batch summary, "Export N clips" — on the right). Submission goes through the existing server POST /export/batch; job polling/cancel is unchanged. Entry points seed the builder the way the desktop does: playback passes the viewed camera plus the bracketed timeline selection (builder opens pre-filled, one click to add); the Exports tab starts in list mode with the selected wall camera pre-picked.

Rejected.

  • Keeping the single-shot model (or shipping both flows side by side): re-litigating the ratified "desktop is the reference UX" direction, and two export UIs is worse than one.
  • A Windows-identical persisted destination-folder picker on macOS/iOS. Platform-inappropriate: sandboxed macOS/iOS apps get durable folder access only via security-scoped bookmarks, and iOS has no folder workflow at all. Outputs keep the platform-native ends: NSSavePanel per output file (macOS) and the share sheet fed a locally-downloaded file (iOS) — preserving the C1/C2 token-leak fixes. Revisit if operators ask for one-click batch saves.

Deferred, stated explicitly (component-map §3 parity walk):

  • Android still has the single-shot export flow; porting the batch model there is follow-up work under issue #22's umbrella, not silently dropped.
  • Wall-tile thumbnail crispness (issue #22 item 5) — since addressed: the playback wall + single-camera scrub previews requested ~160px stills that blurred blown up to tile size on a large display. The scrub-still width is now a shared constant (iOS MediaUrls.scrubThumbWidth = 480) kept equal to the server's THUMB_PREGEN_WIDTH default (raised 160 → 480) so the two agree and requests hit the pre-generated cache when it is enabled (and are cached lazily at that width, grid-snapped, when it is not — the default). 480 sits at the top of the maintainer's suggested 320–480 range: notably crisper without paying the full 640 cap on per-tick on-demand extraction for a multi-camera wall. Trade-off: when an operator enables pre-generation the cache is ~3–4× the bytes of the old 160px cache; lowering THUMB_PREGEN_WIDTH is safe and just drops those clients back to on-demand at their width.
  • Issue #22 item 6 (format-set parity) was verified a no-op: both clients already offer exactly MP4/MKV × {H.264 (MP4 only), H.265, copy}.

Revisit triggers: the desktop export flow changes shape (this port follows it); operators request persisted batch-save destinations on macOS.


2026-07-07, Scrub preview: pre-generated JPEG proxy (API-side); keyframe index rejected​

Problem. Timeline scrubbing does not yet feel like a leading commercial VMS: buttery, instant scrub (including synchronized multi-camera) and frame-accurate seek. The open question was whether that requires (a) a low-res preview proxy, (b) a finer-than-per-segment seek index, or (c) a custom video container. A grounded audit (services/api/src/filmstrip.rs, services/recorder/src/recording.rs, motion.rs, the segment schema, and all four clients) answered it.

Findings that shaped the decision:

  • The preview-proxy plumbing already exists as an explicit "Phase 1": filmstrip.rs serves /filmstrip/{cam} + /frame from on-demand single-frame ffmpeg extraction cached under {export_dir}/.thumbs. db::list_thumbnail_times is a stub returning empty; there is no background pre-generation. iOS (single-cam plus a multi-camera synchronized wall), Android (single-cam), and the desktop export-preview already consume these frames. The UX is built; the server starves it.
  • Two live defects make the existing cache nearly useless: thumbnail filenames are exact millisecond timestamps but clients request arbitrary cursor times, so the hit rate is near zero and every scrub re-spawns ffmpeg; and extraction has no concurrency cap (unlike /play's play_semaphore) and .thumbs is never evicted.
  • Segments are standard fMP4, ~4 s each (SEGMENT_SECONDS, clamped 2-6), written -movflags +frag_keyframe+empty_moov+default_base_moof (fragment boundaries are keyframe boundaries). Only the policy-selected stream is recorded (default main); the sub stream is NOT recorded for playback.

Options considered:

#OptionVerdict
1Pre-generate the JPEG preview proxy, API-side background worker reusing extract_thumbnail, deriving slot times from segments coverage (no migration), grid-aligned cache keys, hour subdirsCHOSEN. Zero recorder changes, zero write-path risk (API mount is read-only), covers all cameras and both recording modes, and three client UIs already render it.
2Recorder piggyback on the motion decoder's in-RAM framesDeferred. The motion frames are grayscale (format=gray); color needs a filtergraph split; coverage holes (Frigate-source cameras bypass the frame pipeline); couples a cosmetic feature to the always-must-work recorder. Revisit only if option 1's API-side CPU is measured too high.
3Dedicated long-running ffmpeg-per-camera off go2rtcRejected. Duplicates the sub-stream decode the motion task already pays, the exact cost the power-optimization work fought.
4Finer-grained seek index (per-keyframe / byte offsets)REJECTED. At 4 s segments over LAN with native fMP4 fragment parsing in every player, nothing inside a ~2 MB segment is worth indexing server-side. Frame accuracy is a decode problem an index cannot solve (an index cannot create keyframes); all three players already expose exact-seek / frame-step. Would matter only if segments were 5-15 minutes.
5Custom video containerOut of scope. A container buys storage packing / inline metadata / evidence integrity, not scrub smoothness, and would cost fMP4 interop + per-client demuxers + write-path risk.
6Dual-stream recording (record sub continuously for cheap multi-cam scrub)Out of scope here; separate write-path decision, tracked as ROADMAP dual-stream (#7) and option 5 of the 2026-07-03 motion-recording entry. Do not bundle.

Chosen approach. Finish the preview proxy as an API-side, read-side feature. Phase 0 (grid-snap cache keys + extraction semaphore + .thumbs eviction) fixes the two live defects and stands alone. Phase 1 adds the background pre-generation worker and a real list_thumbnail_times derived from segments (no new table, no migration). Phase 2 adds the desktop timeline preview UI (the one client lacking it). Phasing in docs/ROADMAP.md initiative 8.

Trades knowingly accepted:

  • Preview granularity equals the generation interval (recommended 10 s), so during a drag the preview steps at ~10 s; sub-second precision still comes from the real video on release (desktop already live-seeks in-segment). This matches commercial VMS behavior.
  • Thumbnails are extra small files (~16-39 GB and 2.6-6.5 M files for 10 cams / 30 d at recommended settings, under 1% of video bytes; file count is the real cost, mitigated by hour subdirs; sprite atlases deferred until file count actually hurts).
  • The Phase 1 thumbnail-retention task is a NEW deletion path; it is path-guarded to .thumbs, extension-filtered to .jpg, and gets a test, per golden rule 2.

Revisit triggers:

  • API-side extraction CPU measured unacceptably high on real deployments, reopen option 2 (recorder motion-decoder piggyback).
  • Segment length raised beyond ~15 s, or WAN/remote scrubbing becomes a first-class target, reopen option 4 (finer index) and sprite atlases.
  • .thumbs file count demonstrably hurts backup/inode performance, build sprite atlases.

2026-07-06, Docs site: Docusaurus, self-hosted behind cloudflared (docs.crumbvms.com)​

Context. Crumb needs a public, versioned, searchable documentation site in the style of Frigate's. docs/ROADMAP.md initiative 4 had leaned MkDocs Material as an unratified note. The site is built in docs-site/.

Decision. Docusaurus v3, classic preset, docs-only mode. Client-side local search (@easyops-cn/docusaurus-search-local, a build-time lunr index, zero external calls), built-in versioning cut at pinned releases (deferred during alpha), no third-party trackers/analytics/CDN fonts, static output that is always self-hostable. Single-source: user docs authored in docs-site/docs/; a whitelisted subset of docs/ engineering docs (DECISIONS.md, RECORDER-CORRECTNESS.md, MOTION-RECORDING.md) is copied into an Architecture section at build time by scripts/sync-arch-docs.mjs (those generated pages are gitignored and regenerated on every build, local and CI, so they cannot drift). Anti-drift is enforced by docs/COMPONENT-MAP.md (the docs site is a propagation surface) plus a CI link-check build on every docs PR (.github/workflows/docs.yml, onBrokenLinks: 'throw').

Deploy: self-hosted, not Cloudflare Pages. The site ships as an nginx:alpine image (docs-site/Dockerfile + nginx.conf + docker-compose.yml) served as a static site on port 3000 and reached over a Cloudflare tunnel at docs.crumbvms.com, the same self-hosted pattern the crumbvms.com marketing site already uses. This was chosen over a managed static host (Cloudflare Pages) because it matches the running marketing-site setup, keeps everything self-hosted (consistent with the product's own posture), and adds no new hosting dependency.

Rejected: MkDocs Material (second, Python, doc toolchain next to the Node marketing site; versioning is a mike bolt-on); Astro Starlight (versioning only via an immature plugin); VitePress (no built-in versioning); mdBook (single-book, no versioning). Algolia DocSearch rejected on privacy grounds regardless of generator. Cloudflare Pages rejected for deploy (see above).

Cost accepted. Docusaurus is a large npm dev-dependency tree, but it is build-time-only tooling in an isolated docs-site/ workspace: it never ships in a product image and adds nothing to the runtime (golden rule 6 reviewed). Builds run on dev hosts and CI, never on the clean workstation. The docs-site Docker build context is the repo root (not docs-site/ alone) so the sync script can see docs/ and docs-site/ as siblings; called out in the Dockerfile/compose.

Revisit triggers: Starlight ships first-class versioning and the npm tree becomes a maintenance burden; the docs corpus needs capabilities Docusaurus lacks; the local-search plugin is abandoned and forces a swap; or the self-hosted static path is retired in favor of a managed static host (then revisit Cloudflare Pages).


2026-07-06, go2rtc stream model: reconcile PATCHes existing streams, only PUTs missing ones​

Context. Crumb is the sole puller of each camera: the api's reconcile loop (services/api/src/go2rtc.rs) owns go2rtc's stream table and every consumer (recorder record, recorder motion, Frigate, live desktop/Android clients, snapshots) is supposed to fan out from one producer per stream, so a camera sees exactly two RTSP sessions (main + sub) no matter how many viewers. It did not. On the session-capped Uniview LPR camera, live and snapshot consumers were intermittently refused at RTSP SETUP, and GET /api/streams?src=<cam> showed consumers: null on every camera even while recording was live.

Root cause (verified against go2rtc v1.9.14 source + live prod, read-only): go2rtc's PUT /api/streams handler does streams[name] = NewStream(...), an unconditional replace. The reconcile loop re-PUTs all managed streams every RECONCILE_INTERVAL (60 s) for drift correction, so every minute each stream's in-memory object was swapped for a fresh idle one. The old object kept its live camera session and attached consumers running (orphaned, invisible to the API); every consumer that attached in a later window landed on a new object and had to dial the camera again. Steady state converged to one camera RTSP session per long-lived consumer, and on a capped camera that exhausts the slots. H.265 was a red herring.

Decision. Make reconcile diff-based. Each pass GETs the names go2rtc already has; a MISSING name is created with PUT (a fresh name orphans nothing — this is the cold-start / go2rtc-restart path, unchanged), and an EXISTING name is updated in place with PATCH, which go2rtc implements as SetSource on the existing object, a true no-op for an unchanged source on a running producer, and no object replacement, so consumers keep sharing the one producer. reconnect() (DELETE + PUT) stays the explicit "source really changed, force a re-dial" path. One guard: go2rtc's Patch() aliases instead of applying the source when the source is rtsp:// with a single-segment path equal to a managed stream name, so Crumb detects that collision and keeps PUT for those (no prod camera hits it). We do not diff sources against the GET body, go2rtc masks credentials in API responses, so a compare would be unreliable. Control-plane only: one file plus unit tests, no recorder / DB / compose / client / migration changes.

Rejected / not chosen:

OptionVerdict
Keep PUT-all, accept the churnRejected. It is the bug: orphaned producers accumulate one camera session per consumer and exhaust session-capped cameras; observability (consumers) is blind fleet-wide.
Client-side applied-state map (only PUT when desired != applied)Rejected. Still trusts PUT-replace, re-clobbers once per api restart, and PATCH is the in-place primitive go2rtc actually provides.
Carry a one-hunk patch to go2rtc making New() a no-op for identical sourcesRejected for now. Fixes it for all API consumers but means patching/forking the pinned binary (golden rule 6); the PATCH-verb fix needs no binary change. Worth proposing upstream separately.
Fall back to the sub-stream for capped camerasRejected earlier in-session. Masks a fundamental control-plane defect; three clients would still each take a slot.

Cost accepted. Reconcile now issues an extra GET per pass (negligible; passes are rare in steady state). During the deploy transition, orphans created by the old PUT-all behavior persist until the next go2rtc/recorder restart clears them (a one-time artifact). DELETE also orphans running producers (documented on reconnect()): after a camera swap, consumers on the old object keep pulling the old source until their own watchdogs (~12 s recorder) reconnect, inherent to go2rtc's API, not fixable here without a "drain consumers" primitive it doesn't expose.

Revisit triggers:

  • go2rtc upstream makes PUT idempotent for identical sources, then the create/patch split can collapse back to PUT-always.
  • A camera source legitimately needs the single-segment rtsp:// path form that the alias guard currently steers to PUT, then implement a first-class DELETE+PUT fallback for it.
  • A need for immediate source propagation without reconnect() (e.g. bulk camera re-IP), consider a "drain consumers" admin action, not resurrecting PUT-all.

2026-07-06, Storage: Crumb owns recording/storage; do not read Frigate's storage for playback​

Context. Crumb's headline value is smooth, frame-level timeline scrubbing across many cameras. The question came up: for operators who already run Frigate, could Crumb keep its own clients and operator UI but let Frigate own recording and archiving, with Crumb's timeline/playback reading Frigate's stored footage directly instead of Crumb's own storage system, as an optional "compose with Frigate" mode? A deep dive (2026-07-06, reasoned against Frigate 0.17.x stable, verified from docs.frigate.video and the dev source) settled it. Note the inverse topology already ratified earlier (2026-06-19): Crumb is the streaming hub and sole NVR, Frigate pulls from Crumb; this is its storage-side counterpart.

Decision. Crumb keeps owning recording and storage. Composition with Frigate stays at the event / clip / live-stream level (MQTT detection events, proxied clips and snapshots, live-stream peer), never at the storage level. The pivotal finding: Crumb's smooth scrubbing is a property of its recorder (2 to 6 s clock-aligned, keyframe-guaranteed fMP4 segments plus the Postgres index plus prefetch), not its player. Frigate's stored files are faststart plain MP4 and are seekable by libmpv/Media3, so raw file seekability is not the blocker one might assume; the recorder properties that make scrubbing smooth simply cannot be recovered by reading Frigate's storage.

Rejected / not chosen:

OptionVerdict
Frigate owns storage, Crumb's operator UI treats those cameras as first-classRejected. Four core guarantees are unimplementable or structurally degraded (see below). A mode that silently downgrades Crumb's sacred guarantees for some cameras is worse than no mode.
Read-only "Frigate history browser" overlay (explicitly second-class)Deferred, not rejected. Buildable as a bounded feature: mirror Frigate's recordings API into a side table (never the segments table), RO-mount its recordings dir behind the existing path-guarded file server, badge footage as Frigate-owned, no protect/policy knobs, best-effort export. Real work for a second-class experience; build only on demonstrated user demand.
Compose at the event/clip/stream level (already shipped)Chosen. Gets nearly all the "already runs Frigate" value with zero storage coupling.

The five decisive limitations of a "Frigate owns storage" mode:

  1. Segment shape is uncontrolled. Frigate cuts ~10 s segments at the camera's keyframe (no forced GOP, no clock alignment, audio stripped by default). Seek precision and multi-camera boundary sync degrade to the operator's camera settings, versus Crumb's 2 to 6 s clock-aligned keyframe-guaranteed segments.
  2. Timeline gaps are the steady state. Frigate's tiered retention deliberately turns each camera's history into islands of footage as tiers age out; Crumb's contiguous-scrub / prefetch model has no good answer to per-camera gaps.
  3. Protected bookmarks are unimplementable. Frigate has no "hold a time range" primitive (only retain_indefinitely on detected-object events), and its emergency pruner deletes the oldest hour regardless of retention. The only honest fallback (copy protected footage into Crumb storage) reintroduces Crumb-owned storage into the mode.
  4. Index and lifecycle races. Frigate's index is single-writer SQLite, local disk only, schema changing every minor release; any Crumb mirror is always stale against hourly plus 5-minute emergency deletion, so mid-scrub 404s and mid-export file loss are structural, not transient. No equivalent for per-policy size caps, free-space headroom, archive tiers, or the max-retention cap.
  5. Recorder correctness becomes someone else's cache. Frigate's cache overflow discards the oldest unprocessed segments (documented silent footage loss), the exact failure the 2026-07-03 motion-recording decision rejected by name. Crumb's UI would present footage it can neither protect nor detect the loss of, which makes golden rule 2 (losing footage is the one unforgivable bug) unenforceable for the footage it displays.

Cost accepted. An operator with a large existing Frigate archive cannot browse it inside Crumb today; the compose story is detection/clips/live, not "see my old Frigate recordings." That is accepted over silently downgrading the storage guarantees Crumb treats as sacred.

Revisit triggers:

  • Frigate adds a retention-hold (protect-a-time-range) API and a stable recordings API contract → reconsider the bounded read-only overlay above.
  • Real user demand for a read-only "browse my existing Frigate archive inside Crumb" view → build it as the explicitly second-class overlay, never as a peer storage backend.

2026-07-05, Retention: a configurable time cap + a neutral over-retention nudge (no hardcoded jurisdictional number)​

Context. A pass over EU/UK data-minimization considerations flagged two things. GDPR Art. 5(1)(e) requires footage be kept "no longer than necessary" for a documented purpose, and the ICO explicitly says there is no fixed statutory min/max. The "30 days / 72 hours" figures operators cite are sector custom or an individual DPA's non-binding benchmark, not law. Liability sits with the operator (CrumbVMS holds no footage and is neither controller nor processor); the vendor's only exposure is if a product feature misstates the law.

Decision.

  1. Feature, an opt-in, per-policy absolute time cap (max_retention_days, migration 0042). It sits alongside the existing size caps (live_max_bytes/archive_max_bytes) and the per-tier retention windows. It is a hard ceiling across both live and archive stages: footage older than the cap is deleted regardless of the other knobs. Default OFF (NULL) so it can never surprise-delete on an existing install, and when set it only ever removes footage sooner, never keeps it longer. Protected bookmarks still win (an explicit human pin is never auto-deleted). The recorder enforces it in archive::max_retention_sweep under the same crash-safe file-then-row ordering and ARCHIVE_GUARD serialization as the other sweeps.
  2. UI nudge, general information + disclaimer only. A neutral note next to the retention controls in the policy editor: "Keep footage only as long as you need it for your purpose. Some places regulate how long recordings of people may be kept, review your retention against your purpose and local law." plus an explicit "this is general information, not legal advice, and does not assess your compliance" line.

Rejected / not chosen:

OptionVerdict
Hardcode a default number (e.g. ship "30 days" as the retention or as the field's default)Rejected, there is NO fixed legal number; presenting one as "the GDPR number" is exactly the misstatement that creates vendor liability. The field ships blank (OFF); the operator chooses.
Assess/assert compliance in-app ("✓ GDPR-compliant", "you are over the limit")Rejected, a compliance judgement is legal advice and forfeits the liability-free framing. The nudge is deliberately non-committal: general info + disclaimer, never a verdict.
Make the cap a replacement for the size/tier retention knobsRejected, it's an additional constraint. Folding it into the existing knobs would change their meaning and risk deleting footage operators expected the tier settings to keep.
Delete protected/bookmarked footage to honour the cap strictlyRejected, an explicit human "protect from auto-delete" pin must win over an automatic ceiling (golden rule 2: prefer the change that cannot surprise-delete footage). Documented as a known exemption in docs/RESPONSIBLE-USE.md.

Cost accepted. The cap is not a strict guarantee (protected bookmarks and, by construction, the batch-per-tick drain mean "older than N days" converges rather than being instantaneous), and the nudge intentionally gives the operator no compliance answer, both are deliberate: correctness/anti-footage-loss and liability-framing discipline outrank a stricter or more opinionated design.

Revisit triggers:

  • A DPA (or statute) publishes a binding numeric retention limit for a jurisdiction Crumb operators are in → revisit whether to surface that specific number (still as the operator's choice, clearly scoped to that jurisdiction), never as a global default.
  • Operators report the batch-drain convergence is too slow to satisfy a real retention obligation → revisit the per-tick batch limit / add an immediate purge path.
  • A future counsel review lands on whether an in-app retention/DPIA nudge is safe as framed → adjust wording to match.

2026-07-05, Contributor licensing: CLA (Apache ICLA v2.0), superseding DCO-only​

Context. Crumb is AGPL-3.0, "free and open source, forever" for users. The maintainer wants to preserve future optionality, specifically the ability to dual-license (offer a paid commercial license alongside AGPL, the MongoDB/Qt model) or otherwise change licensing course, without foreclosing it before the project goes public. That ability requires the maintainer to hold, or be granted, a sublicensable copyright license over all contributions.

Prior stance. CONTRIBUTING said DCO, not a CLA, chosen for contributor-friendliness. But the DCO only certifies a contributor's right to submit; it grants no relicensing rights. Under DCO-only, once outside contributions land, the maintainer could never dual-license or relicense those parts without tracking down every contributor. Pre-launch, solo, no outside contributors yet → the maintainer owns 100%, so this is the cheapest moment to change.

Decision. Adopt a Contributor License Agreement for outside contributions: the Apache Individual CLA v2.0, adopted as-is (only the party name changed), in CLA.md. Section 2's "sublicense" grant is what preserves dual-licensing; contributors keep ownership. Enforced by the free contributor-assistant CLA bot (.github/workflows/cla.yml), one comment per contributor. The DCO per-commit sign-off is retained as a lightweight origin certification, not the operative license grant.

Rejected / not chosen:

OptionVerdict
DCO only (prior)Rejected, no relicensing rights; permanently forecloses dual-licensing once contributions arrive.
Copyright assignmentRejected, heavier, worse optics for a trust-first solo project; a broad license grant achieves the goal without taking ownership.
Switch to source-available / non-compete (BSL, PolyForm Shield) to block commercial exploitation outrightNot chosen now, forfeits the "open source" identity and reverses the public AGPL-forever commitment; premature before knowing whether Crumb is a business. The CLA keeps this door open without walking through it.
Custom-drafted CLARejected, defeats the "no lawyer needed" goal; adopting a recognized standard as-is is the low-risk path.

Cost accepted. CLAs add contributor friction (some decline to sign) and can read as a "trust me" ask. Accepted because the optionality outweighs the marginal friction this early, and the bot makes signing one click. Not a lawyer, the ICLA text is adopted unmodified; a lawyer's review is deferred until an actual commercial-license transaction, when it pays for itself.

Revisit triggers:

  • Crumb commits permanently to "no commercial licensing, ever" → the CLA's relicensing purpose is moot; drop back to DCO-only to cut friction.
  • A contributor base forms and CLA friction measurably deters contributions → reconsider (e.g. DCO + a narrower inbound license grant).
  • An actual dual-license deal materializes → get the lawyer review then.

2026-07-03, Motion recording: RAM pre-buffer + persist-on-motion​

Problem. RecordingMode::Motion was cosmetic: ffmpeg recorded 24/7 and retention was purely time/size-based, identical to Continuous. Motion mode delivered zero disk or storage savings.

Research summary (full survey in the session that produced this entry; mechanism doc in docs/MOTION-RECORDING.md):

  • Enterprise / control-room VMS platforms generally never gate capture: they ingest continuously into a short RAM pre-buffer and flush to the recording store on a trigger, so pre-event footage is always available.
  • Some prosumer NVRs gate capture in motion mode, and their own docs note that true pre-alarm playback then requires continuous mode.
  • The cleanest hybrid records a low-res sub-stream continuously and the main stream only on motion.
  • Some consumer NVRs label a mode "motion-only" but actually record continuously and prune afterward, so the saving is retention-side, not ingest-side.
  • Frigate: continuous 10 s segments into a tmpfs cache; a mover keeps only segments overlapping motion/events ± pre/post capture. Its worst documented failures are cache-related (tmpfs exhaustion, orphaned handles from crashed ffmpeg → silent footage loss).
  • ZoneMinder / Blue Iris communities: recommend continuous recording over motion-gated capture because missed detections lose footage forever.

Convergent industry finding: every system that prioritizes not losing footage captures first and decides afterward; the disagreement is only where undecided footage waits (RAM / tmpfs / disk) and how long before the keep-or-drop call is final.

Options considered:

#OptionVerdict
1Capture-gating (start/stop ffmpeg on motion)Rejected outright, no pre-roll, misses event starts, a missed detection means footage never existed. No reliability-focused system does this.
2RAM cache + persist-on-motion (the commercial-VMS model)CHOSEN, zero idle disk writes, zero idle storage; maps directly onto the existing 2–6 s segment pipeline and the already-built MotionBuffer state machine.
3Record to disk → prune non-motion at segment closeRejected: full continuous disk write load and transient storage "for no reason".
4Record to disk → prune at retention with a grace window (24–72 h full-coverage safety net)Rejected same grounds as 3. Chief advantage lost: a missed detection could still be recovered within the grace window.
5Dual-stream hybrid (sub-stream continuous + main motion-gated)Deferred to roadmap, best long-term answer for "never blind, still cheap", but a second recording pipeline + playback source switching is a separate project. Layers cleanly on top of option 2.

Safety rails that made option 2 acceptable (both are invariants, see docs/RECORDER-CORRECTNESS.md):

  1. Fail-open: a camera whose motion detector is unhealthy (stalled sub-stream, dead decoder, no frames analyzed yet) persists everything until detection recovers, and raises a health alert. Blind-but-recording beats blind-and-empty.
  2. Spill, never drop: cache pressure persists the oldest buffered segments to disk instead of deleting them. Footage is never lost to a full cache (Frigate's worst failure mode).
  3. Shadow mode (MOTION_RECORDING_SHADOW=1) for rollout: record everything as before while stamping segments.motion_shadow_keep with the verdict the buffer would have made, so the keep/drop behavior is validated against real footage before any camera goes live.

Trades knowingly accepted:

  • A genuinely missed detection (below threshold, not a pipeline failure) means that footage never existed. There is no safety net by design.
  • A recorder crash loses whatever was in RAM, bounded by pre-roll seconds (commercial VMSes have the same property).
  • Pre/post-roll resolution rounds to segment boundaries (2–6 s).

Revisit triggers:

  • Missed-event reports from testers/users where the detector simply scored the motion below threshold → revisit option 4 (grace-window prune) as an opt-in per-policy "keep everything for N hours" safety net, or accelerate option 5.
  • Deployments on hardware where RAM is scarcer than disk (SBCs, tiny NAS boxes) → option 3/4 as an alternative cache backend (disk cache dir instead of tmpfs, the commercial-VMS "disk-based pre-buffer" fallback).
  • Demand for full 24/7 timeline coverage alongside motion savings → option 5 (dual-stream hybrid, already on docs/ROADMAP.md).
  • If shadow-mode validation shows the detector's keep/drop verdicts are not trustworthy on real footage, do not ship enforce mode, fix detection first or fall back to option 4.