diff --git a/README.md b/README.md index 13adeaa..974f41a 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,8 @@ Execute append-only Python while source is still arriving. Python 3.11+, no runtime dependencies. Experimental API. +> The block-streaming API and `aclose()` below are unreleased; they are not in the published `0.1.0a2` release. + ```sh uv add 'partial-python==0.1.0a2' ``` @@ -24,7 +26,29 @@ await executor.finish() # Successful EOF permits baz. `feed()` accepts new text deltas, not accumulated snapshots. `feed()` and `finish()` return completed `Execution` events. The executor retains `events`, `failed_unit`, sealed but unstarted `queued` units, and an immutable `parser_state` snapshot containing the unsealed `pending` tail. Read results from `executor.namespace`. -`finish()` declares successful source completion. On disconnects, token limits, cancellation, or failed responses, use `abort()` for an idle executor; cancel and await an active operation first. Failure is terminal: earlier effects remain, later units do not start, and nothing is retried. [Lifecycle and integration](docs/api.md). +`finish()` declares successful source completion. On disconnects, token limits, cancellation, or failed responses, use `await executor.aclose()` to abandon pending source and release open contexts. `abort()` is a synchronous alternative when no context is open; cancel and await an active operation first. Failure is terminal: earlier effects remain, later units do not start, and nothing is retried. [Lifecycle and integration](docs/api.md). + +## Streaming blocks + +`Executor` and `incremental_exec` accept `stream_blocks`, defaulting to `ALL`. `Block` is a `Flag`; `NONE`, `MODULE`, `IF`, `WITH`, `ASYNC_WITH`, and `ALL` are its aliases, exported from both `partial_python` and `partial_python.blocks`. + +```python +from partial_python import ALL, ASYNC_WITH, MODULE, NONE, WITH, Executor + +executor = Executor() # ALL: stream all supported block kinds. +without_async_contexts = Executor(stream_blocks=ALL & ~ASYNC_WITH) +without_contexts = Executor(stream_blocks=ALL & ~(WITH | ASYNC_WITH)) +top_level_only = Executor(stream_blocks=MODULE) +whole_module = Executor(stream_blocks=NONE) +``` + +The argument **replaces** the selection; it does not extend the default. Include `MODULE` to execute before EOF. Without it, even with another flag selected, the executor buffers the whole source and compiles it once at successful EOF. `NONE` is the explicit whole-module mode. + +`IF`, `WITH`, and `ASYNC_WITH` allow executing stable statements inside those blocks before the enclosing block closes. Conditions and context headers execute once. `ALL` is exactly `MODULE | IF | WITH | ASYNC_WITH`; it does not opt into unsupported compound kinds. Loops, `try`, `match`, functions, and classes still require their complete statement. + +A context can stay open while more source arrives. With `ASYNC_WITH`, an `asyncio.timeout(...)` includes time spent waiting for later source; locks and transactions can also span generation. Disable a flag with `& ~` when that lifetime is unsuitable, or select `MODULE` to hold every compound until it closes. Operations spanning an open context must use the same caller task. + +An early body effect does **not** emit an `Execution` event. Events still represent completed top-level units. A failed or abandoned block can therefore have effects without a completed event, and those effects are never replayed or rolled back. ## Async text iterators @@ -40,6 +64,8 @@ Execution starts while source is arriving; the await completes after execution a ## Stable boundaries +These are the boundaries exposed by `Parser` and by `stream_blocks=MODULE`. The default `ALL` permits earlier body effects in supported blocks without changing the completed top-level units. + | Input | Execution boundary | | --- | --- | | Top-level simple statement | A real logical newline or successful EOF. | @@ -68,7 +94,7 @@ The default returns only the stable prefix. `Allow` flags opt into provisional d Units share one namespace and support native top-level `await`. Execution requires an asyncio event loop; use the asyncio backend with AnyIO. `Parser` and `complete` are synchronous. -This uses sequential compilation units, with [explicit differences from whole-module execution](docs/semantics.md#execution-is-a-sequence-of-compilation-units). Future imports remain in the prologue, only the initial string sets the module docstring, and module-scope `global` declarations are rejected. On Python 3.14+, module annotations require an explicit `from __future__ import annotations`. +With `MODULE` enabled, execution uses sequential compilation units, with [explicit differences from whole-module execution](docs/semantics.md#execution-is-a-sequence-of-compilation-units). Future imports remain in the prologue, only the initial string sets the module docstring, and module-scope `global` declarations are rejected. On Python 3.14+, module annotations require an explicit `from __future__ import annotations`. Choose `NONE` for native whole-module `global` and deferred-annotation semantics. In-process execution provides no sandbox or rollback. Hosts own permissions, background tasks, source limits, and hard deadlines. The [integration examples](docs/api.md#host-examples) demonstrate transport completion, concurrent reception, and traceback source lifetime. diff --git a/docs/api.md b/docs/api.md index 28b6e31..706724b 100644 --- a/docs/api.md +++ b/docs/api.md @@ -2,12 +2,13 @@ ## Public entry points -Start with `Executor.feed()` / `finish()` / `abort()` when integrating a model response. They keep source reception and the provider's completion status explicit. The async iterator APIs adapt sources that already validate successful completion. +Start with `Executor.feed()` / `finish()` / `aclose()` when integrating a model response. They keep source reception and the provider's completion status explicit. The async iterator APIs adapt sources that already validate successful completion. | Entry point | Input | Output | Purpose | | --- | --- | --- | --- | | `Executor.feed(delta)` / `finish()` | Append-only raw Python deltas / explicit EOF | Tuple of completed `Execution` events | Own provider status handling explicitly. | -| `Executor.abort()` | No arguments; executor must be idle | `None`; retains diagnostic state | Abandon pending source without executing it. | +| `await Executor.aclose()` | No arguments; executor must be idle | `None`; awaits open context cleanup | Abandon pending source without declaring EOF. | +| `Executor.abort()` | No arguments; executor must be idle with no open context | `None`; retains diagnostic state | Synchronous abandonment when no context needs cleanup. | | `await incremental_exec(deltas)` | A validated async text iterator | The namespace used, after successful execution | Convenience wrapper when per-unit events are unnecessary. | | `Executor.stream(deltas)` | The same validated iterator | Completed events with retained executor diagnostics | Consume events as each unit completes. | | `Parser.feed(delta)` / `finish()` | Append-only raw Python deltas / explicit EOF | Immutable original-source `CodeUnit` ranges | Integrate with another execution runtime. | @@ -17,28 +18,59 @@ A validated iterator ends normally only after authoritative successful generatio `feed` always means a new delta. It must not accept whole accumulated snapshots implicitly: guessing whether repeated text is a retransmission would make legitimate repeated Python indistinguishable from duplication. A snapshot adapter should independently enforce `new.startswith(previous)` and emit only the new suffix; a changed prefix is terminal. A reconnect adapter needs its own durable replay/offset policy and must not feed an already executed prefix again. -The execution rule should not gain an eager mode that closes an unfinished loop or call. Configuration belongs to preview detail, caller namespace, diagnostics, host resource limits, and transport ownership. Waiting longer is safe; inventing an execution boundary is not a tuning option. +`stream_blocks` selects where stable original statements may execute before their enclosing block closes. It never repairs source or invents an execution boundary. Preview permissions remain separate: `Allow` values cannot be passed as execution options. ## Namespace and results -`Executor(namespace=None, *, filename="")` uses a supplied dictionary as-is. Without one, it creates a namespace with `__name__ = "__main__"`. Include that binding explicitly when a supplied namespace should behave as a script. No module is registered in `sys.modules`. +`Executor(namespace=None, *, filename="", stream_blocks=ALL)` uses a supplied dictionary as-is. Without one, it creates a namespace with `__name__ = "__main__"`. Include that binding explicitly when a supplied namespace should behave as a script. No module is registered in `sys.modules`. -`await incremental_exec(validated_deltas, namespace=None, *, filename="")` follows the same namespace rules and returns that exact dictionary on success. It executes while source arrives; the await finishes only after execution and source cleanup complete. Keep an `Executor` when you need diagnostics after failure; use its `stream()` when you also need events as each unit completes. +`await incremental_exec(validated_deltas, namespace=None, *, filename="", stream_blocks=ALL)` follows the same namespace rules and returns that exact dictionary on success. It executes while source arrives; the await finishes only after execution and source cleanup complete. Keep an `Executor` when you need diagnostics after failure; use its `stream()` when you also need events as each unit completes. -Each `Execution` records its index, original `unit`, and monotonic `started_at` / `completed_at` times. It does not capture expression results or stdout. Assign results in source (`result = await foo()`) and read them from `executor.namespace`. +Each `Execution` records its index, original completed top-level `unit`, and monotonic `started_at` / `completed_at` times. Streaming a body can cause effects before any event exists; its enclosing top-level unit emits only on successful completion. It does not capture expression results or stdout. Assign results in source (`result = await foo()`) and read them from `executor.namespace`. Reuse the namespace with a new executor for another logical model response. Bindings persist; compiler flags do not. Each new stream must repeat its required future imports. See [compilation-unit semantics](semantics.md#execution-is-a-sequence-of-compilation-units). +## Block selection + +`Block` is a `Flag`, not an integer mask. Its members have identical aliases in `partial_python` and `partial_python.blocks`; use either `Block.IF` or `IF`. + +| Option | Effect | +| --- | --- | +| `NONE` | Buffer the whole module and compile it once at successful EOF. | +| `MODULE` | Execute complete top-level units as they arrive, holding all compound bodies until closure. | +| `IF` | Stream stable statements in the selected `if` / `elif` / `else` suite. Each reached condition is evaluated once. | +| `WITH` | Enter synchronous contexts once, stream their stable bodies, and exit when the block closes. | +| `ASYNC_WITH` | The same behavior with awaited context entry and exit. | +| `ALL` | The default: exactly `MODULE \| IF \| WITH \| ASYNC_WITH`; no unimplemented block kinds. | + +Disable flags using bitwise AND with their complement: `ALL & ~ASYNC_WITH`, or `ALL & ~(WITH | ASYNC_WITH)` to hold both context kinds. Use `MODULE` for top-level-only streaming. `NONE` and `ALL & ~MODULE` both select whole-module execution. + +`stream_blocks` replaces the default selection. `MODULE | IF` enables top-level and conditional streaming; `IF` alone does not. Streaming also requires enabled ancestors: `MODULE | IF` cannot stream an `if` nested inside an unselected `with` or a loop. Every selection without `MODULE` buffers and compiles the whole module at EOF, preserving native module-scope `global` declarations and Python 3.14 deferred annotations. Whole-module mode emits one `Execution` even for empty input, which still initializes a missing `__builtins__` binding as native `exec("")` does. `stream_blocks` rejects integers, booleans, and preview `Allow` values. The executor exposes the selected value as its read-only `stream_blocks` property. + +```python +from partial_python import IF, MODULE, Executor + +effects = [] +executor = Executor({"effects": effects}, stream_blocks=MODULE | IF) +assert await executor.feed("if True:\n effects.append('early')\n") == () +assert effects == ["early"] # Body effects precede the completed top-level event. +assert len(await executor.finish()) == 1 +``` + +With the default `ALL`, open contexts span source reception. A real `asyncio.timeout(...)` can expire while the executor awaits the next source chunk; selecting `MODULE` holds that entire context until its source closes. Locks, context variables, and transactions likewise retain their lifetime until the block closes. `for`, `while`, `try`, `match`, function and class definitions still wait for their complete statement. + ## Lifecycle and diagnostics -`finish()` declares authoritative successful source completion. It can release a final call without a newline or an entire compound suite. It is not a generic cleanup method. `abort()` abandons the stream while preserving evidence; `finally: await finish()` is therefore the wrong integration pattern. +`finish()` declares authoritative successful source completion. It can release a final call without a newline or an entire compound suite. It is not a generic cleanup method. `await executor.aclose()` abandons pending source and awaits open context exits; `abort()` provides synchronous abandonment only when no context is open. Neither declares EOF. Cancel and await an active operation before closing the executor; `finally: await finish()` is the wrong integration pattern. + +Operations spanning an open streaming block must run in the task that opened it, including `finish()` and `aclose()`. Ordinary body exceptions follow native context-manager suppression: suppression skips the rest of that with-body, then execution can resume after it. Source failure, invalid EOF, and cancellation remain terminal even when a manager returns a suppression value. An exit method can still raise a replacement exception, as with native Python contexts. Successfully closing an open executor leaves state `"aborted"` without inventing an error. Closing an already terminal executor leaves its state unchanged. -The current diagnostic model is useful when its distinctions are explicit: +Diagnostics describe accepted source and execution progress: | Field | Meaning | | --- | --- | -| `events` | Units that completed successfully; immutable snapshots. | -| `failed_unit` | The attempted unit whose completion was not acknowledged; partial or complete effects may exist. A parser EOF error has no fabricated attempted unit. | +| `events` | Top-level units that completed successfully; immutable snapshots, excluding unfinished blocks with early effects. | +| `failed_unit` | The attempted original-source range whose completion was not acknowledged; it may be a streaming block header or an inner body statement. Partial or complete effects may exist. A parser EOF error has no fabricated attempted unit. | | `queued` | Accepted, sealed units that have not started. Excludes the unsealed tail; retained for diagnostics, not automatic retry. | | `parser_state` | Immutable `ParserState` snapshot of `pending`, `committed`, and `closed`; read the property again for current values. | | `parser_state.pending` | Source still awaiting a grammatical boundary. | @@ -47,7 +79,7 @@ The current diagnostic model is useful when its distinctions are explicit: | `error` | The recorded terminal failure; rejected later calls must not replace it. Native generator control exceptions may be wrapped when propagated; see [exception semantics](semantics.md#failures-cancellation-and-effects). | | `state` | `ExecutorState`: `"open"`, `"finished"`, `"failed"`, or `"aborted"`. | -Successful events plus the failed range, queued ranges and pending tail preserve the accepted source after a mid-chunk failure. Syntax errors retain the original filename and line numbers. Cooperative cancellation is terminal, including when a producer or statement catches `CancelledError` without clearing the new cancellation request. This is not a hard deadline for code that loops forever or deliberately removes cancellation state. +A `CodeUnit` represents an exact source span; the API or field returning it determines whether that span is a completed top-level unit. With `stream_blocks=MODULE`, successful events plus the failed range, queued ranges and pending tail preserve the accepted source after a mid-chunk failure. With block streaming, an unsealed pending range may already have effects, and inner failure ranges can overlap it; these fields are diagnostics, not a resumable execution offset. Syntax errors retain the original filename and line numbers. Cooperative cancellation is terminal, including when a producer or statement catches `CancelledError` without clearing the new cancellation request. This is not a hard deadline for code that loops forever or deliberately removes cancellation state. Catching `CancelledError` can let a unit run its remaining body, assign its result, and return normally. Without `uncancel()`, the outstanding new cancellation still causes `failed_unit` and no success event. The event journal is an acknowledgement record, not a rollback log or proof that an unacknowledged unit had no effects. @@ -57,9 +89,9 @@ Source ranges use half-open character offsets and one-based cursor lines. A fina `Executor.stream(chunks) -> AsyncGenerator[Execution, None]` gives streaming callers per-unit events and access to diagnostics after failure. `incremental_exec()` consumes the same stream in the calling task, handling closure internally without a second execution state machine. -The stream reserves the executor from its first consumption through exhaustion or explicit close, including source waits and suspended event yields. Interleaved `feed`, `finish`, `abort`, or another stream are rejected. Merely constructing an unstarted stream does not acquire the source or reserve the executor. It can continue a prefix already accepted through `feed`. +The stream reserves the executor from its first consumption through exhaustion or explicit close, including source waits and suspended event yields. Interleaved `feed`, `finish`, `abort`, `aclose`, or another stream are rejected. Merely constructing an unstarted stream does not acquire the source or reserve the executor. It can continue a prefix already accepted through `feed`. -The method maintains the same queue/error journal as direct calls and attempts to close its acquired source iterator on exit. Normal validated source exhaustion permits `finish`; early consumer close abandons pending source and retains the unexecuted queue. Runtime failure, invalid EOF, or source failure retain their original exception and source diagnostics. Ordinary cleanup errors must not replace an existing execution failure. New cancellation or process-level interrupts during cleanup propagate with the original failure in Python’s exception chain and leave a failed terminal state. +The method maintains the same queue/error journal as direct calls and attempts to close its acquired source iterator on exit. Normal validated source exhaustion permits `finish`; early consumer close abandons pending source and retains the unexecuted queue. Runtime failure, invalid EOF, or source failure retain their exception and source diagnostics, including native exception replacement by an open context exit. Ordinary source-iterator cleanup errors must not replace an existing execution failure. New cancellation or process-level interrupts during cleanup propagate with the original failure in Python’s exception chain and leave a failed terminal state. An async generator that yields while processing `aclose()` violates Python's close protocol and raises `RuntimeError`. With no earlier failure, the executor records that error and enters `failed`; after an execution failure, an ordinary cleanup exception is attached to the original error as a best-effort note. Broken exception formatting cannot replace that primary failure; a new cancellation or process-level interrupt still propagates. The library does not suppress the violation or promise that a broken iterator has finished releasing its resources. @@ -106,7 +138,7 @@ The example's JSON is record framing: each record is decoded completely before i The standalone executor does not own tasks created by user code. `asyncio.create_task()` must survive parser flushes so a later statement can await the resulting task. Closing or failing a stream does not imply canceling every task in the process: that would also kill unrelated application work. Applications needing scoped cleanup should supply their own task registry or task group around a logical model call. Hard timeouts for CPU-bound code require a process boundary; canceling an asyncio task only works when execution cooperates. -Units execute in the calling task's context, with no hidden task per unit. A single consuming task therefore preserves `ContextVar` changes and tokens across units, which matters for output routing. A shared globals dictionary does not transfer task-local context between separate calls to `asyncio.create_task(anext(events))`. Consume the logical stream in one task and place `asyncio.timeout(...)` around that scope when its context must persist; a source iterator's own context-manager tokens may also require that lifetime. +Units execute in the calling task's context, with no hidden task per unit. A single consuming task therefore preserves `ContextVar` changes and tokens across units, which matters for output routing. A shared globals dictionary does not transfer task-local context between separate calls to `asyncio.create_task(anext(events))`; moving an open streaming block to another task is rejected. Consume the logical stream in one task and place `asyncio.timeout(...)` around that scope when its context must persist; a source iterator's own context-manager tokens may also require that lifetime. For notebook integration, retain a single logical cell's output/history lifecycle while executing its sealed statements. Calling `run_cell_async()` separately for each statement changes `_`, `Out[n]`, final-expression display, transform semantics, and task cleanup. A raw-Python execution backend is the initial default; IPython `%`, `!`, and `%%` forms need their own cell-level contract. diff --git a/docs/design.md b/docs/design.md index d93cf7e..32015de 100644 --- a/docs/design.md +++ b/docs/design.md @@ -4,7 +4,7 @@ The product has three layers: a syntactic commit frontier, an effectful executor, and a provisional display completer. Keeping them separate is essential: a parser accepting a prefix at EOF does not prove future append-only text cannot extend it, and a renderable repaired string must never authorize side effects. -An emitted `CodeUnit` is an exact original-source slice whose AST cannot be extended by a valid continuation. This is syntactic stability, not equivalence to compiling an entire future module or a promise of runtime isolation. See [the semantic contract](semantics.md) for counterexamples and explicit restrictions. +Each `CodeUnit` returned by `Parser` is an exact source slice whose AST cannot be extended by a valid continuation. This is syntactic stability, not equivalence to compiling an entire future module or a promise of runtime isolation. See [the semantic contract](semantics.md) for counterexamples and explicit restrictions. ## Why Python and the standard library @@ -14,7 +14,7 @@ The execution host's `tokenize` supplies lexical candidate boundaries; its compi ## Boundary rules -The [semantic contract](semantics.md#boundaries) defines when an original-source slice is stable. No execution option may relax that boundary; configurable completion belongs to [display preview](preview.md). +The [semantic contract](semantics.md#boundaries) defines when a complete top-level unit is stable. `stream_blocks` also permits stable headers and body statements to execute before their enclosing unit closes. It never authorizes repaired source; completion belongs to [display preview](preview.md). A partial name such as `e` or exact `else` at temporary EOF is still ambiguous. A name that cannot grow into a continuation clause, such as `next`, already proves a successor. Known operator, number and string tokens establish the same boundary, even when the literal itself may still grow. Actual f/t-string start tokens and host-proven opaque string openers also establish successors before their contents finish. Unresolved lexical errors remain conservative. A successor keeps its entire logical-line prefix, including formfeeds and explicit joins, so original columns and physical lines remain intact. For a prefix spanning explicit joins, a native AST probe with a placeholder `pass` verifies that it is truly at module indentation; Python 3.11’s pure-Python tokenizer can disagree with the compiler here. The placeholder never enters a `CodeUnit` or execution. @@ -32,13 +32,13 @@ For a proven unfinished string, a retry gate skips fragments containing no possi A logical response owns one executor and namespace. Units run sequentially; source reception uses pull backpressure. The core creates no reception task. An optional host adapter can overlap reception and execution with explicit queue and task ownership; `examples/overlap.py` verifies that arrangement. No detached tasks are created or cancelled at unit boundaries. A host may own/cancel tasks at the end of the whole logical response. -Failure and cancellation are terminal. The journal separates completed units, the failed attempted unit, sealed units never started, and the unsealed suffix. Parser diagnostics are immutable snapshots so a caller cannot accidentally consume source around the execution journal. Accepted code is never automatically replayed. +Unhandled failures and cancellation are terminal. Events acknowledge completed top-level units; an open block can already have effects while its source remains pending. Failure ranges can overlap that pending source, so diagnostics are not resume offsets. Parser snapshots are immutable, and accepted code is never automatically replayed. `stream` owns its acquired iterator and attempts to await its `aclose()` on every exit when provided. Its write guard stays active across yielded events. Each accepted chunk reaches a cooperative checkpoint even if it is empty or has no sealed unit; an immediately returning buffered source cannot starve cancellation by endlessly supplying unfinished code. Cancellation checks surround each current task's receive/execution/cleanup boundary; historical cancellation counts alone do not poison a fresh operation. Ordinary cleanup errors do not mask an existing execution error. New cancellation or process-level exceptions during cleanup remain observable failures. CPU-bound or cancellation-defeating code requires a process boundary. ## Compiler context -Future flags persist across units with stream-prologue checks. Only the initial string can become a module docstring. Module `global` declarations are rejected. On Python 3.14+, module annotated assignments require source-explicit future annotations so separate lazy annotation functions cannot overwrite one another. Function/class scopes remain intact. Policy traversal skips expressions and uses an explicit stack, avoiding artificial recursion limits on native-compilable expressions. +With `MODULE` enabled, future flags persist across units with stream-prologue checks. Only the initial string can become a module docstring. Module `global` declarations are rejected. On Python 3.14+, module annotated assignments require source-explicit future annotations so separate lazy annotation functions cannot overwrite one another. Function/class scopes remain intact. Policy traversal skips expressions and uses an explicit stack, avoiding artificial recursion limits on native-compilable expressions. Without `MODULE`, the entire source is compiled once at EOF with native module semantics. ## Validation and remaining scope diff --git a/docs/preview.md b/docs/preview.md index ebe3b0a..f145124 100644 --- a/docs/preview.md +++ b/docs/preview.md @@ -1,6 +1,6 @@ # Display completion -`partial_python.complete()` is a separate, display-only API. It never executes source and never configures `Parser` or `Executor`. The runtime executes original `CodeUnit` slices sealed by actual streaming boundaries. +`partial_python.complete()` is a separate, display-only API. It never executes source and never configures `Parser` or `Executor`. Execution uses only stable original source, including statements inside selected open blocks. ```python from partial_python import Allow, complete diff --git a/docs/semantics.md b/docs/semantics.md index 33c1c66..7f64672 100644 --- a/docs/semantics.md +++ b/docs/semantics.md @@ -6,12 +6,14 @@ Let `P` be the source received so far and `C` the source already committed. `C` is an exact, contiguous prefix of `P`: no inserted quotes, brackets, `pass`, indentation, or newlines. For every suffix `S` for which `P + S` is valid under the stream's Python grammar, the committed top-level statements remain an unchanged prefix of its statement AST. Source locations may be translated when comparing standalone slices. -This promise concerns the structure of statements, not every observable property of compiling their surrounding module. Invalid later source cannot retract effects that already happened. An append-only producer cannot revise an earlier token; edits require a new stream. +This promise concerns completed top-level units returned by `Parser` and recorded as execution events. Block streaming can execute stable inner statements before their enclosing top-level unit is committed, so `C` is not an execution watermark. The promise concerns statement structure, not every observable property of compiling the surrounding module. Invalid later source cannot retract effects that already happened. An append-only producer cannot revise an earlier token; edits require a new stream. `feed()` means more characters may arrive. Only `finish()` declares actual EOF. A dropped connection, cancellation, length limit, or failed model response must abort the stream instead of calling `finish()`. A normal async-iterator end is therefore appropriate only when the adapter knows the source completed successfully. ## Boundaries +These are `Parser` boundaries and the `stream_blocks=MODULE` execution boundaries. + | Source received | Reason to wait | | --- | --- | | `foo()` | Can become `foo() + bar()` before the logical newline. | @@ -25,7 +27,7 @@ This promise concerns the structure of statements, not every observable property | `@decorate` | Decorators belong to the following definition. | | A compound followed by the character `e` | The token may still become `else`, `elif`, or `except`. | -A real logical newline seals a top-level simple statement. All semicolon-separated statements on that line are one execution unit. A compound waits for a real, unambiguous top-level successor or explicit EOF. Blank lines and comments do not close suites. One-line compound suites obey the same rule because their continuation clauses can still arrive later. +A real logical newline seals a top-level simple statement. All semicolon-separated statements on that line are one execution unit. A completed compound unit waits for a real, unambiguous top-level successor or explicit EOF. Blank lines and comments do not close suites. One-line compound suites obey the same rule because their continuation clauses can still arrive later. The standard tokenizer creates virtual `NEWLINE` and `DEDENT` tokens at EOF. A parser repeatedly run against a growing buffer therefore reports apparent closures that are not stream boundaries. Likewise, `codeop.compile_command(..., symbol="exec")` accepts a loop whose body can still grow. Neither result alone proves append stability. Python's [lexical rules](https://docs.python.org/3.14/reference/lexical_analysis.html#indentation) and [compound grammar](https://docs.python.org/3.14/reference/compound_stmts.html) explain these distinctions. @@ -33,7 +35,9 @@ All three Python newline conventions are accepted. CRLF remains one physical new ## Execution is a sequence of compilation units -Execution shares one globals dictionary and runs units sequentially, including top-level `await`. Every compound stays in a single unit, so loops, exception handlers, context managers, function bodies, and class bodies retain their ordinary internal control flow. There is no implicit task parallelism. +Execution shares one globals dictionary and runs sequentially, including top-level `await`. The default `ALL` permits stable body statements inside `IF`, `WITH`, and `ASYNC_WITH` to run before those blocks close; loops, exception handlers, function and class definitions remain complete units. Select `MODULE` to execute every compound as a complete unit with native internal control flow. There is no implicit task parallelism. + +Without `MODULE` in the selection, including `NONE`, the executor buffers the entire source and compiles it once at successful EOF. This mode retains native module-scope `global` and deferred-annotation behavior. The incremental-compilation restrictions below apply when `MODULE` is enabled. It is impossible to guarantee arbitrary whole-module equivalence while executing before EOF. These executable counterexamples matter even when lexical boundaries are correct: @@ -52,7 +56,7 @@ b = (1000, 2000) same = a is b ``` -Whole-module constant pooling can produce different object identity from separately compiled units. Frame inspection, code-object constants, tracing, and compilation audit events can also observe the unit boundaries. Programs that depend on those observations must use ordinary whole-module execution. +Whole-module constant pooling can produce different object identity from separately compiled units. Frame inspection, code-object constants, tracing, and compilation audit events can also observe the unit boundaries. Programs that depend on compilation-unit boundaries should select `NONE` or use ordinary whole-module execution. Other deliberate rules address common accidental differences: @@ -65,11 +69,19 @@ Compiler warnings can be emitted by speculative AST probes as well as final comp These distinctions follow the documented [future/global rules](https://docs.python.org/3.14/reference/simple_stmts.html#future), [interactive compiler state](https://docs.python.org/3.14/library/codeop.html), and [AST compilation caveat](https://docs.python.org/3.14/library/ast.html#ast.parse). +## Streaming selected block bodies + +Block streaming retains execution state rather than rerunning a growing source snapshot. An `if` condition is evaluated once when reached; later `elif` and `else` clauses cannot rerun a taken branch. A context header enters each manager once, and successful closure exits managers in reverse order. A suppressed body exception exits that with-statement and skips its remaining body. + +Open blocks retain the caller task. A context stays active during source waits, so `asyncio.timeout(...)`, locks, context variables, and transactions also span those waits. These observable lifetimes are part of the default `ALL` behavior. Disable selected kinds with `ALL & ~ASYNC_WITH` or `ALL & ~(WITH | ASYNC_WITH)`, or select `MODULE` to hold all compounds. Source reception is not isolated in a hidden task. Continue or close an open block from the same task; `await executor.aclose()` releases contexts without completing pending source, while synchronous `abort()` rejects open contexts. + +Events still acknowledge only completed top-level units. A partial body can have irreversible effects with no event, and later invalid source cannot undo them. Flags select supported scopes; they do not enable loops, `try`, `match`, or definition bodies, and they never authorize repaired source. See [block selection](api.md#block-selection) for the exact mask and API. + ## Failures, cancellation, and effects -A completed event means that execution of its unit returned normally. Its timestamps and original source range identify that unit. If compilation, execution, or awaiting raises, the executor becomes terminal. Ordinary Python exception and coroutine rules apply. Earlier effects remain. The failing unit may already have performed effects before it raised; cancellation has the same limitation. No implicit retry is safe. +A completed event means that execution of its unit returned normally. Its timestamps and original source range identify that unit. If a compilation or runtime exception escapes the active Python contexts, the executor becomes terminal. Source failure, invalid EOF, and cancellation are terminal even if an open manager returns a suppression value. Ordinary Python exception and coroutine rules apply. Earlier effects remain. The failing unit may already have performed effects before it raised; cancellation has the same limitation. No implicit retry is safe. -An ordinary source-cleanup error does not replace an execution failure already in flight; it is attached as a best-effort exception note. A new cancellation or process-level exception during cleanup does propagate and becomes `executor.error`; Python’s native `__context__` chain retains the earlier failure. Hosts should retain or render the full exception chain, not only the terminal message. +Open context exits retain native exception replacement, including `asyncio.timeout` converting its cancellation to `TimeoutError`. An ordinary source-iterator cleanup error does not replace an execution failure already in flight; it is attached as a best-effort exception note. A new cancellation or process-level exception during cleanup does propagate and becomes `executor.error`; Python’s native `__context__` chain retains the earlier failure. Hosts should retain or render the full exception chain, not only the terminal message. Iterator control exceptions keep Python’s native behavior. `StopIteration` escaping a coroutine becomes `RuntimeError`; `StopAsyncIteration` raised by executed code becomes `RuntimeError` at the event-stream boundary rather than successful source exhaustion. Its original instance remains in `executor.error` and the propagated exception’s `__cause__`. Conversely, Python’s [`agen.aclose()` protocol](https://docs.python.org/3.14/reference/expressions.html#agen.aclose) consumes a propagated `GeneratorExit`, even one originating in a source closer; the executor still records that cleanup failure. A `GeneratorExit` from source acquisition, reading, or executed code is a failure, distinct from a consumer closing at an event yield. diff --git a/docs/validation.md b/docs/validation.md index e4bae08..30a1fb4 100644 --- a/docs/validation.md +++ b/docs/validation.md @@ -26,10 +26,10 @@ Corpus decoding uses `tokenize.open`, which normalizes newlines. Separate fixtur ## Execution and host integration -Execution tests cover ordering, terminal failure/cancellation, compiler context, source diagnostics, and iterator/task ownership. The [host examples](api.md#host-examples) have tests for real loopback sockets, bounded reception, task cleanup, and persistent traceback source. These controlled fixtures verify behavior; they are not model evaluations or evidence of improved CodeAct performance. +Execution tests cover ordering, terminal failure/cancellation, compiler context, source diagnostics, and iterator/task ownership. Block tests compare native execution across source partitions and cover default `ALL`, flag exclusions, early effects without replay, exception suppression, and cleanup. Gated sources and real `asyncio.timeout()` verify effects and context lifetimes before EOF. The [host examples](api.md#host-examples) have tests for real loopback sockets, bounded reception, task cleanup, and persistent traceback source. These controlled fixtures verify behavior; they are not model evaluations or evidence of improved CodeAct performance. ## Performance and packaging Work-count regressions cover deferred buffer joining, geometric probe windows, delimiter checkpoints, and escape-aware string retry gates. No general linear-time guarantee is made: growing multiline suites, frequent unescaped candidate closers, malformed input, or repeatedly reading the entire growing `pending` value can still incur repeated work. Benchmark representative inputs before changing those optimizations; do not weaken commit boundaries to meet a timing target. -Before release, build and install both wheel and sdist in isolated environments outside the checkout. Verify installed source against the checkout, `py.typed`, zero runtime dependencies, preview behavior, early awaits, compound holdback, and failure cleanup on the oldest and newest supported interpreters. +Before release, build and install both wheel and sdist in isolated environments outside the checkout. Verify installed source against the checkout, `py.typed`, zero runtime dependencies, preview behavior, early awaits, selected block streaming, compound holdback, and failure cleanup on the oldest and newest supported interpreters. diff --git a/examples/tracebacks.py b/examples/tracebacks.py index 299a532..cc21015 100644 --- a/examples/tracebacks.py +++ b/examples/tracebacks.py @@ -38,7 +38,7 @@ async def record_and_execute(executor, source_file, chunks): if task is not None and task.cancelling() > cancellations: raise asyncio.CancelledError except BaseException: - executor.abort() + await executor.aclose() raise else: await executor.finish() # Only normal source exhaustion authorizes EOF. diff --git a/src/partial_python/__init__.py b/src/partial_python/__init__.py index b65d67d..0d4d5aa 100644 --- a/src/partial_python/__init__.py +++ b/src/partial_python/__init__.py @@ -1,7 +1,27 @@ """Safe syntactic boundaries for streaming Python.""" +from .blocks import ALL, ASYNC_WITH, IF, MODULE, NONE, WITH, Block from .executor import Execution, Executor, ExecutorState, ParserState, UnsupportedSyntaxError, incremental_exec from .parser import CodeUnit, Parser from .preview import Allow, Completion, complete -__all__ = ["Allow", "CodeUnit", "Completion", "Execution", "Executor", "ExecutorState", "Parser", "ParserState", "UnsupportedSyntaxError", "complete", "incremental_exec"] +__all__ = [ + "ALL", + "ASYNC_WITH", + "IF", + "MODULE", + "NONE", + "WITH", + "Allow", + "Block", + "CodeUnit", + "Completion", + "Execution", + "Executor", + "ExecutorState", + "Parser", + "ParserState", + "UnsupportedSyntaxError", + "complete", + "incremental_exec", +] diff --git a/src/partial_python/_blocks.py b/src/partial_python/_blocks.py new file mode 100644 index 0000000..e761306 --- /dev/null +++ b/src/partial_python/_blocks.py @@ -0,0 +1,497 @@ +"""Internal lexical events for selected streaming suites. + +Header probes recover AST fields only. Their dummy bodies never become events, +code units, or executable code; every source span points into the original input. +""" + +import ast +import io +import re +import tokenize +from dataclasses import dataclass, field +from typing import Literal + +from .blocks import Block +from .parser import _COMPOUND, _FUTURES, CodeUnit, _candidates, _has_unescaped_closer, _line_end, _normalize, _quote_window, _tree + + +@dataclass(frozen=True, slots=True) +class BlockEvent: + kind: Literal["enter", "branch", "statement", "exit"] + unit: CodeUnit + depth: int + node: ast.Module | ast.If | ast.With | ast.AsyncWith | None = None + + +@dataclass(slots=True) +class _Frame: + node: ast.If | ast.With | ast.AsyncWith + unit: CodeUnit + indent: str + width: int + alternate: int + body_width: int | None = None + body_alternate: int | None = None + body_indent: str | None = None + seen_body: bool = False + seen_else: bool = False + inline: bool = False + parts: list[str] = field(default_factory=list) + + +@dataclass(frozen=True, slots=True) +class _Line: + start: int + end: int | None + tokens: tuple[tokenize.TokenInfo, ...] + indent: str + stable: bool + row_shift: int + token_start: int + + @property + def word(self) -> str: + return self.tokens[0].string + + +_TRIVIA = frozenset({tokenize.COMMENT, tokenize.NL, tokenize.ENCODING, tokenize.INDENT, tokenize.DEDENT, tokenize.ENDMARKER}) +_CLAUSES = ("elif", "else", "except", "finally") +_COMPOUND_WORDS = frozenset({"if", "for", "while", "with", "try", "def", "class", "match", "async", "@"}) + + +def _width(indent: str, tab: int) -> int: + column = 0 + for char in indent: + if char == "\t": + column = (column // tab + 1) * tab + elif char == "\f": + column = 0 + else: + column += 1 + return column + + +def _lines(source: str, prefix: str, eof: bool, *, first_only: bool = False) -> tuple[_Line, ...]: + # CPython 3.12's tokenizer can raise SystemError for NUL. It can never be + # repaired by appending; leave the original span for CPython's EOF diagnostic. + if "\0" in source: + return () + normalized, offsets = _normalize(source + "\n" if eof and source.endswith("\r") else source) + if eof and source.endswith("\r"): + offsets = [min(offset, len(source)) for offset in offsets] + starts = [0, *(index + 1 for index, char in enumerate(normalized) if char == "\n")] + rows = prefix.count("\n") + result: list[_Line] = [] + tokens: list[tokenize.TokenInfo] = [] + indentation = [""] + current_start = 0 + current_indent = "" + + def offset(position: tuple[int, int]) -> int: + row, column = position + row -= rows + index = starts[row - 1] + column if row <= len(starts) else len(normalized) + return offsets[min(index, len(offsets) - 1)] + + def finish(end: int | None) -> None: + if not tokens: + return + first = tokens[0] + start = current_start + indent = current_indent + leading = source[start : offset(first.start)] + joined = list(re.finditer(r"([ \t\f]*)\\(?:\r\n|\r|\n)", leading)) + if joined and joined[0].start() == 0: + # Python 3.11's tokenizer omits indentation after explicit joins. + # CPython uses the first nonempty indentation in this physical chain. + tail = leading[joined[-1].end() :] + if not tail.strip(" \t\f"): + indent = next((match[1] for match in joined if _width(match[1], 8)), tail) + # An unfinished name can still grow into else/elif. Lexical punctuation, + # a complete physical line, or a following character seals its identity. + stable = end is not None or offset(first.end) < len(source) or first.type in {tokenize.OP, tokenize.NUMBER, tokenize.STRING} + stable = stable or (first.type == tokenize.NAME and not any(clause.startswith(first.string) for clause in _CLAUSES)) + result.append(_Line(start, end, tuple(tokens), indent, stable, rows, offset(first.start))) + tokens.clear() + + try: + for token in tokenize.generate_tokens(io.StringIO(prefix + normalized).readline): + if token.type == tokenize.INDENT: + indentation.append(token.string) + elif token.type == tokenize.DEDENT and len(indentation) > 1: + indentation.pop() + if token.start[0] <= rows: + continue + if token.type == tokenize.NEWLINE: + finish(offset(token.end) if token.string or eof else None) + if first_only and result: + break + if token.string: + current_start = offset(token.end) + elif token.type == tokenize.NL and not tokens: + current_start = offset(token.end) + elif token.type not in _TRIVIA: + if not tokens: + current_indent = indentation[-1] + tokens.append(token) + except (tokenize.TokenError, IndentationError, SyntaxError, UnicodeError): + pass + finish(None) + return tuple(result) + + +class BlockParser: + """Emit internal block events with original source spans.""" + + def __init__(self, *, filename: str = "", stream_blocks: Block = Block.MODULE): + self.filename = filename + self.blocks = stream_blocks + self._chunks: list[str] = [] + self._pending_chunks: list[str] = [] + self._pending = "" + self._offset = 0 + self._committed = 0 + self._line = 1 + self._closed = False + self._frames: list[_Frame] = [] + self._flags = 0 + self._reset_scan() + + @property + def pending(self) -> str: + return "".join(self._chunks)[self._committed :] + + @property + def committed(self) -> int: + return self._committed + + @property + def closed(self) -> bool: + return self._closed + + def _ensure_open(self) -> None: + if self._closed: + raise RuntimeError("parser is closed") + + def _reset_scan(self) -> None: + self._scan = 0 + self._retry_full_window = False + self._line_started = False + self._delimiters: tuple[str, ...] = () + self._logical_root = True + self._await_quote = "" + self._quote_tail = "" + self._quote_tail_escaped = False + self._opaque_width: int | None = None + + def _ready(self) -> bool: + # Reuse Parser's lexical checkpoints only as a wakeup gate. Full original + # spans still pass _lines/_parse before any executable event is produced. + scan = self._scan + window_end = len(self._pending) if self._retry_full_window else _line_end(self._pending, scan) + self._retry_full_window = False + while scan < len(self._pending): + checkpoint = None + ready = False + window = self._pending[scan:window_end] + if "\0" in window: + return False + for boundary in _candidates(window, self._delimiters, self._logical_root): + kind = boundary.kind + if kind == "string": + if window_end == len(self._pending): + self._await_quote = boundary.quote + self._quote_tail, self._quote_tail_escaped = _quote_window(self._pending, False) + continue + if kind == "started": + self._line_started = True + if not self._delimiters and (self._frames or self._opaque_width is not None): + lines = _lines(window, self._lexical_prefix(), False, first_only=True) + if lines: + first = lines[0] + width = _width(first.indent, 8) + edge = self._opaque_width if self._opaque_width is not None else self._frames[-1].width + if width <= edge: + self._line_started = first.stable + ready = first.stable and (self._opaque_width is None or width < edge or first.word not in _CLAUSES) + continue + if kind in {"resume", "continuation"}: + self._line_started = kind == "continuation" + self._delimiters = boundary.delimiters + self._logical_root = boundary.logical_root + checkpoint = scan + boundary.offset + ready |= kind == "resume" and self._opaque_width is None + break + if checkpoint is not None and checkpoint > scan: + scan = checkpoint + self._scan = scan + if ready: + return True + window_end = _line_end(self._pending, scan) + else: + if ready: + self._scan = scan + return True + if window_end == len(self._pending): + self._scan = scan + self._retry_full_window = True + # A comment cannot become a statement before its newline. + self._line_started |= not self._delimiters and window.lstrip(" \t\f").startswith("#") + break + window_end = min(len(self._pending), scan + max(1, window_end - scan) * 2) + return False + + def _prefix(self) -> str: + return "".join(frame.indent + "if True:\n" for frame in self._frames) + + def _lexical_prefix(self) -> str: + # Existing body indentation must be present before an explicit join: + # tokenize otherwise loses it when the next physical line starts at zero. + return "".join(frame.indent + "if True:\n" + (frame.body_indent + "pass\n" if frame.body_indent is not None else "") for frame in self._frames) + + def _parse(self, source: str) -> ast.Module: + prefix = self._prefix() + tree = _tree(prefix + source, self.filename, self._flags) + body = tree.body + for _ in self._frames: + node = body[0] + assert isinstance(node, ast.If), "lexical scope prefix changed" + body = node.body + result = ast.Module(body=body, type_ignores=[]) + ast.increment_lineno(result, self._line - 1 - prefix.count("\n")) + return result + + def _unit(self, end: int) -> CodeUnit: + source = self._pending[:end] + last_line = self._line + source.count("\n") + source.count("\r") - source.count("\r\n") + return CodeUnit(source, self._offset, self._offset + end, self._line, last_line) + + def _consume(self, end: int) -> CodeUnit: + unit = self._unit(end) + for frame in self._frames: + frame.parts.append(unit.source) + self._offset = unit.end + self._line = unit.end_line + self._pending = self._pending[end:] + self._reset_scan() + return unit + + def _statement(self, end: int, tree: ast.Module) -> BlockEvent: + if self._frames and tree.body: + self._frames[-1].seen_body = True + for node in tree.body: + if isinstance(node, ast.ImportFrom) and node.module == "__future__": + for name in node.names: + self._flags |= _FUTURES.get(name.name, 0) + unit = self._consume(end) + if not self._frames: + self._committed = unit.end + return BlockEvent("statement", unit, len(self._frames), node=tree) + + def _header(self, line: _Line, branch: bool = False) -> tuple[ast.If | ast.With | ast.AsyncWith, list[ast.stmt], int] | None: + if line.end is None or line.word not in {"if", "with", "async", "elif", "else"}: + return None + source = self._pending[: line.end] + if branch: + # Equal-width replacements preserve the original expression columns. + start = line.token_start + source = source[:start] + ("if " if line.word == "elif" else "if 1") + source[start + 4 :] + multiline = line.tokens[-1].string == ":" + try: + tree = self._parse(source + line.indent + " pass\n" if multiline else source) + except (SyntaxError, ValueError, UnicodeError): + return None + if len(tree.body) != 1 or not isinstance(tree.body[0], (ast.If, ast.With, ast.AsyncWith)): + return None + node = tree.body[0] + body = [] if multiline else node.body + node.body = [] + if isinstance(node, ast.If): + node.orelse = [] + if multiline: + colon = line.tokens[-1] + end = line.end + else: + first = body[0] + before = [ + token + for token in line.tokens + if token.string == ":" and (self._line + token.start[0] - line.row_shift - 1, len(token.line[: token.start[1]].encode())) < (first.lineno, first.col_offset) + ] + if not before: + return None + colon = before[-1] + normalized, offsets = _normalize(self._pending) + row = colon.end[0] - line.row_shift + starts = [0, *(index + 1 for index, char in enumerate(normalized) if char == "\n")] + end = offsets[starts[row - 1] + colon.end[1]] + # A probe pass is never exposed, even through the header's end range. + node.end_lineno = self._line + colon.end[0] - line.row_shift - 1 + node.end_col_offset = len(colon.line[: colon.end[1]].encode()) + return node, body, end + + def _enabled(self, node: ast.If | ast.With | ast.AsyncWith) -> bool: + flag = Block.IF if isinstance(node, ast.If) else Block.ASYNC_WITH if isinstance(node, ast.AsyncWith) else Block.WITH + return bool(self.blocks & flag) + + def _exit(self) -> BlockEvent: + frame = self._frames.pop() + self._reset_scan() + unit = CodeUnit("".join(frame.parts), frame.unit.start, self._offset, frame.unit.start_line, self._line) + if not self._frames: + self._committed = unit.end + return BlockEvent("exit", unit, len(self._frames)) + + def _first_line(self, eof: bool) -> tuple[_Line, ...]: + end = _line_end(self._pending, 0) + while True: + lines = _lines(self._pending[:end], self._lexical_prefix(), eof and end == len(self._pending), first_only=True) + if (lines and lines[0].end is not None) or end == len(self._pending): + return lines + end = min(len(self._pending), max(end * 2, 1)) + + def _drain(self, eof: bool = False) -> tuple[BlockEvent, ...]: + events: list[BlockEvent] = [] + while self._pending: + lines = self._first_line(eof) + if not lines: + if eof: + events.append(self._statement(len(self._pending), ast.Module(body=[], type_ignores=[]))) + break + first = lines[0] + width, alternate = _width(first.indent, 8), _width(first.indent, 1) + if self._frames: + frame = self._frames[-1] + if width <= frame.width: + if width == frame.width and alternate != frame.alternate: + break + if not frame.seen_body: + break + is_branch = isinstance(frame.node, ast.If) and width == frame.width and first.word in {"elif", "else"} + if width == frame.width and isinstance(frame.node, ast.If) and not first.stable: + break + if is_branch: + if first.end is None or frame.seen_else: + break + saved = self._frames.pop() + header = self._header(first, branch=True) + self._frames.append(saved) + if header is None: + break + node, body, end = header + frame.seen_else = first.word == "else" + frame.seen_body = False + frame.body_width = frame.body_alternate = None + frame.body_indent = None + frame.inline = bool(body) + events.append(BlockEvent("branch", self._consume(end), len(self._frames) - 1, node if first.word == "elif" else None)) + if body: + events.append(self._statement(first.end - end, ast.Module(body=body, type_ignores=[]))) + continue + if first.tokens[0].type == tokenize.ERRORTOKEN: + break + # Leading comments belong to the suite that just ended. A + # backslash join is not trivia and stays with its successor. + if first.start: + try: + trivia = self._parse(self._pending[: first.start]) + except (SyntaxError, ValueError, UnicodeError): + trivia = None + if trivia is not None and not trivia.body: + events.append(self._statement(first.start, trivia)) + continue + events.append(self._exit()) + continue + if frame.inline: + break + if frame.body_width is None: + if alternate <= frame.alternate: + break + frame.body_width, frame.body_alternate = width, alternate + frame.body_indent = first.indent + if width != frame.body_width or alternate != frame.body_alternate: + break + elif width: + break + header = self._header(first) + if header is not None and self._enabled(header[0]): + node, body, end = header + if self._frames: + self._frames[-1].seen_body = True + unit = self._consume(end) + events.append(BlockEvent("enter", unit, len(self._frames), node)) + self._frames.append(_Frame(node, unit, first.indent, width, alternate, inline=bool(body), parts=[unit.source])) + assert first.end is not None + if body: + events.append(self._statement(first.end - end, ast.Module(body=body, type_ignores=[]))) + continue + if first.end is not None: + try: + tree = self._parse(self._pending[: first.end]) + except (SyntaxError, ValueError, UnicodeError): + tree = None + if tree is not None and not any(isinstance(node, _COMPOUND) for node in tree.body): + events.append(self._statement(first.end, tree)) + continue + compound = first.word in _COMPOUND_WORDS + if compound: + self._opaque_width = width + lines = _lines(self._pending, self._lexical_prefix(), eof) + end = None + opaque_tree = None + for successor in lines[1:]: + successor_width = _width(successor.indent, 8) + if successor_width > width or (successor_width == width and (not successor.stable or successor.word in _CLAUSES)): + continue + try: + tree = self._parse(self._pending[: successor.start]) + except (SyntaxError, ValueError, UnicodeError): + continue + if tree.body: + end = successor.start + opaque_tree = tree + break + if end is not None and opaque_tree is not None: + events.append(self._statement(end, opaque_tree)) + continue + if eof: + tree = self._parse(self._pending) + events.append(self._statement(len(self._pending), tree)) + continue + break + if eof: + if self._pending: + raise SyntaxError("could not seal the remaining streaming suite", (self.filename, self._line, 1, self._pending.split("\n", 1)[0])) + while self._frames: + events.append(self._exit()) + return tuple(events) + + def feed(self, delta: str) -> tuple[BlockEvent, ...]: + self._ensure_open() + if not isinstance(delta, str): + raise TypeError("delta must be str") + resolves_cr = self._pending.endswith("\r") + if delta: + self._chunks.append(delta) + self._pending_chunks.append(delta) + if self._await_quote: + window = self._quote_tail + delta + if not _has_unescaped_closer(window, self._await_quote, self._quote_tail_escaped): + self._quote_tail, self._quote_tail_escaped = _quote_window(window, self._quote_tail_escaped) + return () + self._await_quote = "" + if self._line_started and not resolves_cr and "\n" not in delta and "\r" not in delta: + return () + self._pending += "".join(self._pending_chunks) + self._pending_chunks.clear() + return self._drain() if self._ready() else () + + def finish(self) -> tuple[BlockEvent, ...]: + self._ensure_open() + self._closed = True + # Only actual EOF validates the entire original program and authorizes + # closure of remaining suites. No probe participates in this validation. + self._pending += "".join(self._pending_chunks) + self._pending_chunks.clear() + _tree("".join(self._chunks), self.filename, self._flags) + return self._drain(True) diff --git a/src/partial_python/_contexts.py b/src/partial_python/_contexts.py new file mode 100644 index 0000000..654c27f --- /dev/null +++ b/src/partial_python/_contexts.py @@ -0,0 +1,98 @@ +"""Native context-manager lifetimes suspended between source fragments.""" + +import ast +from collections.abc import AsyncGenerator +from types import CodeType +from typing import Any, NoReturn, Self, cast + + +def reraise(error: BaseException) -> NoReturn: + """Propagate cleanup failures without replacing their native exception chain.""" + context = error.__context__ + try: + raise error + except BaseException: + error.__context__ = context + raise + + +async def _drive(manager: Any, asynchronous: bool) -> AsyncGenerator[tuple[bool, Any], BaseException | None]: + entered = requested = False + outcome = None + # Recreate the handled-exception state inside the native suite, preserving + # the body traceback and chain. Keep both branches inline: a helper call + # would add a driver frame to the traceback seen by the context manager. + try: + if asynchronous: + async with manager as value: + entered = True + error = yield True, value + requested = True + if error is not None: + traceback, context = error.__traceback__, error.__context__ + try: + raise error + except BaseException: + error.__traceback__, error.__context__ = traceback, context + raise + else: + with manager as value: + entered = True + error = yield True, value + requested = True + if error is not None: + traceback, context = error.__traceback__, error.__context__ + try: + raise error + except BaseException: + error.__traceback__, error.__context__ = traceback, context + raise + except BaseException as error: + # Actual generator closure must never yield, even when a manager replaces + # GeneratorExit. Explicit body errors instead travel as values below. + if entered and not requested: + raise + outcome = error + if not entered or requested: + # Transport exceptions as data: crossing an async-generator boundary can + # otherwise wrap StopIteration/StopAsyncIteration or consume GeneratorExit. + yield False, outcome + + +class Scope: + def __init__(self, driver: AsyncGenerator[tuple[bool, Any], BaseException | None]): + self._driver: AsyncGenerator[tuple[bool, Any], BaseException | None] | None = driver + + @classmethod + async def open(cls, manager: Any, asynchronous: bool) -> tuple[Self | None, Any]: + driver = _drive(manager, asynchronous) + entered, value = await anext(driver) + if not entered: + await driver.aclose() + return None, value + return cls(driver), value + + async def close(self, error: BaseException | None = None) -> BaseException | None: + """Exit once and return the remaining error, avoiding coroutine conversion.""" + driver, self._driver = self._driver, None + if driver is None: + return error + try: + _, outcome = await driver.asend(error) + finally: + await driver.aclose() + return cast(BaseException | None, outcome) + + +def compile_binding(target: ast.expr, filename: str, flags: int) -> tuple[CodeType, int]: + """Compile an as-target without introducing a visible temporary name.""" + # NaN is non-reflexive, so compiler constant pooling cannot merge this fresh + # marker with any target literal, including another constant-folded NaN. + marker = float("nan") + statement = ast.copy_location(ast.Assign(targets=[target], value=ast.copy_location(ast.Constant(marker), target)), target) + tree = ast.fix_missing_locations(ast.Module(body=[statement], type_ignores=[])) + code = cast(CodeType, compile(tree, filename, "exec", flags=flags, dont_inherit=True)) + indices = [index for index, constant in enumerate(code.co_consts) if constant is marker] + if len(indices) != 1: + raise RuntimeError("compiler did not preserve the context binding marker") + return code, indices[0] diff --git a/src/partial_python/blocks.py b/src/partial_python/blocks.py new file mode 100644 index 0000000..2ac3d53 --- /dev/null +++ b/src/partial_python/blocks.py @@ -0,0 +1,24 @@ +"""Explicit scopes for incremental execution; independent of display completion.""" + +from enum import Flag, auto + + +class Block(Flag): + """Select which statement bodies may execute before their enclosing source ends.""" + + NONE = 0 + MODULE = auto() + IF = auto() + WITH = auto() + ASYNC_WITH = auto() + ALL = MODULE | IF | WITH | ASYNC_WITH + + +NONE = Block.NONE +MODULE = Block.MODULE +IF = Block.IF +WITH = Block.WITH +ASYNC_WITH = Block.ASYNC_WITH +ALL = Block.ALL + +__all__ = ["ALL", "ASYNC_WITH", "IF", "MODULE", "NONE", "WITH", "Block"] diff --git a/src/partial_python/executor.py b/src/partial_python/executor.py index f599d61..0bab100 100644 --- a/src/partial_python/executor.py +++ b/src/partial_python/executor.py @@ -1,4 +1,4 @@ -"""Sequential execution of original source under explicit interactive semantics.""" +"""Sequential execution of stable original source.""" import __future__ @@ -9,11 +9,14 @@ from collections import deque from collections.abc import AsyncGenerator, AsyncIterable from contextlib import aclosing -from dataclasses import dataclass +from dataclasses import dataclass, field from time import monotonic from types import CodeType from typing import Any, Literal, cast +from ._blocks import BlockEvent, BlockParser +from ._contexts import Scope, compile_binding, reraise +from .blocks import Block from .parser import _FUTURES, CodeUnit, Parser, _source_line, _tree @@ -27,7 +30,7 @@ def _character_column(text: str, byte_column: int | None) -> int | None: class UnsupportedSyntaxError(SyntaxError): - """Syntax whose cross-unit semantics cannot be preserved by this executor.""" + """Syntax whose semantics cannot be preserved across compilation units.""" @dataclass(frozen=True, slots=True) @@ -45,10 +48,10 @@ class ParserState: @dataclass(frozen=True, slots=True) class Execution: - """One successfully completed unit, with zero-based index and monotonic-second timestamps. + """One completed top-level unit, with a zero-based index and monotonic-second timestamps. - Timing includes compilation and scheduling; an absent event does not prove - that a failed or cancelled unit had no effects. + Timing includes compilation, scheduling, and source waits within open blocks. + An open, failed, or cancelled unit can have effects without a completed event. """ index: int @@ -81,17 +84,78 @@ def visit(self, tree: ast.AST) -> None: pending.extend(reversed(list(ast.iter_child_nodes(node)))) +class _ModuleParser(Parser): + """Buffer a whole compilation unit without speculative parsing or EOF repair.""" + + def feed(self, delta: str) -> tuple[CodeUnit, ...]: + self._ensure_open() + if not isinstance(delta, str): + raise TypeError("delta must be str") + if delta: + self._chunks.append(delta) + return () + + def finish(self) -> tuple[CodeUnit, ...]: + self._ensure_open() + self._closed = True + source = self.pending + self._pending = "" + return (self._statement(source),) + + +@dataclass(slots=True) +class _Frame: + started: float + active: bool + parent_active: bool + taken: bool = False + scopes: list[Scope] = field(default_factory=list) + + +@dataclass(slots=True) +class _Evaluation: + value: Any = None + error: BaseException | None = None + + def unwrap(self) -> Any: + if self.error is not None: + reraise(self.error) + return self.value + + +def _has_frame(error: BaseException, code: CodeType) -> bool: + traceback = error.__traceback__ + while traceback is not None: + if traceback.tb_frame.f_code is code: + return True + traceback = traceback.tb_next + return False + + class Executor: """One append-only execution stream sharing a caller-owned global namespace. + By default, stream stable bodies in if, with, and async with statements. Failure and cancellation are terminal: earlier effects remain, and accepted statements are never retried. This is an in-process executor, not a sandbox. Concurrent or recursive writes are rejected rather than silently reordered. """ - def __init__(self, namespace: dict[str, Any] | None = None, *, filename: str = ""): + def __init__(self, namespace: dict[str, Any] | None = None, *, filename: str = "", stream_blocks: Block = Block.ALL): + if not isinstance(stream_blocks, Block): + raise TypeError("stream_blocks must be a Block member or combination") + self._stream_blocks = stream_blocks self._namespace = namespace if namespace is not None else {"__name__": "__main__"} - self._parser = Parser(filename=filename) + self._parser: Parser | BlockParser + if Block.MODULE not in stream_blocks: + self._parser = _ModuleParser(filename=filename) + elif stream_blocks == Block.MODULE: + self._parser = Parser(filename=filename) + else: + self._parser = BlockParser(filename=filename, stream_blocks=stream_blocks) + self._frames: list[_Frame] = [] + self._owner: asyncio.Task[Any] | None = None + self._started_block: int | None = None self._events: list[Execution] = [] self._flags = ast.PyCF_ALLOW_TOP_LEVEL_AWAIT self._prologue = True @@ -100,7 +164,11 @@ def __init__(self, namespace: dict[str, Any] | None = None, *, filename: str = " self._state: ExecutorState = "open" self._failed_unit: CodeUnit | None = None self._error: BaseException | None = None - self._queued: deque[CodeUnit] = deque() + self._queued: deque[CodeUnit | BlockEvent] = deque() + + @property + def stream_blocks(self) -> Block: + return self._stream_blocks @property def namespace(self) -> dict[str, Any]: @@ -122,7 +190,11 @@ def parser_state(self) -> ParserState: @property def queued(self) -> tuple[CodeUnit, ...]: """Sealed units not yet started; excludes the unsealed ``parser_state.pending`` tail.""" - return tuple(self._queued) + return tuple( + item if isinstance(item, CodeUnit) else item.unit + for item in self._queued + if isinstance(item, CodeUnit) or item.depth == 0 and item.kind in {"statement", "exit"} and item.unit.start != self._started_block + ) @property def events(self) -> tuple[Execution, ...]: @@ -137,28 +209,40 @@ def _enter(self) -> None: raise RuntimeError("executor already has an active operation") if self._state != "open": raise RuntimeError(f"executor is {self._state}") + self._check_owner() self._busy = True + def _check_owner(self) -> None: + if self._frames and self._owner is not asyncio.current_task(): + raise RuntimeError("open streaming blocks must be resumed and closed in their owning task") + def _syntax_error(self, error_type: type[SyntaxError], message: str, statement: CodeUnit, node: ast.stmt, *, shifted: bool = False) -> SyntaxError: line = node.lineno - (statement.start_line - 1 if shifted else 0) text = _source_line(statement.source, line) column = _character_column(text, node.col_offset + 1) return error_type(message, (self._parser.filename, statement.start_line + line - 1, column, text)) - def _compile(self, statement: CodeUnit) -> CodeType: - tree = _tree(statement.source, self._parser.filename, self._flags, statement.start_line) + def _compile(self, statement: CodeUnit, tree: ast.Module | None = None) -> CodeType: + if Block.MODULE not in self._stream_blocks: + # Whole-module mode compiles once and keeps native global/annotation + # semantics. Incremental-unit restrictions do not apply here. + return compile(statement.source, self._parser.filename, "exec", flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT, dont_inherit=True) + shifted = tree is not None + if tree is None: + tree = _tree(statement.source, self._parser.filename, self._flags, statement.start_line) scope = _ModuleScope() scope.visit(tree) if scope.globals: - raise self._syntax_error(UnsupportedSyntaxError, "module-scope global declarations are unsupported across incremental compilation units", statement, scope.globals[0]) + raise self._syntax_error(UnsupportedSyntaxError, "module-scope global declarations are unsupported across incremental compilation units", statement, scope.globals[0], shifted=shifted) future = [node for node in tree.body if isinstance(node, ast.ImportFrom) and node.module == "__future__"] if future and not self._prologue: - raise self._syntax_error(SyntaxError, "from __future__ imports must occur at the beginning of the stream", statement, future[0]) + raise self._syntax_error(SyntaxError, "from __future__ imports must occur at the beginning of the stream", statement, future[0], shifted=shifted) docstring = bool(tree.body and isinstance(tree.body[0], ast.Expr) and isinstance(tree.body[0].value, ast.Constant) and isinstance(tree.body[0].value.value, str)) if docstring and not self._first: # Each code object otherwise treats its first string as a new module docstring. tree.body.insert(0, ast.copy_location(ast.Pass(), tree.body[0])) - ast.increment_lineno(tree, statement.start_line - 1) + if not shifted: + ast.increment_lineno(tree, statement.start_line - 1) try: code = compile(tree, self._parser.filename, "exec", flags=self._flags, dont_inherit=True) except SyntaxError as error: @@ -193,7 +277,9 @@ def _compile(self, statement: CodeUnit) -> CodeType: self._first = False return cast(CodeType, code) - async def _run(self, statement: CodeUnit) -> Execution: + async def _run(self, statement: CodeUnit | BlockEvent) -> Execution | None: + if isinstance(statement, BlockEvent): + return await self._run_block(statement) started = monotonic() try: task = asyncio.current_task() @@ -218,10 +304,164 @@ async def _run(self, statement: CodeUnit) -> Execution: self._events.append(event) return event + async def _evaluate(self, code: CodeType) -> _Evaluation: + try: + result = eval(code, self.namespace, self.namespace) + # Await only syntactic top-level await, never an ordinary expression + # whose value happens to be an awaitable (e.g. a context manager). + if code.co_flags & inspect.CO_COROUTINE: + result = await result + except BaseException as error: # noqa: BLE001 - the enclosing streamed with must see the original exception. + cause = error.__cause__ + # Python 3.11 wraps StopIteration at this artificial module-coroutine + # boundary. A real user-coroutine wrapper has already passed through + # our frame, so it must retain its native RuntimeError semantics. + if code.co_flags & inspect.CO_COROUTINE and type(error) is RuntimeError and isinstance(cause, StopIteration) and _has_frame(cause, code) and not _has_frame(error, code): + error = cause + return _Evaluation(error=error) + return _Evaluation(value=result) + + async def _close_frame(self, frame: _Frame, error: BaseException | None, *, fatal: bool = False) -> BaseException | None: + task = asyncio.current_task() + cancellations = task.cancelling() if task is not None else 0 + while frame.scopes: + scope = frame.scopes.pop() + suppressed = False + try: + remaining = await scope.close(error) + suppressed = error is not None and remaining is None + if not suppressed: + error = remaining + except BaseException as replacement: # noqa: BLE001 - outer exits must receive cleanup failures, including cancellation. + error = replacement + # A cleanup can swallow a newly delivered cancellation. Preserve it + # before another manager could mistake this for normal completion. + if task is not None and task.cancelling() > cancellations: + cancellations = task.cancelling() + fatal = True + if suppressed or error is None: + cancellation = asyncio.CancelledError() + cancellation.__context__ = error + error = cancellation + if suppressed and not fatal: + error = None + return error + + async def _unwind(self, error: BaseException, *, fatal: bool = False) -> BaseException | None: + current: BaseException | None = error + task = asyncio.current_task() + cancellations = task.cancelling() if task is not None else 0 + # Keep structural frames until parser exits arrive, even after resources + # close: a suppressed exception must still skip its unread suite. + for frame in reversed(self._frames): + frame.active = frame.parent_active = False + current = await self._close_frame(frame, current, fatal=fatal) + fatal |= task is not None and task.cancelling() > cancellations + if current is None: + # Suppression exits this with statement. Its unread body stays + # inactive, while the enclosing suite may continue when it closes. + return None + return current + + async def _fail(self, error: BaseException) -> BaseException: + # Source failure/cancellation is never successful EOF. Even a manager + # that suppresses it cannot authorize more execution or a normal commit. + remaining = await self._unwind(error, fatal=True) + if remaining is not None: + error = remaining + self._frames.clear() + self._owner = None + self._error = error + self._state = "failed" + return error + + async def _run_block(self, item: BlockEvent) -> Execution | None: + if item.kind == "enter" and item.depth == 0: + self._started_block = item.unit.start + started = monotonic() + task = asyncio.current_task() + cancellations = task.cancelling() if task is not None else 0 + try: + await asyncio.sleep(0) + node = item.node + code = None + bindings: list[tuple[CodeType, tuple[CodeType, int] | None]] = [] + if item.kind == "statement": + assert isinstance(node, ast.Module) + code = self._compile(item.unit, node) + elif item.kind in {"enter", "branch"}: + self._first = self._prologue = False + if isinstance(node, ast.If): + code = compile(ast.Expression(node.test), self._parser.filename, "eval", flags=self._flags, dont_inherit=True) + elif isinstance(node, (ast.With, ast.AsyncWith)): + for context in node.items: + expression = compile(ast.Expression(context.context_expr), self._parser.filename, "eval", flags=self._flags, dont_inherit=True) + binding = compile_binding(context.optional_vars, self._parser.filename, self._flags) if context.optional_vars is not None else None + bindings.append((expression, binding)) + # Compile even inactive suites, but never let a with suppress a + # compiler error. Only actual user-code execution is handled below. + except BaseException: + self._failed_unit = item.unit + raise + try: + if item.kind == "enter": + active = not self._frames or self._frames[-1].active + frame = _Frame(started, active, active) + self._frames.append(frame) + self._owner = task + if isinstance(node, ast.If): + assert code is not None + frame.active = frame.taken = active and bool((await self._evaluate(code)).unwrap()) + elif active: + for expression, binding in bindings: + manager = (await self._evaluate(expression)).unwrap() + scope, value = await Scope.open(manager, isinstance(node, ast.AsyncWith)) + if scope is None: + reraise(value) + frame.scopes.append(scope) + if binding is not None: + assignment, index = binding + constants = list(assignment.co_consts) + constants[index] = value + (await self._evaluate(assignment.replace(co_consts=tuple(constants)))).unwrap() + elif item.kind == "branch": + frame = self._frames[-1] + frame.active = frame.parent_active and not frame.taken and (code is None or bool((await self._evaluate(code)).unwrap())) + frame.taken |= frame.active + elif item.kind == "statement": + assert code is not None + if not self._frames or self._frames[-1].active: + (await self._evaluate(code)).unwrap() + else: + frame = self._frames.pop() + started = frame.started + error = await self._close_frame(frame, None) + if error is not None: + reraise(error) + if not self._frames: + self._owner = None + if task is not None and task.cancelling() > cancellations: + raise asyncio.CancelledError + except BaseException as error: # noqa: BLE001 - native with may suppress any user exception. + self._failed_unit = item.unit + fatal = task is not None and task.cancelling() > cancellations + remaining = await self._unwind(error, fatal=fatal) + if remaining is not None: + reraise(remaining) + if task is not None and task.cancelling() > cancellations: + raise asyncio.CancelledError + self._failed_unit = None + if item.depth == 0 and item.kind in {"statement", "exit"}: + self._started_block = None + event = Execution(len(self._events), item.unit, started, monotonic()) + self._events.append(event) + return event + return None + async def feed(self, delta: str) -> tuple[Execution, ...]: - """Append new source and execute its sealed units in order. + """Append new source and execute stable code in order. - Return only this call's completed events. On failure, earlier effects + Return only this call's completed top-level events. On failure, earlier effects remain; inspect ``events``, ``failed_unit``, ``queued`` and ``parser_state``. """ self._enter() @@ -229,11 +469,14 @@ async def feed(self, delta: str) -> tuple[Execution, ...]: self._queued.extend(self._parser.feed(delta)) events = [] while self._queued: - events.append(await self._run(self._queued.popleft())) + event = await self._run(self._queued.popleft()) + if event is not None: + events.append(event) return tuple(events) except BaseException as error: - self._error = error - self._state = "failed" + failure = await self._fail(error) + if failure is not error: + reraise(failure) raise finally: self._busy = False @@ -249,23 +492,56 @@ async def finish(self) -> tuple[Execution, ...]: self._queued.extend(self._parser.finish()) events = [] while self._queued: - events.append(await self._run(self._queued.popleft())) + event = await self._run(self._queued.popleft()) + if event is not None: + events.append(event) self._state = "finished" return tuple(events) except BaseException as error: - self._error = error - self._state = "failed" + failure = await self._fail(error) + if failure is not error: + reraise(failure) raise finally: self._busy = False def abort(self) -> None: - """Abandon pending source after a transport failure, retaining it for diagnostics.""" + """Abandon pending source when no context is open, retaining it for diagnostics.""" if self._busy: raise RuntimeError("cancel the active operation before aborting") + if any(frame.scopes for frame in self._frames): + raise RuntimeError("open contexts require `await executor.aclose()`") if self._state == "open": + self._frames.clear() + self._owner = None self._state = "aborted" + async def aclose(self) -> None: + """Abandon source and await open context exits without declaring EOF.""" + if self._busy: + raise RuntimeError("cancel the active operation before closing") + if self._state != "open": + return + self._enter() + try: + task = asyncio.current_task() + cancellations = task.cancelling() if task is not None else 0 + abandoned = GeneratorExit() + error = await self._unwind(abandoned, fatal=True) + if error is not abandoned and error is not None: + reraise(error) + if task is not None and task.cancelling() > cancellations: + raise asyncio.CancelledError + self._state = "aborted" + except BaseException as error: + self._error = error + self._state = "failed" + raise + finally: + self._frames.clear() + self._owner = None + self._busy = False + async def stream(self, chunks: AsyncIterable[str]) -> AsyncGenerator[Execution, None]: """Execute a source iterator, retaining diagnostics on this executor. @@ -280,7 +556,8 @@ async def stream(self, chunks: AsyncIterable[str]) -> AsyncGenerator[Execution, try: iterator = aiter(chunks) while True: - # Each anext may be resumed by a different task (e.g. wait_for). + self._check_owner() + # With no open block, each anext may resume in a different task. task = asyncio.current_task() cancellations = task.cancelling() if task is not None else 0 try: @@ -298,22 +575,25 @@ async def stream(self, chunks: AsyncIterable[str]) -> AsyncGenerator[Execution, await asyncio.sleep(0) while self._queued: event = await self._run(self._queued.popleft()) - yielding = True - yield event - yielding = False + if event is not None: + yielding = True + yield event + yielding = False self._queued.extend(self._parser.finish()) while self._queued: event = await self._run(self._queued.popleft()) - yielding = True - yield event - yielding = False + if event is not None: + yielding = True + yield event + yielding = False self._state = "finished" except BaseException as error: # Only GeneratorExit injected at our event yield is consumer closure. # The same exception from a source or executed unit is a real failure. if not (yielding and isinstance(error, GeneratorExit)): - self._error = error - self._state = "failed" + failure = await self._fail(error) + if failure is not error: + reraise(failure) raise finally: if self._state == "open": @@ -345,13 +625,13 @@ async def stream(self, chunks: AsyncIterable[str]) -> AsyncGenerator[Execution, self._busy = False -async def incremental_exec(chunks: AsyncIterable[str], namespace: dict[str, Any] | None = None, *, filename: str = "") -> dict[str, Any]: +async def incremental_exec(chunks: AsyncIterable[str], namespace: dict[str, Any] | None = None, *, filename: str = "", stream_blocks: Block = Block.ALL) -> dict[str, Any]: """Execute validated source as it arrives and return the namespace used. Normal iterator exhaustion authorizes EOF. The source adapter must raise on truncation or failure. Use ``Executor.stream`` for events and diagnostics. """ - executor = Executor(namespace, filename=filename) + executor = Executor(namespace, filename=filename, stream_blocks=stream_blocks) async with aclosing(executor.stream(chunks)) as events: async for _ in events: pass diff --git a/tests/test_async_scope.py b/tests/test_async_scope.py index ce3a0e8..f75ef9c 100644 --- a/tests/test_async_scope.py +++ b/tests/test_async_scope.py @@ -7,7 +7,7 @@ import pytest -from partial_python import Executor +from partial_python import MODULE, Executor async def numbers(): @@ -113,7 +113,7 @@ async def manager(): else: calls.append('else') """ - executor = Executor({"manager": manager, "numbers": numbers, "double": double, "calls": calls}) + executor = Executor({"manager": manager, "numbers": numbers, "double": double, "calls": calls}, stream_blocks=MODULE) for character in source: assert await executor.feed(character) == () assert calls == [] diff --git a/tests/test_block_execution.py b/tests/test_block_execution.py new file mode 100644 index 0000000..a5a60c1 --- /dev/null +++ b/tests/test_block_execution.py @@ -0,0 +1,623 @@ +"""Public streaming-block behavior: source delivery must never replay effects.""" + +import asyncio +import sys +from types import ModuleType + +import pytest + +from partial_python import ALL, ASYNC_WITH, IF, MODULE, NONE, WITH, Executor, incremental_exec +from partial_python.preview import Allow + + +class Scope: + def __init__(self, effects, name="scope", suppress=()): + self.effects = effects + self.name = name + self.suppress = suppress + self.exits = [] + self.tasks = [] + + def __enter__(self): + self.tasks.append(asyncio.current_task()) + self.effects.append(("enter", self.name)) + return self.name + + def __exit__(self, error_type, error, traceback): + self.tasks.append(asyncio.current_task()) + self.exits.append(error) + self.effects.append(("exit", self.name)) + return isinstance(error, self.suppress) + + +class AsyncScope(Scope): + async def __aenter__(self): + return self.__enter__() + + async def __aexit__(self, error_type, error, traceback): + return self.__exit__(error_type, error, traceback) + + +@pytest.mark.parametrize("options", [{}, {"stream_blocks": MODULE}]) +async def test_default_and_explicit_module_keep_loops_opaque(options): + effects = [] + executor = Executor({"effects": effects}, **options) + first = await executor.feed("effects.append('first')\n") + assert len(first) == 1 and effects == ["first"] + assert await executor.feed("for item in ['loop']:\n effects.append(item)\n") == () + assert effects == ["first"] + last = await executor.finish() + assert len(last) == 1 and effects == ["first", "loop"] + assert [event.index for event in executor.events] == [0, 1] + + +@pytest.mark.parametrize("options", [{}, {"stream_blocks": ALL}], ids=["default", "all"]) +async def test_default_streams_each_supported_block_once(options): + effects = [] + sync_scope, async_scope = Scope(effects, "sync"), AsyncScope(effects, "async") + + def condition(): + effects.append("condition") + return True + + executor = Executor({"effects": effects, "condition": condition, "sync_scope": sync_scope, "async_scope": async_scope}, **options) + assert executor.stream_blocks == ALL + source = "if condition():\n with sync_scope:\n async with async_scope:\n effects.append('first')\n" + for character in source: + assert await executor.feed(character) == () + assert effects == ["condition", ("enter", "sync"), ("enter", "async"), "first"] + assert sync_scope.exits == async_scope.exits == [] + assert await executor.feed(" effects.append('second')\n") == () + assert effects[-1] == "second" and executor.events == () + events = await executor.feed("effects.append('after')\n") + assert [event.index for event in events] == [0, 1] + assert effects == ["condition", ("enter", "sync"), ("enter", "async"), "first", "second", ("exit", "async"), ("exit", "sync"), "after"] + assert sync_scope.exits == async_scope.exits == [None] + assert sync_scope.tasks == async_scope.tasks == [asyncio.current_task()] * 2 + assert await executor.finish() == () + + +@pytest.mark.parametrize("options", [{}, {"stream_blocks": ALL}], ids=["default", "all"]) +async def test_incremental_exec_default_streams_before_source_exhaustion(options): + effects = [] + scope = AsyncScope(effects) + + async def chunks(): + yield "if True:\n async with scope:\n effects.append('first')\n" + assert effects == [("enter", "scope"), "first"] and scope.exits == [] + yield " effects.append('second')\n" + assert effects == [("enter", "scope"), "first", "second"] and scope.exits == [] + + namespace = {"effects": effects, "scope": scope} + assert await incremental_exec(chunks(), namespace, **options) is namespace + assert effects == [("enter", "scope"), "first", "second", ("exit", "scope")] + assert scope.exits == [None] + + +@pytest.mark.parametrize("stream_blocks", [ALL & ~ASYNC_WITH, ALL & ~(WITH | ASYNC_WITH)], ids=["without-async-with", "without-contexts"]) +@pytest.mark.parametrize("scope_type,keyword,flag", [(Scope, "with", WITH), (AsyncScope, "async with", ASYNC_WITH)]) +async def test_excluded_contexts_wait_for_closure_while_if_still_streams(stream_blocks, scope_type, keyword, flag): + effects = [] + scope = scope_type(effects) + executor = Executor({"effects": effects, "scope": scope}, stream_blocks=stream_blocks) + source = f"if True:\n effects.append('before')\n {keyword} scope:\n effects.append('inside')\n" + assert await executor.feed(source) == () + assert effects == (["before", ("enter", "scope"), "inside"] if flag in stream_blocks else ["before"]) + assert scope.exits == [] and executor.events == () + assert await executor.feed(" effects.append('after-context')\n") == () + assert effects == ["before", ("enter", "scope"), "inside", ("exit", "scope"), "after-context"] + assert scope.exits == [None] + assert len(await executor.finish()) == 1 + assert scope.tasks == [asyncio.current_task()] * 2 + + +@pytest.mark.parametrize("stream_blocks", [NONE, ALL & ~MODULE], ids=["none", "without-module"]) +async def test_without_module_buffers_and_executes_one_module_in_the_caller_namespace(stream_blocks): + effects = [] + namespace = {"effects": effects, "value": 40} + executor = Executor(namespace, stream_blocks=stream_blocks) + source = "global value\nvalue += 2\neffects.append(value)\n" + for character in source: + assert await executor.feed(character) == () + assert effects == [] and namespace["value"] == 40 and executor.events == () + events = await executor.finish() + assert executor.namespace is namespace + assert effects == [42] and namespace["value"] == 42 + assert len(events) == 1 and events[0].unit.source == source + assert executor.events == events and executor.state == "finished" + + +@pytest.mark.parametrize("stream_blocks", [NONE, ALL & ~MODULE], ids=["none", "without-module"]) +async def test_without_module_compiles_all_source_before_any_effect(stream_blocks): + effects = [] + executor = Executor({"effects": effects}, stream_blocks=stream_blocks) + assert await executor.feed("effects.append('never')\nglobal effects\n") == () + with pytest.raises(SyntaxError): + await executor.finish() + assert effects == [] and executor.events == () and executor.state == "failed" + + +@pytest.mark.parametrize("stream_blocks", [NONE, ALL & ~MODULE], ids=["none", "without-module"]) +async def test_without_module_preserves_module_future_and_docstring_semantics(stream_blocks): + namespace = {} + executor = Executor(namespace, stream_blocks=stream_blocks) + source = '"whole module"\nfrom __future__ import annotations\nvalue: Missing = 3\n"later expression"\n' + for line in source.splitlines(keepends=True): + assert await executor.feed(line) == () + assert namespace == {} + await executor.finish() + assert namespace["__doc__"] == "whole module" + assert namespace["__annotations__"] == {"value": "Missing"} + assert namespace["value"] == 3 + + +@pytest.mark.skipif(sys.version_info < (3, 14), reason="deferred module annotations require Python 3.14") +async def test_none_preserves_deferred_module_annotations_without_future_import(): + import annotationlib + + actual, expected = ModuleType("actual"), ModuleType("expected") + source = "first: int = 1\nsecond: str = 'two'\n" + exec(compile(source, "native_module.py", "exec", dont_inherit=True), expected.__dict__) # noqa: S102 - compare against native whole-module semantics. + executor = Executor(actual.__dict__, stream_blocks=NONE) + for line in source.splitlines(keepends=True): + assert await executor.feed(line) == () + await executor.finish() + assert annotationlib.get_annotations(actual) == annotationlib.get_annotations(expected) == {"first": int, "second": str} + assert actual.first == 1 and actual.second == "two" + + +async def test_none_abort_never_executes_valid_buffered_source(): + effects = [] + executor = Executor({"effects": effects}, stream_blocks=NONE) + await executor.feed("effects.append('never')\n") + executor.abort() + assert executor.state == "aborted" and executor.error is None and effects == [] + with pytest.raises(RuntimeError): + await executor.finish() + assert effects == [] + + +async def test_none_source_failure_does_not_execute_buffered_code(): + effects, closed = [], [] + failure = OSError("transport broke") + + async def chunks(): + try: + yield "effects.append('never')\n" + raise failure + finally: + closed.append(True) + + executor = Executor({"effects": effects}, stream_blocks=NONE) + with pytest.raises(OSError) as caught: + async for _ in executor.stream(chunks()): + pytest.fail("a failed whole-module source cannot complete an execution") + assert caught.value is failure and executor.error is failure + assert effects == [] and closed == [True] and executor.state == "failed" + + +async def test_none_cancellation_during_finish_stops_the_module(): + effects = [] + entered = asyncio.Event() + + async def wait(): + entered.set() + await asyncio.Event().wait() + + executor = Executor({"effects": effects, "wait": wait}, stream_blocks=NONE) + await executor.feed("effects.append('before')\nawait wait()\neffects.append('never')\n") + assert not entered.is_set() and effects == [] + task = asyncio.create_task(executor.finish()) + try: + await asyncio.wait_for(entered.wait(), 1) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert effects == ["before"] and executor.state == "failed" and executor.events == () + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.parametrize("invalid", [0, 1, False, True, None, "MODULE", Allow.NONE, Allow.ALL]) +def test_stream_blocks_rejects_values_from_other_option_domains(invalid): + with pytest.raises(TypeError, match="Block|stream_blocks"): + Executor(stream_blocks=invalid) + + +@pytest.mark.parametrize("first,second,selected,conditions", [(True, True, "if", ["if"]), (False, True, "elif", ["if", "elif"]), (False, False, "else", ["if", "elif"])]) +async def test_if_branches_cross_chunks_without_reevaluating_conditions(first, second, selected, conditions): + effects, evaluated = [], [] + + def condition(label): + evaluated.append(label) + return first if label == "if" else second + + executor = Executor({"effects": effects, "condition": condition}, stream_blocks=MODULE | IF) + chunks = ["if condition('if'):\n effects.append('if')\n", "elif condition('elif'):\n effects.append('elif')\n", "else:\n effects.append('else')\n"] + for index, chunk in enumerate(chunks): + assert await executor.feed(chunk) == () + assert effects == ([selected] if ["if", "elif", "else"].index(selected) <= index else []) + assert evaluated == conditions and executor.events == () + events = await executor.finish() + assert len(events) == 1 and events[0].unit.source == "".join(chunks) + assert evaluated == conditions and effects == [selected] + + +async def test_if_condition_and_body_remain_once_only_at_character_boundaries(): + effects = [] + + def condition(): + effects.append("condition") + return True + + executor = Executor({"effects": effects, "condition": condition}, stream_blocks=ALL) + for character in "if condition():\n effects.append('body')\n": + assert await executor.feed(character) == () + assert effects == ["condition", "body"] and executor.events == () + for character in "else:\n effects.append('never')\n": + assert await executor.feed(character) == () + assert len(await executor.finish()) == 1 + assert effects == ["condition", "body"] + + +@pytest.mark.parametrize("scope_type,keyword,flag", [(Scope, "with", WITH), (AsyncScope, "async with", ASYNC_WITH)]) +async def test_context_header_and_stable_body_execute_once_before_its_event(scope_type, keyword, flag): + effects, made = [], [] + scope = scope_type(effects) + owner = asyncio.current_task() + + def make(): + made.append(True) + return scope + + executor = Executor({"effects": effects, "make": make}, stream_blocks=MODULE | flag) + first = f"{keyword} make() as value:\n effects.append(value)\n" + assert await executor.feed(first) == () + assert made == [True] and effects == [("enter", "scope"), "scope"] + assert scope.exits == [] and executor.events == () + assert await executor.feed(" effects.append('second')\n") == () + assert effects == [("enter", "scope"), "scope", "second"] + events = await executor.feed("effects.append('after')\n") + assert len(events) == 2 and scope.exits == [None] + assert effects == [("enter", "scope"), "scope", "second", ("exit", "scope"), "after"] + assert scope.tasks == [owner, owner] and made == [True] + assert await executor.finish() == () + + +@pytest.mark.parametrize("scope_type,keyword", [(Scope, "with"), (AsyncScope, "async with")]) +async def test_multiple_context_managers_enter_once_and_exit_in_reverse_order(scope_type, keyword): + effects = [] + outer, inner = scope_type(effects, "outer"), scope_type(effects, "inner") + executor = Executor({"effects": effects, "outer": outer, "inner": inner}, stream_blocks=ALL) + assert await executor.feed(f"{keyword} outer as first, inner as second:\n effects.append((first, second))\n") == () + assert effects == [("enter", "outer"), ("enter", "inner"), ("outer", "inner")] + assert len(await executor.finish()) == 1 + assert effects[-2:] == [("exit", "inner"), ("exit", "outer")] + assert outer.exits == inner.exits == [None] + + +@pytest.mark.parametrize("scope_type,keyword", [(Scope, "with"), (AsyncScope, "async with")]) +async def test_suppressed_body_failure_skips_remaining_body_but_not_following_unit(scope_type, keyword): + effects = [] + failure = ValueError("body failed") + scope = scope_type(effects, suppress=(ValueError,)) + executor = Executor({"effects": effects, "scope": scope, "failure": failure}, stream_blocks=ALL) + assert await executor.feed(f"{keyword} scope:\n effects.append('before')\n raise failure\n") == () + assert effects == [("enter", "scope"), "before", ("exit", "scope")] + assert scope.exits == [failure] and executor.state == "open" + assert await executor.feed(" effects.append('skipped')\n") == () + events = await executor.feed("effects.append('after')\n") + assert len(events) == 2 and effects[-1] == "after" and "skipped" not in effects + assert scope.exits == [failure] + await executor.finish() + + +@pytest.mark.parametrize("scope_type,keyword", [(Scope, "with"), (AsyncScope, "async with")]) +async def test_unsuppressed_body_failure_closes_context_without_replaying_prefix(scope_type, keyword): + effects = [] + failure = ValueError("body failed") + scope = scope_type(effects) + executor = Executor({"effects": effects, "scope": scope, "failure": failure}, stream_blocks=ALL) + with pytest.raises(ValueError) as caught: + await executor.feed(f"{keyword} scope:\n effects.append('before')\n raise failure\n effects.append('never')\n") + assert caught.value is failure and executor.error is failure and executor.state == "failed" + assert effects == [("enter", "scope"), "before", ("exit", "scope")] + assert scope.exits == [failure] and executor.events == () + with pytest.raises(RuntimeError): + await executor.finish() + await executor.aclose() + assert scope.exits == [failure] + + +@pytest.mark.parametrize("scope_type,keyword", [(Scope, "with"), (AsyncScope, "async with")]) +@pytest.mark.parametrize("options", [{}, {"stream_blocks": ALL}], ids=["default", "all"]) +async def test_transport_failure_closes_open_context_and_cannot_be_suppressed_as_eof(scope_type, keyword, options): + effects, closed = [], [] + scope = scope_type(effects, suppress=(BaseException,)) + failure = OSError("source disconnected") + + async def chunks(): + try: + yield f"{keyword} scope:\n effects.append('before')\n" + assert effects == [("enter", "scope"), "before"] + raise failure + finally: + closed.append(True) + + executor = Executor({"effects": effects, "scope": scope}, **options) + with pytest.raises(OSError) as caught: + async for _ in executor.stream(chunks()): + pytest.fail("the incomplete context cannot emit a completed unit") + assert caught.value is failure and executor.error is failure and executor.state == "failed" + assert effects == [("enter", "scope"), "before", ("exit", "scope")] + assert len(scope.exits) == 1 and closed == [True] + + +@pytest.mark.parametrize("scope_type,keyword", [(Scope, "with"), (AsyncScope, "async with")]) +async def test_open_context_requires_aclose_and_cleanup_does_not_finish_pending_source(scope_type, keyword): + effects = [] + scope = scope_type(effects) + executor = Executor({"effects": effects, "scope": scope}, stream_blocks=ALL) + await executor.feed(f"{keyword} scope:\n effects.append('before')\n") + await executor.feed(" effects.append('unfinished'") + with pytest.raises(RuntimeError, match="aclose"): + executor.abort() + assert executor.state == "open" and scope.exits == [] + await executor.aclose() + assert executor.state == "aborted" and executor.error is None and executor.events == () + assert effects == [("enter", "scope"), "before", ("exit", "scope")] + await executor.aclose() + assert len(scope.exits) == 1 + + +async def test_aclose_waits_for_async_cleanup_in_the_owning_task(): + effects = [] + cleanup_entered, cleanup_release = asyncio.Event(), asyncio.Event() + + class GatedScope(AsyncScope): + async def __aexit__(self, error_type, error, traceback): + cleanup_entered.set() + await cleanup_release.wait() + return await super().__aexit__(error_type, error, traceback) + + scope = GatedScope(effects) + + async def worker(): + executor = Executor({"scope": scope}, stream_blocks=ALL) + await executor.feed("async with scope:\n pass\n") + await executor.aclose() + return executor + + task = asyncio.create_task(worker()) + try: + await asyncio.wait_for(cleanup_entered.wait(), 1) + assert not task.done() and scope.exits == [] + cleanup_release.set() + executor = await task + assert executor.state == "aborted" and scope.tasks == [task, task] + assert effects == [("enter", "scope"), ("exit", "scope")] + finally: + cleanup_release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.parametrize("scope_type,keyword", [(Scope, "with"), (AsyncScope, "async with")]) +async def test_cancellation_during_body_closes_context_even_when_it_suppresses_cancellation(scope_type, keyword): + effects = [] + entered = asyncio.Event() + scope = scope_type(effects, suppress=(asyncio.CancelledError,)) + + async def wait(): + entered.set() + await asyncio.Event().wait() + + executor = Executor({"effects": effects, "scope": scope, "wait": wait}, stream_blocks=ALL) + task = asyncio.create_task(executor.feed(f"{keyword} scope:\n await wait()\n effects.append('never')\n")) + try: + await asyncio.wait_for(entered.wait(), 1) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert executor.state == "failed" and executor.events == () + assert effects == [("enter", "scope"), ("exit", "scope")] + assert len(scope.exits) == 1 and scope.tasks == [task, task] + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.parametrize("scope_type,keyword", [(Scope, "with"), (AsyncScope, "async with")]) +async def test_cancellation_while_receiving_source_closes_the_open_context(scope_type, keyword): + effects, closed = [], [] + waiting = asyncio.Event() + scope = scope_type(effects) + + async def chunks(): + try: + yield f"{keyword} scope:\n effects.append('before')\n" + waiting.set() + await asyncio.Event().wait() + finally: + closed.append(True) + + executor = Executor({"effects": effects, "scope": scope}, stream_blocks=ALL) + + async def consume(): + async for _ in executor.stream(chunks()): + pytest.fail("an unclosed context cannot emit an execution") + + task = asyncio.create_task(consume()) + try: + await asyncio.wait_for(waiting.wait(), 1) + assert effects == [("enter", "scope"), "before"] + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert executor.state == "failed" and closed == [True] + assert effects == [("enter", "scope"), "before", ("exit", "scope")] + assert len(scope.exits) == 1 and scope.tasks == [task, task] + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.parametrize("scope_type,keyword", [(Scope, "with"), (AsyncScope, "async with")]) +async def test_invalid_eof_closes_open_context_without_committing_the_unit(scope_type, keyword): + effects = [] + scope = scope_type(effects) + executor = Executor({"effects": effects, "scope": scope}, stream_blocks=ALL) + await executor.feed(f"{keyword} scope:\n effects.append('before')\n") + await executor.feed(" unfinished =") + with pytest.raises(SyntaxError) as caught: + await executor.finish() + assert executor.error is caught.value and executor.state == "failed" + assert effects == [("enter", "scope"), "before", ("exit", "scope")] + assert len(scope.exits) == 1 and executor.events == () + + +async def test_incremental_exec_forwards_block_selection_and_preserves_namespace_identity(): + effects = [] + namespace = {"effects": effects} + + async def chunks(): + yield "if True:\n effects.append('early')\n" + assert effects == ["early"] + yield " effects.append('later')\n" + + assert await incremental_exec(chunks(), namespace, stream_blocks=MODULE | IF) is namespace + assert effects == ["early", "later"] + + +async def test_incremental_exec_none_waits_for_normal_source_exhaustion(): + effects = [] + + async def chunks(): + yield "effects.append('first')\n" + assert effects == [] + yield "effects.append('second')\n" + assert effects == [] + + await incremental_exec(chunks(), {"effects": effects}, stream_blocks=NONE) + assert effects == ["first", "second"] + + +@pytest.mark.parametrize("invalid", [1, True, Allow.ALL]) +async def test_incremental_exec_rejects_wrong_options_before_pulling_source(invalid): + pulled = [] + + async def chunks(): + pulled.append(True) + yield "pass\n" + + source = chunks() + try: + with pytest.raises(TypeError, match="Block|stream_blocks"): + await incremental_exec(source, stream_blocks=invalid) + assert pulled == [] + finally: + await source.aclose() + + +@pytest.mark.parametrize("options,streamed", [({}, True), ({"stream_blocks": ALL}, True), ({"stream_blocks": ALL & ~ASYNC_WITH}, False)], ids=["default", "all", "without-async-with"]) +async def test_real_asyncio_timeout_includes_source_wait_only_when_context_streaming_is_selected(options, streamed): + effects, closed = [], [] + waiting, release = asyncio.Event(), asyncio.Event() + timeout = asyncio.timeout(None) + + async def chunks(): + try: + yield "async with timeout:\n effects.append('body')\n" + waiting.set() + await release.wait() + finally: + closed.append(True) + + executor = Executor({"timeout": timeout, "effects": effects}, **options) + + async def consume(): + return [event async for event in executor.stream(chunks())] + + task = asyncio.create_task(consume()) + try: + await asyncio.wait_for(waiting.wait(), 1) + assert executor.events == () + deadline = asyncio.get_running_loop().time() - 1 + if streamed: + assert effects == ["body"] + # An explicit expired deadline cancels the owner at its next await; + # there is no timing race or sleep-based guess about source progress. + timeout.reschedule(deadline) + with pytest.raises(TimeoutError) as caught: + await task + assert executor.error is caught.value and executor.state == "failed" + assert timeout.expired() and executor.events == () + else: + assert effects == [] + with pytest.raises(RuntimeError, match="has not been entered"): + timeout.reschedule(deadline) + release.set() + assert len(await task) == 1 + assert effects == ["body"] and executor.state == "finished" + assert not timeout.expired() + assert closed == [True] + finally: + release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.parametrize("fail", [False, True]) +async def test_queued_snapshot_excludes_started_compound_during_await_and_after_failure(fail): + effects = [] + entered, release = asyncio.Event(), asyncio.Event() + failure = ValueError("body failed after waiting") + scope = Scope(effects) + + async def wait(): + entered.set() + await release.wait() + if fail: + raise failure + + executor = Executor({"effects": effects, "scope": scope, "wait": wait}, stream_blocks=ALL) + following = "effects.append('following')\n" + source = "with scope:\n effects.append('before')\n await wait()\n effects.append('body-end')\n" + following + task = asyncio.create_task(executor.feed(source)) + try: + await asyncio.wait_for(entered.wait(), 1) + snapshot = executor.queued + assert [unit.source for unit in snapshot] == [following] + assert executor.events == () and effects == [("enter", "scope"), "before"] + release.set() + if fail: + with pytest.raises(ValueError) as caught: + await task + assert caught.value is failure and executor.state == "failed" + assert executor.queued == snapshot + assert effects == [("enter", "scope"), "before", ("exit", "scope")] + else: + assert len(await task) == 2 + assert executor.queued == () + assert effects == [("enter", "scope"), "before", "body-end", ("exit", "scope"), "following"] + assert [unit.source for unit in snapshot] == [following] + finally: + release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +async def test_none_empty_module_matches_native_namespace_initialization_and_emits_one_event(): + native, namespace = {}, {} + exec("", native) # noqa: S102 - native empty-module initialization is the comparison oracle. + executor = Executor(namespace, stream_blocks=NONE) + assert await executor.feed("") == () + assert namespace == {} + events = await executor.finish() + assert "__builtins__" in namespace and namespace == native + assert len(events) == 1 and events[0].unit.source == "" + assert executor.events == events and executor.state == "finished" diff --git a/tests/test_block_options.py b/tests/test_block_options.py new file mode 100644 index 0000000..4fcd360 --- /dev/null +++ b/tests/test_block_options.py @@ -0,0 +1,50 @@ +from enum import Flag + +import pytest + +import partial_python +from partial_python import blocks +from partial_python.blocks import ALL, ASYNC_WITH, IF, MODULE, NONE, WITH, Block +from partial_python.preview import Allow + + +@pytest.mark.parametrize("name", ["NONE", "MODULE", "IF", "WITH", "ASYNC_WITH", "ALL"]) +def test_block_aliases_are_identical_at_both_import_paths(name): + member = getattr(Block, name) + assert getattr(blocks, name) is member + assert getattr(partial_python, name) is member + assert name in blocks.__all__ and name in partial_python.__all__ + + +def test_block_type_is_public_at_both_import_paths(): + assert partial_python.Block is blocks.Block is Block + assert "Block" in blocks.__all__ and "Block" in partial_python.__all__ + + +def test_all_contains_exactly_the_implemented_independent_scopes(): + assert ALL == MODULE | IF | WITH | ASYNC_WITH + assert set(Block) == {MODULE, IF, WITH, ASYNC_WITH} + assert set(Block.__members__) == {"NONE", "MODULE", "IF", "WITH", "ASYNC_WITH", "ALL"} + assert NONE.value == 0 + assert not NONE and ALL + assert ALL & ~MODULE == IF | WITH | ASYNC_WITH + + +def test_block_options_do_not_enable_other_scopes_implicitly(): + assert (IF | WITH) & MODULE == NONE + assert (IF | WITH) & ASYNC_WITH == NONE + assert MODULE & IF == NONE + + +@pytest.mark.parametrize("foreign", [0, 1, False, True, Allow.NONE, Allow.TAIL, Allow.ALL]) +def test_execution_options_do_not_mix_with_integers_or_preview_options(foreign): + assert isinstance(MODULE, Flag) and not isinstance(MODULE, int) + with pytest.raises(TypeError): + MODULE | foreign + with pytest.raises(TypeError): + foreign | MODULE + + +def test_unknown_block_bits_are_rejected(): + with pytest.raises(ValueError): + Block(1 << 4) diff --git a/tests/test_block_parser.py b/tests/test_block_parser.py new file mode 100644 index 0000000..f3f4b03 --- /dev/null +++ b/tests/test_block_parser.py @@ -0,0 +1,339 @@ +"""Internal block events are proven by physical source, never temporary EOF.""" + +import ast + +import pytest + +from partial_python import ALL, ASYNC_WITH, IF, MODULE, WITH, Parser +from partial_python._blocks import BlockParser + +PROGRAMS = [ + "first()\nsecond()\n", + "if condition:\n first()\n second()\nelif other:\n third()\nelse:\n fourth()\nlast()\n", + "if outer:\n if inner:\n first()\n else:\n second()\nelse:\n third()\nlast()\n", + "if condition: first(); second()\nelif other: third()\nelse: fourth()\nlast()\n", + "if condition:\n first()\nelif other: second(); third()\nelse: fourth()\n", + "with first() as x, second() as y:\n use(x, y)\nlast()\n", + "async with first() as x, second() as y:\n await use(x, y)\nlast()\n", + "with (\n first() as x,\n second() as y,\n):\n use(x, y)\n", + "with first(): one(); two()\nnext()\n", + "with first():\n if test:\n with second():\n use()\n else:\n other()\nlast()\n", + "if condition:\n for value in values:\n if nested:\n use(value)\n else:\n done()\n next()\nlast()\n", + "with manager:\n try:\n use()\n except ValueError:\n recover()\n finally:\n clean()\n next()\nlast()\n", + "if condition:\n @decorate\n def f():\n with manager:\n use()\n f()\nlast()\n", + "if condition:\n match value:\n case [x, *xs]:\n use(x, xs)\n case _:\n skip()\n next()\nlast()\n", + "if condition:\n value = [\n first(),\n second(),\n ]\n use(value)\nlast()\n", + "if condition:\n value = '''first\nnot_a_dedent\nthird'''\n use(value)\nlast()\n", + 'if condition:\n value = f"hello {name!r:>10}"\n use(value)\nlast()\n', + "if condition:\n\tfirst()\n\tif other:\n\t\tsecond()\n\telse:\n\t\tthird()\nlast()\n", + "if condition:\r\n first()\r\nelse:\r\n second()\r\nlast()\r\n", + "if condition:\r first()\relse:\r second()\rlast()\r", + "# before\nwith manager:\n # body\n first()\n# between\nlast()\n# tail", + "with manager:\n first()\n \\\nsecond()\nlast()\n", + "with manager:\n \\\nfirst()\nlast()\n", + "with manager:\n\\\n first()\nlast()\n", + "with outer:\n with inner:\n first()\n\\\n second()\nlast()\n", + "with outer:\n with inner:\n first()\n\\\n \\\nsecond()\nlast()\n", + "if condition:\n first()\n\\\nelse:\n second()\nlast()\n", + "with manager:\n 变量 = 'é🙂'\n if 变量:\n 使用(变量)\nlast()", + "# only a comment\n", + "\n\n", + "", +] + + +def signature(event): + return event.kind, event.unit, event.depth, ast.dump(event.node, include_attributes=True) if event.node else None + + +def parse(chunks, flags=ALL): + parser = BlockParser(stream_blocks=flags) + events = [] + for chunk in chunks: + events.extend(parser.feed(chunk)) + events.extend(parser.finish()) + return events + + +@pytest.mark.parametrize("source", PROGRAMS) +def test_partition_independent_events_and_original_top_level_units(source): + expected = [signature(event) for event in parse([source])] + for chunks in [source, *([source[:split], source[split:]] for split in range(len(source) + 1))]: + actual = parse(chunks) + assert [signature(event) for event in actual] == expected, chunks + units = [event.unit for event in actual if event.depth == 0 and event.kind in {"statement", "exit"}] + assert "".join(unit.source for unit in units) == source + assert all(source[event.unit.start : event.unit.end] == event.unit.source for event in actual) + + +def test_header_and_body_are_early_but_only_real_dedent_closes_the_unit(): + parser = BlockParser(stream_blocks=ALL) + header = "with manager:\n" + (enter,) = parser.feed(header) + assert enter.kind == "enter" + assert isinstance(enter.node, ast.With) and enter.node.body == [] + (body,) = parser.feed(" first()\n") + assert body.kind == "statement" and body.depth == 1 + assert parser.committed == 0 + assert parser.pending == header + body.unit.source + assert parser.feed("\n# comment\n") == () + (close,) = parser.feed("n") + assert close.kind == "exit" + assert close.unit.source == header + body.unit.source + assert parser.committed == close.unit.end + assert parser.pending == "\n# comment\nn" + parser.feed("ext()\n") + parser.finish() + + +@pytest.mark.parametrize("word", ["e", "el", "eli", "elif", "els", "else"]) +def test_partial_continuation_keyword_never_closes_if(word): + parser = BlockParser(stream_blocks=ALL) + parser.feed("if first:\n one()\n") + assert parser.feed(word) == () + assert parser.committed == 0 + + +def test_branch_headers_keep_one_frame_and_original_expression_locations(): + source = "if first:\n one()\nelif second:\n two()\nelse:\n three()\nafter()\n" + events = parse(source) + enter = next(event for event in events if event.kind == "enter") + branches = [event for event in events if event.kind == "branch"] + close = next(event for event in events if event.kind == "exit") + assert [event.unit.source.split()[0] for event in branches] == ["elif", "else:"] + assert all(event.depth == enter.depth for event in [*branches, close]) + assert isinstance(branches[0].node, ast.If) + assert (branches[0].node.test.lineno, branches[0].node.test.col_offset) == (3, 5) + assert branches[0].node.end_lineno == 3 + assert branches[1].node is None + + +def test_multiple_context_items_and_ast_locations_are_untouched(): + source = "if enabled:\n with first() as x, second(x) as y:\n use(x, y)\nlast()\n" + events = parse(source) + with_event = next(event for event in events if isinstance(event.node, ast.With)) + original = ast.parse(source).body[0].body[0] + assert ast.dump(ast.Module(body=[item.context_expr for item in with_event.node.items]), include_attributes=True) == ast.dump( + ast.Module(body=[item.context_expr for item in original.items]), include_attributes=True + ) + use = next(event.node.body[0] for event in events if event.kind == "statement" and event.depth == 2) + assert ast.dump(use, include_attributes=True) == ast.dump(original.body[0], include_attributes=True) + + +@pytest.mark.parametrize("flags, expanded", [(MODULE, []), (MODULE | IF, [ast.If]), (MODULE | WITH, [ast.With]), (MODULE | ASYNC_WITH, [ast.AsyncWith]), (ALL, [ast.If, ast.With, ast.AsyncWith])]) +def test_only_selected_bodies_expand(flags, expanded): + source = "if yes:\n first()\nwith manager:\n second()\nasync with manager:\n third()\nlast()\n" + assert [type(event.node) for event in parse(source, flags) if event.kind == "enter"] == expanded + + +@pytest.mark.parametrize( + "compound", + [ + "for x in xs:\n with manager:\n use(x)\n", + "while condition:\n if test:\n use()\n", + "try:\n with manager:\n use()\nfinally:\n clean()\n", + "def function():\n if condition:\n use()\n", + "class C:\n if condition:\n attribute = 1\n", + "match value:\n case _:\n with manager:\n use()\n", + ], +) +def test_unsupported_compounds_are_opaque_even_when_their_children_are_enabled(compound): + parser = BlockParser(stream_blocks=ALL) + assert parser.feed(compound) == () + (event,) = parser.feed("n") + assert event.kind == "statement" and event.unit.source == compound + assert isinstance(event.node, ast.Module) + parser.feed("ext()\n") + parser.finish() + + +@pytest.mark.parametrize( + "source", ["if condition:\n", "with manager:\n value = (\n", "with manager:\n value = '''open", "if condition:\n one()\nelse:\n", "if condition:\n one()\n invalid()\n"] +) +def test_invalid_eof_does_not_invent_exit_events(source): + parser = BlockParser(stream_blocks=ALL) + parser.feed(source) + with pytest.raises((SyntaxError, ValueError)): + parser.finish() + assert parser.closed and parser.committed == 0 + with pytest.raises(RuntimeError): + parser.feed("later()\n") + + +def test_default_parser_still_returns_only_complete_original_units(): + parser = Parser() + source = "with manager:\n one()\n two()\n" + assert parser.feed(source) == () + (unit,) = parser.feed("n") + assert unit.source == source + + +def test_lifecycle_and_type_checking(): + parser = BlockParser() + with pytest.raises(TypeError): + parser.feed(b"code") + assert parser.feed("") == () + assert parser.finish() == () + with pytest.raises(RuntimeError): + parser.finish() + + +class _DifferentialContext: + def __init__(self, log, name, value=None, suppress=False): + self.log, self.name, self.value, self.suppress = log, name, value, suppress + + def __enter__(self): + self.log.append(("enter", self.name)) + return self.value if self.value is not None else self.name + + def __exit__(self, kind, _error, _traceback): + self.log.append(("exit", self.name, kind.__name__ if kind else None)) + return self.suppress + + async def __aenter__(self): + return self.__enter__() + + async def __aexit__(self, *error): + return self.__exit__(*error) + + +EXECUTION_PROGRAMS = [ + "if check('if', first):\n with ctx('outer') as name:\n log.append(name)\n if check('nested', second): log.append('nested')\n else: log.append('other')\nelif check('elif', second):\n log.append('elif')\nelse:\n log.append('else')\nlog.append('end')\n", + "with ctx('outer'):\n\ttext = '''literal\nelse:\nwith untouched:\n'''\n\tif first:\n\t\tlog.append(text)\n\telse:\n\t\tlog.append('else')\nlog.append('end')\n", + "with ctx('outer'):\r\n values = [\r\n 1,\r\n 2,\r\n ]\r\n log.append(f'值:{values!r}')\r\nlog.append('end')\r\n", + "if first:\n for value in [1, 2]:\n with ctx(str(value)):\n log.append(value)\n else:\n log.append('loop-else')\n log.append('after-loop')\nlog.append('end')\n", + "with ctx('outer'):\n try:\n if first:\n raise ValueError('expected')\n log.append('try')\n except ValueError:\n log.append('except')\n finally:\n log.append('finally')\n log.append('after-try')\nlog.append('end')\n", + "with ctx('outer'):\n match [first, second]:\n case [True, value] if check('guard', value):\n log.append('matched')\n case _:\n log.append('fallback')\n log.append('after-match')\nlog.append('end')\n", + "if first:\n def function():\n with ctx('function'):\n return 42\n log.append(function())\nlog.append('end')\n", + "async with ctx('first') as x, ctx('second') as y:\n await record((x, y))\n if first:\n async with ctx('inner'):\n await record('inner')\n else:\n await record('else')\nlog.append('end')\n", + "with ctx('unpack', (1, 2)) as (x, y):\n log.append((x, y))\n with ctx('suppress', suppress=True):\n log.append('before-error')\n raise ValueError('suppressed')\n log.append('unreachable')\n log.append('after-suppressed')\nlog.append('end')\n", + "with ctx('outer'):\n with ctx('inner'):\n log.append('inner')\n\\\n \\\nlog.append('outer')\nlog.append('end')\n", +] + + +@pytest.mark.parametrize("source", EXECUTION_PROGRAMS) +@pytest.mark.parametrize("first,second", [(True, True), (False, True), (False, False)]) +@pytest.mark.parametrize("partition", ["whole", "characters", "seven"]) +async def test_original_block_ast_matches_whole_program_execution(source, first, second, partition): + import inspect + + from partial_python import Executor + + def namespace(): + log = [] + + def check(label, value): + log.append(("check", label)) + return value + + async def record(value): + log.append(value) + + return {"log": log, "first": first, "second": second, "check": check, "record": record, "ctx": lambda *args, **kwargs: _DifferentialContext(log, *args, **kwargs)} + + expected, actual = namespace(), namespace() + result = eval(compile(source, "differential.py", "exec", ast.PyCF_ALLOW_TOP_LEVEL_AWAIT), expected, expected) + if inspect.isawaitable(result): + await result + chunks = [source] if partition == "whole" else source if partition == "characters" else [source[start : start + 7] for start in range(0, len(source), 7)] + executor = Executor(actual, filename="differential.py", stream_blocks=ALL) + for chunk in chunks: + await executor.feed(chunk) + await executor.finish() + assert actual["log"] == expected["log"] + assert "".join(event.unit.source for event in executor.events) == source + assert executor.parser_state.committed == len(source) + assert executor.parser_state.pending == "" + + +@pytest.mark.parametrize("tail", [" broken = (\n", " broken = '''open\n", " broken = \0\n", "\0", "\\"]) +async def test_invalid_suffix_never_repairs_or_completes_an_open_context(tail): + from partial_python import Executor + + log = [] + executor = Executor({"log": log, "ctx": _DifferentialContext(log, "scope")}, filename="broken.py", stream_blocks=ALL) + prefix = "with ctx:\n log.append('stable')\n" + assert await executor.feed(prefix) == () + assert log == [("enter", "scope"), "stable"] + assert await executor.feed(tail) == () + assert executor.parser_state.pending == prefix + tail + assert executor.parser_state.committed == 0 and executor.events == () + with pytest.raises((SyntaxError, ValueError)): + await executor.finish() + assert executor.state == "failed" + assert executor.parser_state.closed + assert executor.parser_state.pending == prefix + tail + assert log[:2] == [("enter", "scope"), "stable"] + assert len(log) == 3 and log[-1][:2] == ("exit", "scope") + assert executor.events == () + + +@pytest.mark.parametrize("newline", ["\n", "\r\n", "\r"]) +@pytest.mark.parametrize("partition", ["whole", "characters"]) +async def test_failed_statement_uses_exact_original_source_and_absolute_traceback_line(newline, partition): + import traceback + + from partial_python import Executor + + log = [] + lines = ["log.append('root')", "with ctx:", " 变量 = 'é🙂'", " missing_name()", " log.append('never')", "log.append('after')"] + source = newline.join(lines) + newline + executor = Executor({"log": log, "ctx": _DifferentialContext(log, "scope")}, filename="failure.py", stream_blocks=ALL) + with pytest.raises(NameError) as caught: + for chunk in [source] if partition == "whole" else source: + await executor.feed(chunk) + await executor.finish() + assert log == ["root", ("enter", "scope"), ("exit", "scope", "NameError")] + unit = executor.failed_unit + assert unit is not None + assert unit.source == lines[3] + newline + assert source[unit.start : unit.end] == unit.source + assert (unit.start_line, unit.end_line) == (4, 5) + assert [frame.lineno for frame in traceback.extract_tb(caught.value.__traceback__) if frame.filename == "failure.py"] == [4] + assert [event.unit.source for event in executor.events] == [lines[0] + newline] + + +@pytest.mark.parametrize("shape", ["literal", "multiline-string", "brackets", "opaque", "comment"]) +def test_streaming_scanner_work_grows_with_new_source(monkeypatch, shape): + import tokenize + + import partial_python._blocks as blocks + import partial_python.parser as ordinary + + generate = tokenize.generate_tokens + tree = ordinary._tree + scanned = parsed = 0 + + def measured_tokens(readline): + def measured_read(): + nonlocal scanned + line = readline() + scanned += len(line) + return line + + return generate(measured_read) + + def measured_tree(source, *args, **kwargs): + nonlocal parsed + parsed += len(source) + return tree(source, *args, **kwargs) + + monkeypatch.setattr(tokenize, "generate_tokens", measured_tokens) + monkeypatch.setattr(ordinary, "_tree", measured_tree) + monkeypatch.setattr(blocks, "_tree", measured_tree) + totals = [] + for count in [256, 1024]: + source = { + "literal": "with manager:\n '" + "a" * count + "'\n", + "multiline-string": "with manager:\n text = '''\n" + "line\n" * count + "'''\n", + "brackets": "with manager:\n values = [\n" + " 1,\n" * count + " ]\n", + "opaque": "with manager:\n for value in []:\n" + " use(value)\n" * count + " next()\n", + "comment": "with manager:\n #" + "a" * count + "\n pass\n", + }[shape] + scanned = parsed = 0 + parse(source) + totals.append(scanned + parsed) + assert scanned + parsed < 60 * len(source) + # Count actual tokenizer input and compilation spans, not elapsed time. A + # fourfold input must not regress to reparsing each complete prefix again. + assert totals[1] < 6 * totals[0] diff --git a/tests/test_block_runtime_edges.py b/tests/test_block_runtime_edges.py new file mode 100644 index 0000000..a9cea37 --- /dev/null +++ b/tests/test_block_runtime_edges.py @@ -0,0 +1,443 @@ +"""Control-flow and resource boundaries of opened streaming blocks.""" + +import ast +import asyncio +import inspect +from contextlib import asynccontextmanager, contextmanager, suppress +from contextvars import ContextVar + +import pytest + +from partial_python import Block, Executor + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("error_type", [asyncio.CancelledError, GeneratorExit, KeyboardInterrupt, SystemExit]) +async def test_explicit_body_baseexception_can_be_suppressed_without_task_cancellation(asynchronous, error_type): + calls = [] + + @contextmanager + def sync_manager(): + try: + yield + except error_type: + calls.append("suppressed") + + @asynccontextmanager + async def async_manager(): + with sync_manager(): + yield + + keyword, manager = ("async with", async_manager) if asynchronous else ("with", sync_manager) + executor = Executor({"manager": manager, "error_type": error_type, "calls": calls}, stream_blocks=Block.ALL) + cancellations = asyncio.current_task().cancelling() + await executor.feed(f"{keyword} manager():\n raise error_type()\n") + await executor.feed(" calls.append('skipped')\ncalls.append('after')\n") + await executor.finish() + assert calls == ["suppressed", "after"] + assert executor.state == "finished" and asyncio.current_task().cancelling() == cancellations + + +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_suppressed_nested_if_cannot_revive_elif_or_else(asynchronous): + calls = [] + + @contextmanager + def sync_manager(): + try: + yield + except ZeroDivisionError: + calls.append("suppressed") + + @asynccontextmanager + async def async_manager(): + with sync_manager(): + yield + + keyword, manager = ("async with", async_manager) if asynchronous else ("with", sync_manager) + executor = Executor({"manager": manager, "calls": calls}, stream_blocks=Block.ALL) + lines = [ + "if True:\n", + f" {keyword} manager():\n", + " if True:\n", + " 1 / 0\n", + " elif calls.append('elif condition'):\n", + " calls.append('elif')\n", + " else:\n", + " calls.append('else')\n", + " calls.append('with tail')\n", + " calls.append('outer resumed')\n", + "else:\n", + " calls.append('outer else')\n", + "calls.append('after')\n", + ] + for line in lines: + await executor.feed(line) + await executor.finish() + assert calls == ["suppressed", "outer resumed", "after"] + + +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_assignment_failure_unwinds_multiple_managers_in_native_order(asynchronous): + calls = [] + + @contextmanager + def sync_manager(name): + calls.append((name, "enter")) + try: + yield (1,) + except ValueError: + calls.append((name, "suppressed")) + finally: + calls.append((name, "exit")) + + @asynccontextmanager + async def async_manager(name): + with sync_manager(name) as value: + yield value + + keyword, manager = ("async with", async_manager) if asynchronous else ("with", sync_manager) + executor = Executor({"manager": manager, "calls": calls}, stream_blocks=Block.ALL) + await executor.feed(f"{keyword} manager('first'), manager('second') as (left, right):\n") + assert calls == [("first", "enter"), ("second", "enter"), ("second", "suppressed"), ("second", "exit"), ("first", "exit")] + await executor.feed(" calls.append('skipped')\ncalls.append('after')\n") + await executor.finish() + assert calls[-1] == "after" and "skipped" not in calls + assert "left" not in executor.namespace and "right" not in executor.namespace + + +async def test_foreign_task_cannot_resume_finish_or_close_context_owned_by_caller(): + marker = ContextVar("block_owner", default="host") + calls = [] + owner = asyncio.current_task() + + @asynccontextmanager + async def manager(): + token = marker.set("body") + calls.append(("enter", asyncio.current_task())) + try: + yield + finally: + calls.append(("exit", asyncio.current_task())) + marker.reset(token) + + executor = Executor({"manager": manager, "calls": calls, "marker": marker}, stream_blocks=Block.ALL) + await executor.feed("async with manager():\n") + assert marker.get() == "body" + + async def foreign(): + for operation in (lambda: executor.feed(" calls.append('wrong')\n"), executor.finish, executor.aclose): + with pytest.raises(RuntimeError, match="owning task"): + await operation() + + await asyncio.create_task(foreign()) + assert executor.state == "open" and marker.get() == "body" + assert calls == [("enter", owner)] + await executor.feed(" calls.append(marker.get())\n") + await executor.finish() + assert calls == [("enter", owner), "body", ("exit", owner)] + assert marker.get() == "host" + + +async def test_taskgroup_spans_fragments_without_changing_parent_task(): + owner, gate, calls = asyncio.current_task(), asyncio.Event(), [] + + async def child(): + await gate.wait() + calls.append("child") + + executor = Executor({"asyncio": asyncio, "owner": owner, "gate": gate, "child": child, "calls": calls}, stream_blocks=Block.ALL) + await executor.feed("async with asyncio.TaskGroup() as group:\n task = group.create_task(child())\n") + task = executor.namespace["task"] + assert not task.done() + await executor.feed(" assert asyncio.current_task() is owner\n gate.set()\n") + await executor.feed("calls.append('after')\n") + await executor.finish() + assert task.done() and calls == ["child", "after"] + + +async def test_source_failure_preserves_falsey_cleanup_exception(): + class CleanupFailure(Exception): + def __bool__(self): + return False + + replacement = CleanupFailure("cleanup") + original = OSError("source") + + @contextmanager + def manager(): + try: + yield + finally: + raise replacement + + async def source(): + yield "with manager():\n pass\n" + raise original + + executor = Executor({"manager": manager}, stream_blocks=Block.ALL) + with pytest.raises(CleanupFailure) as caught: + async for _ in executor.stream(source()): + pass + assert caught.value is replacement and executor.error is replacement + assert replacement.__context__ is original and executor.state == "failed" + + +async def test_timeout_scope_covers_waiting_for_source_and_restores_cancellation_count(): + owner = asyncio.current_task() + cancellations = owner.cancelling() + + async def source(): + yield "async with asyncio.timeout(0.01):\n pass\n" + await asyncio.Event().wait() + yield "unreachable = True\n" + + executor = Executor({"asyncio": asyncio}, stream_blocks=Block.ALL) + with pytest.raises(TimeoutError): + async for _ in executor.stream(source()): + pass + assert executor.state == "failed" and owner.cancelling() == cancellations + assert "unreachable" not in executor.namespace + + +async def test_aclose_cancellation_cannot_be_swallowed_by_async_exit(): + entered, calls = asyncio.Event(), [] + holder = [] + + class Manager: + async def __aenter__(self): + pass + + async def __aexit__(self, *details): + calls.append("exit") + entered.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + calls.append("swallowed cancellation") + return True + + async def owner(): + executor = Executor({"manager": Manager()}, stream_blocks=Block.ALL) + holder.append(executor) + await executor.feed("async with manager:\n pass\n") + await executor.aclose() + + task = asyncio.create_task(owner()) + await asyncio.wait_for(entered.wait(), 1) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert calls == ["exit", "swallowed cancellation"] + assert holder[0].state == "failed" and isinstance(holder[0].error, asyncio.CancelledError) + + +@pytest.mark.parametrize("nested", [False, True]) +@pytest.mark.parametrize("source_failure", [False, True]) +async def test_multiple_cleanup_failures_keep_the_complete_exception_chain(nested, source_failure): + primary, inner_error, outer_error = ValueError("body or source"), LookupError("inner exit"), RuntimeError("outer exit") + calls = [] + + @contextmanager + def manager(name, error): + try: + yield + finally: + calls.append(name) + raise error + + header = "with manager('outer', outer_error):\n with manager('inner', inner_error):\n" if nested else "with manager('outer', outer_error), manager('inner', inner_error):\n" + body_indent = " " if nested else " " + executor = Executor({"manager": manager, "outer_error": outer_error, "inner_error": inner_error, "primary": primary}, stream_blocks=Block.ALL) + with pytest.raises(RuntimeError) as caught: + if source_failure: + + async def source(): + yield header + body_indent + "pass\n" + raise primary + + async for _ in executor.stream(source()): + pass + else: + await executor.feed(header + body_indent + "raise primary\n") + assert caught.value is outer_error and executor.error is outer_error + assert outer_error.__context__ is inner_error + assert inner_error.__context__ is primary + assert calls == ["inner", "outer"] + + +@pytest.mark.parametrize("nested", [False, True]) +@pytest.mark.parametrize("body_failure", [False, True]) +async def test_cancellation_during_unwind_never_commits_outer_context_or_runs_following_code(nested, body_failure): + waiting, calls, holder = asyncio.Event(), [], [] + + class Inner: + async def __aenter__(self): + pass + + async def __aexit__(self, *details): + waiting.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + calls.append("inner swallowed cancellation") + return True + + class Outer: + async def __aenter__(self): + pass + + async def __aexit__(self, kind, error, traceback): + calls.append(("outer", kind)) + return True + + async def owner(): + executor = Executor({"outer": Outer(), "inner": Inner(), "calls": calls}, stream_blocks=Block.ALL) + holder.append(executor) + header = "async with outer:\n async with inner:\n" if nested else "async with outer, inner:\n" + body = "raise ValueError('body')" if body_failure else "pass" + await executor.feed(header + (" " if nested else " ") + body + "\ncalls.append('after')\n") + + task = asyncio.create_task(owner()) + await asyncio.wait_for(waiting.wait(), 1) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert calls == ["inner swallowed cancellation", ("outer", asyncio.CancelledError)] + assert holder[0].state == "failed" and isinstance(holder[0].error, asyncio.CancelledError) + + +@pytest.mark.parametrize("flags", [Block.MODULE | Block.WITH, Block.ALL]) +@pytest.mark.parametrize( + "fragment", + [ + "raise StopIteration('body')", + "raise StopIteration('body'); await noop()", + "stop(); await noop()", + "if True: stop(); await noop()", + "with Manager('enter'):\n pass", + "with Manager('exit'):\n pass", + "with Manager('enter'):\n await noop()", + "with Manager('exit'):\n await noop()", + "with Manager('none') as target.value:\n pass", + "if stop():\n await noop()", + "next(iter(())); await noop()", + "if next(iter(())): await noop()", + "with Manager('none') as mapping[next(iter(()))]:\n pass", + "with Manager('none') as (await target_mapping())[next(iter(()))]:\n pass", + ], +) +async def test_streamed_with_preserves_native_synchronous_stopiteration_suppression(flags, fragment): + def namespace(): + calls = [] + + class Manager: + def __init__(self, phase): + self.phase = phase + + def __enter__(self): + calls.append("enter") + if self.phase == "enter": + raise StopIteration("enter") + return object() + + def __exit__(self, *details): + calls.append("exit") + if self.phase == "exit": + raise StopIteration("exit") + + class Target: + def __setattr__(self, name, value): + calls.append("assignment") + raise StopIteration("assignment") + + def stop(): + calls.append("stop") + raise StopIteration("sync function") + + async def noop(): + calls.append("await") + + async def target_mapping(): + calls.append("target await") + return {} + + return {"calls": calls, "Manager": Manager, "target": Target(), "mapping": {}, "target_mapping": target_mapping, "stop": stop, "noop": noop, "suppress": suppress} + + source = "with suppress(StopIteration):\n" + "".join(" " + line + "\n" for line in fragment.splitlines()) + " calls.append('inside after')\ncalls.append('after')\n" + native, streamed = namespace(), namespace() + result = eval(compile(source, "native.py", "exec", flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT), native, native) + if inspect.isawaitable(result): + await result + executor = Executor(streamed, stream_blocks=flags) + await executor.feed(source) + await executor.finish() + assert streamed["calls"] == native["calls"] + assert streamed["calls"][-1] == "after" and "inside after" not in streamed["calls"] + assert executor.state == "finished" + + +@pytest.mark.parametrize( + "fragment", + [ + "await stop()", + "async with Manager('enter'):\n pass", + "async with Manager('exit'):\n pass", + "raise RuntimeError('manual') from StopIteration(); await stop()", + "next(generator_stop()); await stop()", + "wrapped(); await stop()", + ], +) +async def test_real_user_coroutine_generator_or_explicit_runtimeerror_is_never_unwrapped(fragment): + async def stop(): + raise StopIteration("user coroutine") + + class Manager: + def __init__(self, phase): + self.phase = phase + + async def __aenter__(self): + if self.phase == "enter": + raise StopIteration("async enter") + + async def __aexit__(self, *details): + if self.phase == "exit": + raise StopIteration("async exit") + + def generator_stop(): + raise StopIteration("user generator") # noqa: PLR1708 - exercise the native PEP 479 failure, not normal exhaustion. + yield + + class UserRuntimeError(RuntimeError): + pass + + def wrapped(): + try: + raise StopIteration("explicit cause") + except StopIteration as error: + raise UserRuntimeError("custom wrapper") from error + + source = "with suppress(StopIteration):\n" + "".join(" " + line + "\n" for line in fragment.splitlines()) + "after = True\n" + native = {"suppress": suppress, "stop": stop, "Manager": Manager, "generator_stop": generator_stop, "wrapped": wrapped} + with pytest.raises(RuntimeError) as native_error: + result = eval(compile(source, "native.py", "exec", flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT), native, native) + if inspect.isawaitable(result): + await result + streamed = {"suppress": suppress, "stop": stop, "Manager": Manager, "generator_stop": generator_stop, "wrapped": wrapped} + executor = Executor(streamed, stream_blocks=Block.ALL) + with pytest.raises(RuntimeError) as streamed_error: + await executor.feed(source) + await executor.finish() + assert isinstance(native_error.value.__cause__, StopIteration) + assert isinstance(streamed_error.value.__cause__, StopIteration) + assert type(streamed_error.value) is type(native_error.value) + assert str(streamed_error.value) == str(native_error.value) + assert "after" not in streamed and executor.state == "failed" + + +async def test_exception_instance_remains_an_ordinary_expression_value(): + namespace = {"error": ValueError("a value")} + executor = Executor(namespace, stream_blocks=Block.ALL) + await executor.feed("if error:\n selected = error\n") + await executor.finish() + assert namespace["selected"] is namespace["error"] diff --git a/tests/test_context.py b/tests/test_context.py index 537a3a3..d222046 100644 --- a/tests/test_context.py +++ b/tests/test_context.py @@ -6,7 +6,7 @@ import pytest -from partial_python import Executor, UnsupportedSyntaxError +from partial_python import MODULE, Executor, UnsupportedSyntaxError def execute_native(source, namespace=None): @@ -289,7 +289,7 @@ async def test_deep_compound_keeps_all_nested_effects_until_successor(): native_calls = [] execute_native(source, {"calls": native_calls}) calls = [] - executor = Executor({"calls": calls}) + executor = Executor({"calls": calls}, stream_blocks=MODULE) for line in lines: await executor.feed(line) assert calls == [] diff --git a/tests/test_context_scopes.py b/tests/test_context_scopes.py new file mode 100644 index 0000000..8a6d46d --- /dev/null +++ b/tests/test_context_scopes.py @@ -0,0 +1,381 @@ +"""Native context protocols retained across independently supplied fragments.""" + +import ast +import asyncio +import inspect +import math +import sys +from contextlib import asynccontextmanager +from contextvars import ContextVar +from types import SimpleNamespace + +import pytest + +from partial_python._contexts import Scope, compile_binding + + +class Manager: + def __init__(self, *, value=None, result=False, exit_error=None): + self.value, self.result, self.exit_error = value, result, exit_error + self.calls = [] + + def __enter__(self): + self.calls.append(("enter", asyncio.current_task())) + return self.value + + async def __aenter__(self): + return self.__enter__() + + def __exit__(self, kind, error, traceback): + self.calls.append(("exit", asyncio.current_task(), kind, error, traceback, sys.exception())) + if self.exit_error is not None: + raise self.exit_error + return self.result + + async def __aexit__(self, *details): + return self.__exit__(*details) + + +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_scope_keeps_calling_task_and_exits_exactly_once(asynchronous): + owner = asyncio.current_task() + manager = Manager(value=object()) + scope, value = await Scope.open(manager, asynchronous) + assert value is manager.value + assert [call[0] for call in manager.calls] == ["enter"] + assert await scope.close() is None + assert await scope.close() is None + assert [call[0] for call in manager.calls] == ["enter", "exit"] + assert all(call[1] is owner for call in manager.calls) + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("suppressed", [False, True]) +@pytest.mark.parametrize("error_type", [ValueError, StopIteration, StopAsyncIteration, GeneratorExit, asyncio.CancelledError]) +async def test_close_preserves_control_exceptions_and_active_exception(asynchronous, suppressed, error_type): + error = error_type("body") + try: + raise error + except error_type: + original_traceback = error.__traceback__ + manager = Manager(result=suppressed) + scope, _ = await Scope.open(manager, asynchronous) + assert await scope.close(error) is (None if suppressed else error) + call = manager.calls[-1] + assert call[2] is error_type and call[3] is error and call[4] is original_traceback and call[5] is error + assert error.__traceback__ is original_traceback + + +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_normal_exit_never_tests_truthiness_of_exit_result(asynchronous): + class UnusableTruth: + def __bool__(self): + raise AssertionError("Native normal exit ignores its return value") + + scope, _ = await Scope.open(Manager(result=UnusableTruth()), asynchronous) + assert await scope.close() is None + + +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_exit_failure_replaces_body_failure_and_preserves_chain(asynchronous): + original, replacement = ValueError("body"), RuntimeError("cleanup") + manager = Manager(exit_error=replacement) + scope, _ = await Scope.open(manager, asynchronous) + assert await scope.close(original) is replacement + assert replacement.__context__ is original + assert manager.calls[-1][-1] is original + assert await scope.close() is None + assert [call[0] for call in manager.calls] == ["enter", "exit"] + + +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_assignment_failure_is_given_to_entered_manager(asynchronous): + manager = Manager(value=(1,), result=True) + scope, value = await Scope.open(manager, asynchronous) + try: + _first, _second = value + except ValueError as error: + assert await scope.close(error) is None + assert manager.calls[-1][2] is ValueError + + +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_native_special_lookup_ignores_instance_attributes(asynchronous): + def wrong(*args): + raise AssertionError("Instance attributes must not override the protocol") + + manager = Manager() + manager.__enter__ = manager.__aenter__ = manager.__exit__ = manager.__aexit__ = wrong + # Avoid the test fixture's explicit calls through overridden instance methods. + if asynchronous: + + class AsyncManager(Manager): + async def __aenter__(self): + return Manager.__enter__(self) + + async def __aexit__(self, *details): + return Manager.__exit__(self, *details) + + manager = AsyncManager() + manager.__aenter__ = manager.__aexit__ = wrong + scope, _ = await Scope.open(manager, asynchronous) + assert await scope.close() is None + assert [call[0] for call in manager.calls] == ["enter", "exit"] + + +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_native_special_descriptors_bind_the_manager_instance(asynchronous): + calls = [] + + class Method: + def __init__(self, name): + self.name = name + + def __get__(self, instance, owner): + assert instance is not None + calls.append((self.name, instance)) + if asynchronous: + + async def method(*args): + return instance if self.name == "enter" else False + + return method + return lambda *args: instance if self.name == "enter" else False + + class DescriptorManager: + __enter__ = __aenter__ = Method("enter") + __exit__ = __aexit__ = Method("exit") + + manager = DescriptorManager() + scope, value = await Scope.open(manager, asynchronous) + assert value is manager + assert await scope.close() is None + actual = calls.copy() + calls.clear() + if asynchronous: + async with manager: + pass + else: + with manager: + pass + assert actual == calls and len(calls) == 2 + + +async def test_contextvar_token_is_reset_in_its_original_context(): + marker = ContextVar("scope_marker", default="host") + + @asynccontextmanager + async def manager(): + token = marker.set("body") + try: + yield + finally: + marker.reset(token) + + scope, _ = await Scope.open(manager(), True) + assert marker.get() == "body" + await asyncio.sleep(0) + assert await scope.close() is None + assert marker.get() == "host" + + +async def test_taskgroup_can_span_fragments_in_its_calling_task(): + calls = [] + scope, group = await Scope.open(asyncio.TaskGroup(), True) + + async def child(): + await asyncio.sleep(0) + calls.append("done") + + task = group.create_task(child()) + assert await scope.close() is None + assert task.done() and calls == ["done"] + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("error_type", [ValueError, StopIteration, StopAsyncIteration, GeneratorExit, asyncio.CancelledError]) +async def test_enter_failure_propagates_without_calling_exit(asynchronous, error_type): + original = error_type("enter") + + class FailingEnter(Manager): + def __enter__(self): + raise original + + manager = FailingEnter() + scope, error = await Scope.open(manager, asynchronous) + assert scope is None + if asynchronous and error_type is StopIteration: + assert isinstance(error, RuntimeError) and error.__cause__ is original + else: + assert error is original + assert manager.calls == [] + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("error_type", [StopIteration, StopAsyncIteration, GeneratorExit, asyncio.CancelledError]) +async def test_exit_control_exception_is_not_consumed(asynchronous, error_type): + original, replacement = ValueError("body"), error_type("exit") + scope, _ = await Scope.open(Manager(exit_error=replacement), asynchronous) + error = await scope.close(original) + if asynchronous and error_type is StopIteration: + assert isinstance(error, RuntimeError) and error.__cause__ is replacement + else: + assert error is replacement + assert replacement.__context__ is original + assert await scope.close() is None + + +async def test_unrelated_caller_exception_does_not_replace_original_body_chain(): + original = ValueError("body") + manager = Manager() + scope, _ = await Scope.open(manager, False) + try: + raise OSError("host") + except OSError: + assert await scope.close(original) is original + assert original.__context__ is None + assert manager.calls[-1][-1] is original + + +async def test_cancellation_during_exit_is_propagated_without_replaying_cleanup(): + started, calls = asyncio.Event(), [] + + class WaitingExit: + async def __aenter__(self): + pass + + async def __aexit__(self, *details): + calls.append("exit") + started.set() + await asyncio.Event().wait() + + async def owner(): + scope, _ = await Scope.open(WaitingExit(), True) + try: + error = await scope.close() + if error is not None: + raise error + finally: + assert await scope.close() is None + + task = asyncio.create_task(owner()) + await asyncio.wait_for(started.wait(), 1) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert calls == ["exit"] + + +@pytest.mark.parametrize( + "target", + [ + "bound", + "box.value", + "box.items[index()]", + "mapping[key()]", + "mapping[tuple(sorted(locals()))]", + "mapping[globals() is locals()]", + "(await fetch()).value", + "mapping[await async_key()]", + "mapping[1e1000 - 1e1000]", + ], +) +async def test_binding_matches_native_assignment_without_namespace_temporaries(target): + value = object() + + def namespace(): + log = [] + box = SimpleNamespace(items=[None, None]) + + def index(): + log.append("index") + return 1 + + def key(): + log.append("key") + return "item" + + async def fetch(): + log.append("fetch") + return box + + async def async_key(): + log.append("async_key") + return "item" + + return {"manager": Manager(value=value), "box": box, "mapping": {}, "index": index, "key": key, "fetch": fetch, "async_key": async_key, "log": log} + + source = f"with manager as {target}:\n pass\n" + tree = ast.parse(source) + code, index = compile_binding(tree.body[0].items[0].optional_vars, "binding.py", ast.PyCF_ALLOW_TOP_LEVEL_AWAIT) + constants = list(code.co_consts) + constants[index] = value + binding = code.replace(co_consts=tuple(constants)) + actual, expected = namespace(), namespace() + for compiled, scope in [(binding, actual), (compile(source, "native.py", "exec", flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT), expected)]: + result = eval(compiled, scope, scope) + if inspect.isawaitable(result): + await result + assert actual.keys() == expected.keys() + assert actual["log"] == expected["log"] + assert vars(actual["box"]) == vars(expected["box"]) + assert list(actual["mapping"].values()) == list(expected["mapping"].values()) + if "1e1000" not in target: + assert actual["mapping"] == expected["mapping"] + else: + assert all(isinstance(key, float) and math.isnan(key) for key in actual["mapping"]) + if "bound" in actual: + assert actual["bound"] is value + + +@pytest.mark.parametrize("value", [[1, 2, 3, 4], [1], {"not": "a literal"}, lambda: 1, ValueError("value")]) +async def test_binding_accepts_arbitrary_objects_and_preserves_unpacking(value): + target = ast.parse("first, *middle, last = None").body[0].targets[0] + code, index = compile_binding(target, "binding.py", 0) + constants = list(code.co_consts) + constants[index] = value + namespace = {} + if not isinstance(value, list) or len(value) < 2: + expected_error = ValueError if isinstance(value, (dict, list)) else TypeError + with pytest.raises(expected_error): + eval(code.replace(co_consts=tuple(constants)), namespace, namespace) + else: + eval(code.replace(co_consts=tuple(constants)), namespace, namespace) + assert (namespace["first"], namespace["middle"], namespace["last"]) == (1, [2, 3], 4) + assert set(namespace) <= {"__builtins__", "first", "middle", "last"} + + +async def test_bound_value_is_not_inspected_or_computed_as_a_user_expression(): + class Opaque: + def __repr__(self): + raise AssertionError("binding must not render the object") + + def __eq__(self, other): + raise AssertionError("binding must not compare the object") + + def __hash__(self): + raise AssertionError("binding must not hash the object") + + value = Opaque() + target = ast.parse("bound = None").body[0].targets[0] + code, index = compile_binding(target, "binding.py", 0) + constants = list(code.co_consts) + constants[index] = value + namespace = {} + eval(code.replace(co_consts=tuple(constants)), namespace, namespace) + assert namespace["bound"] is value + assert set(namespace) == {"__builtins__", "bound"} + + +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_nested_scope_cleanup_chain_survives_unrelated_handled_exception(asynchronous): + primary, inner_error, outer_error = ValueError("body"), LookupError("inner exit"), RuntimeError("outer exit") + outer, _ = await Scope.open(Manager(exit_error=outer_error), asynchronous) + inner, _ = await Scope.open(Manager(exit_error=inner_error), asynchronous) + try: + raise primary + except ValueError: + assert await inner.close(primary) is inner_error + assert await outer.close(inner_error) is outer_error + assert outer_error.__context__ is inner_error + assert inner_error.__context__ is primary diff --git a/tests/test_execution.py b/tests/test_execution.py index 848e99b..2f14a10 100644 --- a/tests/test_execution.py +++ b/tests/test_execution.py @@ -7,7 +7,7 @@ import pytest -from partial_python import Executor, UnsupportedSyntaxError, incremental_exec +from partial_python import MODULE, Executor, UnsupportedSyntaxError, incremental_exec async def test_executes_closed_await_before_receiving_more_source(): @@ -51,7 +51,7 @@ async def test_entire_loop_waits_for_successor_including_else(): async def test_normal_eof_seals_compound_but_abort_does_not(): for finish in (True, False): calls = [] - executor = Executor({"calls": calls}) + executor = Executor({"calls": calls}, stream_blocks=MODULE) await executor.feed("if True:\n calls.append(1)\n") assert calls == [] if finish: @@ -347,7 +347,7 @@ async def chunks(): closed.append(True) with pytest.raises(ConnectionError) as captured: - await incremental_exec(chunks(), {"calls": calls}) + await incremental_exec(chunks(), {"calls": calls}, stream_blocks=MODULE) assert captured.value is failure assert calls == [1] and closed == [True] diff --git a/tests/test_execution_edges.py b/tests/test_execution_edges.py index bfa4bc9..477047e 100644 --- a/tests/test_execution_edges.py +++ b/tests/test_execution_edges.py @@ -4,7 +4,7 @@ import pytest -from partial_python import Executor, UnsupportedSyntaxError, incremental_exec +from partial_python import MODULE, Executor, UnsupportedSyntaxError, incremental_exec async def test_closing_stream_closes_its_source_iterator(): @@ -277,7 +277,7 @@ async def chunks(): return source = chunks() - stream = Executor({"calls": calls}).stream(source) + stream = Executor({"calls": calls}, stream_blocks=MODULE).stream(source) task = asyncio.create_task(anext(stream)) try: await asyncio.wait_for(entered.wait(), 1) diff --git a/tests/test_stream.py b/tests/test_stream.py index 28215a8..ca90b66 100644 --- a/tests/test_stream.py +++ b/tests/test_stream.py @@ -4,7 +4,7 @@ import pytest -from partial_python import Executor +from partial_python import MODULE, Executor async def chunks_of(*chunks): @@ -151,7 +151,7 @@ async def source(): finally: closed.append(True) - executor = Executor() + executor = Executor(stream_blocks=MODULE) with pytest.raises(ConnectionError) as captured: async for _ in executor.stream(source()): pass diff --git a/tests/test_transport.py b/tests/test_transport.py index 31a1b05..e9754be 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -7,7 +7,7 @@ from examples import overlap from examples import transport as example from examples.transport import SourceAborted, SourceProtocolError, execute_connection, record_bytes, source_deltas -from partial_python import Executor, incremental_exec +from partial_python import MODULE, Executor, incremental_exec def reader_for(*records): @@ -57,7 +57,7 @@ async def test_final_source_rewrite_rejected_before_sealing_pending_suite(): reader = reader_for({"type": "delta", "text": source}, {"type": "done", "status": "completed", "source": source + "# rewritten"}) calls = [] with pytest.raises(SourceProtocolError, match="does not match"): - await incremental_exec(source_deltas(reader), {"calls": calls}) + await incremental_exec(source_deltas(reader), {"calls": calls}, stream_blocks=MODULE) # A final consistency check cannot roll back the previously committed call. assert calls == ["early"]