Skip to content

Phase 5c-3: offloader-side submit_job + output stream - #540

Merged
J. Nick Koston (bdraco) merged 11 commits into
mainfrom
5c-3-offloader-submit-job
May 10, 2026
Merged

J. Nick Koston (bdraco) merged 11 commits into
mainfrom
5c-3-offloader-submit-job

Conversation

@bdraco

Copy link
Copy Markdown
Member

What does this implement/fix?

Phase 5c-3 of issue #106. Adds the offloader-side half of the peer-link submit_job flow — the actual build dispatch over the persistent peer-link, paired with the receiver-side accept path landed in 5c-2.

The offloader can now:

  1. Take a YAML filename + compile/upload target via the new remote_build/submit_job WS command.
  2. Bundle the YAML + every referenced file (includes, secrets, fonts, images) via esphome.bundle.ConfigBundleCreator.
  3. Send the submit_job header and stream the bundle as submit_job_chunk frames over the live peer-link Noise session.
  4. Await the receiver's submit_job_ack and surface the response (or typed errors) to the WS caller.
  5. Receive job_state_changed / job_output frames as the build runs and re-broadcast them as OFFLOADER_JOB_STATE_CHANGED / OFFLOADER_JOB_OUTPUT bus events through the existing subscribe_events stream.

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_job WS command on the offloader. Typed CommandError surface: INVALID_ARGS for shape errors (pin / target / empty configuration), 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 — registers a per-job_id ack future before the header goes out, drives the chunk loop through PeerLinkChannel.send_frame, awaits the ack with a 60s timeout. No mid-session retry — the receiver may already have queued the job under that job_id, and a duplicate send under a fresh id would land a second FirmwareJob. Operator-initiated retry on a fresh session is the correct recovery.
  • Receive-loop additions: submit_job_ack resolves the matching ack future; job_state_changed / job_output validate 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_loops rather than a chain of if msg_type == ... branches.
  • 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 already gone.

Helpers (extracted for DRY):

  • helpers/peer_link_frames.py — validate_frame_shape extracted from submit_job._validate_frame_shape so 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) wraps read_config + ConfigBundleCreator behind a process-wide asyncio.Lock (CORE.config_path / CORE.config are global; concurrent calls would race the global). CORE state is saved + restored in a finally so 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_OUTPUT enum members. Auto-broadcast by subscribe_events's existing event-type filter ([et for et in EventType if et is not DEVICE_REACHABILITY]) — no change to the dispatcher.
  • OffloaderJobStateChangedData / OffloaderJobOutputData TypedDict payloads — wire frame fields plus the receiver's coords.
  • SubmitJobNoSessionError / SubmitJobTimeoutError / SubmitJobSessionLostError exception types in peer_link_client. The WS layer maps them to typed CommandError responses.

Internal change:

  • _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 that could drift. Test sites updated to access .task.

DRY notes:

  • submit_job body 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.
  • The four receive-loop frame branches dispatch through a single lookup table built once per session.
  • submit_job._validate_frame_shape extracted to helpers/peer_link_frames.py:validate_frame_shape so the receiver and the offloader share one validator.

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 per gate, and an integration-style path-traversal test using the real DashboardSettings (the existing _make_offloader_controller uses a MagicMock Settings, which silently no-ops rel_path — the new test uses make_settings to confirm the production gate actually rejects ../etc/passwd).
  • tests/test_peer_link_frames.py covers the extracted validator's bool-vs-int special case + missing-field rejection.
  • tests/test_config_bundle.py covers the helper's CORE save/restore on success and failure paths.

Verification:

  • 2649 tests pass (3 pre-existing test_device_yaml.py failures excluded — unrelated, fail on origin/main).
  • Mypy clean (78 source files).
  • Ruff + pre-commit clean.

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

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

(Frontend will gain a remote_build/submit_job call and event handlers for OFFLOADER_JOB_STATE_CHANGED / OFFLOADER_JOB_OUTPUT in a follow-up frontend chunk; backend is shipping ahead so the wire is ready when the UI lands.)

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.

(Architecture docs reference the peer-link layers conceptually; the new frame types live in models/remote_build.py next to the existing submit_job_* TypedDicts that 5c-1 added, which is where docs/API.md's "Peer-link wire frames" section already points. A follow-up doc pass after the frontend chunk lands will round out docs/API.md's WS-command catalogue with the new remote_build/submit_job entry.)

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.
Copilot AI review requested due to automatic review settings May 10, 2026 16:24
@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 5c-3-offloader-submit-job (597f468) with main (a18f2f6)

Open in CodSpeed

@codecov-commenter

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

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.42254% with 13 lines in your changes missing coverage. Please review.
✅ Project coverage is 99.07%. Comparing base (d767144) to head (597f468).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
esphome_device_builder/helpers/subprocess.py 68.18% 7 Missing ⚠️
...ilder/controllers/remote_build/peer_link_client.py 96.46% 4 Missing ⚠️
esphome_device_builder/helpers/config_bundle.py 94.73% 2 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            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     
Flag Coverage Δ
py3.12 99.03% <95.42%> (-0.11%) ⬇️
py3.14 99.07% <95.42%> (-0.11%) ⬇️

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

Files with missing lines Coverage Δ
...ome_device_builder/controllers/firmware/helpers.py 100.00% <100.00%> (ø)
...ice_builder/controllers/remote_build/controller.py 99.65% <100.00%> (+0.07%) ⬆️
...ice_builder/controllers/remote_build/submit_job.py 100.00% <100.00%> (ø)
esphome_device_builder/device_builder.py 96.97% <100.00%> (+<0.01%) ⬆️
esphome_device_builder/helpers/peer_link_frames.py 100.00% <100.00%> (ø)
esphome_device_builder/helpers/process.py 100.00% <100.00%> (ø)
esphome_device_builder/models/common.py 100.00% <100.00%> (ø)
esphome_device_builder/models/remote_build.py 98.83% <100.00%> (+0.13%) ⬆️
esphome_device_builder/helpers/config_bundle.py 94.73% <94.73%> (ø)
...ilder/controllers/remote_build/peer_link_client.py 98.82% <96.46%> (-1.18%) ⬇️
... and 1 more
🚀 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

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_job WS command on the offloader, including input gating + typed error mapping and per-peer client lookup.
  • Extends PeerLinkClient with submit_job(...), inbound dispatch for submit_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.

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 10 out of 10 changed files in this pull request and generated 3 comments.

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.

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 14 out of 14 changed files in this pull request and generated 3 comments.

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.
@bdraco
J. Nick Koston (bdraco) merged commit 2c84d81 into main May 10, 2026
13 checks passed
@bdraco
J. Nick Koston (bdraco) deleted the 5c-3-offloader-submit-job branch May 10, 2026 19:13
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