Skip to content

Explore disk-usage limits and estimated storage remaining #14

Done

Description

@mouldybread

Rescoped request

Replace the original proposal for continuous recording until disk-full with an investigation of two storage-management options:

  1. 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.
  2. 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 .mp4 files in the camera root, valid day folders, and buffer/ and temp/ staging, with the documented cache and incomplete-inspection behavior.
  • SIMPLENVR_MIN_FREE_BYTES is 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

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

Activity

  1. changed the title [-]Continuous recording until disk full, then automatically prune the oldest recordings[/-] [+]Explore disk-usage limits and estimated storage remaining[/+] on Nov 25, 2026
  2. mouldybread commented on Nov 28, 2026

    @mouldybread
    OwnerAuthor

    Suggested prompt for a coding assistant:

    Repo: mouldybread/SimpleNVR. Issue #14. Base: main. Research only: compare a configurable recording-filesystem usage ceiling with an estimate of days remaining. Do not implement either.
    
    Trace recordingDiskUsage.render and calculateDiskUsage in disk_usage.go, and checkRecordingStorage and storageReserveFits in storage_admission.go. Read docs/DISK_USAGE.md, docs/STORAGE_DEPLOYMENT_BOUNDARIES.md and docs/RETENTION_SELECTION.md. Distinguish counted camera media bytes from filesystem capacity and process-available space.
    
    Done: recommend either option, both or neither, with checkable acceptance criteria for owner approval. For the ceiling, specify the measurement, covered mounts, thresholds and hysteresis, what the user sees, and behavior above the limit or when measurement fails. Distinguish admission checks from enforcement on running recorders. For the forecast, specify the input, observation window and uncertainty; cover insufficient history, incomplete scans, event-only and intermittent recording, and changes to camera mix or recording modes. Consider shared volumes, quotas, reserved blocks, restart, staging and retention. Ask which filesystems and owner objective matter if unclear.
    
    Do not change code, config, retention, cleanup, mounts or recovery artifacts. Do not propose automatic deletion. Research can run independently of #15–#17; defer any approved UI implementation that touches playback until #17 lands, and coordinate paths with #16.
    
    Review and, if feasible, run the disk usage, storage admission and retention tests using go test ./...; cite disk_usage_test.go, storage_admission_test.go and retention_policy_test.go when explaining what they cover. Return a short recommendation, source references, exact commands and outcomes, owner decisions, and anything unverified.
    
  3. mouldybread commented on Nov 28, 2026

    @mouldybread
    OwnerAuthor

    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

    • Metric: filesystem used % from Statfs on 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.
    • Setting: maximum filesystem used %, default 80, persisted as a new top-level field in cameras.json. Prune trigger is ceiling - 2 (78 at the default).
    • Checks: Statfs every 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).
    • Unknown measurement: if Statfs fails, usage is unknown, no pruning happens, the failure is logged, and the UI shows "unavailable".
    • Prune pass: if used % >= trigger, remove the oldest day of each camera (one pass = at most one day per camera). "Oldest day" means the oldest UTC day folder that still contains at least one .mp4 file. Repeat on the next check while still at or above trigger. Partial days are removed like any other.
    • Days that cannot be fully emptied: remove what can be removed and log what remains. A day folder holding only leftovers (no .mp4) is skipped silently on later passes, without logging again each time.
    • Floor: never remove the newest UTC day folder of a camera. Day folders are UTC days, so just after UTC midnight the newest folder can hold only minutes of footage; this is accepted, and a later pass runs again if needed. If nothing prunable remains and usage is still at or above trigger, log it and show "ceiling not met" in the UI.
    • No-effect guard: read available bytes (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.
    • Events: when a day is pruned for a camera, remove event records with that camera name whose StartTime falls on that UTC day. Events carry no camera ID or media path, so cameras that share a name share the match; this is accepted.
    • Partial failure: log camera and day, continue with the next camera; the next pass retries.
    • Retention days: kept as an optional maximum age. 0 means off, with no migration or conversion (all installations are new). Whichever limit applies first wins.
    • Recording is never stopped or rejected by the ceiling. SIMPLENVR_MIN_FREE_BYTES is unchanged and independent.
    • Never touched: .tmp, temp/, buffer/, event staging, recovery artifacts, legacy root files. Camera deletion, orphan cleanup, delete-all and evidence rules are unchanged.
    • Not done: per-camera ceilings, multi-filesystem support, deletion preview, forecast.

    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.

    • Add a 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).
    • A separate background job: 5-minute ticker, first check 5 minutes after startup, clean start/stop, joined on shutdown. On Statfs failure: log, treat usage as unknown, no pruning.
    • Docs: document the measurement and its limits (filesystem-wide, includes non-SimpleNVR data).
    • Acceptance: unit tests for percentage maths (reserved blocks, zero blocks, overflow), measurement failure logging, first-check timing and shutdown join; no deletion yet.

    CP3: Ceiling setting and settings display (names agreed here).

    • Propose and get owner approval for the setting name, API field, the cameras.json key, and the valid range (default 80) before implementing this checkpoint. Add the top-level field to persistedState and its validation in decodeState.
    • UI (new modal or section; there is no existing settings page): current used % (or "unavailable"), the ceiling, and the "ceiling not met" state once it exists.
    • Check on UI open (display only) and on setting change (calls the evaluation hook; still no deletion in this checkpoint).
    • Docs: update settings and user-facing documentation for the new setting and display.
    • Acceptance: invalid values rejected before mutation and persisted state preserved on a failed save (matching existing retention tests); UI shows used % and ceiling; page load never prunes.

    CP4: Prune pass.

    • Pass logic: trigger at ceiling - 2, oldest day with .mp4 files 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.
    • Deletion goes through the same media-lease acquisition and lock order as retention cleanup (media ownership, then retentionPolicyMu, then NVR.mu) and reuses the published deletion engine's safety model (identity checks, individual unlinks, no RemoveAll, 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.
    • Docs: document prune behavior, the floor, the guard, and that deleted footage is not recoverable.
    • Acceptance tests: below trigger = no deletion; at/above trigger = one oldest day per camera; newest day never removed; guard stops repeats when available bytes do not rise by 1 MiB and resumes when they do; unknown measurement = no deletion and a log; partial failure continues; leftover-only day is skipped without repeated logs; .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 from cameraRetentionDuration; update the retention API and persisted-state validation, the UI, and cleanupEventsFor so cameras with max age off are not expired by age.
    • Tests: rewrite the three retention_policy_test.go tests that expect 0 to convert to 7 days or to be rejected, plus any other affected tests listed in CP1.
    • Docs: update retention documentation and UI help text.
    • Acceptance: whichever limit applies first wins; changed validation tests are updated deliberately and listed in the PR; no change to other retention selection rules.

    CP6: End-to-end acceptance.

    • Review all docs touched by CP2-CP5 for consistency (disk usage, storage boundaries, retention).
    • Run the full suite, race and vet on the exact head; record commands and outcomes.

    Open items to settle during implementation

    • Exact Statfs formula (CP2).
    • Setting name, API field, cameras.json key and valid range (CP3, owner approval).
  4. mouldybread commented on Nov 28, 2026

    @mouldybread
    OwnerAuthor

    CP1 findings: re-baseline (read-only, no code change)

    Read against main at 023e558 (after #16/#17 merged). Go sources are still under cmd/simplenvr/; frontend is under web/static and web/templates; docs under docs/. No tests were run and nothing was changed. Files I did not read are marked below.

    1. Current code relevant to the plan

    Area Where Finding
    Cleanup scheduler cleanup.go cleanupRoutine / runCleanupTicks A 5-minute ticker already exists, started from main.go via gate.startBackgroundJob. Each tick runs cleanupEventsFor, then cleanupRetentionSnapshot per camera.
    Retention acquisition retention_snapshot.go Lock order is media ownership, then retentionPolicyMu, then NVR.mu. admitRetentionDeletion acquires 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.
    Deletion engine published_deletion_engine.go deletePublishedLeasedWithWork opens day folders no-follow, pins identity, preflights every candidate, unlinks files individually, and removes a day folder only by atomic rmdir. It never uses RemoveAll. It stops at the first error (fail fast).
    Retention policy retention_policy.go cameraRetentionDuration: 0 currently means the legacy 7-day default; valid range is 1 to 365.
    Retention API handlers.go updateRetentionHandler; routes in main.go Rejects values below 1 or above 365. Routes: /api/cameras/update-retention and /api/cameras/update-retention-all.
    Persistence persistence.go persistedState holds cameras, camera_order and events only. There is no global settings field. decodeState validates retention with cameraRetentionDuration. validateCameraPath forces every camera directory to be exactly /recordings/<id>, so the common recordings root is /recordings.
    Capacity reading storage_status.go readRecordingStorageCapacity Uses Fstatfs on an O_NOFOLLOW directory descriptor but returns only Bavail * Bsize (and free inodes). It does not read Blocks or Bfree, so used % does not exist yet.
    Admission storage_admission.go checkRecordingStorage is unchanged from the research: Statfs on the camera directory, Bavail against SIMPLENVR_MIN_FREE_BYTES.
    Global settings precedent auth.go routes /api/settings/session and /api/settings/restart; web/static/js/session-settings.js; settings buttons in web/templates/index.html Session settings are a modal opened from index.html and 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 in main.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.
    • cleanupEventsFor removes 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.
    • "Remove event records with the footage" therefore has to mean: when a day is pruned for a camera, remove events with that camera name whose StartTime falls 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

    1. Engine selection is not day-scoped. selectFile receives 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.
    2. An emptied day can survive. The engine deletes only .mp4 files and removes the day folder only if it is empty. A leftover .tmp or other non-.mp4 file keeps the folder (ENOTEMPTY is not an error). "Oldest day" must therefore mean the oldest day that still contains deletable .mp4 files, or the same day would be chosen forever.
    3. Existing event cleanup depends on 0 meaning 7 days. Making 0 mean "max age off" (CP5) also changes cleanupEventsFor, which would otherwise expire those cameras' events at 7 days or treat them oddly. It must be changed in the same checkpoint.
    4. A persisted 0 already means 7 days. Existing cameras.json files that contain retention_days: 0 would silently switch from 7 days to "off" after CP5. Fresh installs are unaffected.
    5. The scheduler can reuse the existing tick. The cleanup ticker already fires every 5 minutes, first after 5 minutes, and is started and joined by the app lifecycle. The prune check can run there or in a sibling job; either meets the agreed timing.
    6. A global field needs a place to live. Add a new top-level field to persistedState in cameras.json (older readers ignore unknown fields, and decodeState does 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 and API (CP3, CP5): retention_policy_test.go. It currently expects 0 to 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 selection and engine (CP4): 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 tick and events (CP2, CP4, CP5): cleanup_test.go, background_cleanup_test.go, event_retention_test.go, event_terminal_retention_integration_test.go, event_coverage_retention_test.go.
    • Capacity and persistence (CP2, CP3): storage_status_test.go, storage_admission_test.go, persistence_test.go, persistence_save_recovery_test.go, persistence_write_failure_test.go.
    • Frontend (CP3, CP5): the *_frontend_test.go files that cover settings and retention UI; which of them do so was not determined.
    • New files (CP2 to CP4): tests for the used-% reading and ticker, the ceiling setting, and the prune pass.
    • Frontend sources: 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 (CP2 to CP5): docs/RETENTION_SELECTION.md, docs/DISK_USAGE.md, docs/STORAGE_DEPLOYMENT_BOUNDARIES.md, README.md.

    5. Questions for the owner

    1. Where to persist the ceiling: top-level field in cameras.json (recommended) or alongside session settings?
    2. Events are matched by camera name and UTC start day. Is it acceptable that two cameras with the same name share that match?
    3. For a day that cannot be fully emptied (a leftover .tmp), skip it and take the next oldest day that has deletable .mp4 files?
    4. After CP5, should existing persisted retention_days: 0 mean "off", or be converted to 7 on load?
    5. Prune check in the existing cleanup tick, or a separate job?

    6. Not verified

    • No tests were run, and no code was built.
    • Not read: main.go beyond search excerpts, handlers.go beyond the retention handler excerpt, auth.go settings code, the web sources, and most test files listed above.
    • Whether the settings UI for retention days lives in modals.js, cameras.js or app.js (all three call the retention API).
  5. mouldybread commented on Nov 28, 2026

    @mouldybread
    OwnerAuthor

    CP3 approved names (owner-approved)

    • Persisted key: top-level max_filesystem_used_percent in cameras.json, beside cameras, camera_order and events. 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.
    • Valid range: whole number from 10 to 95 inclusive. Anything else, including non-integers, is rejected with HTTP 400.
    • Prune trigger: ceiling minus 2 percentage points. It is derived and never stored.
    • Read API: the existing storage status response gains filesystem_used_percent (number, or null when unknown), max_filesystem_used_percent and filesystem_prune_trigger_percent. Existing fields are unchanged.
    • Write API: POST /api/storage/ceiling with {"max_filesystem_used_percent": <int>}. It validates, saves through the existing cameras.json write path, and returns the stored value.
    • Settings UI: a "Filesystem usage" row showing used percent (or "Unknown") and a numeric ceiling input. Opening settings refreshes the display. The per-camera Disk Usage figure is unchanged.
    • Scope: CP3 stores and displays the ceiling only. Nothing is deleted until CP4.

    Implementation is on PR #23.

  6. mouldybread commented on Nov 28, 2026

    @mouldybread
    OwnerAuthor

    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_id query 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/ceiling returns max_filesystem_used_percent, filesystem_prune_trigger_percent, filesystem_used_percent (number, or null when unknown) and filesystem_observed_at (or null). It takes a fresh reading on each request, so settings show current usage even before the monitor's first check. A failed reading yields null rather than an error status, so the ceiling stays visible.
    • POST /api/storage/ceiling is unchanged: {"max_filesystem_used_percent": <int>}, validated 10 to 95, saved through the existing cameras.json write path, and the stored value is returned.
  7. added 4 commits that reference this issue on Nov 28, 2026
  8. added
    run-checkpoint-ci
    and removed
    run-checkpoint-ci
    on Nov 28, 2026
  9. mouldybread commented on Nov 28, 2026

    @mouldybread
    OwnerAuthor

    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.

    Checkpoint Status
    CP1: read-only analysis Complete; findings in the issue discussion
    CP2: filesystem measurement and monitor Complete; initial CI green on 60df3d7
    CP3: ceiling setting and settings display Complete, including the auth integration correction below
    CP4: prune pass Complete, including the log suppression correction below
    CP5: optional maximum age Complete, including the duplicate-input correction below
    CP6: end-to-end acceptance Complete; automated acceptance passed on d86f255fab03936b4a57b7174eb22e8e44743f8d; owner signed off

    Final CI result

    All nine check runs on the exact PR head d86f255fab03936b4a57b7174eb22e8e44743f8d report 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

    • Ceiling POST blocked by auth: the method policy rejected POST /api/storage/ceiling before it reached the handler. Fixed in fd8cbd6 with 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.
    • Retention read the hidden duplicate input: per-camera Update read the hidden list's stale value rather than the edited settings-dialog input. Fixed in f9b1dc2 by preferring the dialog-scoped input, with a frontend regression test.
    • Repeated ceiling-not-met logging: saving an unchanged ceiling reset log suppression. Fixed in d86f255 by 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

    • Measure the filesystem holding /recordings every five minutes, first five minutes after startup; opening settings takes a fresh display reading without requesting pruning.
    • Top-level max_filesystem_used_percent in cameras.json: default 80, whole numbers 10 through 95, written explicitly on save. GET and POST /api/storage/ceiling serve the setting and measurement; the existing per-camera storage-status endpoint is unchanged.
    • Prune at ceiling minus two percentage points: one oldest eligible day per camera per pass, preserving the newest UTC day folder. Only regular .mp4 files in the selected day are candidates. Leftover-only days are silently skipped. Individual unlinks, identity checks, no recursive deletion, empty-directory rmdir only.
    • Exclusive media lease and retention-policy lock order serialize pruning with retention deletion. Recorders are not stopped. .tmp, temp/, buffer/, staging and recovery evidence are preserved.
    • A gain under 1 MiB in available bytes pauses pruning until available space rises by at least 1 MiB from the guard baseline. An unavailable pre-pass measurement means no pruning and a log. The accepted fallback for an unavailable post-pass reading uses the pre-pass baseline. Ceiling changes do not bypass an active pause.
    • Matching event records are removed by camera name and UTC start day for successfully pruned days; partial-failure days keep their events. Ceiling-not-met is log-only.
    • retention_days: 0 means no age limit; 1 through 365 means maximum age. API updates require an explicit retention_days field. Names shared with an age-off camera keep their events from age expiry; orphan cleanup remains. Ceiling pruning still applies when age cleanup is off. New cameras retain the seven-day default; no migration.

    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.

  10. added 2 commits that reference this issue on Nov 29, 2026
  11. mouldybread commented on Nov 29, 2026

    @mouldybread
    OwnerAuthor

    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, so fstatfs reports a real used percentage and real available bytes. The real image runs with that directory bound at /recordings, the same file-fed FFmpeg substitution, and SIMPLENVR_MIN_FREE_BYTES unset. Two cameras are seeded: one with retention_days 7, one with 0. Each has several UTC day folders of dd-generated .mp4 files, 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 from df in 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

    1. Usage below the trigger: POST the current ceiling. Nothing is deleted and no prune line is logged.
    2. Lower the ceiling below usage: one pass removes only the oldest day with .mp4 files 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_recording still true in cameras.json).
    3. Repeat POSTs: one more day per camera per pass, stopping at the newest day. Usage falls below the trigger and later passes do nothing.
    4. No-effect guard on a real filesystem: before a pass, hard-link the oldest day's files to a hold directory on the same volume (this stands in for a snapshot). Deleting the names then frees no space, so the pass logs paused, and further POSTs delete nothing. Remove the hard links; available bytes rise by at least 1 MiB, the next POST logs resumed and prunes.
    5. Partial failure: chattr +i one file in a day. The rest of that day is removed, the run logs incomplete for camera, that day's events are kept, the other camera is still pruned. The script runs chattr -i in cleanup.
    6. A camera with retention_days 0 is still pruned by the ceiling (apart from its newest day); neither camera's recorder is touched.
    7. Clean shutdown: docker stop exits 0 and logs Shutdown complete; recording intent persisted. cameras.json is mode 0600 and contains max_filesystem_used_percent explicitly. 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, send retention_days: 0, and show 0 after 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.md with steps to run on a dataset with a quota and a snapshot: record df and zfs list before; 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 against df. 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

    • A passes on the exact PR head, as a required check, with every scenario above asserted (file existence and hashes, log lines, cameras.json, process presence), not only exit codes.
    • B passes in the isolated Chrome runs.
    • C is run by the owner and the outcome is recorded; CP6 is not marked complete without it, or without the owner explicitly waiving it.
    • All existing required checks stay green.

    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.sh and a small Python helper for the login and assertions, new docs/FILESYSTEM_ACCEPTANCE.md, a new job in the safety workflow wired into the required-checks gate, and an extension of tests/acceptance/runtime-browser-acceptance.py. I have not yet read .github/workflows/safety-ci.yml or 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

    1. Is a loopback ext4 image acceptable as the CI stand-in for the real volume, with hard links standing in for snapshots?
    2. Should the new container acceptance be a required check, like the existing ones?
    3. Do you want the settings-row browser checks added to the existing Chrome acceptance, as proposed?
    4. Will you run section C on the TrueNAS volume, and should CP6 wait for it?
    5. Is excluding the 5-minute tick and age-cleanup timing from CI acceptable, given the unit tests and section C?
  12. added 2 commits that reference this issue on Nov 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions