Skip to content

fix(response-stream): avoid exponential path enumeration - #400

Merged
QuantumGhost merged 10 commits into
langgenius:mainfrom
QuantumGhost:codex/eng-1501-response-reachability
Nov 18, 2026
Merged

QuantumGhost merged 10 commits into
langgenius:mainfrom
QuantumGhost:codex/eng-1501-response-reachability

Conversation

@QuantumGhost

@QuantumGhost QuantumGhost commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

AI disclosure: This PR was primarily drafted with Codex using gpt-6.1-sol. Final review and responsibility remain with the human author.

Important

  1. Make sure you have read our contribution guidelines
  2. Search existing issues and pull requests to confirm this change is not a duplicate
  3. Open or identify the issue this pull request resolves or advances
  4. Use a Conventional Commits title for this pull request, and mark breaking changes with !
  5. Remember that the pull request title will become the squash merge commit message
  6. If CLA Assistant prompts you, sign CLA.md in the pull request conversation

Related Issue

Closes #398.

Builds on #271, #374 and #401. Related downstream tracking: langgenius/dify#41851.

Summary

A 43-node workflow can contain 2^41 structural paths when each conditional's two handles converge on the next node. Response initialization materialized every complete path before the first graph-start event. Reverse pruning from #271 cannot help when all paths reach the response.

Approach

  • Each native frame owns one first-edge-decision map (TAKEN / SKIPPED), read by independent per-response reachability caches with their own selector-dependent blocking edges. Nonblocking edges are open immediately; blocking edges open from consumed taken events. A blocking edge skipped before it is taken remains rejected. Shared suffixes are visited once per response, preserving any-path activation and frame isolation.
  • Index outgoing edges in declarative child graphs, so both built-in root and child graph implementations provide indexed adjacency. Preserve upstream template/value/retry behavior, feat(response-stream): order parallel and nested replies #401's ordered parallel/nested presentation, and child snapshot/resumption restrictions (including pending container reservations).
  • Keep native reachability and imported legacy paths in mutually exclusive runtime types. Write v3 root checkpoints using the existing flat edge-decision fields and separate observed-skip metadata. Reject legacy paths combined with nonempty native decision lists at parse time, including before initialization. Existing v3 taken/rejected overlap still decodes as first-skip wins. Read v1/v2 checkpoints by retaining their residual path conditions, session order, execution IDs, buffers and cursors. Migration never enumerates new paths; historical fixtures are unchanged.

Complexity

For an already scoped frame graph, let V/E be nodes/edges, R >= 1 responses, and T/S consumed taken/skipped events. These are graph-operation bounds; frame discovery, selector/blocking-hook evaluation, templates and output/buffer processing are additional costs.

  • Native setup and cumulative reachability expansion use O(R(V + E)) graph work and gating memory, plus O(RT + S) decision/activation dispatch. The shared first-decision map itself uses O(E) memory. Each node becomes reachable once per response; there is no complete-path-count factor.
  • Existing response sorting and observed-skip rendering scans add O(TR log R + S(V + E)) work. This is not an unconditional linear bound for the entire filter.
  • Fresh edge-decision/response-ID checkpoint data is O(E + R). The full checkpoint also includes execution IDs, render metadata and stream progress/buffers. Imported legacy residual lists retain input-sized storage and their previous per-event scan cost.

Test methods and validation

Performance and behavioral equivalence are tested independently.

  • Deterministic complexity regression: parameterized diamond chains with 6, 12 and 24 stages retain V=n+2, E=2n+1, paths=2^n (the middle case is 14 nodes / 25 edges / 4,096 paths). A test-side graph wrapper meters incoming/outgoing adjacency API calls and raises on the first over-budget call during initialize(). No timing assertions or unbounded old-path runs are needed.
  • Budget derivation: allowing two adjacency passes per response gives 2RV <= 2V^2 <= 4VE for these connected graphs (R <= V, E >= V-1, V >= 2). The conservative budget is therefore 4VE primitive invocations. Doubling stages has a limiting quadratic factor of four; both consecutive measured count ratios must be below four, and the second ratio must not exceed the first. Current initialization counts are 2, 2, 2, hence ratios 1, 1. API invocations exclude the work inside each accessor; the regression is not a proof of an end-to-end time bound.
  • Retained state and checkpoints: measure retained owned filter/session containers and UTF-8 snapshot payload independently at initialization and after each chosen edge. Both must stay below 1024(V+E) bytes. Shared input graph/value-pool objects and code are excluded, while owned container reference slots and fixed rendering overhead are included. This bound is for fresh one-response fixtures with bounded IDs and no source buffers, not arbitrary values, stream buffers or migrated legacy paths. Derivation and measurement scope are in the implementation notes.
  • Ordered behavior: assert complete emitted event sequences and the exact response event fields. A satisfied path emits before the remaining alternative handles are taken. A separate sequential-response case emits its first chunk before the last downstream blocking edge is taken. Two indexed interleaved frames consume identical local edge IDs independently and emit to distinct response targets with their own reserved execution IDs and final markers. A later-ready frame waits for its predecessor to finish its presentation slot; opening its gate cannot open the earlier frame.
  • Hypothesis differential law (logic only): on DAGs of at most ten nodes, compare response activation after every event prefix with a test-only copy of the old complete-path enumeration and residual-condition updates. Run 100 examples for each of nine reachability/gate combinations: all nodes on a root-to-response path, dead branches, or dead branches plus disconnected predecessors; AND, OR, or AND/OR blocking. Vary forward shortcuts, parallel handles, event order, duplicates, skip-before-taken and taken-before-skip. There are no performance assertions in this test. Existing 24 seeded cyclic oracle cases remain.
  • Compatibility/integration: retain live edge-state independence, selector-dependent blocking, native/legacy restoration, consumed decisions, buffered content/cursors, execution IDs, waiting-response order, historical fixture bytes, and existing container response behavior.
  • Native checkpoint and boundary regression: checkpoint after the first of two serial blocking edges, restore through both loading orders, and require the remaining edge to emit buffered content exactly once. A process-local mutation clearing serialized taken_edges makes both cases fail at the release assertion. Eight mixed-mode input cases must raise immediately and preserve existing pending/live state; two existing-v3 input cases protect overlapping taken/rejected fields and separate observed-skip metadata.
  • Legacy HITL/host-pause integration: nine root-flow cases use paired runtime/filter checkpoints captured by actual historical writers: c3870df (runtime v2/filter v1) and 069cd55 (runtime v3/filter v2), plus current-writer controls. Resume from two HITL positions, approve/re-pause, save current checkpoints and resume again; separately resume a real PauseCommand checkpoint. Assert reasons, real paused-node execution identity, callback/work continuation, ordered text/selectors/final flags, no replay or loss, and final answers. Synthetic root presentation chunk UUIDs are deliberately not a continuity contract. These fixtures have empty producer buffers; the separate checkpoint tests cover buffered stream progress.
  • Required old-code check: run the unchanged complexity and Hypothesis modules in an isolated git archive 069cd554 tree, with production imports pointing to that tree. Result after integrating feat(response-stream): order parallel and nested replies #401: 6 failed / 10 passed. The 12/24-stage initialization aborts at 1,401 > 1,400 / 5,097 > 5,096 calls; the 6-stage retained state also exceeds its byte bound. All 9 Hypothesis differential cases pass on the old code, as expected for unchanged gating logic. Frame presentation ordering is tested separately against feat(response-stream): order parallel and nested replies #401's current contract.
  • Current branch: the new regression suite has 18 passed; related response/frame/snapshot tests: 144 passed; just test: 1,402 passed on Python 3.12.12 (two existing pandas warnings). just check: passed (lockfile, format, lint, types and import boundaries).
  • Bounded diagnostic: the previously run synthetic 41-stage DSL reached its first event in about 0.1ms and completed event consumption in about 25ms; the earlier enumerating filter exceeded a 3-second subprocess limit. These historical local samples are not capacity/p95 measurements. The issue includes a public-API reproducer; no customer workflow or credentials are included.

Checklist

  • This pull request links the issue it resolves or advances
  • This pull request title follows Conventional Commits, and any breaking change is marked with !
  • If CLA Assistant prompted me, I signed CLA.md in the pull request conversation

No new CLA signing prompt was received during preparation.

QuantumGhost and others added 4 commits November 16, 2026 12:49
Cover filter-consumed traversal events when live engine state is ahead.
Preserve partially consumed v1/v2 paths, buffered chunks, template and
stream positions, execution IDs, and waiting-response order on restore.

Assisted-by: Codex:gpt-6.1-sol
Track per-response reachability through nonblocking edges and consumed
root traversal events instead of enumerating complete paths.

Write v3 checkpoints with consumed edge IDs, retaining residual conditions
when upgrading v1/v2 snapshots. Preserve session order and stream progress.

Refs: ENG-1501
Assisted-by: Codex:gpt-6.1-sol
Merge current upstream response sessions while retaining independent
incremental gating and versioned legacy checkpoint compatibility.
Preserve first skipped/taken decisions, index child adjacency, and replace
obsolete path-list assertions with public activation oracle checks.

Refs: langgenius#398
Assisted-by: Codex:gpt-6.1-sol
@QuantumGhost
QuantumGhost marked this pull request as draft November 16, 2026 08:30
Bound diamond-chain initialization at 6, 12 and 24 stages with traversal
budgets, growth ratios, retained-state and checkpoint byte limits.
Compare gating against old path conditions with Hypothesis independently
of resource checks, and assert ordered replies and distinct frame targets.

Refs: langgenius#398
Assisted-by: Codex:gpt-6.1-sol
Keep native reachability and imported legacy paths in exclusive runtime
states, and reject mixed v3 input before binding it to a graph.

Own first taken/skipped decisions once per frame, with response caches
reading the map. Keep observed skips separate and decode existing v3
intersections as first-skip wins without changing the wire fields.

Protect partially consumed native checkpoints and both loading orders;
verify that dropping serialized taken edges fails the release assertions.

Refs: langgenius#398
Assisted-by: Codex:gpt-6.1-sol
Use nominal NodeID and EdgeID types for response gating and v3 snapshots,
converting graph/event and legacy inputs at their existing boundaries.
Document first-decision lists, observed skips, and residual AND/OR paths.

Keep serialized IDs as strings and retain the existing v3 JSON schema.

Refs: langgenius#398
Assisted-by: Codex:gpt-6.1-sol
@QuantumGhost

QuantumGhost commented Nov 17, 2026 •

Copy link
Copy Markdown
Member Author

I have run the differential tests with ~10k iterations each on my machine. I'm pretty sure that the claimed property holds.

laipz8200
laipz8200 previously approved these changes Nov 18, 2026

@laipz8200 laipz8200 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Exciting.

Resume paired runtime/filter checkpoints captured by the c3870df and
069cd55 writers, with current-writer controls. Cover two HITL pause points,
recheckpointing after migration, and host PauseCommand resumption.

Assert meaningful execution identity and output behavior without treating
synthetic root chunk UUID continuity as a restoration contract.

Add reproducible historical fixture capture and test navigation.

Refs: langgenius#398
Assisted-by: Codex:gpt-6.1-sol
QuantumGhost and others added 2 commits November 18, 2026 15:18
Merge upstream main reply ordering while retaining per-response incremental
gates, frame-owned first edge decisions, v3 snapshot compatibility and
nominal node/edge IDs.

Keep the interleaved-frame regression aligned with ordered presentation:
opening B cannot open A, and B waits until frame A finishes.

Validation: 1402 tests passed; static checks passed. Historical filter
v1/v2 pause checkpoints continue to restore with the current v3 writer.

Refs: langgenius#398, langgenius#401
Assisted-by: Codex:gpt-6.1-sol
@QuantumGhost
QuantumGhost marked this pull request as ready for review November 18, 2026 09:27
@QuantumGhost
QuantumGhost merged commit eb75e38 into langgenius:main Nov 18, 2026
12 checks passed
laipz8200 added a commit that referenced this pull request Nov 19, 2026
Merge main at eb75e38 into the
pause/resume branch without rewriting the existing PR commits.

Preserve first consumed edge decisions and legacy residual paths in v4
frame snapshots while retaining v1/v2/v3 readers and child reply progress.
Reject mixed gating state before replacing saved progress and keep current
snapshots independent of legacy codecs.

Reconcile retained-state accounting with the caller-owned filter context
and update the affected compatibility and ownership documentation.

Refs #356, #400, #412.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Response-stream initialization remains exponential when all paths reach a response

3 participants