Skip to content

Conversation

@OlegWock
Copy link
Member

@OlegWock OlegWock commented Nov 18, 2025

You can test this by executing slow query, e.g. this one (takes around 30-40 seconds for me). Then stopping block execution and checking BigQuery "Jobs explorer" (in GCP console) that job was created and cancelled (if you cancel too quickly after start of execution it's possible job won't be created at all, so to test it I'd recommend to wait 10s before cancelling block execution).

-- Heavier long-running demo query (no real tables)
WITH a AS (
  SELECT x AS i
  FROM UNNEST(GENERATE_ARRAY(1, 10000)) AS x         -- tune this up/down
),
b AS (
  SELECT y AS j
  FROM UNNEST(GENERATE_ARRAY(1, 10000)) AS y         -- tune this up/down
),
pairs AS (
  SELECT
    i,
    j,
    SIN(i * j) AS s,
    COS(i + j) AS c
  FROM a
  CROSS JOIN b
),
heavy AS (
  SELECT
    i,
    j,
    -- intentionally nasty CPU-heavy expression
    EXP(
      SIN(s) * COS(c)
      + LOG(ABS(s) + 1.000001)
      + LOG(ABS(c) + 1.000001)
    )
    + EXP(
      SIN(i) * COS(j)
      + LOG(i + 1.000001)
      + LOG(j + 1.000001)
    ) AS heavy_val
  FROM pairs
)
SELECT
  COUNT(*) AS row_count,
  SUM(heavy_val) AS total_heavy_val
FROM heavy;

Summary by CodeRabbit

  • New Features

    • Improved keyboard-interrupt handling for BigQuery queries — interrupted queries now trigger cancellation so they don't hang.
  • Tests

    • Added unit test covering interrupt + cancellation behavior to ensure queries cancel and the interrupt propagates.
  • Other

    • Runtime now applies a patch at startup to enable the improved interrupt/cancel behavior (failures are logged).

@linear
Copy link

linear bot commented Nov 18, 2025

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 18, 2025

📝 Walkthrough

Walkthrough

During Deepnote runtime initialization, apply_runtime_patches() is called; it attempts to monkeypatch google.cloud.bigquery._job_helpers._wait_or_cancel to call job.result(...) and, on exception (including KeyboardInterrupt), call job.cancel(retry=None, timeout=api_timeout) before re-raising. A session-scoped autouse test fixture ensures the patch is applied for unit tests. A new unit test asserts that _wait_or_cancel propagates KeyboardInterrupt and invokes job.cancel with the expected args.

Sequence Diagram(s)

sequenceDiagram
    participant Init as Deepnote Runtime Init
    participant RuntimePatches as runtime_patches.apply_runtime_patches
    participant BigQueryHelpers as google.cloud.bigquery._job_helpers
    participant Job as BigQuery Job
    participant Tests as Unit Tests (autouse fixture)

    Init->>RuntimePatches: call apply_runtime_patches()
    RuntimePatches->>BigQueryHelpers: attempt monkeypatch _wait_or_cancel
    Note right of RuntimePatches: log success or warning on failure

    Tests->>RuntimePatches: ensure patches applied (autouse)
    Tests->>Job: invoke job.result() (via _wait_or_cancel)
    activate Job
    Job-->>Job: raise KeyboardInterrupt / exception
    Job->>Job: patched _wait_or_cancel catches exception
    Job->>Job: call job.cancel(retry=None, timeout=api_timeout)
    Job-->>Tests: re-raise KeyboardInterrupt
    deactivate Job
Loading

Pre-merge checks

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.36% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and specifically describes the main change: adding a monkeypatch to BigQuery that cancels active queries on KeyboardInterrupt.

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 8137ef0 and c896b7b.

📒 Files selected for processing (1)
  • tests/unit/conftest.py (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
tests/unit/conftest.py (1)
deepnote_toolkit/runtime_patches.py (1)
  • apply_runtime_patches (52-53)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: Build and push artifacts for Python 3.9
  • GitHub Check: Build and push artifacts for Python 3.12
  • GitHub Check: Build and push artifacts for Python 3.13
  • GitHub Check: Build and push artifacts for Python 3.11
  • GitHub Check: Build and push artifacts for Python 3.10
  • GitHub Check: Test - Python 3.12
  • GitHub Check: Test - Python 3.11
  • GitHub Check: Test - Python 3.10
  • GitHub Check: Test - Python 3.9
🔇 Additional comments (1)
tests/unit/conftest.py (1)

10-16: LGTM!

Shadowing concern from previous review resolved by renaming fixture to apply_patches.


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

@github-actions
Copy link

github-actions bot commented Nov 18, 2025

📦 Python package built successfully!

  • Version: 1.1.4.dev7+e15efb1
  • Wheel: deepnote_toolkit-1.1.4.dev7+e15efb1-py3-none-any.whl
  • Install:
    pip install "deepnote-toolkit @ https://deepnote-staging-runtime-artifactory.s3.amazonaws.com/deepnote-toolkit-packages/1.1.4.dev7%2Be15efb1/deepnote_toolkit-1.1.4.dev7%2Be15efb1-py3-none-any.whl"

@codecov
Copy link

codecov bot commented Nov 18, 2025

Codecov Report

❌ Patch coverage is 73.07692% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 72.89%. Comparing base (8135e40) to head (c896b7b).
⚠️ Report is 1 commits behind head on main.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
deepnote_toolkit/runtime_initialization.py 20.00% 4 Missing ⚠️
deepnote_toolkit/runtime_patches.py 85.71% 3 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main      #34   +/-   ##
=======================================
  Coverage   72.88%   72.89%           
=======================================
  Files          93       94    +1     
  Lines        5142     5168   +26     
  Branches      754      754           
=======================================
+ Hits         3748     3767   +19     
- Misses       1150     1157    +7     
  Partials      244      244           
Flag Coverage Δ
combined 72.89% <73.07%> (+<0.01%) ⬆️

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

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
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: 2

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 8135e40 and 13fd0ee.

📒 Files selected for processing (2)
  • deepnote_toolkit/sql/sql_execution.py (3 hunks)
  • tests/unit/test_sql_execution_internal.py (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
tests/unit/test_sql_execution_internal.py (1)
deepnote_toolkit/sql/sql_execution.py (1)
  • _wait_or_cancel (53-73)
🪛 Ruff (0.14.5)
deepnote_toolkit/sql/sql_execution.py

46-46: Missing return type annotation for private function _monkeypatch_bigquery_wait_or_cancel

Add return type annotation: None

(ANN202)


57-57: Dynamically typed expressions (typing.Any) are disallowed in retry

(ANN401)


71-72: try-except-pass detected, consider logging the exception

(S110)


71-71: Do not catch blind exception: Exception

(BLE001)


79-79: Do not catch blind exception: Exception

(BLE001)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
  • GitHub Check: Test - Python 3.11
  • GitHub Check: Test - Python 3.10
  • GitHub Check: Test - Python 3.12
  • GitHub Check: Test - Python 3.13
  • GitHub Check: Test - Python 3.9
  • GitHub Check: Build and push artifacts for Python 3.10
  • GitHub Check: Build and push artifacts for Python 3.9
  • GitHub Check: Build and push artifacts for Python 3.13
  • GitHub Check: Build and push artifacts for Python 3.12
  • GitHub Check: Build and push artifacts for Python 3.11
🔇 Additional comments (4)
tests/unit/test_sql_execution_internal.py (1)

12-31: LGTM – Test correctly validates KeyboardInterrupt handling.

The test properly verifies that KeyboardInterrupt propagates and that job cancellation occurs with the expected parameters.

deepnote_toolkit/sql/sql_execution.py (3)

7-7: LGTM – Imports support logging and typing.

Also applies to: 28-28, 38-38


76-83: LGTM – Module-level invocation with appropriate error handling.

Applying the monkeypatch at import time ensures it's active before BigQuery usage. Error handling gracefully degrades when the library isn't available.


70-70: Cannot verify upstream PR reference; pattern appears intentional.

PR 2331 reference couldn't be located in public repositories. However, the design of passing retry to cancel() is defensible: it maintains consistency with the function's retry parameter and aligns with Google Cloud client patterns. The trade-off (potentially slower cancellation with aggressive retry settings) is worth documenting if not already covered in docstrings.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
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: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 13fd0ee and d5779b0.

📒 Files selected for processing (1)
  • deepnote_toolkit/sql/sql_execution.py (3 hunks)
🧰 Additional context used
🪛 Ruff (0.14.5)
deepnote_toolkit/sql/sql_execution.py

57-57: Dynamically typed expressions (typing.Any) are disallowed in retry

(ANN401)


71-72: try-except-pass detected, consider logging the exception

(S110)


71-71: Do not catch blind exception: Exception

(BLE001)


83-83: Do not catch blind exception: Exception

(BLE001)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Combine and Upload Coverage
  • GitHub Check: Build and push artifacts for Python 3.12
  • GitHub Check: Build and push artifacts for Python 3.9
  • GitHub Check: Build and push artifacts for Python 3.13
  • GitHub Check: Build and push artifacts for Python 3.10
  • GitHub Check: Build and push artifacts for Python 3.11
🔇 Additional comments (2)
deepnote_toolkit/sql/sql_execution.py (2)

7-7: LGTM: Clean import additions.

Imports support the monkeypatch logging and type annotations.

Also applies to: 28-28, 38-38


87-87: Appropriate module-level execution.

Applying the monkeypatch at import time ensures it's active before any BigQuery operations. The comprehensive error handling in the function prevents import failures.

@deepnote-bot
Copy link

deepnote-bot commented Nov 18, 2025

🚀 Review App Deployment Started

📝 Description 🌐 Link / Info
🌍 Review application ra-34
🔑 Sign-in URL Click to sign-in
📊 Application logs View logs
🔄 Actions Click to redeploy
🚀 ArgoCD deployment View deployment
Last deployed 2025-11-19 12:05:31 (UTC)
📜 Deployed commit 0c6bb557024a5b3499e0e041e97c7e303d6b9e98
🛠️ Toolkit version e15efb1

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 18, 2025
@OlegWock OlegWock marked this pull request as ready for review November 18, 2025 17:04
@OlegWock OlegWock requested a review from a team as a code owner November 18, 2025 17:04
…does-not-cancel' of github.com:deepnote/deepnote-toolkit into oleh/blu-5131-moon-active-cancelling-query-in-deepnote-does-not-cancel
Copy link
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: 2

Caution

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

⚠️ Outside diff range comments (1)
deepnote_toolkit/runtime_initialization.py (1)

9-33: Tighten logging and linter story for apply_runtime_patches failure path

Catching Exception here is reasonable (patch failure shouldn’t break runtime), but it’s worth making this explicit and improving diagnostics.

You could both satisfy the linter and get a traceback:

     logger.debug("Initializing Deepnote runtime environment started.")
 
-    try:
-        apply_runtime_patches()
-    except Exception as e:
-        logger.error("Failed to apply runtime patches with a error: %s", e)
+    try:
+        apply_runtime_patches()
+    except Exception:  # pylint: disable=broad-exception-caught  # noqa: BLE001
+        logger.exception("Failed to apply runtime patches with error")

This matches the rest of the file’s defensive style while giving you stack traces when the monkeypatching goes wrong.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between d5779b0 and 8137ef0.

📒 Files selected for processing (3)
  • deepnote_toolkit/runtime_initialization.py (2 hunks)
  • deepnote_toolkit/runtime_patches.py (1 hunks)
  • tests/unit/conftest.py (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (3)
deepnote_toolkit/runtime_initialization.py (2)
deepnote_toolkit/runtime_patches.py (1)
  • apply_runtime_patches (52-53)
tests/unit/conftest.py (1)
  • apply_runtime_patches (11-15)
tests/unit/conftest.py (1)
deepnote_toolkit/runtime_patches.py (1)
  • apply_runtime_patches (52-53)
deepnote_toolkit/runtime_patches.py (1)
tests/unit/conftest.py (1)
  • apply_runtime_patches (11-15)
🪛 Ruff (0.14.5)
deepnote_toolkit/runtime_initialization.py

31-31: Do not catch blind exception: Exception

(BLE001)


32-32: Use logging.exception instead of logging.error

Replace with exception

(TRY400)

deepnote_toolkit/runtime_patches.py

13-13: Missing return type annotation for private function _monkeypatch_bigquery_wait_or_cancel

Add return type annotation: None

(ANN202)


22-22: Dynamically typed expressions (typing.Any) are disallowed in retry

(ANN401)


36-37: try-except-pass detected, consider logging the exception

(S110)


36-36: Do not catch blind exception: Exception

(BLE001)


48-48: Do not catch blind exception: Exception

(BLE001)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: Test - Python 3.9
  • GitHub Check: Test - Python 3.10
  • GitHub Check: Test - Python 3.11
  • GitHub Check: Build and push artifacts for Python 3.10
  • GitHub Check: Build and push artifacts for Python 3.13
  • GitHub Check: Build and push artifacts for Python 3.11
  • GitHub Check: Build and push artifacts for Python 3.9
  • GitHub Check: Build and push artifacts for Python 3.12
🔇 Additional comments (1)
deepnote_toolkit/runtime_patches.py (1)

52-53: Clear single entrypoint for runtime patches

Having apply_runtime_patches() as the only public entry that delegates to private helpers keeps the surface area small and makes future patches easy to add.

@OlegWock OlegWock merged commit 9dadd3d into main Nov 19, 2025
35 checks passed
@OlegWock OlegWock deleted the oleh/blu-5131-moon-active-cancelling-query-in-deepnote-does-not-cancel branch November 19, 2025 12:53
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.

4 participants