Skip to content

feat: add Ctrl-] x3 hotkey to power cycle board from serial console - #791

Merged
evakhoni merged 20 commits into
jumpstarter-dev:mainfrom
evakhoni:feat/console-power-hotkey
Nov 1, 2026
Merged

evakhoni merged 20 commits into
jumpstarter-dev:mainfrom
evakhoni:feat/console-power-hotkey

Conversation

@evakhoni

@evakhoni evakhoni commented Jun 14, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Add a Ctrl-] x3 hotkey to the serial console that power-cycles the DUT without exiting the session
  • Per review, the implementation is client-side and child-only: the console uses the serial device's power child (typically a ref: to the exporter's power driver) when its client is a PowerClient, and calls cycle() — so any power driver works with no exporter-side config
  • The hotkey logic lives in console.py: Console takes the PowerClient (power_control) and runs its cycle() in a worker thread, so a blocking cycle doesn't stall the console's event loop; scripts can call client.children["power"].cycle() directly
  • jumpstarter-driver-power is now a runtime dependency of jumpstarter-driver-pyserial (it was dev-only)
  • Drivers that build their console internally (qemu, renode, dutlink, corellium) pass their own power driver as the console's power child, so the hotkey works there out of the box (qemu: except in sidecar mode)
  • The console stays attached through the cycle: the exporter's fanout reconnects the serial device while clients remain connected, and the client-side reconnect loop is gone (input typed while the device is still away currently tears down the stream, tracked in Serial console stream is torn down when input is sent while the serial device is reconnecting #1231)
  • The hotkey is disabled gracefully when there is no power child, or the child isn't a PowerClient (including a client that is unavailable — not installed or rejected by the allow list, so it is a StubDriverClient), and in observe mode; none of these prevent the console from opening

Example

export:
  serial:
    type: jumpstarter_driver_pyserial.driver.PySerial
    config:
      url: "/dev/ttyUSB0"
      baudrate: 115200
    children:
      power:
        ref: "power" # any power driver
  power:
    type: jumpstarter_driver_yepkit.driver.Ykush
    config:
      serial: "YK112233"
      port: "1"

Test plan

  • 90 unit tests in jumpstarter-driver-pyserial (plus 1 strict xfail for Serial console stream is torn down when input is sent while the serial device is reconnecting #1231): power child resolution incl. ref: wiring and the real PowerClient cycling the power driver, a power child that isn't a PowerClient or is unavailable (stub) not breaking the console, the hotkey running cycle() on a worker thread and surviving a failing cycle, console banner, observe mode
  • Identity tests in qemu, renode, dutlink and corellium that the console's power child is the driver's own power instance (dutlink's skips without hardware)
  • QEMU smoke test on the new implementation: Ctrl-] x3 in the console reboots the VM and the console stays attached through the outage (fanout reconnect, [disconnected]/[reconnected] markers)
  • Real hardware with a PDU-powered board

@coderabbitai

coderabbitai Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
Walkthrough

Adds configurable power-cycle support and reconnect handling to the pyserial console. ConsoleStreamDrop signals dropped serial streams. Ctrl-] invokes an asynchronous power-cycle callback. The CLI discovers power clients, retries dropped streams, and propagates root-client references.

Changes: Serial Console Power-Cycle and Reconnect

Layer / File(s) Summary
Root client propagation
python/packages/jumpstarter/jumpstarter/client/client.py
client_from_channel sets a shared root attribute while traversing the client tree.
Power-control configuration
python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/driver.py
PySerial adds power-control reference and method settings, normalizes string methods, and exports the settings as labels.
Console stream and input handling
python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/console.py
The console converts EndOfStream to ConsoleStreamDrop. Three Ctrl-B inputs exit. Three Ctrl-] inputs invoke the optional power-cycle callback.
Power discovery and reconnect loop
python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/client.py
The client discovers power controllers, validates configurable cycle steps, creates an asynchronous callback, and retries console sessions after stream drops.
Behavior validation
python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/client_test.py, python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/console_test.py
Tests cover discovery, ambiguous and missing references, custom methods, disabled control, control-key handling, and clean console shutdown.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related PRs

Suggested reviewers: mangelajo

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 16.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Title check Passed The title clearly and concisely describes the primary change: adding a Ctrl-] x3 hotkey to power-cycle the board from the serial console.
Description check Passed The pull request description clearly describes the serial-console hotkey, power-cycle behavior, power-client handling, reconnect behavior, dependencies, and tests. These topics match the changes in th…
Full details: Description check

Explanation

The pull request description clearly describes the serial-console hotkey, power-cycle behavior, power-client handling, reconnect behavior, dependencies, and tests. These topics match the changes in the pull request.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

🐇 Ctrl-] wakes the power line,
Ctrl-B ends the console time.
Dropped streams return and retry,
Root links mark the tree nearby.
The rabbit hops through every cycle.

Comment @coderabbitai help to get the list of available commands.

@LuuOW LuuOW left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Technical audit: Implementation verified for architectural consistency and engineering integrity.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/client.py`:
- Around line 135-142: The `_search_power()` method only checks the children of
the provided client node but skips checking if the client node itself is
power-capable. This causes power-driver discovery to fail when the root node has
power capabilities. Modify the method to first check if the current `client`
parameter has a `cycle` method or both `on` and `off` methods before recursing
into `client.children`, ensuring the root node is included in the power-driver
discovery process.

In
`@python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/console_test.py`:
- Around line 17-37: The slave_file opened via os.fdopen() in the
_start_console() function is never explicitly closed, causing file descriptor
leaks across multiple test runs. Ensure proper cleanup by either returning
slave_file as part of the function's return tuple so the caller can close it
after the thread completes, or by adding a cleanup mechanism that closes
slave_file after the console.run() thread finishes executing. The key is to
guarantee that the file handle opened for slave_fd is properly closed to prevent
descriptor exhaustion.

In
`@python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/console.py`:
- Around line 47-52: The exception re-raising in the except* ConsoleStreamDrop
and except EndOfStream blocks violates Ruff B904 linting rules by not using
explicit exception chaining. For each exception handler block that raises an
exception (the except* ConsoleStreamDrop block that raises ConsoleStreamDrop()
and the except EndOfStream block that raises ConsoleStreamDrop()), capture the
caught exception as a variable in the except clause (e.g., except*
ConsoleStreamDrop as exc) and use the from keyword when raising to provide
explicit chaining (e.g., raise ConsoleStreamDrop() from exc). Alternatively, use
make lint-fix to automatically apply the necessary fixes to satisfy B904
requirements.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7c042f0b-f525-40fa-9c8d-e51bfe0279df

📥 Commits

Reviewing files that changed from the base of the PR and between 24473f3 and 5118a4a.

📒 Files selected for processing (4)
  • python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/client.py
  • python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/console.py
  • python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/console_test.py
  • python/packages/jumpstarter/jumpstarter/client/client.py

@evakhoni
evakhoni force-pushed the feat/console-power-hotkey branch 3 times, most recently from 67ebd74 to beac1ee Compare June 14, 2026 18:30

@coderabbitai coderabbitai Bot 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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/client_test.py (1)

8-33: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Consolidate new driver-package tests into driver_test.py per repository policy.

Both files add comprehensive driver-package test coverage, but not in the required module location.

  • python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/client_test.py#L8-L33: move/merge the power discovery and power-cycle tests into jumpstarter_driver_pyserial/driver_test.py.
  • python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/console_test.py#L40-L91: move/merge the Ctrl-B/Ctrl-] integration tests into jumpstarter_driver_pyserial/driver_test.py.

As per coding guidelines, **/jumpstarter-driver-*/jumpstarter_driver_*/*_test.py: Add comprehensive tests in driver_test.py file within the driver package.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/client_test.py`
around lines 8 - 33, Move the power discovery and power-cycle tests
(test_find_power_client_no_root, test_find_power_client_with_cycle,
test_make_power_cycle_calls_cycle) from
python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/client_test.py
lines 8-33 into
python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/driver_test.py,
and similarly move the Ctrl-B/Ctrl-] integration tests from
python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/console_test.py
lines 40-91 into the same driver_test.py file. Per the coding guidelines,
comprehensive driver-package tests must be consolidated in the driver_test.py
file within the driver package rather than scattered across individual module
test files.

Source: Coding guidelines

🧹 Nitpick comments (2)
python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/client_test.py (1)

24-33: ⚡ Quick win

Add coverage for the _make_power_cycle fallback branch.

test_make_power_cycle_calls_cycle validates only the cycle() path; the off() → sleep(2) → on() path in python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/client.py is still untested.

💡 Suggested test addition
+def test_make_power_cycle_calls_off_on_when_cycle_missing():
+    called_off = threading.Event()
+    called_on = threading.Event()
+    power = MagicMock(spec=["off", "on"])
+    power.off = MagicMock(side_effect=lambda: called_off.set())
+    power.on = MagicMock(side_effect=lambda: called_on.set())
+
+    with serve(PySerial(url="loop://")) as client:
+        cycle_fn = client._make_power_cycle(power)
+        client.portal.call(cycle_fn)
+
+    assert called_off.is_set()
+    assert called_on.is_set()
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/client_test.py`
around lines 24 - 33, The test_make_power_cycle_calls_cycle test only covers the
cycle() code path in the _make_power_cycle method, but the fallback branch that
uses off() followed by sleep(2) followed by on() remains untested. Add a new
test case that mocks the power object to trigger the fallback path (either by
not providing a cycle method or having it unavailable), then verify that the
fallback sequence of off(), sleep(), and on() method calls is executed properly
when the cycle function is invoked through client.portal.call().
python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/console_test.py (1)

44-45: ⚡ Quick win

Replace fixed sleeps with deterministic readiness signaling.

Line 44, Line 64, and Line 81 use time.sleep(0.1) to assume console readiness; this can cause intermittent CI flakes.

Also applies to: 64-65, 81-83

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/console_test.py`
around lines 44 - 45, Replace the three instances of time.sleep(0.1) calls with
deterministic readiness signaling instead of relying on fixed delays to assume
console readiness. For each location where time.sleep(0.1) precedes an os.write
operation, implement a proper synchronization mechanism such as using select,
poll, or event-based signaling to confirm the file descriptor is actually ready
for writing before proceeding, eliminating the intermittent CI flakes caused by
timing assumptions.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In
`@python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/client_test.py`:
- Around line 8-33: Move the power discovery and power-cycle tests
(test_find_power_client_no_root, test_find_power_client_with_cycle,
test_make_power_cycle_calls_cycle) from
python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/client_test.py
lines 8-33 into
python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/driver_test.py,
and similarly move the Ctrl-B/Ctrl-] integration tests from
python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/console_test.py
lines 40-91 into the same driver_test.py file. Per the coding guidelines,
comprehensive driver-package tests must be consolidated in the driver_test.py
file within the driver package rather than scattered across individual module
test files.

---

Nitpick comments:
In
`@python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/client_test.py`:
- Around line 24-33: The test_make_power_cycle_calls_cycle test only covers the
cycle() code path in the _make_power_cycle method, but the fallback branch that
uses off() followed by sleep(2) followed by on() remains untested. Add a new
test case that mocks the power object to trigger the fallback path (either by
not providing a cycle method or having it unavailable), then verify that the
fallback sequence of off(), sleep(), and on() method calls is executed properly
when the cycle function is invoked through client.portal.call().

In
`@python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/console_test.py`:
- Around line 44-45: Replace the three instances of time.sleep(0.1) calls with
deterministic readiness signaling instead of relying on fixed delays to assume
console readiness. For each location where time.sleep(0.1) precedes an os.write
operation, implement a proper synchronization mechanism such as using select,
poll, or event-based signaling to confirm the file descriptor is actually ready
for writing before proceeding, eliminating the intermittent CI flakes caused by
timing assumptions.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: cb30cdcc-eb35-42ef-8a00-b909cd4dc09f

📥 Commits

Reviewing files that changed from the base of the PR and between 67ebd74 and beac1ee.

📒 Files selected for processing (2)
  • python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/client_test.py
  • python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/console_test.py

@mangelajo mangelajo left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This one is close @evakhoni :D

evakhoni added a commit to evakhoni/jumpstarter that referenced this pull request Jul 31, 2026
Replace duck-typing power discovery with conservative label-based detection
to prevent false positives (GPIO pins, storage mux drivers) and handle
multi-power setups safely.

Changes:
- Add power_control_ref config field for explicit device selection
- Add power_control_method config field for custom sequences (default: ["cycle"])
- Implement allowlist: only PowerClient/VirtualPowerClient auto-discovered
- Add ambiguity detection: warn and disable when multiple candidates found
- Support method sequences: ["off", "sleep:2", "on"], ["reset"], etc.
- Support disable via empty list: power_control_method: []
- Pass config to client via extra_labels() following DbusNetwork pattern

Addresses reviewer feedback on PR jumpstarter-dev#791 about auto-discovery risks in
multi-power environments. Feature remains enabled by default for simple
setups but disables itself at first sign of trouble.

Tests: 71/71 pass, lint and type checks clean

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/client_test.py (1)

13-23: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Test VirtualPowerClient discovery.

This test covers PowerClient only. KNOWN_POWER_CLIENTS also accepts VirtualPowerClient. Add a parameterized case for "jumpstarter_driver_power.client.VirtualPowerClient" so a regression in that supported label is detected.

As per coding guidelines, python/**/*_test.py must “Provide comprehensive package test coverage.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/client_test.py`
around lines 13 - 23, Extend test_find_power_client_auto_discover to cover both
supported client labels by parameterizing the test and including
"jumpstarter_driver_power.client.VirtualPowerClient" alongside the existing
PowerClient label. Keep the discovery setup and assertion unchanged for each
parameterized case.

Source: Coding guidelines

🧹 Nitpick comments (1)
python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/driver.py (1)

103-103: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Align the annotation with the accepted input.

Line [103] declares power_control_method as list[str], but Lines [112-115] accept a str. A typed caller cannot pass a supported string value without a type-checking error. Use a union at the input boundary, then normalize the stored value to list[str].

Also applies to: 112-115

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/driver.py`
at line 103, Update the power_control_method annotation and initialization in
the driver configuration to accept both str and list[str] at the input boundary,
matching the handling in lines 112-115. Normalize a supplied string to a
one-element list so the stored value remains list[str], while preserving the
existing default and list behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/client.py`:
- Around line 188-204: Update the power-control setup around _cycle to validate
every step before enabling the hotkey: require non-sleep operations on
power_client to be callable, parse each sleep: delay during construction, and
catch invalid values by logging a warning and returning None. Preserve valid
operation ordering, and add tests covering a non-callable attribute and an
invalid sleep value.

---

Outside diff comments:
In
`@python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/client_test.py`:
- Around line 13-23: Extend test_find_power_client_auto_discover to cover both
supported client labels by parameterizing the test and including
"jumpstarter_driver_power.client.VirtualPowerClient" alongside the existing
PowerClient label. Keep the discovery setup and assertion unchanged for each
parameterized case.

---

Nitpick comments:
In
`@python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/driver.py`:
- Line 103: Update the power_control_method annotation and initialization in the
driver configuration to accept both str and list[str] at the input boundary,
matching the handling in lines 112-115. Normalize a supplied string to a
one-element list so the stored value remains list[str], while preserving the
existing default and list behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: eeb0681c-6d5e-451d-b312-e5f4f45568d6

📥 Commits

Reviewing files that changed from the base of the PR and between beac1ee and ae02650.

📒 Files selected for processing (3)
  • python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/client.py
  • python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/client_test.py
  • python/packages/jumpstarter-driver-pyserial/jumpstarter_driver_pyserial/driver.py

evakhoni added a commit to evakhoni/jumpstarter that referenced this pull request Jul 31, 2026
Replace duck-typing power discovery with conservative label-based detection
to prevent false positives (GPIO pins, storage mux drivers) and handle
multi-power setups safely.

Changes:
- Add power_control_ref config field for explicit device selection
- Add power_control_method config field for custom sequences (default: ["cycle"])
- Implement allowlist: only PowerClient/VirtualPowerClient auto-discovered
- Add ambiguity detection: warn and disable when multiple candidates found
- Support method sequences: ["off", "sleep:2", "on"], ["reset"], etc.
- Support disable via empty list [], empty string "", or null
- Pass config to client via extra_labels() following DbusNetwork pattern
- Pre-validate callable methods and parse sleep values at construction
- Fix type annotation: power_control_method accepts list[str] | str | None
- Add field docstrings and update README with config table and hotkey docs

Addresses reviewer feedback on PR jumpstarter-dev#791 about auto-discovery risks in
multi-power environments and CodeRabbit findings on validation timing.
Feature remains enabled by default for simple setups but disables itself
at first sign of trouble.

Tests: 74/74 pass, coverage improved from 78% to above 80% threshold

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
@evakhoni
evakhoni force-pushed the feat/console-power-hotkey branch from ae02650 to ea0e41a Compare July 31, 2026 16:48
@evakhoni
evakhoni requested a review from mangelajo July 31, 2026 16:55
evakhoni and others added 5 commits July 31, 2026 21:53
- Add on_power_cycle callback to Console; Ctrl-] x3 triggers it
- Add root back-reference to DriverClient, stamped during tree construction
- Auto-discover power client from DUT siblings in PySerialClient
- Prefer cycle() when available, fall back to off()+on()

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
- Add ConsoleStreamDrop exception to signal a dropped serial stream
- Add retry loop in start_console to reconnect on stream drop
- Use object.__setattr__ to stamp root back-reference without polluting pydantic schema
- Remove root field from DriverClient; it is now a dynamic attribute

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
- Ctrl-B x3 exits cleanly
- Ctrl-] x3 triggers on_power_cycle and console stays alive
- Ctrl-] x3 without a power client does nothing

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Replace duck-typing power discovery with conservative label-based detection
to prevent false positives (GPIO pins, storage mux drivers) and handle
multi-power setups safely.

Changes:
- Add power_control_ref config field for explicit device selection
- Add power_control_method config field for custom sequences (default: ["cycle"])
- Implement allowlist: only PowerClient/VirtualPowerClient auto-discovered
- Add ambiguity detection: warn and disable when multiple candidates found
- Support method sequences: ["off", "sleep:2", "on"], ["reset"], etc.
- Support disable via empty list [], empty string "", or null
- Pass config to client via extra_labels() following DbusNetwork pattern
- Pre-validate callable methods and parse sleep values at construction
- Fix type annotation: power_control_method accepts list[str] | str | None
- Add field docstrings and update README with config table and hotkey docs

Addresses reviewer feedback on PR jumpstarter-dev#791 about auto-discovery risks in
multi-power environments and CodeRabbit findings on validation timing.
Feature remains enabled by default for simple setups but disables itself
at first sign of trouble.

Tests: 74/74 pass, coverage improved from 78% to above 80% threshold

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
Fixes two power auto-discovery bugs:

1. **Proxy dedup**: When a Proxy driver delegates to a power client
   (e.g., Proxy(ref="qemu.power")), the same driver instance appears
   twice in the client tree — once via proxy, once via direct parent.
   This triggered false "Multiple power drivers found" ambiguity.
   Fixed by tracking UUIDs in `_collect_power_clients` to skip
   already-seen drivers.

2. **Allowlist expansion**: RideSXPowerClient, NoyitoPowerClient, and
   SNMPServerClient all extend PowerClient but weren't in the allowlist,
   causing auto-discovery to silently find nothing on those targets.
   Added all three to `KNOWN_POWER_CLIENTS`.

Also adds user feedback: when Ctrl-] x3 is pressed without a power
driver, log a warning instead of silently doing nothing.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@evakhoni
evakhoni force-pushed the feat/console-power-hotkey branch from ea0e41a to f807a7f Compare July 31, 2026 18:56
@coderabbitai coderabbitai Bot mentioned this pull request Aug 13, 2026
@raballew

raballew commented Sep 24, 2026 •

Copy link
Copy Markdown
Member

@mangelajo @evakhoni whats the plan with this one? It seems quite old. Do we want to merge or close this one?

@evakhoni

evakhoni commented Oct 5, 2026 •

Copy link
Copy Markdown
Member Author

@mangelajo @evakhoni whats the plan with this one? It seems quite old. Do we want to merge or close this one?

good question. I was away for quite some time on a vacation, but before I left it was awaiting a final review more or less 🤔
I see it collected a little merge conflict, but that can be solved quickly I guess. @mangelajo your suggestion, do we like that one to get merged? I have addressed the concerns about it, so last question would be if you think it's a useful feature. wdyt?

edit: solved the merge conflict so in case we decide it's a merger - should be ready to go

Merged changes from upstream/main, resolving conflicts in pyserial driver:

1. **driver.py**: Added upstream's `always_on` field alongside power control
   fields (`power_control_ref`, `power_control_method`)

2. **client.py**:
   - Merged imports (logging, os, stat)
   - Integrated `--observe` flag for read-only console mode with power cycle
     logic. Power cycle hotkey is disabled in observe mode (passive observer
     shouldn't control power)
   - Preserved retry loop for both modes (benefits active users after power
     cycle and observers after connection drops)

3. **console.py**:
   - Console now accepts both `observe` and `on_power_cycle` parameters
   - Merged observe mode logic (uses "observe" vs "connect" method, passes
     None for stream when observe=True) with exception handling for
     ConsoleStreamDrop and EndOfStream
   - stdin handler resets ctrl_bracket_count AND checks stream is not None

4. **README.md**: Added documentation for all new parameters (`power_control_ref`,
   `power_control_method`, `always_on`)

All tests pass (83 tests).

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
@evakhoni
evakhoni force-pushed the feat/console-power-hotkey branch from f2c78f4 to d5a7610 Compare October 5, 2026 19:12
@bennyz

bennyz commented Oct 6, 2026

Copy link
Copy Markdown
Member

@evakhoni @mangelajo i thought about this a bit, perhaps we can simplify this if we opt-in when the power driver is referenced from serial, then we don't need auto discovery and the pyserial code can be simplified to something like:

@base.command()
@click.option("--observe", is_flag=True, default=False, help="Watch-only mode (read-only)")
def console(observe):
    """Start serial port console"""
    power = None if observe else self.children.get("power")
    if power is not None and not callable(getattr(power, "cycle", None)):
        click.echo("Warning: 'power' child has no cycle() method, power hotkey disabled", err=True)
        power = None

    hint = "exit with CTRL+B x 3 times"
    if power is not None:
        hint += ", power cycle with CTRL+] x 3 times"
    click.echo(f"\nStarting serial console{' in observe mode' if observe else ''} ... {hint}\n")

    Console(serial_client=self, observe=observe, power=power).run()

Address review feedback from bennyz on PR jumpstarter-dev#791:

1. **Fix retry counter accumulation** (client.py):
   - Reset retry counter after healthy sessions (≥5s duration)
   - Reduce max retries from 30 to 10 (sufficient for rapid failures)
   - Add named constants for clarity (SUCCESSFUL_SESSION_THRESHOLD, MAX_RAPID_FAILURES)

2. **Extract HotkeyDetector class** (console.py):
   - Reusable class for detecting repeated key sequences
   - Simplifies stdin handling logic
   - Behavior change: Ctrl-] bytes now forwarded to serial when no power client available
     (previously swallowed with warning)

3. **Fix critical stream error handling** (console.py):
   - Add STREAM_ERRORS constant (EndOfStream, BrokenResourceError, ClosedResourceError)
   - Suppress send() errors in __read_stdin (silent drop during power cycle)
   - Map all stream errors to ConsoleStreamDrop in __serial_to_stdout
   - Fixes crash when typing during power cycle USB re-enumeration (2-5s window)
   - Power cycle now survives without tearing down console session

4. **Add comprehensive tests** (console_test.py):
   - test_send_failure_does_not_kill_console: verify resilience to send() failures
   - test_receive_failure_raises_stream_drop: verify receive() error routing
   - 6 HotkeyDetector unit tests: three presses, reset on unrelated byte,
     alternating keys, byte outside keys, counter reset after hit

All 90 tests pass. Linter clean.

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
@evakhoni

Copy link
Copy Markdown
Member Author

@evakhoni @mangelajo i thought about this a bit, perhaps we can simplify this if we opt-in when the power driver is referenced from serial, then we don't need auto discovery and the pyserial code can be simplified to something like:

@base.command()
@click.option("--observe", is_flag=True, default=False, help="Watch-only mode (read-only)")
def console(observe):
    """Start serial port console"""
    power = None if observe else self.children.get("power")
    if power is not None and not callable(getattr(power, "cycle", None)):
        click.echo("Warning: 'power' child has no cycle() method, power hotkey disabled", err=True)
        power = None

    hint = "exit with CTRL+B x 3 times"
    if power is not None:
        hint += ", power cycle with CTRL+] x 3 times"
    click.echo(f"\nStarting serial console{' in observe mode' if observe else ''} ... {hint}\n")

    Console(serial_client=self, observe=observe, power=power).run()

@bennyz hmm.. sounds a bit limiting imho. hardcoding the power client to be named "power" in order for the hotkey to appear sounds like something the users gonna miss easily.

Comment on lines -616 to 621
Full teardown happens at session end via shutdown().

Deliberately does not chain to super().close(): that would close child
drivers (e.g. a `power` ref, switching the DUT off) on a remote kick.
Full teardown, children included, happens at session end via shutdown().
"""
if self._fanout is not None:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is incorrect, closing the power driver does not switch off.

Please restore fanout.py

@evakhoni evakhoni Oct 22, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

ah even opus was wrong here.. it mentioned that FanOutStreamMixin.close() kicks the clients and then calls Driver.close(), which calls close() on every child, which in case of qemu/renode can call QemuPower.close() or RenodePower.close() which would power them off, but turns out our hotkey is unaffected at all, and it's only a theoretical path if called programmatically. removing this one 🆗

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think it's right, but that's more like a bug on those drivers that we will need to tackle separately.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Anyway, this cannot be triggered in production: The hotkey and normal console exit never call the exporter's close(). serial_client.close() only closes local streams, and no production caller of serial_client.call("close") was found. It would require an explicit remote call from custom code.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

yeah that's my impression as well. the issue exist, but it doesn't trigger by the hotkey so it's out of scope of this pr I guess. I wonder should I open an issue about it wdyt?

@mangelajo mangelajo left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@evakhoni I left a few comments, it's getting close but there are some problems

evakhoni and others added 2 commits October 22, 2026 16:28
Per review, the console owns the Ctrl-] x3 hotkey: Console takes the
power client (power_control) and runs its cycle() in a worker thread,
so the public dut_power_cycle() and the client-side hook are removed.

Also fix opening the console when the `power` child's client is
unavailable (not installed or rejected by the allow list): the child is
then a StubDriverClient whose attribute lookup raises ImportError, which
getattr(..., None) does not swallow. Treat it as no usable power child.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Per review, revert the kick change from 12c3280: the power hotkey
never calls close() on the serial driver, so a power child is only
closed through a direct remote close() call, which nothing in the
product makes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@mangelajo mangelajo left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

a couple of extra changes, we can just use PowerInterface there.

evakhoni and others added 2 commits October 25, 2026 13:19
Per review, type the console's power control as PowerClient instead of
a local Protocol, make jumpstarter-driver-power a runtime dependency of
pyserial, and reduce _power_child() to an isinstance check. A power
child that is unavailable (StubDriverClient) or not a PowerClient still
just disables the hotkey.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
The power-cycle thread assertion compared against the console thread
instead of the event loop's thread, so it could not catch cycle() running
on the loop. Compare against the loop thread, and wait for the console to
attach (raw mode set) instead of sleeping before sending keys.

Drop comments that described the PR's earlier states or restated the
code, and rename the test helpers that referred to them.

Note in the README that qemu's hotkey wiring does not apply in sidecar
mode.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@evakhoni

Copy link
Copy Markdown
Member Author

@mangelajo ok, done that, and a little cleanup, and have tested locally on qemu. all seems fine - I guess it's ready now.

@mangelajo
mangelajo requested a review from bennyz October 26, 2026 15:16
@mangelajo
mangelajo added this pull request to the merge queue Oct 26, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to no response for status checks Oct 26, 2026
@evakhoni
evakhoni added this pull request to the merge queue Nov 1, 2026
Merged via the queue into jumpstarter-dev:main with commit c89c3c1 Nov 1, 2026
32 checks passed
@evakhoni
evakhoni deleted the feat/console-power-hotkey branch November 1, 2026 10:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants