Heuristic:1kbgz Tributary Generator Unrolling In Streaming Nodes
| Knowledge Sources | |
|---|---|
| Domains | Streaming, Optimization |
| Last Updated | 2026-10-14 09:15 GMT |
Overview
Streaming nodes dynamically swap their internal function to unroll generators, replacing the wrapped callable with a `next()`-based iterator on first detection.
Description
When a streaming Node's wrapped function returns a generator (via `yield`), the node detects this at runtime and swaps its internal `_func` to a lambda that calls `next()` on the generator. The original function is preserved in `_old_func`. On `StopIteration`, the generator is exhausted and returns `StreamEnd`. On `ValueError` (e.g., generator already exhausted), the node swaps back to `_old_func` to create a fresh generator on the next iteration.
For async generators, the same pattern applies using `_agen_to_func` which calls `__anext__()` and catches `StopAsyncIteration`.
For the lazy Node, generator functions are detected at construction time via `inspect.isgeneratorfunction()`, and the node is set to `_dynamic=True` (always reevaluated) since generators produce new values on each call.
Usage
Use this heuristic when:
- Understanding why a streaming node with a generator function behaves differently from one with a regular function.
- Debugging `ValueError` exceptions in streaming pipelines (the node is recovering from generator exhaustion).
- Wrapping generators that produce a finite series — the node will emit `StreamEnd` when the generator is exhausted.
The Insight (Rule of Thumb)
- Action: When wrapping a generator function in a streaming Node, be aware that the node auto-detects the generator and swaps to `next()`-based unrolling.
- Value: `_old_func` preserves the original function; `_func` becomes a `next()` wrapper; on `StopIteration`, returns `StreamEnd`; on `ValueError`, restores `_old_func`.
- Trade-off: Generator unrolling adds a small overhead on the first call (type detection + function swap), but subsequent calls are fast (direct `next()`).
- Compatibility: Works with both sync generators (`types.GeneratorType`) and async generators (`types.AsyncGeneratorType`). Lazy nodes detect generators at construction and set `_dynamic=True`.
Reasoning
Streaming nodes need to produce one value per tick, but generators produce a sequence of values. The unrolling pattern bridges this gap: each tick calls `next()` on the generator, yielding one value at a time. When the generator is exhausted (`StopIteration`), the node signals stream completion via `StreamEnd`. The `ValueError` recovery path handles edge cases where a generator's state becomes invalid — rather than crashing, the node creates a fresh generator.
The `ZeroDivisionError` is also caught during execution and returns `float("inf")`, preventing pipeline crashes from division-by-zero in user functions.