Skip to content

Add receiver-side TTL cleanup sweep for cold remote-build subtrees (6c) - #559

Merged
J. Nick Koston (bdraco) merged 9 commits into
mainfrom
receiver-cleanup-sweep
May 11, 2026
Merged

J. Nick Koston (bdraco) merged 9 commits into
mainfrom
receiver-cleanup-sweep

Conversation

@bdraco

@bdraco J. Nick Koston (bdraco) commented May 10, 2026 •

Copy link
Copy Markdown
Member

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 / .pio caches 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. No FirmwareJob queue entries are deleted either; on-disk artefacts only.

The asymmetry is by design:

  • Remote-build subtrees are a transient build cache. The submitting offloader has its own canonical .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.
  • Local build subtrees belong to the user's own devices. They might rebuild on a quiet schedule (weekly, monthly), and the local .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/delete flow 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.py built paths via Path operators
  • the prospective sweeper walked iterdir over the same shape
  • the controller's in-flight-key derivation indexed PurePosixPath(...).parts[...] to recover (dashboard_id, device_name) from FirmwareJob.configuration

Drift 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_SUFFIX constants + RemoteBuildPath frozen dataclass (hashable for the sweep's frozenset of in-flight keys) + parse_from_configuration reverse-factory.
  • helpers/remote_build_cleanup.py — sweep_remote_builds synchronous sweep designed to run inside an executor. Walks subtrees, rmtrees the cold ones + their sibling .tar.gz bundles, 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: int field on RemoteBuildSettings (and matching view) with DEFAULT_CLEANUP_TTL_SECONDS=86400, MIN_CLEANUP_TTL_SECONDS=3600, MAX_CLEANUP_TTL_SECONDS=2592000 cap constants the WS validator references.
  • controllers/remote_build/controller.py — set_settings gains an optional cleanup_ttl_seconds kwarg (validated against MIN/MAX with not_bool to prevent True slipping through as int); _run_cleanup_loop async task spawns through the existing _track_task helper on start() so the _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 instead of inline Path operators.

Why directory mtime tracks "last submitted-to"

Upstream esphome.bundle.prepare_bundle_for_compile wipes the subtree contents and re-extracts on every submission, so the subtree's own st_mtime bumps 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 before JOB_STARTED fires) and for the brief gap between a job completing and the next submission.

Tests

  • test_remote_build_layout.py — RemoteBuildPath construction, sibling-not-child bundle invariant, round-trip with parse_from_configuration, and the parse's None-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

  • Frontend exposure of the TTL knob — cleanup_ttl_seconds rides on RemoteBuildSettingsView for 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

  • Bugfix (non-breaking change which fixes an issue) — bugfix
  • New feature (non-breaking change which adds functionality) — new-feature
  • Enhancement to an existing feature — enhancement
  • Breaking change (fix or feature that would cause existing functionality to not work as expected) — breaking-change
  • Refactor (no behaviour change) — refactor
  • Documentation only — docs
  • Maintenance / chore — maintenance
  • CI / workflow change — ci
  • Dependencies bump — dependencies

Frontend coordination

RemoteBuildSettingsView.cleanup_ttl_seconds is 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.

  • No frontend change needed
  • Companion frontend PR: esphome/device-builder-dashboard-frontend#

Checklist

  • The code change is tested and works locally.
  • Pre-commit hooks pass (ruff, codespell, yaml/json/python checks).
  • Tests have been added or updated under tests/ where applicable.
  • components.json has not been hand-edited (regenerate via script/sync_components.py if a sync is needed).
  • Architecture-level changes are reflected in docs/ARCHITECTURE.md and/or docs/API.md.

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.
Copilot AI review requested due to automatic review settings May 10, 2026 23:50
@github-actions github-actions Bot added the new-feature New feature label May 10, 2026
@codspeed

codspeed Bot commented May 10, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 12 untouched benchmarks


Comparing receiver-cleanup-sweep (1ebccc2) with main (cfad65d)

Open in CodSpeed

@codecov-commenter

Codecov Comments Bot (codecov-commenter) commented May 10, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.15%. Comparing base (cfad65d) to head (1ebccc2).

Additional details and impacted files

Impacted file tree graph

@@            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              
Flag Coverage Δ
py3.12 99.12% <100.00%> (+0.01%) ⬆️
py3.14 99.15% <100.00%> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
..._device_builder/controllers/firmware/controller.py 100.00% <100.00%> (ø)
...ice_builder/controllers/remote_build/controller.py 99.72% <100.00%> (+<0.01%) ⬆️
...ice_builder/controllers/remote_build/submit_job.py 100.00% <100.00%> (ø)
...ome_device_builder/helpers/remote_build_cleanup.py 100.00% <100.00%> (ø)
...home_device_builder/helpers/remote_build_layout.py 100.00% <100.00%> (ø)
esphome_device_builder/models/remote_build.py 99.00% <100.00%> (+0.04%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 2 comments.

Comment thread tests/test_remote_build_cleanup.py Resolved
* 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.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 1 comment.

J. Nick Koston (bdraco) and others added 2 commits May 10, 2026 20:03
* 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.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 11 out of 11 changed files in this pull request and generated 1 comment.

@bdraco
J. Nick Koston (bdraco) merged commit a9c197e into main May 11, 2026
13 checks passed
@bdraco
J. Nick Koston (bdraco) deleted the receiver-cleanup-sweep branch May 11, 2026 01:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

new-feature New feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants