Repository navigation
Done
Description
Rescoped request
Replace the original proposal for continuous recording until disk-full with an investigation of two storage-management options:
- Configurable disk-usage ceiling: let the owner set a maximum percentage of the recording filesystem that SimpleNVR may use, and decide what the system should do when the ceiling is reached.
- Estimated days remaining: use current recording usage and observed growth to estimate how many days of storage remain at the current recording configuration, and display the estimate to the owner.
The first question is which option solves the owner's problem better. They could be alternatives, or a limit and a visibility feature used together. This issue starts with research and a proposal; it does not assume either behavior is approved for implementation.
Existing behavior and constraints
- Checkpoint 6's Disk Usage figure estimates the bytes counted for each camera. It is not a filesystem-capacity percentage or a forecast. It counts regular
.mp4files in the camera root, valid day folders, andbuffer/andtemp/staging, with the documented cache and incomplete-inspection behavior. SIMPLENVR_MIN_FREE_BYTESis an opt-in start/admission check based on filesystem-available bytes. It does not impose a maximum-usage ceiling, monitor an already-running recorder, reserve space, or predict remaining days.- Retention remains time-based per camera. The agreed checkpoint 5 policy skips day folders newer than the cutoff UTC day, with its documented delayed-cleanup exception.
- Event staging has separate optional admission limits.
.tmp,temp/,buffer/and retained recovery evidence must not be automatically removed or miscounted as safely reclaimable published recordings. - Storage can be shared with non-SimpleNVR data, use quotas/reserved blocks, or change independently while a recorder is running. A usage total must not be described as free filesystem capacity.
Investigation and proposed deliverables
- Clarify the owner's objective and which filesystem(s) the setting/report should cover. Inspect the current disk-usage implementation and storage-admission semantics; do not conflate camera-recording bytes with total or available filesystem bytes.
- Compare the two options, including whether they should be alternatives or complementary features. Document assumptions, uncertainty, configuration scope (global versus per camera), and how shared volumes, staging, retention, camera add/remove, restart and changing recording modes affect the result.
- For an estimated-days figure, propose a defensible growth estimator and its data source/window. State how it behaves with no history, changing segment sizes, event-only cameras, variable frame rates, intermittent recording, retention, and incomplete disk-usage scans. Label forecasts as estimates, not guarantees.
- For a configurable ceiling, propose the threshold semantics, filesystem metric, reserve/hysteresis, user-visible behavior, and safe handling when current use is already above the limit or the measurement is unavailable. Distinguish admission control from enforcement on active recorders.
- Present a short recommendation and acceptance criteria for owner approval before implementation. Implementation, migrations, UI changes and configuration names require a separately agreed plan; do not silently enable deletion or change retention behavior.
Explicitly out of scope unless separately approved
- Automatically deleting the oldest recordings or any other media to stay under a cap.
- Changing time-based retention, camera deletion, orphan cleanup or evidence-preservation rules.
- Deleting
.tmp,temp/,buffer/, event staging or recovery artifacts. - Treating filesystem usage estimates as quotas, reservations or proof that recording can continue.
- Changing recording duration, codec, camera behavior, Docker mounts or deployment policy.
Any future pruning proposal needs its own explicit decision, safety model, partial-failure semantics and tests. This rescoping does not authorize cleanup or deletion.
Acceptance
- A source-backed comparison of a disk-usage ceiling and estimated days remaining, including tradeoffs and failure/uncertainty cases.
- A recommendation that states whether to pursue one option, both, or neither, and the exact behavior the owner must approve next.
- No automatic pruning, deletion or retention-policy change is implemented under this exploratory scope.
- If implementation is later approved, define its own tests, documentation and exact-head CI acceptance before work begins.
Metadata
Metadata
Assignees
Labels
No labels
Activity
[-]Continuous recording until disk full, then automatically prune the oldest recordings[/-][+]Explore disk-usage limits and estimated storage remaining[/+]mouldybread commentedon Nov 28, 2026
Suggested prompt for a coding assistant:
mouldybread commentedon Nov 28, 2026
Approved design and implementation plan (owner decisions recorded 2026-11-29, revision 3)
Supersedes the research recommendation in this issue. The original "no automatic deletion" scope is explicitly replaced by the owner for the behavior below. Estimated days remaining is dropped. #16 (PR #20) and #17 (PR #18) are merged. CP1 findings: #14 (comment)
Agreed behavior
Statfson the common recordings root/recordings(every camera directory is/recordings/<id>). Displayed and used for pruning. No separate "SimpleNVR share" figure. The existing per-camera "Disk Usage" figure on the camera list stays as is.cameras.json. Prune trigger is ceiling - 2 (78 at the default).Statfsevery 5 minutes in its own background job (started and joined through the same app lifecycle as the cleanup job), first check 5 minutes after startup; when the settings UI is opened (display only, never prunes); and when the setting is changed (immediate check, prunes if needed).Statfsfails, usage is unknown, no pruning happens, the failure is logged, and the UI shows "unavailable"..mp4file. Repeat on the next check while still at or above trigger. Partial days are removed like any other..mp4) is skipped silently on later passes, without logging again each time.Bavail * Bsize) before and after a pass. If available bytes did not increase by at least 1 MiB, the pass counts as having no effect: log it and do not prune again until a later check shows available bytes have increased by at least 1 MiB compared with the post-pass reading. The guard state is in memory and resets on restart.StartTimefalls on that UTC day. Events carry no camera ID or media path, so cameras that share a name share the match; this is accepted.0means off, with no migration or conversion (all installations are new). Whichever limit applies first wins.SIMPLENVR_MIN_FREE_BYTESis unchanged and independent..tmp,temp/,buffer/, event staging, recovery artifacts, legacy root files. Camera deletion, orphan cleanup, delete-all and evidence rules are unchanged.Checkpoints (one at a time; each ends with exact-head CI green and owner sign-off; each updates the docs for what it changes)
CP1: Re-baseline and read-only analysis. DONE. Findings and test-file list are in the comment linked above. Owner decisions on its questions are recorded in this plan.
CP2: Filesystem measurement and 5-minute job.
Statfs-based used-% reading. Extend the existing capacity reader (readRecordingStorageCapacity, which today returns only available bytes) to also read total and free blocks; document the exact formula (process-available space, reserved blocks).Statfsfailure: log, treat usage as unknown, no pruning.CP3: Ceiling setting and settings display (names agreed here).
cameras.jsonkey, and the valid range (default 80) before implementing this checkpoint. Add the top-level field topersistedStateand its validation indecodeState.CP4: Prune pass.
.mp4files per camera, one-day floor, no-effect guard (1 MiB available-bytes rule), "ceiling not met" state, per-camera partial-failure logging, silent skip of leftover-only days.retentionPolicyMu, thenNVR.mu) and reuses the published deletion engine's safety model (identity checks, individual unlinks, noRemoveAll, rmdir only when empty). The engine needs a day-scoped selection added, because its current policy only classifies days against a retention cutoff. It removes event records for the pruned day by camera name and UTC start day..tmp/temp//buffer//staging untouched; events removed for the pruned day; ceiling below current usage prunes on setting change; recording is never stopped; prune and retention cleanup never delete concurrently.CP5: Retention days becomes optional maximum age.
0= off and the default for new cameras. Remove the legacy 7-day branch fromcameraRetentionDuration; update the retention API and persisted-state validation, the UI, andcleanupEventsForso cameras with max age off are not expired by age.retention_policy_test.gotests that expect0to convert to 7 days or to be rejected, plus any other affected tests listed in CP1.CP6: End-to-end acceptance.
Open items to settle during implementation
Statfsformula (CP2).cameras.jsonkey and valid range (CP3, owner approval).mouldybread commentedon Nov 28, 2026
CP1 findings: re-baseline (read-only, no code change)
Read against
mainat023e558(after #16/#17 merged). Go sources are still undercmd/simplenvr/; frontend is underweb/staticandweb/templates; docs underdocs/. No tests were run and nothing was changed. Files I did not read are marked below.1. Current code relevant to the plan
cleanup.gocleanupRoutine/runCleanupTicksmain.goviagate.startBackgroundJob. Each tick runscleanupEventsFor, thencleanupRetentionSnapshotper camera.retention_snapshot.goretentionPolicyMu, thenNVR.mu.admitRetentionDeletionacquires the media lease, re-validates the camera snapshot with a guard, then calls the deletion operation. A prune pass must go through the same acquisition layer.published_deletion_engine.godeletePublishedLeasedWithWorkopens day folders no-follow, pins identity, preflights every candidate, unlinks files individually, and removes a day folder only by atomicrmdir. It never usesRemoveAll. It stops at the first error (fail fast).retention_policy.gocameraRetentionDuration:0currently means the legacy 7-day default; valid range is 1 to 365.handlers.goupdateRetentionHandler; routes inmain.go/api/cameras/update-retentionand/api/cameras/update-retention-all.persistence.gopersistedStateholdscameras,camera_orderandeventsonly. There is no global settings field.decodeStatevalidates retention withcameraRetentionDuration.validateCameraPathforces every camera directory to be exactly/recordings/<id>, so the common recordings root is/recordings.storage_status.goreadRecordingStorageCapacityFstatfson anO_NOFOLLOWdirectory descriptor but returns onlyBavail * Bsize(and free inodes). It does not readBlocksorBfree, so used % does not exist yet.storage_admission.gocheckRecordingStorageis unchanged from the research:Statfson the camera directory,BavailagainstSIMPLENVR_MIN_FREE_BYTES.auth.goroutes/api/settings/sessionand/api/settings/restart;web/static/js/session-settings.js; settings buttons inweb/templates/index.htmlindex.htmland saved with a restart. There is no existing "settings page", so the ceiling UI will be a new modal or section. How session settings are stored was not read.2. How events relate to media
Event(declared inmain.go) is metadata: ID,CameraName, label,StartTime, duration, created time. It has no camera ID and no media path. Nothing links an event to a day folder or file.cleanupEventsForremoves events older than the camera's retention duration, and removes events whose camera name no longer exists. Cameras sharing a name use the longest retention.StartTimefalls on that UTC day. This is a matching rule, not a stored link. It cannot tell apart two cameras with the same name, which the existing code already treats as ambiguous.3. Findings that change the plan
selectFilereceives only a file name and mtime. The engine's only day policy is the retention cutoff (classifyRetentionDay, skipping newer days). Pruning exactly one chosen day needs a new work policy or selector, and it will read every day folder under the 400-day bound..mp4files and removes the day folder only if it is empty. A leftover.tmpor other non-.mp4file keeps the folder (ENOTEMPTY is not an error). "Oldest day" must therefore mean the oldest day that still contains deletable.mp4files, or the same day would be chosen forever.0meaning 7 days. Making0mean "max age off" (CP5) also changescleanupEventsFor, which would otherwise expire those cameras' events at 7 days or treat them oddly. It must be changed in the same checkpoint.0already means 7 days. Existingcameras.jsonfiles that containretention_days: 0would silently switch from 7 days to "off" after CP5. Fresh installs are unaffected.persistedStateincameras.json(older readers ignore unknown fields, anddecodeStatedoes not reject them), or reuse the auth store like the session settings. The first is simpler and keeps the setting with the data it affects.4. Test files CP2 to CP5 will change or extend
Read in full:
retention_policy_test.go,storage_admission_test.go. The rest are listed by name from the directory listing only; I did not read their contents.retention_policy_test.go. It currently expects0to convert to 7 days, to be rejected by the update API, and to be valid in persisted state, so CP5 changes three tests deliberately.retention_snapshot_test.go,retention_day_selection_test.go,retention_day_folders_test.go,retention_deletion_engine_test.go,retention_publication_serialization_test.go,retention_wiring_bounds_test.go,retention_scale_evidence_test.go,published_deletion_engine_test.go,published_deletion_admission_test.go.cleanup_test.go,background_cleanup_test.go,event_retention_test.go,event_terminal_retention_integration_test.go,event_coverage_retention_test.go.storage_status_test.go,storage_admission_test.go,persistence_test.go,persistence_save_recovery_test.go,persistence_write_failure_test.go.*_frontend_test.gofiles that cover settings and retention UI; which of them do so was not determined.web/static/js/modals.js,web/static/js/cameras.js,web/static/app.js(retention inputs),web/static/js/session-settings.js,web/templates/index.html,web/templates/cameras.html.docs/RETENTION_SELECTION.md,docs/DISK_USAGE.md,docs/STORAGE_DEPLOYMENT_BOUNDARIES.md,README.md.5. Questions for the owner
cameras.json(recommended) or alongside session settings?.tmp), skip it and take the next oldest day that has deletable.mp4files?retention_days: 0mean "off", or be converted to 7 on load?6. Not verified
main.gobeyond search excerpts,handlers.gobeyond the retention handler excerpt,auth.gosettings code, the web sources, and most test files listed above.modals.js,cameras.jsorapp.js(all three call the retention API).Add recording filesystem usage measurement and 5-minute monitor job (#14
Share one statfs reader between storage status and filesystem usage (#14
mouldybread commentedon Nov 28, 2026
CP3 approved names (owner-approved)
max_filesystem_used_percentincameras.json, besidecameras,camera_orderandevents. A missing key reads as 80. The value is written out explicitly the first time settings are saved, including when it is still the default.filesystem_used_percent(number, ornullwhen unknown),max_filesystem_used_percentandfilesystem_prune_trigger_percent. Existing fields are unchanged.POST /api/storage/ceilingwith{"max_filesystem_used_percent": <int>}. It validates, saves through the existingcameras.jsonwrite path, and returns the stored value.Implementation is on PR #23.
mouldybread commentedon Nov 28, 2026
CP3 amendment (owner-approved)
This replaces the Read API bullet in #14 (comment). Everything else in that comment stands.
The existing storage status handler is per camera: it requires exactly one
camera_idquery parameter, inspects that camera's directory, and returns 503 whenever any part of its report is incomplete. The ceiling and filesystem usage are global, so they are not added to it, and that handler is left unchanged.GET /api/storage/ceilingreturnsmax_filesystem_used_percent,filesystem_prune_trigger_percent,filesystem_used_percent(number, ornullwhen unknown) andfilesystem_observed_at(ornull). It takes a fresh reading on each request, so settings show current usage even before the monitor's first check. A failed reading yieldsnullrather than an error status, so the ceiling stays visible.POST /api/storage/ceilingis unchanged:{"max_filesystem_used_percent": <int>}, validated 10 to 95, saved through the existingcameras.jsonwrite path, and the stored value is returned.CP3 (#14): filesystem usage ceiling setting, API and settings display
CP3 (#14): register /api/storage/ceiling and document the ceiling
CP3 (#14): add frontend regression test for the filesystem ceiling row
CP4 (#14): filesystem prune pass
mouldybread commentedon Nov 28, 2026
Status: CP1 through CP6 complete
Implementation is in PR #23: #23. The owner has signed off CP6 based on automated acceptance. The additional manual TrueNAS/ZFS runbook is not a completion requirement. ZFS-specific behavior remains untested; no local-volume test is claimed. This supersedes the manual-run requirement in the CP6 proposal and docs/FILESYSTEM_ACCEPTANCE.md.
60df3d7d86f255fab03936b4a57b7174eb22e8e44743f8d; owner signed offFinal CI result
All nine check runs on the exact PR head
d86f255fab03936b4a57b7174eb22e8e44743f8dreport success, including the required-checks gate, Core build/race/storage/lifecycle, prepared_go build/race/vet, two isolated Chrome runs, two prepared_browser attempts, ordered-content measurements, and the new real-container filesystem-pruning acceptance.Run: https://github.com/mouldybread/SimpleNVR/actions/runs/46217386829
Check conclusions were inspected, not the full uploaded evidence or every per-test result. Historical checkpoint-green results did not establish end-to-end correctness; CP6 uncovered the three defects below.
Defects uncovered and fixed during acceptance
fd8cbd6with a read-write mutation allowlist and route registration; regression tests exercise the real auth middleware, method restrictions, session requirement and cross-origin refusal. The route is also tracked by the shutdown gate.f9b1dc2by preferring the dialog-scoped input, with a frontend regression test.d86f255by remembering the ceiling associated with the state, with a regression test. Repeated saves of the same value remain silent; a different ceiling can log again.Implemented behavior
Automated acceptance and limits
The required filesystem-pruning job uses the real runtime image, HTTPS server, headless Chrome, and a disposable ext4 loopback filesystem. It checks settings saves and persistence, explicit retention 0, no deletion below trigger, one oldest day per camera, event removal, protected-file hashes, retained-space pause/resume using hard links, immutable-file partial failure, ceiling-not-met suppression, recorder-process presence, clean shutdown and restart persistence.
Not claimed: live RTSP qualification, actual ZFS snapshots or host-specific quota behavior, scheduled five-minute tick/age-cleanup timing in the container acceptance, or large-tree performance. Hard links test retained allocation, not ZFS implementation details. The owner accepted these limits and marked CP6 complete.
Docs include FILESYSTEM_USAGE.md, FILESYSTEM_PRUNING.md, RETENTION_MAX_AGE.md and FILESYSTEM_ACCEPTANCE.md. Older audit notes describe superseded zero-retention behavior; RETENTION_MAX_AGE.md identifies the replacement. docs/DISK_USAGE.md was not changed.
All checkpoints are complete. This update does not merge PR #23 or close issue #14; merging the PR carries Closes #14.
CP5 (#14): retention days as an optional maximum age
CP5 (#14): use a stamped name in the age-versus-ceiling test
mouldybread commentedon Nov 29, 2026
CP6 plan: end-to-end acceptance (proposed, awaiting owner approval)
Nothing below is implemented. CP1 to CP5 are complete (see the status comment, #14 (comment)). Every CP1 to CP5 test so far uses temporary directories and fake usage readers. CP6 checks the shipped behavior against a real filesystem, the real runtime image and a real browser, and says plainly what it still does not cover.
What it builds on
The repository already has
tests/acceptance/active-container-storage.sh: it runs the real runtime image with a bind-mounted state directory, substitutes only the camera capture input with a file-fed FFmpeg (not live RTSP), stops the container, and compares evidence hashes. CP6 follows that pattern with a new script,tests/acceptance/filesystem-prune-acceptance.sh, and extends the existing headless-Chrome acceptance for the settings rows.A. Container acceptance on a real, small filesystem
Setup. A loopback ext4 image of fixed size (about 64 MiB) is mounted at the state directory with
sudo, sofstatfsreports a real used percentage and real available bytes. The real image runs with that directory bound at/recordings, the same file-fed FFmpeg substitution, andSIMPLENVR_MIN_FREE_BYTESunset. Two cameras are seeded: one withretention_days7, one with0. Each has several UTC day folders ofdd-generated.mp4files, plus a leftover-only day, a.tmp,temp/,buffer/and a staging folder. Events are seeded for a pruned and an unpruned day. Sizes are computed fromdfin the script, not hard-coded.Triggering passes. The real job runs every 5 minutes, which is too slow for CI. The script logs in and uses
POST /api/storage/ceiling, which asks for a pass immediately. The login steps are copied from the existing runtime browser acceptance. Each POST is one pass.Scenarios and expected results
.mp4files from each camera. Newest days, the leftover-only day,.tmp,temp/,buffer/, staging and files in the camera root are byte-identical (hash compare). The pruned day's events are gone; others remain. Both recorders keep running (FFmpeg processes still present,is_recordingstill true incameras.json).paused, and further POSTs delete nothing. Remove the hard links; available bytes rise by at least 1 MiB, the next POST logsresumedand prunes.chattr +ione file in a day. The rest of that day is removed, the run logsincomplete for camera, that day's events are kept, the other camera is still pruned. The script runschattr -iin cleanup.retention_days0 is still pruned by the ceiling (apart from its newest day); neither camera's recorder is touched.docker stopexits 0 and logsShutdown complete; recording intent persisted.cameras.jsonis mode 0600 and containsmax_filesystem_used_percentexplicitly. After a restart the ceiling is the same.Result line. On success the script prints a line like the existing one, for example
FILESYSTEM_PRUNE_VERIFIED image_id=... cycles=... filesystem=ext4_loop live_rtsp=not_tested zfs=not_tested age_cleanup_tick=not_tested.B. Real browser (headless Chrome, extend the existing acceptance)
Open camera settings and check that the Filesystem Usage row shows used %, ceiling and trigger level from the running server; set the ceiling to a valid value and see it persist across a reload; an out-of-range value sends nothing. Check that the retention inputs accept
0, sendretention_days: 0, and show0after the list refreshes. The Chrome acceptance gets its own isolated runs as it does today.C. Owner runbook on the real volume (TrueNAS / ZFS), not run by CI
CI cannot create a ZFS dataset. I will write
docs/FILESYSTEM_ACCEPTANCE.mdwith steps to run on a dataset with a quota and a snapshot: recorddfandzfs listbefore; set a ceiling below usage; read the log lines for each pass; confirm whether deleted space is actually freed while the snapshot exists (this is what the 1 MiB guard is for); delete the snapshot and confirm pruning resumes; check the Filesystem Usage row againstdf. It also covers waiting through one 5-minute tick to see age cleanup and the scheduled prune pass. The owner runs it and reports results; I will record them on this issue and will not claim them otherwise.Pass criteria
cameras.json, process presence), not only exit codes.Explicitly not covered by CI
Live RTSP cameras; ZFS or any snapshotting filesystem; the 5-minute tick timing and age cleanup on that tick (age cleanup is covered by unit tests); unknown-usage handling inside the container (unit-tested); performance or very large trees; behavior on a volume shared with other data beyond the hard-link stand-in.
Files I expect to add or change
New
tests/acceptance/filesystem-prune-acceptance.shand a small Python helper for the login and assertions, newdocs/FILESYSTEM_ACCEPTANCE.md, a new job in the safety workflow wired into the required-checks gate, and an extension oftests/acceptance/runtime-browser-acceptance.py. I have not yet read.github/workflows/safety-ci.ymlor the browser acceptance script, so the exact changes may differ; I will read them first and post any surprise before editing.Decisions I need from you
CP6 (#14): real-container acceptance for ceiling pruning
Merge pull request #23 from mouldybread/feature/14-cp2-filesystem-usage