Repository navigation
Add receiver-side TTL cleanup sweep for cold remote-build subtrees (6c) - #559
Merged
Merged
Conversation
Closes phase 6c of issue #106. Background sweep over every <config>/.esphome/.remote_builds/<dashboard_id>/<device_name>/ subtree under the receiver's config root; deletes subtrees whose mtime exceeds the operator-configured TTL (default 24h, bounded 1h-30d via the WS validator) AND aren't currently queued or running on the firmware controller. Without this, per-peer per-device subtrees accumulate forever for offloaders that pair once and never come back -- the .pioenvs / .esphome / .pio caches inside each subtree are tens of MiB per device, so even a small fleet chews through receiver disk over months. Single source of truth for the on-disk shape lives in the new helpers/remote_build_layout.py module. Forward construction (RemoteBuildPath.subtree / .bundle) and reverse parse (parse_from_configuration on FirmwareJob.configuration) both flow through the same dataclass. submit_job.py, the cleanup module, and the controller's cleanup loop all import from there -- previously the layout was implicit at three sites (writer's Path operators, sweeper's iterdir walk, controller's parts[...] index chain), with drift between them silently breaking the sweep. Pieces: * helpers/remote_build_layout.py: REMOTE_BUILDS_SUBDIR / BUNDLE_SUFFIX constants + RemoteBuildPath frozen dataclass + parse_from_configuration reverse-factory. * helpers/remote_build_cleanup.py: sweep_remote_builds synchronous sweep (designed for executor). Walks subtrees, rmtrees the cold ones + their sibling .tar.gz bundles, prunes empty dashboard_id parents, best-effort against per-subtree exceptions. * models/remote_build.py: cleanup_ttl_seconds field on RemoteBuildSettings + the matching view, plus DEFAULT / MIN / MAX cap constants the WS validator references. * controllers/remote_build/controller.py: set_settings gains an optional cleanup_ttl_seconds kwarg (validated against MIN/MAX); _run_cleanup_loop spawns through _track_task on start() so the existing _tasks cancel-and-gather in stop() reaps it on shutdown. * controllers/remote_build/submit_job.py: now uses RemoteBuildPath.subtree / .bundle for the writer paths. Tests: test_remote_build_layout.py and test_remote_build_cleanup.py cover RemoteBuildPath round-trip and the sweep's full decision tree. Drive-by: removed a pointless ``except CancelledError: raise`` from the cleanup loop; CancelledError inherits from BaseException so the surrounding ``except Exception`` doesn't swallow it.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #559 +/- ##
==========================================
+ Coverage 99.13% 99.15% +0.01%
==========================================
Files 78 80 +2
Lines 10219 10378 +159
==========================================
+ Hits 10131 10290 +159
Misses 88 88
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
Contributor
There was a problem hiding this comment.
Pull request overview
Implements receiver-side disk hygiene for remote-build by adding a periodic TTL-based sweep that deletes cold per-peer/per-device build subtrees under .esphome/.remote_builds/, while avoiding deletion of subtrees that are currently queued/running.
Changes:
- Added a single source of truth for receiver remote-build on-disk layout (
RemoteBuildPath+ reverse-parse helper). - Implemented a TTL cleanup sweep helper and wired it into the receiver controller as a tracked background task.
- Extended remote-build settings and wire view with
cleanup_ttl_seconds(default + bounds), and updated submit-job path construction to use the shared layout helper.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| tests/test_remote_build_layout.py | Adds unit tests for forward path construction and reverse parsing of remote-build layout. |
| tests/test_remote_build_cleanup.py | Adds unit tests covering cleanup sweep decision logic and error isolation. |
| esphome_device_builder/models/remote_build.py | Adds TTL constants and cleanup_ttl_seconds to settings + view. |
| esphome_device_builder/helpers/remote_build_layout.py | Introduces canonical remote-build disk layout definitions and parsing. |
| esphome_device_builder/helpers/remote_build_cleanup.py | Implements synchronous TTL sweep that deletes cold subtrees and prunes empty parents. |
| esphome_device_builder/controllers/remote_build/submit_job.py | Switches submit-job writer paths to use RemoteBuildPath layout helper. |
| esphome_device_builder/controllers/remote_build/controller.py | Adds periodic cleanup loop task and settings validation for TTL updates. |
* helpers/remote_build_cleanup.py: the orphan-bundle helper comment claimed "we don't want to treat a symlink as 'subtree present'", but the code's ``return`` does exactly that. Reworded to match the code: any symlink at the sibling position is treated as "not an orphan we should reclaim". Safe stance because the canonical writer never creates symlinks under the remote-builds root, so an operator-or-attacker-placed symlink is outside our trust scope — leak the tarball rather than make a delete decision off a path we don't control. * tests/test_remote_build_cleanup.py: the dashboard-level symlink test's comment hedged "may or may not be removed by rmdir parent-prune". The sweep ``continue``s before reaching ``_prune_empty_dir`` for symlink dashboard entries, so the symlink definitely stays. Reworded to match, and added an explicit ``link.is_symlink()`` assertion so the surviving symlink is part of the test contract.
helpers/remote_build_cleanup.py to 100%: * test_safe_iterdir_returns_empty_on_oserror — calls the helper directly with a MagicMock Path whose iterdir side_effects PermissionError. * test_is_cold_returns_false_on_stat_error — same shape for the stat-fails arm. * test_sweep_logs_sibling_unlink_failure_but_still_counts_delete — monkeypatches Path.unlink to raise on the bundle path only; pins the docstring contract that the subtree is the load-bearing reclamation. * test_sweep_logs_orphan_unlink_failure — same pattern for the orphan branch. controller.py cleanup loop body: * test_run_cleanup_loop_reclaims_cold_subtree_and_skips_in_flight drives one cycle through patched asyncio.sleep + verifies a cold subtree is reclaimed AND an in-flight subtree (whose FirmwareJob is QUEUED/RUNNING with the matching layout-parse path) is left alone. * test_run_cleanup_loop_logs_per_cycle_exception_and_continues pins the except-Exception arm: sweep raising on the first cycle doesn't kill the loop; the second cycle runs. * test_run_cleanup_loop_short_circuits_when_firmware_missing pins the defense-in-depth firmware-None re-check inside the loop body. controller.py set_settings cleanup_ttl_seconds: * test_set_settings_round_trips_cleanup_ttl — happy path. * test_set_settings_rejects_non_int_cleanup_ttl — parametrized bool / str / float values. * test_set_settings_rejects_out_of_range_cleanup_ttl — parametrized 0 / sub-MIN / past-MAX / negative. 2912 tests pass; mypy clean.
* On-disk validation of cleanup_ttl_seconds (Copilot). The WS validator on set_settings gates write-through-WS, but the on-disk decode path didn't apply the same not_bool / range check. A sidecar with cleanup_ttl_seconds: true would deserialise as 1 (bool is an int subclass) and the sweep would treat anything older than 1s as cold. Other wrong types (string, float, None) would propagate to the sweep's now - ttl_seconds arithmetic and raise TypeError every cycle. New __post_init__ on RemoteBuildSettings coerces non-int / bool back to DEFAULT_CLEANUP_TTL_SECONDS and clamps the result to [MIN, MAX]. Doesn't reject the row (no ValueError) — the load path stays robust against partially-corrupt sidecars; the operator's last-good enabled toggle survives even if the TTL field is broken. Six new tests in test_config_controller.py pin the coerce-to-default branches, the clamp-to-MIN / clamp-to-MAX branches, and the pass-through-on-valid branch. * Public seam on FirmwareController for in-flight remote-peer jobs (reviewer concern #1). Reaching into firmware._jobs from the cleanup loop coupled the two controllers to the private dict shape — a future refactor (lock-wrapped jobs, QUEUED + RUNNING split into two dicts, indexed view) would silently break this loop. New FirmwareController.active_remote_peer_jobs generator filters to QUEUED / RUNNING + non-empty remote_peer. The cleanup loop now consumes through that seam. Two new tests pin every filter branch (local skip, remote queued / running yielded, remote completed skipped, empty case). * Named constant for the parse_from_configuration tail-segment count (reviewer nit). The +3 magic was folklore; replaced with _TAIL_SEGMENT_COUNT and a docstring explaining the three required tail parts (dashboard_id, device_name, YAML filename under the device subtree). Reviewer concern #2 (RAM-canonical settings) and #4 (rate-limit per cycle) deferred per their "worth a small follow-up" framing. Concern #3 (first-sweep latency) was considered but YAGNI for this PR: the receiver-side cleanup ships ahead of any production user (alpha, ~10 beta testers), so no accumulated subtrees exist before this code's first cycle — and the default 24h TTL means even a fresh receiver has nothing to reclaim for the first day regardless.
4 of 13 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What does this implement/fix?
Phase 6c of issue #106. Receiver-side TTL cleanup sweep for cold remote-build subtrees.
Background sweep over every
<config>/.esphome/.remote_builds/<dashboard_id>/<device_name>/subtree the receiver writes; deletes subtrees whose mtime exceeds the operator-configured TTL (default 24h, bounded 1h-30d via the WS validator) AND aren't currently queued or running on the firmware controller. Without this, per-peer per-device subtrees accumulate forever for offloaders that pair once and never come back — the.pioenvs/.esphome/.piocaches inside each subtree are tens of MiB per device, so even a small fleet chews through receiver disk over months.Scope: only remote-build subtrees, NOT local build dirs
This sweep only reclaims
<config>/.esphome/.remote_builds/<dashboard_id>/<device_name>/subtrees — the per-peer-per-device caches the receiver writes when another dashboard submits a remote-build job. Local build dirs at<config>/.esphome/build/<device_name>/are intentionally NOT touched. NoFirmwareJobqueue entries are deleted either; on-disk artefacts only.The asymmetry is by design:
.esphome/build/<device>/tree on its filesystem; the receiver's cache exists only to keep PlatformIO's incremental-compile cache warm between submissions from that offloader. If the offloader stops sending (unpaired, retired, simply doesn't rebuild that device anymore), the receiver's cache is wasted disk..esphome/build/<device>/tree IS where PIO's incremental cache lives for the primary devices the operator manages. Sweeping that aggressively would force cold rebuilds (multi-minute → hours per device) — a regression, not hygiene.A future "stop holding state for devices I no longer build locally" surface (closer to the existing
devices/deleteflow than to a TTL sweep) would be a separate concern.Single source of truth for the on-disk shape
helpers/remote_build_layout.py(new) is the only place that encodes the receiver-side path layout. Forward construction (RemoteBuildPath.subtree(config_dir)/RemoteBuildPath.bundle(config_dir)) and reverse parse (parse_from_configuration(job.configuration) -> RemoteBuildPath | None) both flow through one dataclass.submit_job.py, the cleanup sweeper, and the controller's cleanup loop all import from there.Before this PR the layout was implicit at three sites:
submit_job.pybuilt paths viaPathoperatorsiterdirover the same shapePurePosixPath(...).parts[...]to recover(dashboard_id, device_name)fromFirmwareJob.configurationDrift between them would have silently broken the sweep (deleting a subtree that's still in-flight) or the writer (writing to a path the sweep doesn't recognise). Consolidating means the shape lives in exactly one file: change it here once, every consumer follows.
Pieces
helpers/remote_build_layout.py—REMOTE_BUILDS_SUBDIR/BUNDLE_SUFFIXconstants +RemoteBuildPathfrozen dataclass (hashable for the sweep'sfrozensetof in-flight keys) +parse_from_configurationreverse-factory.helpers/remote_build_cleanup.py—sweep_remote_buildssynchronous sweep designed to run inside an executor. Walks subtrees,rmtrees the cold ones + their sibling.tar.gzbundles, prunes empty<dashboard_id>/parents, best-effort against per-subtree exceptions (permission denied / race against a concurrent submit / broken symlinks).models/remote_build.py—cleanup_ttl_seconds: intfield onRemoteBuildSettings(and matching view) withDEFAULT_CLEANUP_TTL_SECONDS=86400,MIN_CLEANUP_TTL_SECONDS=3600,MAX_CLEANUP_TTL_SECONDS=2592000cap constants the WS validator references.controllers/remote_build/controller.py—set_settingsgains an optionalcleanup_ttl_secondskwarg (validated against MIN/MAX withnot_boolto preventTrueslipping through as int);_run_cleanup_loopasync task spawns through the existing_track_taskhelper onstart()so the_taskscancel-and-gather instop()reaps it on shutdown.controllers/remote_build/submit_job.py— now usesRemoteBuildPath.subtree/.bundlefor the writer paths instead of inline Path operators.Why directory mtime tracks "last submitted-to"
Upstream
esphome.bundle.prepare_bundle_for_compilewipes the subtree contents and re-extracts on every submission, so the subtree's ownst_mtimebumps each time. Compile output writing under the subtree (PIO build cache in.pioenvs/) also bumps the parent's mtime through the same syscall path, so a running compile keeps its subtree warm before the next submit even lands. The in-flight gate is still load-bearing for the QUEUED case (waiting in the queue beforeJOB_STARTEDfires) and for the brief gap between a job completing and the next submission.Tests
test_remote_build_layout.py—RemoteBuildPathconstruction, sibling-not-child bundle invariant, round-trip withparse_from_configuration, and the parse'sNone-on-malformed branches (locally-submitted job, non-remote-builds subdir, missing segment, 4-segment-too-short, empty string).test_remote_build_cleanup.py— sweep's full decision tree: empty root no-op, cold delete, fresh keep, in-flight skip, empty-parent prune, multi-dashboard walk, stray-file ignore,rmtree-failure isolation.2890 tests pass.
What's not in this PR
cleanup_ttl_secondsrides onRemoteBuildSettingsViewfor consumption when the receiver-side Settings UI grows the input. The wire shape is additive (existing clients ignore the unknown key).Related issue or feature (if applicable):
Types of changes
bugfixnew-featureenhancementbreaking-changerefactordocsmaintenancecidependenciesFrontend coordination
RemoteBuildSettingsView.cleanup_ttl_secondsis additive on the wire; existing clients ignore the unknown key. A future frontend PR can surface the input on the receiver-side Settings UI without a coordinated lockstep with this one.Checklist
ruff,codespell, yaml/json/python checks).tests/where applicable.components.jsonhas not been hand-edited (regenerate viascript/sync_components.pyif a sync is needed).docs/ARCHITECTURE.mdand/ordocs/API.md.