Skip to content
This repository was archived by the owner on Jan 23, 2026. It is now read-only.

Handle Ctrl-C in j command#448

Merged
NickCao merged 4 commits intomainfrom
ctrl-c
May 7, 2025
Merged

Handle Ctrl-C in j command#448
NickCao merged 4 commits intomainfrom
ctrl-c

Conversation

@NickCao
Copy link
Copy Markdown
Collaborator

@NickCao NickCao commented May 6, 2025

Summary by CodeRabbit

  • New Features

    • Improved handling and flattening of nested exception groups for better error reporting and debugging.
    • Added an asynchronous signal handler for graceful shutdown on termination signals.
  • Refactor

    • Updated the CLI entrypoint to use asynchronous execution and improved exception handling for enhanced reliability and responsiveness.
  • Chores

    • Updated code linting configuration to target Python 3.11.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 6, 2025

Walkthrough

The changes introduce new utility functions for flattening and combining tracebacks in exception groups, add an asynchronous signal handler for graceful shutdown, and refactor the CLI entrypoint to use asynchronous context management and exception handling. Additionally, the linter configuration is updated to target Python 3.11.

Changes

File(s) Change Summary
jumpstarter_cli_common/exceptions.py Added leaf_exceptions for flattening exception groups and _combine_tracebacks for merging tracebacks.
jumpstarter_cli_common/signal.py Introduced async signal_handler to handle SIGINT/SIGTERM and cancel tasks using AnyIO.
jumpstarter_cli/j.py Refactored CLI entrypoint to async model with j_async, async context managers, and exception handling.
pyproject.toml Updated ruff configuration to set target-version = "py311".

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI (j)
    participant j_async
    participant SignalHandler
    participant TaskGroup
    participant ClientCLI

    User->>CLI (j): Run CLI command
    CLI (j)->>j_async: Call asynchronously
    j_async->>TaskGroup: Start async task group
    j_async->>SignalHandler: Start signal handler (SIGINT/SIGTERM)
    j_async->>ClientCLI: Run CLI logic in thread
    SignalHandler-->>TaskGroup: On signal, cancel tasks
    TaskGroup-->>j_async: Propagate cancellation
    j_async-->>CLI (j): Handle exceptions, exit
Loading

Poem

Through signals and exceptions, we hop with care,
Async adventures now everywhere!
Tracebacks combined, exception groups tamed,
The CLI leaps forward, robustly renamed.
With Python 3.11 as our new springy bed,
This rabbit’s quite proud of the path we now tread! 🐇

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@netlify
Copy link
Copy Markdown

netlify Bot commented May 6, 2025

Deploy Preview for jumpstarter-docs ready!

Name Link
🔨 Latest commit 9d64e6f
🔍 Latest deploy log https://app.netlify.com/sites/jumpstarter-docs/deploys/681a545f45576700086555b3
😎 Deploy Preview https://deploy-preview-448--jumpstarter-docs.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (7)
packages/jumpstarter-cli-common/jumpstarter_cli_common/signal.py (1)

20-22: Minor: the break is redundant once the surrounding scope is cancelled

scope.cancel() will immediately unwind the enclosing CancelScope, so the loop exits naturally.
Keeping break is harmless but not necessary—dropping it simplifies the flow slightly.

packages/jumpstarter-cli-common/jumpstarter_cli_common/exceptions.py (3)

50-58: Rename the first parameter to avoid the misleading “self” outside a class

At module level, a parameter called self suggests a method, but leaf_exceptions() is a standalone function.

-def leaf_exceptions(self: BaseExceptionGroup, *, fix_tracebacks: bool = True) -> list[BaseException]:
+def leaf_exceptions(group: BaseExceptionGroup, *, fix_tracebacks: bool = True) -> list[BaseException]:

(And adjust the internal _flatten call accordingly.)
This improves readability without behaviour changes.


60-74: Type-safety & performance consideration for traceback cloning

Every leaf exception is copied via with_traceback, which allocates new traceback objects for each recursion level.
For very large exception trees this can become expensive.

If you only need the first combined traceback (PEP 654 typical usage), short-circuit once the first non-group exception is found to avoid unnecessary allocations, or expose a flag to skip traceback cloning altogether.


77-105: Guard against future changes in types.TracebackType constructor

types.TracebackType(...) is CPython-specific and positional/keyword parameters can change between versions.
Consider replacing the manual reconstruction with the public helper in the PEP reference implementation:

import traceback
new_tb = traceback.StackSummary.from_list(
    traceback.extract_tb(tb1) + traceback.extract_tb(tb2)
).as_traceback()

This avoids relying on private internals and keeps the code implementation-agnostic.

packages/jumpstarter-cli/jumpstarter_cli/j.py (3)

17-22: Minor: drop the lambda & gain clarity

to_thread.run_sync can accept the callable directly; wrapping the call in a zero-arg lambda introduces an extra stack frame and obscures what is being executed.

-                        await to_thread.run_sync(lambda: client.cli()(standalone_mode=False))
+                        await to_thread.run_sync(
+                            client.cli(),  # click command/function
+                            cancellable=True,
+                            # `standalone_mode=False` is passed via to_thread’s *args
+                            args=(),
+                            kwargs=dict(standalone_mode=False),
+                        )

While purely cosmetic, this preserves introspection (function name in tracebacks) and removes one level of indirection.


24-31: Double-cancelling the task-group is redundant

tg.cancel_scope is already passed to signal_handler, which will call cancel() on SIGINT/SIGTERM.
Invoking tg.cancel_scope.cancel() again in finally: is harmless but unnecessary and slightly obscures intent.

-            finally:
-                tg.cancel_scope.cancel()
+            finally:
+                # Nothing to cancel here; `signal_handler` or normal completion
+                # will already close the scope.
+                pass

Consider dropping the explicit cancel for terser, clearer flow.


45-45: Qualifier for the top-level run call

The bare run(j_async) relies on the earlier from anyio import run import.
For better readability and to avoid confusion with the built-in runpy.run_… helpers, consider aliasing:

-from anyio import create_task_group, get_cancelled_exc_class, run, to_thread
+from anyio import create_task_group, get_cancelled_exc_class, run as anyio_run, to_thread
...
-    run(j_async)
+    anyio_run(j_async)

Purely stylistic, but it makes the origin explicit to future readers.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3ab7b16 and 9d64e6f.

📒 Files selected for processing (4)
  • packages/jumpstarter-cli-common/jumpstarter_cli_common/exceptions.py (2 hunks)
  • packages/jumpstarter-cli-common/jumpstarter_cli_common/signal.py (1 hunks)
  • packages/jumpstarter-cli/jumpstarter_cli/j.py (1 hunks)
  • pyproject.toml (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: e2e
  • GitHub Check: pytest-matrix (3.13)
  • GitHub Check: pytest-matrix (3.11)
  • GitHub Check: pytest-matrix (3.12)
  • GitHub Check: build-and-push-image (jumpstarter-dev/jumpstarter Dockerfile)
  • GitHub Check: build-and-push-image (jumpstarter-dev/jumpstarter-devspace .devfile/Containerfile.client)
  • GitHub Check: build-and-push-image (jumpstarter-dev/jumpstarter-utils Dockerfile.utils)
  • GitHub Check: build-and-push-image (jumpstarter-dev/jumpstarter-dev .devfile/Containerfile)
🔇 Additional comments (1)
pyproject.toml (1)

60-62: Explicitly targeting Python 3.11 requires matching runtime & CI images

Setting target-version = "py311" tells Ruff to lint as if the code is executed under Python 3.11 features (e.g. except*, pattern-matching).
Please double-check that

  1. every published package’s pyproject.toml / setup.cfg already advertises a minimum Python 3.11 (e.g. requires-python = ">=3.11"), and
  2. all CI jobs (lint, tests, wheels) run on a 3.11 interpreter.

Otherwise contributors working on 3.10 or CI still pinned to 3.10 will get false positives/failures.

Comment thread packages/jumpstarter-cli-common/jumpstarter_cli_common/signal.py
Comment thread packages/jumpstarter-cli/jumpstarter_cli/j.py
Comment on lines +32 to +36
except* click.ClickException as excgroup:
for exc in leaf_exceptions(excgroup):
exc.show()

sys.exit(1)
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot May 6, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

except* misses plain ClickException – user-facing errors will leak a traceback

except* only catches ExceptionGroup; a solitary click.ClickException raised by the CLI executed in to_thread.run_sync will bypass this handler and bubble up as an unformatted traceback. Add a regular except click.ClickException branch before (or in addition to) the except* block.

+    except click.ClickException as exc:
+        exc.show()
+        sys.exit(1)
     except* click.ClickException as excgroup:
         for exc in leaf_exceptions(excgroup):
             exc.show()
 
         sys.exit(1)

Failing to do so degrades the UX and breaks the contract of returning exit-code 1 on CLI errors.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
except* click.ClickException as excgroup:
for exc in leaf_exceptions(excgroup):
exc.show()
sys.exit(1)
except click.ClickException as exc:
exc.show()
sys.exit(1)
except* click.ClickException as excgroup:
for exc in leaf_exceptions(excgroup):
exc.show()
sys.exit(1)

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.

Do we ever get a single exception? should we catch it just in case @NickCao ?

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.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

@NickCao NickCao merged commit 9d64e6f into main May 7, 2025
19 checks passed
@mangelajo mangelajo added this to the 0.6.0 milestone May 8, 2025
@mangelajo mangelajo added the backport release-0.6 Backport PR to release-0.6 branch label May 8, 2025
@jumpstarter-backport-bot
Copy link
Copy Markdown

Successfully created backport PR for release-0.6:

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

backport release-0.6 Backport PR to release-0.6 branch

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants