Repository navigation
Phase 5c-3: offloader-side submit_job + output stream - #540
Merged
Merged
Conversation
Adds the WS command, sender, and receive-loop dispatch for the offloader half of the peer-link submit_job flow. Pairs with the receiver-side accept path landed in 5c-2. Backend surface: * `remote_build/submit_job` WS command on the offloader. Validates pin / target / configuration (path-traversal via `rel_path`), resolves an open `PeerLinkClient`, builds the bundle, drives the wire flow, returns the receiver's ack shape. Typed CommandError surface: INVALID_ARGS for shape errors, NOT_FOUND for unknown pairings or missing YAML, PRECONDITION_FAILED for not-yet-approved or disconnected pairings, UNAVAILABLE for ack timeout / session loss. * `PeerLinkClient.submit_job(...)` — async sender that registers a per-job_id ack future, sends the header + every chunk via the live `PeerLinkChannel`, and awaits the receiver's `submit_job_ack` with a 60s timeout. No mid-session retry: the receiver may already have queued the job, and a duplicate send under a fresh `job_id` would land a second `FirmwareJob` on the receiver. * Receive-loop additions: `submit_job_ack` resolves the matching ack future; `job_state_changed` / `job_output` validate frame shape and fire `OFFLOADER_JOB_STATE_CHANGED` / `OFFLOADER_JOB_OUTPUT` bus events tagged with the receiver's coords. The four sync frame branches now flow through a per-session lookup table built once in `_run_session_loops`. * Session-end sweep: any in-flight ack futures get `set_exception(SubmitJobSessionLostError)` from the receive loop's `finally`, so a `submit_job` caller doesn't hang on the timeout when the wire is gone. Helpers: * New `helpers/peer_link_frames.py` with `validate_frame_shape` — extracted from `submit_job._validate_frame_shape` so both the receiver-side accept handlers and the offloader-side receive-loop dispatch share one implementation. * New `helpers/config_bundle.py` with `build_yaml_bundle` — wraps `read_config` + `ConfigBundleCreator` behind a process-wide `asyncio.Lock` (CORE.config_path / CORE.config are global and need serialised access), saves + restores CORE state in a `finally`. Models: * `EventType.OFFLOADER_JOB_STATE_CHANGED` / `OFFLOADER_JOB_OUTPUT` enum members; auto-broadcast by `subscribe_events`'s existing event-type filter. * `OffloaderJobStateChangedData` / `OffloaderJobOutputData` TypedDict payloads — wire frame fields plus `(receiver_hostname, receiver_port, pin_sha256)` so subscribers can disambiguate transitions across paired receivers. Internal: * `_peer_link_clients` upgraded from `dict[str, asyncio.Task]` to `dict[str, _PeerLinkClientHandle]` (`(client, task)` pair) so the WS command can reach `client.submit_job` without a parallel client-only dict. * `submit_job` body broken into `_require_open_channel` / `_register_submit_job_ack_future` / `_send_submit_job_frames` / `_await_submit_job_ack` helpers. Tests: * 19 new tests covering the new dispatch branches (state / output / ack / session-loss drain), the sender's happy / timeout / duplicate / no-session paths, the WS command's typed error mapping, and an integration-style path-traversal gate using `make_settings` with a real `DashboardSettings`. * `tests/test_peer_link_frames.py` covers the extracted validator's bool-vs-int special case. * `tests/test_config_bundle.py` covers the helper's CORE save/restore around success and failure paths.
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #540 +/- ##
==========================================
- Coverage 99.17% 99.07% -0.11%
==========================================
Files 72 74 +2
Lines 9128 9471 +343
==========================================
+ Hits 9053 9383 +330
- Misses 75 88 +13
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
Adds the offloader-side implementation of the peer-link submit_job flow: bundling a YAML + referenced assets, streaming the bundle to a paired receiver, awaiting a typed submit_job_ack, and re-broadcasting receiver-driven job lifecycle/output frames onto the offloader event bus for subscribe_events.
Changes:
- Introduces
remote_build/submit_jobWS command on the offloader, including input gating + typed error mapping and per-peer client lookup. - Extends
PeerLinkClientwithsubmit_job(...), inbound dispatch forsubmit_job_ack/job_state_changed/job_output, and session-end draining of in-flight ack futures. - Extracts shared wire-frame shape validation and adds a CORE-safe bundle-build helper (plus new unit tests).
Reviewed changes
Copilot reviewed 10 out of 10 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/test_remote_build_peer_link_client.py | Updates peer-link client task handle expectations and adds submit/ack/state/output coverage for 5c-3. |
| tests/test_peer_link_frames.py | Adds unit tests for the extracted shared frame-shape validator. |
| tests/test_config_bundle.py | Adds unit tests for the new YAML→bundle helper, including CORE save/restore on success/failure. |
| esphome_device_builder/models/remote_build.py | Adds TypedDict payloads for offloader job state/output bus events. |
| esphome_device_builder/models/common.py | Adds new EventType members for offloader job state/output streaming. |
| esphome_device_builder/helpers/peer_link_frames.py | Introduces shared validate_frame_shape(...) helper for peer-controlled frame dicts. |
| esphome_device_builder/helpers/config_bundle.py | Adds build_yaml_bundle(...) with executor hop, CORE save/restore, and serialization lock. |
| esphome_device_builder/controllers/remote_build/submit_job.py | Switches receiver-side submit handlers to use the shared validate_frame_shape. |
| esphome_device_builder/controllers/remote_build/peer_link_client.py | Adds submit-job sender, inbound ack/state/output dispatch, and session-loss draining for ack futures. |
| esphome_device_builder/controllers/remote_build/controller.py | Adds _PeerLinkClientHandle storage and implements remote_build/submit_job WS command + validation/bundling/dispatch. |
Tightens four branchy spots that drifted toward duplication across the 5c-3 changes, plus the missing patch-coverage lines codecov flagged. DRY: * `_dispatch_queue_status` now goes through `validate_frame_shape` with a `_QUEUE_STATUS_FIELDS` map — same shape the other three sync dispatchers already use. The bool-vs-int special case lives in the shared validator. * `_dispatch_submit_job_ack`'s two debug-and-return branches (no future / future done) collapse into one — same recovery for either case (the awaiter timed out or never registered), the distinguishing detail goes in the log line as flags. * New `_log_malformed(frame_type, parsed)` helper centralises the four dispatchers' identical "malformed X frame from Y:Z" debug calls. * `_lookup_open_peer_link_client` collapses the three "not connected" raises into one — all three were PRECONDITION_FAILED with substantially the same message; the user's recovery is identical, the distinguishing detail (not_spawned / orphaned / disconnected) lives in the message text. * `_build_submit_job_bundle` drops the broad `except Exception` catch-all — the WS dispatcher already surfaces unhandled exceptions as INTERNAL_ERROR, so the catch-all was redundant. Coverage: * New tests for the `_dispatch_submit_job_ack` malformed-frame / no-pending-future / already-done-future branches. * New tests for `_dispatch_job_output` malformed-frame / invalid-stream-literal branches. * New tests for the WS command's `EsphomeError` → INVALID_ARGS, `FileNotFoundError` → NOT_FOUND, and the three sub-branches of `_lookup_open_peer_link_client` (orphaned / session-not-connected / no-session-during-send). * New `test_config_bundle` test covering `read_config returning None → RuntimeError`. After: peer_link_client.py at 99% (3 pre-existing lines), config_bundle.py at 100%, controller.py new lines at 100%.
* Defer `build_yaml_bundle` import into `_build_submit_job_bundle` alongside the existing `EsphomeError` lazy import. Pulls the esphome.bundle / esphome.config import cost off the controller-module import path so dashboards that never offload a build don't pay for it. Tests updated to monkeypatch through the helper module path. * `test_run_session_loops_finally_drains_pending_submit_acks` now monkeypatches `run_peer_link_heartbeat` to its `_idle_heartbeat` stub instead of leaving the inner function defined-but-unused — the intent matches the other tests in this file that disable the heartbeat for a deterministic close path.
Replaces the in-process `ConfigBundleCreator` + `read_config` calls with a subprocess invocation of `esphome bundle <yaml> -o <tmp.tar.gz>`. The CLI subcommand is part of the upstream user-facing contract and shifts much less between releases than the internal `read_config` / `CORE.config_path` / `ConfigBundleCreator` surface this PR was originally coupling to. It also matches the existing firmware-controller pattern (every compile / upload already spawns `esphome` as a subprocess), so a future ESPHome bump only has to be validated against one integration surface. Side effects: * Dropped the process-wide `asyncio.Lock` and the CORE save/restore dance — subprocess has its own CORE, no global mutation to guard. * `BundleBuildError(message, *, output)` replaces the `EsphomeError` mapping: non-zero exit on the subprocess surfaces the captured stdout/stderr verbatim. WS layer maps to `CommandError(INVALID_ARGS)` with the output inlined so the user sees the validator's diagnostic. * 60s timeout guards the subprocess.communicate() — a wedged esphome can't pin the offloader's submit handler forever. * Tests rewritten to fake `create_subprocess_exec` rather than patch `read_config` / `ConfigBundleCreator`. Addresses @bdraco PR review comment on PR #540 suggesting the CLI for stability.
Three rounds of duplication folding across the PR: Production code: * New `helpers.subprocess.run_subprocess_capture(*args, timeout)` collapses the "spawn + communicate-with-timeout + kill-on-overrun + decode stdout" shape. Used by both `helpers.config_bundle.build_yaml_bundle` (new in this PR) and the existing `_verify_esphome_importable` startup probe. Returns a `CapturedSubprocess` dataclass (`returncode`, `stdout`, `timed_out`); callers branch on the flag rather than handling a `TimeoutError`. Drops the duplicate spawn / wait_for / kill_quietly / decode chain at both call sites. * `kill_quietly` moves from `helpers.process` to `helpers.subprocess` so `run_subprocess_capture` can reference it without the circular import (`process.py` already imported `create_subprocess_exec` from `subprocess.py`). `helpers.process` re-exports it via `__all__` so existing call sites keep working. * `build_yaml_bundle` runs all filesystem syscalls (`is_file` → `os.stat`, `NamedTemporaryFile` → `os.open`, `read_bytes`, `unlink`) through `run_in_executor`. blockbuster (Linux CI) caught the `is_file()` direct call as a blocking syscall on the event loop; the rest are guarded for the same reason. Test scaffolding: * New `_DeliverFramesWs(_ParkingWs)` consolidates the ~6 single-frame-then-park WS subclasses (`_StateWs`, `_OutputWs`, `_AckWs`, `_BadWs`, `_QueueStatusWs`, `_BadQueueStatusWs` etc.). Takes a list of plaintext frame dicts + a responder session; encrypts and delivers each on consecutive `__anext__` calls. * New `_make_offloader_client(bus, **overrides)` factory. The 8-line `PeerLinkClient(receiver_hostname=..., receiver_port=..., identity_priv=secrets.token_bytes(32), ...)` block was repeated ~10 times in the 5c-3 tests; all call sites now use the factory. * New `_drive_session_with_frames(client, monkeypatch, frames)` async context manager folds the receive-loop scaffolding (Noise pair, `_DeliverFramesWs`, stubbed heartbeat, drive task, deterministic close on exit). Every 5c-3 dispatcher test was ~30 lines of identical setup before; now it's ~5 lines of test-specific state + the `async with` block. Verification: * All 2663 non-pre-existing-failure tests pass locally. * mypy clean; ruff + format clean. * Blockbuster compatibility verified — the `is_file()` / `read_bytes()` / `unlink()` calls all stage through `run_in_executor` now.
Three fixes from the latest Copilot pass: * `_dispatch_submit_job_ack` only copies `reason` through when `accepted=False`. `SubmitJobAckFrameData.reason` is `NotRequired` and means "rejection code on negative ack"; the previous shape would have propagated a spurious `reason` on a positive ack if the receiver ever included one off-contract. Now drops + debug-logs the stray field instead. * `_send_submit_job_frames` streams chunks via `chunk_bundle`'s generator instead of materialising the full list up front. `num_chunks` is computed via integer ceil on `total_bundle_bytes` so the header still announces the exact count without holding every slice alive simultaneously. Cuts peak memory roughly in half on the bundle hot path (up to `BUNDLE_MAX_TOTAL_BYTES`, 4 MiB). * `_validate_submit_job_config` now returns `(name, yaml_path)` so the downstream `_build_submit_job_bundle` reuses the already-resolved `Path` instead of calling `rel_path` again. Drops a duplicate blocking `Path.resolve` syscall on every submit.
CI was failing because `_find_esphome_cmd()` (which does `Path.exists()`) ran on the event loop inside `build_yaml_bundle`. Blockbuster on Linux CI catches every `os.stat` reaching the loop. Batched all the upfront blocking syscalls (`yaml_path.is_file()`, `_find_esphome_cmd()`, `NamedTemporaryFile`) into one new `_prepare_build_bundle` sync helper invoked via `loop.run_in_executor` so the dashboard's other tasks keep moving on slow disks. Read-back + unlink stage through their own executor hops. Plus two CancelledError fixes — both from the same "never suppress CancelledError" rule (now memorialised in `feedback_no_suppress_cancelled_error.md`): * `peer_link_client.py:_run_session_loops` was draining the heartbeat task with `with suppress(CancelledError): await task` — swallows the outer signal if a second cancellation arrives during the drain. Switched to `asyncio.gather(heartbeat_task, return_exceptions=True)`, which captures the CancelledError into the result list without breaking outer-scope propagation. * `helpers.subprocess.run_subprocess_capture` now handles CancelledError correctly: `kill_quietly(proc)` then bare `raise`. Previously suppressed CancelledError around a shielded `proc.wait()` — same violation. The SIGKILL'd subprocess is reaped by asyncio's child watcher; awaiting its `wait()` during cleanup would either suppress the second cancel or stall propagation. Plus docstring fixes on `RemoteBuildController.submit_job`'s WS-command docstring — it was still describing the in-process `ConfigBundleCreator` + `CORE` mutation + process-wide lock approach that was replaced with the subprocess CLI in an earlier commit. Addresses Copilot review: - pulls/comments/3215324659 (subprocess cancellation) - pulls/comments/3215324681 (stale ConfigBundleCreator docstring) - pulls/comments/3215324692 (stale in-process / CORE lock docstring)
The `_install_fake_subprocess` fake materialised the expected bundle bytes via `output_path.write_bytes(output_bytes)` synchronously inside its async body. Blockbuster on Linux CI walks the frame stack and triggers when `esphome_device_builder` is anywhere upwards — and `build_yaml_bundle` was awaiting the fake, so the call chain had the dashboard module in scope. Real production: the bundle bytes are written by the actual `esphome bundle` subprocess, not on the event loop, so the fake has to mirror that by deferring its write to a worker thread. `await asyncio.to_thread(output_path.write_bytes, output_bytes)` matches the production no-event-loop-block contract.
Closes the late-subscriber gap on the offloader side per the project rule "stateful lists ship through subscribe_events": without this cache, a tab that subscribes AFTER a remote job transitioned to ``running`` doesn't see it at all until the next event arrives. Mirror of the existing ``_peer_queue_status`` cache pattern: * New ``OffloaderRemoteJobSnapshotEntry`` TypedDict (the wire ``OffloaderJobStateChangedData`` minus the framing fields that are constant per cache). * New ``_offloader_remote_jobs: dict[str, ...]`` on the controller keyed on offloader-local ``job_id``. * New ``_on_offloader_job_state_changed`` listener wired in ``start`` via the existing ``_listeners`` ExitStack — upserts on non-terminal status, drops on terminal so the snapshot only ever carries actively-running rows. * New ``offloader_remote_jobs_snapshot()`` sync read seeded into ``subscribe_events.initial_state.remote_jobs``. * ``unpair`` drops in-flight entries for the unpaired pin so the snapshot doesn't surface phantom-running jobs after the peer-link client is torn down. * ``stop`` clears the dict alongside the rest of the in-memory state. Five new tests covering: cache populated on running event, cache dropped on each terminal status (parametrised over ``completed`` / ``failed`` / ``cancelled``), cache survives events for other pins on unpair.
* `docs/API.md` gains a row in the remote-build WS commands table for `remote_build/submit_job` (args, response shape, typed error surface, links to the bundle subprocess + peer-link plumbing). * `docs/API.md` events list gains the three offloader-side events we'd been firing without documenting: `offloader_queue_status_changed` (5b — backfilled), `offloader_job_state_changed` (5c-3, with `_offloader_remote_jobs` cache + initial_state seed contract), and `offloader_job_output` (5c-3, high-rate live stream, no cache). * `docs/ARCHITECTURE.md`'s peer-link "Bring-up" section's offloader bullet gains a one-liner on what the dispatch loop handles (queue_status, submit_job_ack, job_state_changed, job_output) so the architecture overview stays in sync with the actual wire surface.
Adds a "Peer-link application messages" table to `docs/API.md`'s "Peer-link Noise WS receiver site" section covering every `AppMessageType` member: `ping`, `pong`, `terminate`, `queue_status`, `submit_job`, `submit_job_chunk`, `submit_job_ack`, `job_state_changed`, `job_output`. Each row carries direction, payload shape, phase, and one-paragraph contract (heartbeat cadence, backpressure / send-lock semantics, ack timeout behaviour, chunk-order guarantees, terminator-preservation contract on job_output, etc.). Also expands `subscribe_events.initial_state` shape to mention `peer_queue_status` (5b — backfilled) and `remote_jobs` (5c-3 — new this PR) with their semantics + drop-on-terminal contract.
This was referenced May 10, 2026
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 5c-3 of issue #106. Adds the offloader-side half of the peer-link
submit_jobflow — the actual build dispatch over the persistent peer-link, paired with the receiver-side accept path landed in 5c-2.The offloader can now:
compile/uploadtarget via the newremote_build/submit_jobWS command.esphome.bundle.ConfigBundleCreator.submit_jobheader and stream the bundle assubmit_job_chunkframes over the live peer-link Noise session.submit_job_ackand surface the response (or typed errors) to the WS caller.job_state_changed/job_outputframes as the build runs and re-broadcast them asOFFLOADER_JOB_STATE_CHANGED/OFFLOADER_JOB_OUTPUTbus events through the existingsubscribe_eventsstream.UI rendering of the streamed events is deferred to a later frontend chunk; this PR is the backend foundation it lands against.
Backend surface:
remote_build/submit_jobWS command on the offloader. TypedCommandErrorsurface:INVALID_ARGSfor shape errors (pin / target / empty configuration),NOT_FOUNDfor unknown pairings or missing YAML,PRECONDITION_FAILEDfor not-yet-approved or disconnected pairings,UNAVAILABLEfor ack timeout / session loss.PeerLinkClient.submit_job(...)async sender — registers a per-job_idack future before the header goes out, drives the chunk loop throughPeerLinkChannel.send_frame, awaits the ack with a 60s timeout. No mid-session retry — the receiver may already have queued the job under thatjob_id, and a duplicate send under a fresh id would land a secondFirmwareJob. Operator-initiated retry on a fresh session is the correct recovery.submit_job_ackresolves the matching ack future;job_state_changed/job_outputvalidate frame shape and fire bus events tagged with(receiver_hostname, receiver_port, pin_sha256)so subscribers can disambiguate transitions across multiple paired receivers. The four sync frame branches now flow through a per-session lookup table built once in_run_session_loopsrather than a chain ofif msg_type == ...branches.set_exception(SubmitJobSessionLostError)from the receive loop'sfinallyso asubmit_jobcaller doesn't hang on the timeout when the wire is already gone.Helpers (extracted for DRY):
helpers/peer_link_frames.py—validate_frame_shapeextracted fromsubmit_job._validate_frame_shapeso both the receiver-side accept handlers (existing 5c-2) and the offloader-side receive-loop dispatch share one implementation. Bool-vs-int special case preserved.helpers/config_bundle.py—build_yaml_bundle(yaml_path)wrapsread_config+ConfigBundleCreatorbehind a process-wideasyncio.Lock(CORE.config_path / CORE.config are global; concurrent calls would race the global). CORE state is saved + restored in afinallyso downstream CORE-dependent helpers (ext_storage_path,read_build_info_hash) see the dashboard layout again after a build.Models:
EventType.OFFLOADER_JOB_STATE_CHANGED/EventType.OFFLOADER_JOB_OUTPUTenum members. Auto-broadcast bysubscribe_events's existing event-type filter ([et for et in EventType if et is not DEVICE_REACHABILITY]) — no change to the dispatcher.OffloaderJobStateChangedData/OffloaderJobOutputDataTypedDict payloads — wire frame fields plus the receiver's coords.SubmitJobNoSessionError/SubmitJobTimeoutError/SubmitJobSessionLostErrorexception types inpeer_link_client. The WS layer maps them to typedCommandErrorresponses.Internal change:
_peer_link_clientsupgraded fromdict[str, asyncio.Task]todict[str, _PeerLinkClientHandle]((client, task)pair) so the WS command can reachclient.submit_jobwithout a parallel client-only dict that could drift. Test sites updated to access.task.DRY notes:
submit_jobbody broken out of one big method into_require_open_channel/_register_submit_job_ack_future/_send_submit_job_frames/_await_submit_job_ack— the public method is now the single-flight orchestrator parenting four named steps.submit_job._validate_frame_shapeextracted tohelpers/peer_link_frames.py:validate_frame_shapeso the receiver and the offloader share one validator.Tests:
DashboardSettings(the existing_make_offloader_controlleruses aMagicMockSettings, which silently no-opsrel_path— the new test usesmake_settingsto confirm the production gate actually rejects../etc/passwd).tests/test_peer_link_frames.pycovers the extracted validator's bool-vs-int special case + missing-field rejection.tests/test_config_bundle.pycovers the helper's CORE save/restore on success and failure paths.Verification:
test_device_yaml.pyfailures excluded — unrelated, fail onorigin/main).Related issue or feature (if applicable):
Types of changes
bugfixnew-featureenhancementbreaking-changerefactordocsmaintenancecidependenciesFrontend coordination
(Frontend will gain a
remote_build/submit_jobcall and event handlers forOFFLOADER_JOB_STATE_CHANGED/OFFLOADER_JOB_OUTPUTin a follow-up frontend chunk; backend is shipping ahead so the wire is ready when the UI lands.)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.(Architecture docs reference the peer-link layers conceptually; the new frame types live in
models/remote_build.pynext to the existingsubmit_job_*TypedDicts that 5c-1 added, which is wheredocs/API.md's "Peer-link wire frames" section already points. A follow-up doc pass after the frontend chunk lands will round outdocs/API.md's WS-command catalogue with the newremote_build/submit_jobentry.)