Skip to content

Commit 674443e

Browse files
lmeyerovclaude
andauthored
perf(gfql/polars): make the chain combine proportional to the traversal result (#1785)
* perf(gfql/polars): make the chain combine proportional to the traversal result Two graph-sized terms sat inside a combine whose answer is a handful of rows. 1. `_combine_edges` ran the prev/next endpoint gates for EVERY step, including the node steps whose edge frame is `g._edges.clear()` -- zero rows. The eager combine skipped those; the collect-once (Track B) rewrite lazified the step frames and `.lazy()` erases the height, so the skip silently went dead. The cost lands on the side that is NOT empty: for the first step the gate's key side is the whole node table, and polars builds the hash table on that side before discovering the probe side has no rows. Isolated in raw polars: 6.99 ms for one such join at N=2M vs 0.22 ms against a one-row key side -- and a chain pays one per node step. `_LazyShim.step` now records the row count while the frame is still eager and an empty step is dropped from the id union. It can contribute no ids, so the result is unchanged by construction. The skip keys on KNOWN-empty only: a frame that arrives already lazy reports no height and is planned normally. 2. The output node rows were materialized in TWO passes over the node table -- one for the ids the steps kept, one more for the surviving edges' endpoints the first pass missed -- then concatenated. The output node set is the UNION of those two id sides, so `_materialize_node_rows` unions the ids first and reads the node table ONCE. The row-level `unique(subset=[node])` is preserved verbatim: those rows go on to feed `how="left"` alias joins where a node table carrying the same id twice multiplies rows. The id sides themselves are NOT deduplicated -- they are semi key sides. Note for the record: the recorded description of this residual ("UNIQUE over a UNION of the per-step FULL frames") named the wrong operator. The union inputs are 1-row step frames; the `unique` costs 0.008 ms. It was the union BRANCHES -- empty-probe joins against graph-sized build sides -- exactly as the earlier semi-dedup finding. MEASURED, one dimension at a time, synthetic LDBC-IS5-shaped graphs (one-row answer, polars-engine resident indexes, local CPU, min of 9): vary NODES at E=2M 250k -> 4M: 10.17 -> 45.48 ms before 7.60 -> 17.17 ms after (2.65x at 4M) node-count slope 3.7x flatter (+35.3 ms -> +9.6 ms over 16x N) vary EDGES at N=1M 500k -> 8M: 13.47 -> 26.02 ms before 7.08 -> 17.57 ms after edge slope essentially unchanged, as expected for a node-side fix; constant ~6 ms lower same 2-3x holds for n-e-n, n-e-n-e-n and undirected shapes PARITY: 280 shape x graph combinations (clean / self-loop / dangling / duplicate keys / multi-edge / back-edge / isolated) and 400 duplicate-node-id combinations x 5 repeats compared as FULL frames including row order -- 0 diffs vs the pre-change tree, and stable across repeated runs. `graphistry/tests/compute/` failure set is byte-identical before and after (119 pre-existing failures, 0 new, +119 passed = the new file). TESTS pin the boundary, not a wall clock. Mutation-checked; each row is a deliberate reintroduction of a bug, run against the new file: drop the empty-step skip -> 2 fail (both structural tests) restore the two-pass materialization -> 1 fail (node table read 2x) drop the row-level node dedup -> 18 fail (parity + dedup + order) drop the endpoint fold -> 2 fail drop the node order restore -> 34 fail skip steps whose height is UNKNOWN -> 1 fail NOT caught, and reported as such: dropping the edge order restore, and dropping `maintain_order` on the node dedup. Neither is observable -- the edge semi-join returns EORD order naturally at 5k/60k/300k across 5 shapes, and the node semi-join feeding the dedup is unordered either way. Both are pre-existing defensive code, untouched here. Also honest about coverage: the endpoint fold could not be shown load-bearing end-to-end (6300 generated chain executions found no graph/shape where the step ids miss an edge endpoint), so it is tested at the helper, where the case can be constructed -- an end-to-end test of it would have passed with the endpoint side removed entirely. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VARwnAqmvczhz5EmP7TYyZ * review(#1785): pin the edge sort under streaming; scope the survivor claim; kill the twin guard Review skill found three items worth fixing; all three were claim-scope or follow-up-hazard rather than defects in the shipped behaviour. 1. `sort(EORD)` is NOT dead code — the probe that called it unpinned was engine blind. It only exercised the in-memory collect, where the frame comes back EORD-ordered even with the sort deleted. Under `GFQL_POLARS_CPU_STREAMING=1` it does not, and a trailing rows(limit=)/skip would then slice the wrong rows. The existing 60k order test is now parametrized over the collect engine. Mutation-checked: deleting the sort fails [streaming] and PASSES [in-memory], which is exactly why the original probe saw nothing. 2. The `maintain_order=True` docstring claimed the surviving duplicate is decided "the same way it was before", citing a 400-combo A/B. That A/B ran on the default engine only; under streaming the survivor genuinely differs. Scoped the claim to the in-memory collect and said plainly that the survivor is a stable property there, not a guaranteed one. 3. `_apply_node_names` still carried the ORIGINAL spelling of the bug this branch exists to fix: `is_lazy(df) or df.height > 0`, where the function is always called with lazified steps, so `is_lazy` short-circuits True and the height test is unreachable. Restated against `edges_empty`, which survives lazification. Unlike the edges combine this guard is SEMANTIC, not a cost guard — an empty next edge step must not empty `named` through the gate below it. I could not make the dead version observable, so this is hardening, not a bug fix; but leaving a known-dead cardinality guard beside a freshly-revived one is precisely how the original defect recurred. lint + mypy clean; 1159 polars chain/combine/semi-dedup tests pass. * review(#1785): type the narrow-combine helpers instead of leaving them inferred The helpers this PR added or reshaped were untyped, which violates the repo's engine-agnostic typing convention. Annotate them with the aliases rather than bare Any: `_LazyShim.__init__` / `.step`, `_known_empty`, `_combine_node_ids`, `_materialize_node_rows`, plus class-level slot annotations on `_LazyShim` (bare annotations only — a class-level value would collide with __slots__). The slots are `Optional[pl.LazyFrame]`, NOT the `PolarsFrame` union: every construction site calls `.lazy()` first, which is the point of the shim, and `pl.concat`'s TypeVar rejects a `DataFrame | LazyFrame` argument outright. The union spelling type-checks as 7 errors; the LazyFrame spelling as none. `_combine_node_ids` takes the `_LazyShim`, not a `Plottable` — the call site passes `g_lz`, a duck-typed stand-in that is not a Plottable subclass. Two consequences worth naming: * `_known_empty` needs an explicit cast for `.height`. `is_lazy` is a plain bool predicate, so mypy cannot narrow its else-branch. Widening it to a `TypeIs` would narrow this for every caller in the engine, but that is a dtypes.py-wide change and not this PR's. * `collect_all`'s results are rebound to new names. `final_nodes` is statically a LazyFrame down that block and `collect_all` returns eager frames, so reusing the name is a type error — and silencing it would cost exactly the lazy/eager distinction the shim exists to preserve. Sibling helpers in the same file (`_semi`, `_align_seed_dtype`, ...) are also untyped but pre-existing, and are left alone. Verified in-container on dgx-spark, differentially: mypy reports 213 errors with 1 in chain.py both before and after this commit — the same pre-existing `maybe_index_hop` arg-type — so this adds none. (The container's pandas-stubs drift from the CI lockfile makes the absolute count meaningless; only the differential is evidence.) The gfql suite with `--gpus all` is byte-identical to the pre-commit tree: 5570 passed, 25 skipped, 15 xfailed, 0 failed on both. ruff clean under the repo config. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015YsqAZQLbqjSDrYSFz2GoB --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
1 parent 8483598 commit 674443e

3 files changed

Lines changed: 521 additions & 24 deletions

File tree

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
1212
- **GFQL secondary node property indexes (`create_index('node_prop', column=...)` / `g.gfql_index_node_props([...])`)**: a seed predicate on a NON-key column — `MATCH (m {id: 42})` where the graph's node id binding is some other column — previously cost a full node scan, because the registry only indexed the node-id binding and the CSR adjacencies. A property index is the same pay-as-you-go sidecar as the existing kinds: sorted distinct values over node **row positions** (CSR, so duplicate values are indexable), never reorders `.nodes`, fingerprint-validated so a `.nodes()` rebind is treated as absent (safe miss, never a wrong answer), engine-polymorphic (numpy host / cupy on-device), and policy-gated (`off`/`use`/`auto`/`force`). The seeded fixed-hop planner picks the **most selective** indexed scalar predicate in the seed filter using a free CSR-offset estimate, gathers those candidates, and applies every remaining predicate to them — so results are identical whether the index is present, absent, stale, or cost-gated out. `show_indexes()` lists property indexes; `drop_index('node_prop', column=...)` drops one. Only integer columns are indexable today (float NaN ordering, strings on cupy, and nulls all decline to the scan); widening that is additive. **Perf (dgx-spark, official LDBC SNB SF1, 3.18M nodes, warm median, value-identical 19-row result):** interactive-short IS7 `71.6 ms -> 19.5 ms` (**3.7x**), with a one-time `112 ms` build — the seed lookup itself goes from a `51.2 ms` scan to `0.096 ms`.
1313

1414
### Performance
15+
- **Native polars chain combine is proportional to the traversal result, not to the graph**: two graph-sized terms sat inside a combine whose answer is a handful of rows, and both are gone. (1) `_combine_edges` ran the prev/next endpoint gates for EVERY step, including the node steps whose edge frame is `g._edges.clear()` — zero rows. The eager combine skipped those, but the collect-once rewrite lazified the step frames and `.lazy()` erases the height, so the skip silently went dead. The cost lands on the side that is NOT empty: for the first step the gate's key side is the whole node table, and polars builds the hash table on that side before discovering the probe side has no rows (isolated: 6.99 ms for one such join at N=2M, and a chain pays one per node step). The pre-lazy row count is now recorded when the step frame is still eager and an empty step is dropped from the id union — it can contribute no ids, so the result is unchanged by construction. The skip keys on KNOWN-empty only; a frame that arrives already lazy reports no height and is planned normally. (2) The output node rows were materialized in TWO passes over the node table — one for the ids the steps kept, one more for the surviving edges' endpoints the first pass missed — then concatenated. The output node set is the UNION of those two id sides, so the ids are unioned first and the node table is read ONCE. The row-level `unique(subset=[node])` is preserved verbatim: those rows feed `how="left"` alias joins where a node table carrying the same id twice would multiply rows. Measured on synthetic LDBC-IS5-shaped graphs (one-row answer, polars-engine resident indexes), varying one dimension at a time: **at fixed E=2M, N=250k → 4M went 10.17 → 45.48 ms before and 7.60 → 17.17 ms after (2.65× at 4M, and the node-count slope is 3.7× flatter)**; the edge-count slope is unchanged, as expected for a node-side fix, with the constant ~6 ms lower. Parity: identical full frames (all columns, row order included) across 280 shape × graph combinations and 400 duplicate-node-id combinations, plus the 1003-case polars chain differential suite. Pinned by tests that assert the boundary rather than a wall clock: the node universe must not appear in the edge plan at all, and the node table must be read at most once per query.
1516
- **GFQL polars chain stops deduplicating semi-join key sides**: the native polars executor applied `.unique()` to every frame it fed into a `how="semi"` join. A semi-join emits a left row iff at least one matching right row exists, so duplicate keys can neither change which rows come back nor multiply them the way an inner join would — the deduplication was a full hash pass over the key column bought for no observable effect. On an unfiltered hop the key side **is** the node table, so this put **O(N) work inside a query whose answer is O(degree)**: the seeded single-hop plan built two such key frames per hop, each costing ~53 ms at 3.18M nodes — more than the rest of the query combined. The `.unique()` is now dropped everywhere the frame is provably a semi key side only (the `_semi` helper, the alias hop-window and next-edge endpoint gates, the two-hop fast path's endpoint gate, the `start_nodes` gate, the single-hop planner's id frames, and the index layer's `select_by_ids` polars branch — where the cuDF and pandas branches already used `isin` with no dedup, so the three engines now agree). It is deliberately **kept** on the alias frame that feeds a `how="left"` join, where duplicates genuinely would multiply rows, and the eager multi-hop loop is untouched (its frames also flow into concat/anti-join bookkeeping, a separate argument). Measured on a 3.18M-node / 14M-edge polars graph (LDBC SNB SF1-shaped), a seeded typed hop goes **127.4 → 57.1 ms (2.23×)** with identical row counts; at 1.75M edges **102.8 → 31.4 ms (3.28×)**, confirming the removed cost scales with node count, not edge count. Parity held across 380 differential comparisons covering duplicate node keys, null ids, dangling edges, duplicate `start_nodes`, and 11 traversal shapes; the gfql and chain suites show identical failure sets before and after. Pinned by tests that assert the boundary rather than the speed: duplicates reaching a semi key side must not change results or multiply rows, a dangling endpoint must still be excluded (the gate is load-bearing, not vacuous), and duplicate `start_nodes` must be inert.
1617
- **Seeded chain combine stops joining against the full frame when the intermediate is empty**: `_lean_prefilter_right` shrinks the big side of the combine's `how='left'` merge to the keys actually present on the left, but it declined to do so in the one case where shrinking is both maximally profitable and trivially correct — an **empty** left. A left merge keeps only the right rows that match, so a zero-row left yields a zero-row result whatever the right side holds; the merge was nonetheless materializing the whole graph-sized frame. It now hands back a zero-row slice of `right` (same columns and dtypes, so the merge still produces an identical schema). Measured: a single-node query whose 0-row intermediate was joined against 14M edges went **112.64 → 17.29 ms**. The shrink is used at exactly one call site, which is `how='left'`; a merge that retains unmatched right rows (`right`/`outer`) would NOT be safe to shrink this way, and the tests pin both directions — the empty-left case must return an empty result, and the non-empty cases must be byte-identical to the unshrunk merge.
1718
- **Native polars chain reuses the synthetic edge id as its stable row order**: when the executor had already added a synthetic edge-index column it also added a second, separate row-index column purely to restore input order at the end — two full `with_row_index` passes over the edge frame, and a redundant column carried through every intermediate. The existing synthetic id is already a contiguous, order-preserving row index, so it is now reused as the sort key and dropped once at the end. Only the pre-existing column is reused; when no synthetic id was added the separate order column is still created, so graphs that bring their own edge id are unaffected. Value-identical including row order (148.22 → 135.43 ms on a 3.18M-node / 14M-edge polars graph).

0 commit comments

Comments
 (0)