Skip to content

Refactor: Each run of a compiled SELECT gets its own state - #3106

Merged
mathiasrw merged 2 commits into
mainfrom
fix/2596-run-object
Nov 22, 2026
Merged

mathiasrw merged 2 commits into
mainfrom
fix/2596-run-object

Conversation

@mathiasrw

@mathiasrw mathiasrw commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Closes #2596. This is step 2 of the issue: each run of a compiled SELECT gets its own state, so a cached statement can run twice at the same time. The hot loops are as they were.

The first fix for the visible cases was #2465 by @imsanupm, for the Promise.all report in #1953. This PR builds on it, and its tests are kept and pass.

What changes

A compiled SELECT keeps one query object and one object per source, and until now every run wrote its notes on them. Now the statement function starts with newRun(query, state) (src/select/select.js) and hands the result to queryfn. Nothing else in the run path changed its shape, because the code already passes query along.

  • newRun makes a copy of the query object and of each source, one level deep. The compiled functions are shared, a write lands on the copy. The copy names every field, see below.
  • The lists a run adds to are copied too: removeKeys, columns and explaination. groupSources gets a new map per run. Without this a push would still change the shared list, as the review pointed out.
  • The compiled query shows data as an empty, frozen list. It was [] between two runs before, through cleanupCache, and test2027 and test1953 read it.

A copy, not Object.create(query)

The issue proposes Object.create(query). I built that first, and all tests passed, but Node got slower where a statement is compiled on every run. An object with the compiled query as its prototype has a shape of its own per compiled statement, so the per-row loops in doJoin lose their inline caches. A CTE over 50,000 rows went from 3.0 ms to 9.0 ms per query in a small script on Node 24, and the performance suite showed cte +93% and index +37% on Node. With the copy the same script gives 2.8 ms, and those dimensions are level. The copy costs one object with the fields of the query per run, and one per source.

The copy names every field

A correlated subquery runs once per outer row, so it makes this copy once per outer row. The first version of this PR copied with new Query(compiled) and Object.assign, which took about 0.8 microseconds per run on Node, and that made the three correlated cases below 17 to 23 percent slower than main. copyQuery and copySource now build the copy as one object literal that names every field, which takes about 25 nanoseconds.

A field that the literal does not name is not lost. At the first run of a statement, unlisted compares the compiled query and its sources with their copies, and every later run copies the missing fields by name. So a new field works without being added to the list, only slower. Test L checks this. This relies on a compiled query not getting a new field after its first run, and the run-state check now lists such a write, also when a later compile makes it.

I also tried to give the compiled query all its fields up front, so that an object spread would be fast. That made the copy slower (65 fields, 14 microseconds), so it is not in the PR.

The values another statement sets for a run

modifier and queriesfn were written on the compiled query of another statement while the outer statement ran. They are now given to the run: the statement function takes a fourth argument, state, and newRun puts it on the copy.

  • The parts of UNION, UNION ALL, EXCEPT and INTERSECT get their modifier this way (src/select/queryfn.js).
  • The subquery of a source gets the queriesfn of the outer query this way (src/select/from.js), which was the write of Give each SELECT its own list of subqueries from parsing on #2666.
  • The writes of modifier in INSERT, UPDATE, DELETE, SET and exists.js, and those in compileQueries, are not changed. They happen right after the compile of that SELECT and before its first run, so they are part of the setup. The run-state check listed six of them as run writes in Devops: Run-state check that lists every write to a compiled query during a run #3105, because it counted every write outside a Select.compile as a run write. Its rule now says that a query that has not run yet is still being compiled.

The guard of #2465 and #2747

Those two PRs give an overlapping run its own compiled copy: runStatement counts the runs of a statement, and alasql.dexec and alasql.compile() parse and compile again when the count is not zero. That stays for every statement that is not a compiled SELECT, because only the SELECT was checked for run state here. INSERT, UPDATE, DELETE and the others keep state on the parsed statement (#2632) and were not looked at.

For a compiled SELECT the guard is skipped (sharesRuns in src/engine/core.js), so an overlapping run shares the compiled statement. That is what the parity check shows as its code differences below, and nothing else. cleanupCache is removed, as no run writes data to the compiled query any more. The run counter itself stays for all statements, so #2875 is as before.

Tests

test/test2596.js gets eight tests, beside the tests of #2465 and #2747 that are kept.

  • E, F and G are the three reproductions of the issue. E and F also count the compiles and expect one, so they fail on the base, where the nested run compiles a copy.
  • H runs three overlapping runs with other parameters in WHERE, LIMIT and a subquery. I is a nested run with other parameters.
  • J checks that the cached statement holds no reference to the parameters, the rows read, the result or the rows of a table after the run, a few levels deep, and that the query and its sources have no params, scope, groups, data or ix of their own.
  • K checks that removeKeys and columns of the compiled query do not grow from run to run.
  • L gives a compiled query and a source a field that the copy does not name, and checks that a run sees both.

Suite: 2731 pass, 213 skip, 0 fail.

Run-state check

yarn test-runstate gives an empty list: 0 writes to a compiled query and 0 to a source during a run. I checked that it still finds a write by planting four in the build (a new property, a push to a shared list, a write inside a shared object and a map), and it listed each.

The check now ends with exit code 1 when the list is not empty, and it is a CI job, "Run-state check of compiled queries". The job uses the same pinned actions as the other jobs and no new one. The recorder also sees writes to a Map, a Set and a WeakMap now, which it did not in #3105, and it lists every write to a query that has run, also one made by a later compile.

Performance

bun test/performance/vs-npm.js with the base build (41040e4) as 100, three runs per build, 172 timed cases.

Before (base) After (this PR)
Score 100 89
Bun 1.4.3 100 88
Node 24 100 89

Lower is faster. Dimensions marked slower: coercion +23% on Bun, memory +13% on Bun, compile +11% on Node, constraints +10% on Bun. Marked faster: join-chain, subquery, core, subquery-derived, left-join and others, by 20 to 50 percent.

How much to trust it: the machine was running other work during the measurement, and a run of the base against itself on five groups moved single dimensions by up to 17 percent. So I read the result as "not slower", not as an 11 percent gain. I did not find out why joins and subqueries measure faster. One possible reason is that the source objects no longer change shape in the middle of a run, but that is a guess. A run on a quiet machine before the release would settle it.

A subquery that runs once per outer row

t1 has 10,000 rows and t2 has 100. Milliseconds per query, the best of six processes of 15 queries each, with main and the PR taking turns. Node 24 and Bun 1.4.3.

Query Runtime main PR, first version PR now
SELECT a, (SELECT MAX(b) FROM t2 WHERE t2.a = t1.a) AS m FROM t1 Node 52.9 +17% 49.1 (-7%)
Bun 59.6 +23% 52.1 (-12%)
SELECT a FROM t1 WHERE x IN (SELECT b FROM t2 WHERE t2.a = t1.a) Node 54.5 +21% 51.2 (-6%)
Bun 41.8 +23% 41.2 (-1%)
SELECT a FROM t1 WHERE EXISTS (SELECT 1 FROM t2 WHERE t2.a = t1.a) Node 48.7 +19% 48.8 (0%)
Bun 39.4 +22% 40.1 (+2%)
SELECT a FROM t1 WHERE a IN (SELECT a FROM t2), not correlated Node 0.76 0% 0.77 (+1%)
Bun 0.71 -15% 0.70 (-1%)

The column "PR, first version" is from its own run against main, so only its percentage is given. The machine was under load from other work during these runs (load average 9 to 15), and two runs of the same pair differed by up to about 10 percent, so I read the last column as level with main. The score of the full suite above was measured on the first version and not again.

Parity differences

From the parity job of this PR, against the base (41040e4) with the test files of this PR. 78,547 statements aligned in 586 files.

Kind Count
result 0
error 0
params 0
generated code 17
only in one recording 0
diverged 0
API paths (1,718) 0

All 17 code differences are the same thing: a run that overlaps another run of the same SELECT no longer compiles its own copy, so the recording has no generated code for that run where the base has the code of the compile. They are in the two test files about overlapping runs.

File Statements Count
test1953.js SELECT COLUMN x FROM SLOW1953(?, ?) ORDER BY x, SELECT * FROM JSON(?), SELECT id, kidsOf1953(kids) AS below FROM ? ORDER BY id (2), SELECT a, SUM(b) AS s, inner1953(a) AS i FROM ? GROUP BY a 5
test2596.js SELECT COLUMN x FROM SLOW2596(?, ?) ORDER BY x (2), SELECT COLUMN x FROM SLOW2596(?, ?), SELECT id, below2596(kids) AS below FROM ? ORDER BY id (2), SELECT id, kidsOf2596(kids) AS below FROM ? ORDER BY id (2), SELECT a, SUM(b) AS s, inner2596(a) AS i FROM ? GROUP BY a, the query of test H (2), the query of test I (2) 12

Every result is the same on both builds. This is the evidence for skipping the guard for a compiled SELECT.

Sizes: alasql.fs.js 946,119 to 949,320 bytes (+0.34%), alasql.min.js 539,600 to 541,629 bytes (+0.38%), gzip +698 bytes on the minified file. The growth is the two lists of field names.

Two local recordings on my machine showed more: the callbacks of two overlapping asynchronous runs arriving in the other order, and an asynchronous WHILE loop of test2979 running on into later files. The machine had a load average near 190 at that time, the base showed the same between its own two runs, and the CI job shows neither. Each callback carried the right rows for its own call.

Behaviour a user could notice

  • statement.query of a statement from alasql.compile() no longer shows the state of the last run. params, scope, groups and explaination entries of a run are not on it. data is an empty list, as before.
  • columns and removeKeys of a compiled query no longer change after the first run. Before, a run could filter or extend them for the next run of the cached statement (Set operation with ORDER BY / LIMIT on the first SELECT gives a different result from the second run #2605 is in this area). No test in the suite changes its result from this.

Not in this PR

@mathiasrw
mathiasrw merged commit 1a730c6 into main Nov 22, 2026
26 checks passed
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.

Cached statements hold per-run state, so two runs of the same SQL at once overwrite each other

1 participant