Skip to content

fix(#7883): make AsyncExecutor.wait_completion(0) poll instead of waiting forever - #8881

Merged
robfrank merged 4 commits into
mainfrom
fix/7883-python-wait-completion-nonpositive-timeout
Oct 2, 2026
Merged

robfrank merged 4 commits into
mainfrom
fix/7883-python-wait-completion-nonpositive-timeout

Conversation

@robfrank

@robfrank robfrank commented Oct 1, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #7883

AsyncExecutor.wait_completion(timeout_ms) handed any non-None value straight to the engine's waitCompletion(long), which clamps timeout <= 0 to Long.MAX_VALUE. So wait_completion(0) (and any negative value) blocked until the whole queue drained and returned normally, never raising TimeoutError. Now:

Test plan

Python tests in bindings/python/tests/test_async_executor.py (new tests park the async worker inside a query callback on a threading.Event, so "busy" is deterministic rather than a race against the drain):

  • test_async_executor_wait_completion_zero_does_not_block_while_busy - RED before the fix (the call never returned while the worker was parked), GREEN after (raises TimeoutError)
  • test_async_executor_wait_completion_rejects_negative_timeout - RED before (no ValueError, blocked until release), GREEN after
  • test_async_executor_wait_completion_zero_returns_when_idle - wait_completion(0) on an idle executor returns None
  • test_async_executor_wait_completion_positive_timeout_still_times_out - pins the unchanged positive-timeout path (50ms on a busy executor raises, 30000ms on idle returns)
  • test_async_executor.py 13/13 green; test_core.py + test_importer_api.py run alongside: the 2 failures there (numpy not installed locally, one importer test needing newer jars than the local bundle) reproduce identically on unmodified main
  • black / isort --profile black clean

Completeness

Invariant: no caller-supplied timeout reaching the engine's waitCompletion(long) from the Python bindings is <= 0.

Sweep (grep -n "waitCompletion\|timeout" bindings/python/src/arcadedb_embedded/*.py):

Entry point Status
async_executor.py wait_completion(timeout_ms) fixed here, tested
async_executor.py is_pending() already fixed by #7107 (uses isProcessing())
core.py:293 async_().waitCompletion() no-arg overload, no caller timeout - not affected
importer.py:254 java_async.waitCompletion() no-arg overload - not affected

No other timeout parameter exists in the bindings source. git grep finds no doc/example passing a non-default timeout to wait_completion.

Coverage

Entry points covered: AsyncExecutor.wait_completion for 0, negative, positive and None.

Known gaps: None.

Residual risk: a 0 poll is a snapshot from isProcessing(), the same answer is_pending() gives. It is not the engine's looped marker-based waitCompletion barrier (#6462), so a cross-slot edge cascade scheduled between the snapshot and the caller's next action is not covered by a successful poll. Callers needing a barrier should use a positive timeout or no argument; the docstring now says so explicitly (point-in-time snapshot, like is_pending()).

Adversarial pass

No subagent tool was available in this run, so the Phase 1.5 independent pass could not be spawned; a self-review covered: non-int inputs (float/bool are unchanged pre-existing behavior, JPype decides), the error-swallowing is_processing() wrapper (avoided, see above), and the poll-vs-barrier semantics (listed under residual risk).

Review cycles

  • cycle 1: d656e01d - claude: LGTM, optional nits. Applied: close() in finally for the two zero-timeout tests; docstring line stating the 0 poll is a snapshot, not a barrier.
  • cycle 2: cc3f32ce - claude: LGTM, optional nits. Applied: close() in finally in the positive-timeout test.
  • cycle 3: 1ebe49b3 - claude: LGTM, only optional nits (none applied, see below). CodeRabbit: no actionable comments.

Deferred / skipped items

  • "Non-int inputs: 0.0 takes the poll path, but a fractional value like 0.5 goes to the engine and relies on JPype's long coercion. bool is also an int..." - skipped: pre-existing behavior, the reviewer itself recommended leaving it; an int check would be a separate API tightening.
  • "An alternative is to map 0 to the shortest bounded wait (e.g. waitCompletion(1)), which keeps the barrier semantics." - skipped: the issue asks for 0 to mean "do not wait"; reviewer called the snapshot approach defensible. Documented in the docstring instead.
  • "In the busy test, if wait_completion(0) regresses to blocking ... just noting it is intentional." - no change needed.
  • "a None case (unchanged path) is not directly asserted" - skipped: every test's cleanup calls wait_completion().

Final state

clean-approval (3 cycles). Merge is the developer's call.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Zero-timeout waits now check immediately and report a timeout if work is still in progress.
    • Negative timeouts now raise a clear error; indefinite and positive-timeout waits retain their existing behavior.
  • Tests
    • Added coverage for idle, busy, and completing tasks across supported timeout values.

…ting forever

The engine's waitCompletion(long) clamps any timeout <= 0 to Long.MAX_VALUE,
so wait_completion(0) blocked until the queue drained and never raised
TimeoutError. 0 is now answered off isProcessing() (raise TimeoutError if
busy, return if idle) and a negative timeout raises ValueError.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@robfrank robfrank added bug python-bindings Python bindings labels Oct 1, 2026
@mergify

mergify Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again.

@codacy-production

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 0 complexity

Metric Results
Complexity 0

View in Codacy

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@coderabbitai

coderabbitai Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: 9ab919ce-cba0-404e-9704-ba1e05d823f3

📥 Commits

Reviewing files that changed from the base of the PR and between 1ebe49b and 1a6dd40.

📒 Files selected for processing (2)
  • bindings/python/src/arcadedb_embedded/async_executor.py
  • bindings/python/tests/test_async_executor.py

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 2 remain after this review.


📝 Walkthrough

Walkthrough

wait_completion treats a zero timeout as a non-blocking poll and raises TimeoutError when work remains. Negative timeouts raise ValueError. Tests cover these cases and positive-timeout behavior.

Changes

Async executor timeout handling

Layer / File(s) Summary
Define and verify timeout behavior
bindings/python/src/arcadedb_embedded/async_executor.py, bindings/python/tests/test_async_executor.py
wait_completion documents and implements zero-timeout polling and negative-timeout rejection. Tests check prompt timeout while work is active, success when idle, rejection of negative values, and positive-timeout behavior.

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: lvca

Merge Risk: ⚪ Minimal · up to 1a6dd

wait_completion(0) now returns or raises immediately instead of blocking indefinitely, and negative timeouts are rejected with a clear error. Positive and omitted timeouts behave as before. No merge-blocking risk is evident.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 1a6dd

The change is narrowly scoped, but a successful zero-timeout poll can leave already executed writes uncommitted. Callers must not interpret that result as confirmation that writes are visible or durable. No introduced authorization bypass or concrete security attack path was established.

Retained concerns

  • Medium · reliability · observed: wait_completion(0) can now return successfully after write tasks finish but before their batch commits. Unlike the previous marker-based wait, it does not trigger batch commit and its associated failure handling. This weakens the completion boundary callers may use before reading writes or proceeding with dependent operations; the documented snapshot caveat does not distinguish task-idle status from committed visibility.
Security review details

Security Blast Radius

  • inferred — The demonstrated exposure is bounded to callers of the Python executor’s zero-timeout completion method and writes held in that executor’s worker transactions. Dependence by security-sensitive callers or exposure across tenants and services was not established.

Trust Boundaries and Controls

  • observed — The caller-controlled timeout selects validation, status polling or waiting on the same executor instance. The changed branch does not select a different database, forward a query payload or introduce an authority-bearing operation.

Resilience and Maintainability Implications

  • observed — Idle task status and transaction completion are separate lifecycle states. The worker can retain a batch between tasks, while a completion marker invokes batch commit and routes commit exceptions to error handling. Successful zero polling therefore cannot establish that this commit or recovery boundary has completed.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 10 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: zero-timeout calls to AsyncExecutor.wait_completion now poll instead of waiting indefinitely.
Description check ✅ Passed The description thoroughly explains the change, motivation, related issue, test coverage, residual risk, and validation results. It does not explicitly confirm the required mvn clean package checklist…
Linked Issues check ✅ Passed PR #8881 satisfies the coding requirements in issue #7883. AsyncExecutor.wait_completion(0) checks _java_async.isProcessing() and raises TimeoutError while work is active, or returns when idle. …
Out of Scope Changes check ✅ Passed The changes stay within issue #7883. They modify only Python AsyncExecutor.wait_completion and add focused tests for its timeout contract. The diff does not modify the excluded no-argument `waitComp…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


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.

@claude

claude Bot commented Oct 1, 2026

Copy link
Copy Markdown

Review

Overall this is a small, well-scoped fix and I have no blocking concerns.

What I checked

Tests

  • Parking the worker inside a query callback on a threading.Event makes "busy" deterministic. Good approach, and the RED/GREEN evidence in the description is convincing.
  • The caller.join(10) in the zero-timeout test is only a hang detector, not a latency assertion, which fits the repo's no-wall-clock-asserts rule.
  • The four tests cover 0 busy, 0 idle, negative, and positive-timeout regression, i.e. every branch of the new code.

Minor / optional

  1. In test_async_executor_wait_completion_zero_does_not_block_while_busy and ..._zero_returns_when_idle, async_exec.close() is not in a finally. If an assertion or the wait_completion() drain fails, the executor leaks into later tests. The other two tests already use try/finally; making these consistent would be tidy.
  2. In the busy test, if wait_completion(0) regresses to blocking, the daemon thread stays blocked until release.set(), and then async_exec.wait_completion() is called while the caller thread is also in the engine. That is fine for the failure path, just noting it is intentional.
  3. Non-int inputs: 0.0 takes the poll path, but a fractional value like 0.5 goes to the engine and relies on JPype's long coercion. bool is also an int (False behaves like 0, True like 1). You noted this is pre-existing behaviour, so I would leave it, but an int check could be added later if stricter typing is wanted.
  4. The 0 poll is a snapshot, not the marker-based barrier. The docstring says "return if everything is done", which might read slightly stronger than the residual-risk note in the PR description. Consider adding one line to the docstring saying it is a point-in-time snapshot like is_pending().

No security or performance concerns (single non-blocking JNI call). The Java side is untouched, so no engine tests are affected.

LGTM, with the small test-hygiene nit above.

@claude

claude Bot commented Oct 1, 2026

Copy link
Copy Markdown

Review

Overall: a small, correct fix with good tests. I found no blocking issues.

Verified against the engine

  • DatabaseAsyncExecutorImpl.waitCompletion(long) does clamp timeout <= 0 to Long.MAX_VALUE (line ~1208), so the root cause in the description is accurate.
  • Calling _java_async.isProcessing() directly instead of the wrapper is_processing() is the right call. The wrapper returns False on any exception (async_executor.py:248-253), so it would report "idle" for an engine error.
  • None and positive-timeout behaviour are unchanged.

Suggestions (non-blocking)

  1. Poll vs. barrier semantics. The engine's waitCompletion loops while (isProcessing()) to catch cascaded cross-slot edge tasks (Async cross-slot bidirectional edge: waitCompletion() can return before the in-edge is created, and a quiesce index build can miss it #6462). wait_completion(0) is only a snapshot, as the PR notes under residual risk. An alternative is to map 0 to the shortest bounded wait (e.g. waitCompletion(1)), which keeps the barrier semantics. The cost is up to ~1ms of blocking, which arguably contradicts "do not wait". The current snapshot approach is defensible and well documented, so this is only a design note.
  2. Message wording. The ValueError text says "must be None or >= 0". That is accurate, but bool/float inputs still go through unchanged. This is pre-existing behaviour and fine to leave.
  3. Test hygiene. In test_async_executor_wait_completion_positive_timeout_still_times_out the final async_exec.close() is outside a try/finally. If the last wait_completion(30000) assertion fails, the executor is not closed. The other tests use finally, so this one could be made consistent.
  4. Test robustness. The 10s caller.join(10) and 30s event waits are hang detectors rather than latency assertions, which fits the repo guidance on wall-clock assertions. Parking the worker on a threading.Event is a deterministic approach and I like it.

Style / conventions

  • Python-only change, so the CLAUDE.md Java rules (final, fully qualified names, etc.) don't apply.
  • Docstring clearly documents 0, negative values and the engine clamp.
  • No new dependencies, no security or performance concerns (the poll is a cheap non-blocking call).

LGTM once the CI checks are green.

@claude

claude Bot commented Oct 1, 2026

Copy link
Copy Markdown

Review

Small, well-scoped fix. The root cause (the engine's waitCompletion(long) clamping timeout <= 0 to an infinite wait) is correctly identified, and handling 0 via isProcessing() and rejecting negatives fits the earlier is_pending() change (#7107). I found nothing blocking.

Code quality

  • Branch order in wait_completion (None / < 0 / == 0 / positive) is clear. Calling _java_async.isProcessing() directly instead of is_processing() is the right call, since the wrapper turns engine errors into "idle" (async_executor.py:248-253). The inline comment explains that non-obvious choice.
  • The docstring documents the snapshot-vs-barrier difference, which is the real semantic trap for callers. Good.
  • Nit (optional): True/False pass timeout_ms < 0 and == 0 as ints, so wait_completion(False) becomes a poll and wait_completion(True) a 1ms wait. That matches the pre-existing JPype behaviour you noted, so I would not change it here.
  • Nit (optional): the TimeoutError message for the poll case, "(0ms poll)", is fine. The positive-timeout branch uses a different wording, but that is pre-existing.

Potential issues

  • The 0 poll is a snapshot, as the PR already states. isProcessing() also counts commandsInFlight (see DatabaseAsyncExecutorImpl), so in-flight async commands are covered, not only queued tasks. No gap there.
  • No concern about the check-then-act race beyond what is documented. The caller gets "idle at this instant", which is what a poll means.

Performance / security

  • No impact. Poll path is a single non-blocking engine call and no new inputs reach the engine.

Tests

  • Parking the worker in a query callback on a threading.Event makes "busy" deterministic, so the tests are not racy. release.set() sits in finally, so a failing assertion cannot leave the worker parked and hang teardown.
  • All four paths (0 busy, 0 idle, negative, positive) are covered, including a pin on the unchanged positive-timeout behaviour.
  • test_..._zero_does_not_block_while_busy uses a join(10) wall-clock bound. That is acceptable here since it is a hang detector (blocked vs returned) and not a latency assertion, which is consistent with the CLAUDE.md guidance on wall-clock bounds. Failure only costs 10s.
  • Minor: the repo guidance prefers assertj-style assertions for Java, but this is a Python module using plain assert / pytest.raises, which is correct for the surrounding file.
  • Consider (optional): a None case (unchanged path) is not directly asserted, though wait_completion() is used in every test's cleanup, so it is exercised implicitly.

Verdict

LGTM. Ready to merge once CI is green and any open CodeRabbit threads are resolved.

🤖 Generated with Claude Code

@claude

claude Bot commented Oct 2, 2026

Copy link
Copy Markdown

Review

Small, well-scoped fix. Root cause is correct: the engine's waitCompletion(long) clamps timeout <= 0 to an infinite wait, so the old pass-through of 0 could never raise TimeoutError. I found nothing blocking.

Good

  • Calling _java_async.isProcessing() directly instead of is_processing() is the right call. The wrapper at async_executor.py:248 swallows engine exceptions and returns False, which would report a completion that never happened.
  • Rejecting negatives with ValueError is better than silently mapping them to an infinite wait.
  • The docstring is honest about the snapshot-versus-barrier difference, which is the main semantic trade-off here.
  • The tests park the worker on a threading.Event, so "busy" is deterministic. The daemon=True thread plus join(10) guards against the regression turning into a hung suite. Cleanup sits in finally blocks.

Minor / optional

  1. bool and fractional inputs: True goes to the engine as 1 and 0.5 relies on JPype's long coercion. This is pre-existing behaviour, so leaving it is reasonable. A 0 < timeout_ms < 1 float would be the one odd case.
  2. test_..._rejects_negative_timeout and ..._positive_timeout_still_times_out both park a worker and have no extra assertion beyond the exception. That is fine, but they could share a small fixture or context manager for park/release/close to cut repetition (not required).
  3. import pytest is placed after import arcadedb_embedded as arcadedb. If isort groups third-party imports separately, it may want reordering, though the PR says isort --profile black is clean.
  4. wait_completion() with no timeout is not asserted directly. It is covered indirectly by every test's cleanup, so this is fine.

Performance and security: no concerns. The poll path is a single non-blocking JNI call.

CLAUDE.md conventions: the change is Python-binding only, so the Java compile and test requirements don't apply. No new dependencies, and the tests include a regression test for the issue.

LGTM.

@robfrank
robfrank merged commit b7fd73f into main Oct 2, 2026
@robfrank
robfrank deleted the fix/7883-python-wait-completion-nonpositive-timeout branch October 2, 2026 14:16
tae898 added a commit to humemai/arcadedb-embedded-python that referenced this pull request Oct 2, 2026
ArcadeData#8881

The sync through 42c57c2 brought upstream's ArcadeData#8881 change to
AsyncExecutor.wait_completion: timeout_ms=0 no longer waits, it returns
when nothing is pending and raises TimeoutError at once otherwise, and a
negative timeout raises ValueError. The API page and the exceptions page
now say so.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Lj5isEaoaGCeaZe5nNoWX4
robfrank added a commit that referenced this pull request Oct 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug python-bindings Python bindings

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Follow-up to #7107: AsyncExecutor.wait_completion(0) hits the same waitCompletion clamp and blocks until the queue drains instead of timing out

1 participant