Skip to content

perf: fix O(N²) lifecycle reinforce-promote query - #286

Merged
hurttlocker merged 1 commit into
mainfrom
fix/lifecycle-perf
Mar 1, 2026
Merged

hurttlocker merged 1 commit into
mainfrom
fix/lifecycle-perf

Conversation

@hurttlocker

Copy link
Copy Markdown
Owner

Problem

cortex lifecycle run hangs indefinitely on production databases. Root cause: the reinforce-promote policy has a correlated subquery that does a full table scan of facts for every row — O(N²) complexity.

With 11,886 facts: 11,886 × 11,886 = ~141 million row comparisons.

QUERY PLAN
`--CORRELATED SCALAR SUBQUERY 2
   `--SCAN f2    ← full table scan per row

Fix

Replace the correlated subquery with a CTE that pre-aggregates source_count via GROUP BY, then LEFT JOIN. Same semantics, O(N) instead of O(N²).

Results

Metric Before After
Time ∞ (killed at 30s) 3.4 seconds
Scanned unknown 25,798
Actions found unknown 10 (conflict-supersede)

Testing

All 890+ tests pass across 17 packages.

The reinforce-promote policy used a correlated subquery that scanned
the entire facts table for every row — O(N²) at 11K+ facts. With our
production DB (11,886 facts), this caused cortex lifecycle run to hang
indefinitely.

Fix: replace the correlated subquery with a CTE that pre-aggregates
source_count via GROUP BY, then JOIN. Same semantics, O(N) instead of
O(N²).

Before: infinite hang (>30s timeout, killed)
After: 3.4 seconds for 25,798 fact scans

All tests pass.
@hurttlocker
hurttlocker merged commit 2f51f88 into main Mar 1, 2026
4 checks passed
@hurttlocker
hurttlocker deleted the fix/lifecycle-perf branch March 1, 2026 16:19
hurttlocker pushed a commit that referenced this pull request Mar 1, 2026
- cortex demo: one-command first-win experience (#293)
- search --source: hard filter by connector origin (#291)
- import/sync progress output (#292)
- shell completions in README (#294)
- lifecycle O(N²) perf fix (#286)
- awesome-mcp-servers submission
hurttlocker pushed a commit that referenced this pull request Mar 1, 2026
- cortex demo: one-command first-win experience (#293)
- search --source: hard filter by connector origin (#291)
- import/sync progress output (#292)
- shell completions in README (#294)
- lifecycle O(N²) perf fix (#286)
- awesome-mcp-servers submission
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.

1 participant