Skip to content

refactor: extract serve() into composable methods - #947

Merged
mangelajo merged 1 commit into
mainfrom
bz/restart-1a
Aug 3, 2026
Merged

refactor: extract serve() into composable methods#947
mangelajo merged 1 commit into
mainfrom
bz/restart-1a

Conversation

@bennyz

@bennyz bennyz commented Aug 3, 2026

Copy link
Copy Markdown
Member
  • serve() → serve / _run_control_plane / _apply_status
  • Transition handlers: _on_lease_acquired, _on_lease_update,
    _on_lease_released, _check_stop_requested
  • Removes the C901 suppression
  • Status transitions are now unit-testable without task-group scaffolding"

Next: #948

@coderabbitai

coderabbitai Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d8f48957-25b6-4fa6-8777-190dedbd7970

📥 Commits

Reviewing files that changed from the base of the PR and between 702a9d2 and 64105bc.

📒 Files selected for processing (1)
  • python/packages/jumpstarter/jumpstarter/exporter/exporter.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • python/packages/jumpstarter/jumpstarter/exporter/exporter.py

📝 Walkthrough

Walkthrough

The exporter refactors serve() into control-plane and lease lifecycle helpers. It preserves lease acquisition, updates, release handling, shutdown checks, and cleanup behavior while moving final state cleanup into a finally block.

Changes

Exporter lifecycle

Layer / File(s) Summary
Control-plane orchestration
python/packages/jumpstarter/jumpstarter/exporter/exporter.py
serve() delegates status processing to _run_control_plane. _apply_status dispatches leased and unleased updates. _check_stop_requested handles shutdown checks. Final cleanup runs in finally.
Lease lifecycle handlers
python/packages/jumpstarter/jumpstarter/exporter/exporter.py
_on_lease_acquired, _on_lease_update, and _on_lease_released manage lease context, logging, status updates, completion waits, cleanup, and exit behavior.

Estimated code review effort: 4 (Complex) | ~40 minutes

Possibly related PRs

Poem

A rabbit hops through lease and stream,
Helpers keep the control flow clean.
Tasks and logs receive their due,
Release waits complete the queue.
Shutdown checks the final sign—
The exporter’s lifecycle aligns.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: extracting serve() into composable methods.
Description check ✅ Passed The description accurately summarizes the extracted methods, transition handlers, and removal of the C901 suppression.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch bz/restart-1a

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

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

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

🧹 Nitpick comments (1)
python/packages/jumpstarter/jumpstarter/exporter/exporter.py (1)

1091-1106: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Compute session_was_created from the local lease context.

_on_lease_released captures lease_ctx at Line 1092, but Line 1100 reads self._lease_context again after the shielded wait. handle_lease clears self._lease_context in its own fallback path once after_lease_hook_done is set, so self._lease_context can already be None here. The 0.2s session-close delay is then skipped for a lease that did create a session. Read the captured reference instead to make the check deterministic.

♻️ Proposed refactor
     async def _on_lease_released(self, previous_leased: bool) -> None:
         """Handle not-leased status: signal handle_lease on transition, clean up context."""
         logger.info("Currently not leased")
 
-        if previous_leased and self._lease_context:
-            lease_ctx = self._lease_context
+        lease_ctx = self._lease_context
+        if previous_leased and lease_ctx:
             logger.info("Lease ended, signaling handle_lease to run afterLease hook")
             lease_ctx.lease_ended.set()
 
             with CancelScope(shield=True):
                 await lease_ctx.after_lease_hook_done.wait()
             logger.info("afterLease hook completed")
 
-        session_was_created = (
-            self._lease_context is not None and self._lease_context.session is not None
-        )
+        session_was_created = lease_ctx is not None and lease_ctx.session is not None
         self._lease_context = None
🤖 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/jumpstarter/exporter/exporter.py` around lines
1091 - 1106, Update _on_lease_released so session_was_created checks the
captured lease_ctx reference rather than rereading self._lease_context after the
shielded wait. Preserve the existing session presence condition and 0.2-second
delay for leases that created a session.
🤖 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.

Nitpick comments:
In `@python/packages/jumpstarter/jumpstarter/exporter/exporter.py`:
- Around line 1091-1106: Update _on_lease_released so session_was_created checks
the captured lease_ctx reference rather than rereading self._lease_context after
the shielded wait. Preserve the existing session presence condition and
0.2-second delay for leases that created a session.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8079b322-b9f9-4673-a7a0-9956d424a1bf

📥 Commits

Reviewing files that changed from the base of the PR and between 5702453 and 702a9d2.

📒 Files selected for processing (1)
  • python/packages/jumpstarter/jumpstarter/exporter/exporter.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.

a couple of nits, I think the sleep(0.2) comment is actually the important one if the types are passing the type checker.

self._status_drain_active = False
clear_log_context()

async def _run_control_plane(self, status_tx, status_rx):

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.

nit: status_tx and status_rx are missing type annotations, unlike the other new methods which all have proper signatures. Consider:

async def _run_control_plane(
    self,
    status_tx: MemoryObjectSendStream[jumpstarter_pb2.StatusResponse],
    status_rx: MemoryObjectReceiveStream[jumpstarter_pb2.StatusResponse],
) -> None:

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.

ack

self._lease_context = None
clear_log_context()
if session_was_created:
await sleep(0.2)

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.

The old code had useful context here explaining why this non-obvious delay exists:

# Brief delay to ensure session is fully closed before next lease
# This prevents SSL corruption from overlapping connections
await sleep(0.2)

Worth preserving -- without the comment this looks like an arbitrary magic sleep that someone might remove in a future cleanup.

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.

ack

 - serve() → serve / _run_control_plane / _apply_status
 - Transition handlers: _on_lease_acquired, _on_lease_update,
   _on_lease_released, _check_stop_requested
 - Removes the C901 suppression
 - Status transitions are now unit-testable without task-group scaffolding"

Signed-off-by: Benny Zlotnik <bzlotnik@redhat.com>
Assited-by: claude-opus-4.6

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

thank you benny!

@mangelajo
mangelajo added this pull request to the merge queue Aug 3, 2026
Merged via the queue into main with commit 821bbf0 Aug 3, 2026
23 checks passed
@mangelajo
mangelajo deleted the bz/restart-1a branch August 3, 2026 14:33
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.

2 participants