Skip to content

fix(backend-native): Bump neon to 1.1.2 to stop leaking N-API async work, thanks @cavi21 - #12461

Merged
ovr merged 1 commit into
cube-js:masterfrom
cavi21:fix/neon-1.1.2-async-work-leak
Oct 28, 2026
Merged

ovr merged 1 commit into
cube-js:masterfrom
cavi21:fix/neon-1.1.2-async-work-leak

Conversation

@cavi21

@cavi21 cavi21 commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Check List

  • Tests have been run in packages where changes have been made if available
  • Linter has been run for changed code
  • Tests for the changes have been added if not covered yet Already covered by packages/cubejs-backend-native/test/cubestore-result.test.ts, which exercises both parseCubestoreResultMessage and getCubestoreResult. A regression test for the leak itself is not practical: it only happens in release builds, where debug_assert_eq! is compiled out. The test suite uses a debug build, where the async work is freed even with neon 1.1.1.
  • Docs have been added / updated if required Not required: dependency bump plus an internal change in the native module, with no user-facing configuration or behavior changes.

Description of Changes Made

This bumps neon (and neon-macros) from 1.1.1 to 1.1.2 in packages/cubejs-backend-native/Cargo.lock and rust/cube/Cargo.lock. The upgrade fixes a native memory leak that makes the refresh worker grow until it is OOM-killed.

Root cause

In neon 1.1.1, call_complete in crates/neon/src/sys/async_work.rs frees the N-API async work inside a debug assertion:

debug_assert_eq!(napi::delete_async_work(env, work), Ok(()));

Release builds compile debug_assert_eq! out, so napi_delete_async_work never runs. Every TaskBuilder::promise call then leaks its napi_async_work and the AsyncResource attached to it, which holds a V8 global handle. The same pattern also skipped napi_release_threadsafe_function in tsfn.rs.

This was fixed upstream in neon-bindings/neon#1145 and released in neon 1.1.2. PostHog found the same leak in production and described it in PostHog/posthog#110220.

In Cube, the hot path is parse_cubestore_result_message, which runs once for every Cube Store result. The refresh worker queries Cube Store constantly, so it leaks the fastest. API instances leak too, more slowly.

Code change in orchestrator.rs

neon 1.1.2 also tightens the lifetime of Context::execute_scoped:

// 1.1.1
fn execute_scoped<'b, T, F>(&mut self, f: F) -> T where 'a: 'b, F: FnOnce(Cx<'b>) -> T
// 1.1.2
fn execute_scoped<T, F>(&mut self, f: F) -> T where F: for<'b> FnOnce(ScopedCx<'a, 'b>) -> T

Under the new signature, a handle created inside the scope can no longer be returned out of it. get_cubestore_result did exactly that: it returned the row object and the result array out of execute_scoped, and used them after the HandleScope had already been closed. With neon 1.1.2 that is a compile error:

src/orchestrator.rs:330:17: error: lifetime may not live long enough: returning this value requires that `'1` must outlive `'2`
src/orchestrator.rs:336:9: error: lifetime may not live long enough: returning this value requires that `'1` must outlive `'2`

Both calls now use compute_scoped, which opens an EscapableHandleScope and escapes the returned value into the parent scope. The output is unchanged.

How we found it

Setup: a self-hosted Cube v1.8.10 (official image) refresh worker with 8 scheduled refresh contexts, running in a container with a 5 GB memory limit.

  • Symptom. Resident memory grew by about 0.25–0.3 GB/h. Every ~17 h the kernel killed the process (Memory cgroup out of memory, CONSTRAINT_MEMCG, anon-rss ≈ 5.2 GB). There was never a JavaScript heap out of memory.

  • Heap limit. Lowering --max-old-space-size from 4096 to 3072 changed nothing: the process was still killed at 5.2 GB every ~17 h.

  • /proc/<pid>/smaps at 10 h uptime. Total RSS was 3.35 GB. The glibc main arena ([heap]) held 2.49 GB, and all anonymous mappings together, V8 heap included, held 0.71 GB.

  • process.memoryUsage() every 15 minutes, first 4 h. rss went from 438 to 1442 MB while heapTotal went from 232 to 387 MB and external stayed at 5–6 MB. The growth was almost entirely native.

  • jemalloc. Running with LD_PRELOAD=libjemalloc.so.2 gave the same growth rate, which rules out glibc fragmentation.

  • jemalloc heap profiling. With MALLOC_CONF=prof:true,lg_prof_interval:34, we compared a profile taken shortly after start with one taken 3 h later using jeprof --base. 520 MB of the 644 MB of native growth (81%) was allocated under napi_create_async_work. We resolved the callers against index.node from the official image:

    cubejs_native::orchestrator::parse_cubestore_result_message
      → neon::event::task::TaskBuilder<..>::promise
        → napi_create_async_work
    

    The share was the same in both halves of the window: 273 of 327 MB, then 247 of 318 MB.

All Cube releases up to v1.8.14 and current master still lock neon 1.1.1, so they are all affected. The Cargo.toml files already require neon = "=1", so only the lockfiles change.

Testing

Run locally with the pinned Rust toolchain (1.98.1) and Node 24:

  • cargo check --locked in packages/cubejs-backend-native. With only the lockfile bump it fails with the two errors above. With the compute_scoped change it passes.
  • cargo metadata --locked passes for both workspaces. The lockfile diff touches only neon and neon-macros.
  • cargo fmt --check passes.
  • cargo clippy --locked --workspace --all-targets --keep-going -- -D warnings in packages/cubejs-backend-native passes.
  • jest in packages/cubejs-backend-native against a debug build (yarn native:build-debug):
    • 3 suites pass (45 tests). 2 suites are skipped because they need the python feature.
    • cubestore-result.test.ts, which covers both parseCubestoreResultMessage and getCubestoreResult, passes all 15 tests. These include the legacy and Arrow result sets, error and truncated messages, and 64 concurrent parses of the same buffer.

Not run locally:

  • The python feature build and its test suites.
  • A production run of a release build with this change. The memory analysis above was done on the official v1.8.10 image.

neon 1.1.1 called napi_delete_async_work inside debug_assert_eq!, so release
builds never freed the async work created by every TaskBuilder::promise. In
Cube this leaks on every Cube Store result parsed by
parse_cubestore_result_message, and the refresh worker grows until it is
OOM-killed. Fixed upstream in neon-bindings/neon#1145 (neon 1.1.2).

neon 1.1.2 also stops handles from escaping execute_scoped, so
get_cubestore_result now uses compute_scoped to return the row and the
result array from their scopes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@cavi21
cavi21 requested a review from a team as a code owner October 28, 2026 12:02
@github-actions github-actions Bot added rust Pull requests that update Rust code pr:community Contribution from Cube.js community members. labels Oct 28, 2026
@ovr ovr self-assigned this Oct 28, 2026
@ovr

ovr commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

Thanks for the thorough investigation! I reproduced the leak locally and can confirm both the root cause and the fix.

Reproduction

Release builds on darwin-arm64 with Node 24. The test calls parseCubestoreResultMessage 1M times in a loop and measures RSS after a forced gc():

Build RSS after 1M calls Growth per call heapUsed macOS leaks after 20k calls
published v1.8.14 62 → 566 MB ~530 B 4.6 → 58 MB 19,993 leaks (5.1 MB)
this PR rebuilt with only neon reverted to 1.1.1 62 → 566 MB ~530 B 4.6 → 58 MB 19,993 leaks
this PR (neon 1.1.2) 53 → 60 MB ~0 3.5 → 3.7 MB 0

All leaked objects are uvimpl::Work (256 B), allocated at:

cubejs_native::orchestrator::parse_cubestore_result_message
  → neon::sys::async_work::schedule
    → napi_create_async_work
      → operator new

The remaining ~270 B per call comes from the AsyncResource that the never-deleted Work keeps alive: its resource object on the V8 heap (this is why heapUsed grows) and its global handle.

The leak covers more than parseCubestoreResultMessage

The bug is in neon's shared call_complete, so every cx.task(...).promise(...) call in the addon leaks. orchestrator.rs has three of them:

  • parseCubestoreResultMessage: runs for every Cube Store WebSocket response, including queue and cache commands. This explains why the refresh worker leaks the fastest.
  • getFinalQueryResult: runs for every result that goes through ResultWrapper.getFinalResult(). This is the API instance leak you mentioned.
  • getFinalQueryResultMulti: the multi-query variant of the same.

I only measured the first one. The other two go through the same neon code path. The bump fixes all three.

The tsfn.rs part probably doesn't apply to Cube

We build neon with napi-6, so cx.channel() returns the shared InstanceData channel, and we never call Channel::new directly. At most one threadsafe function per env is affected by the missing napi_release_threadsafe_function. It does not leak per call.

execute_scoped → compute_scoped

This change is not related to the leak itself, but it is correct. With 1.1.1 the code returned handles out of a closed HandleScope, which only compiled because of the unsound lifetime bound that neon 1.1.2 fixes.

@ovr ovr changed the title fix(backend-native): Bump neon to 1.1.2 to stop leaking N-API async work fix(backend-native): Bump neon to 1.1.2 to stop leaking N-API async work, thanks @cavi21 Oct 28, 2026
@codecov

codecov Bot commented Oct 28, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 85.68%. Comparing base (5701a81) to head (ae9102c).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master   #12461      +/-   ##
==========================================
- Coverage   86.60%   85.68%   -0.93%     
==========================================
  Files         271      271              
  Lines      100660   100660              
==========================================
- Hits        87173    86246     -927     
- Misses      13487    14414     +927     
Flag Coverage Δ
cubesql 85.68% <ø> (-0.93%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@ovr
ovr merged commit 62dbc3f into cube-js:master Oct 28, 2026
120 of 121 checks passed
@ovr

ovr commented Oct 28, 2026

Copy link
Copy Markdown
Member

Thank you @cavi21 for your contribution! 🍰 👍

@cavi21

cavi21 commented Oct 28, 2026

Copy link
Copy Markdown
Contributor Author

@ovr thank you all for all the work done on it :)!

@cavi21
cavi21 deleted the fix/neon-1.1.2-async-work-leak branch October 28, 2026 13:11
ovr pushed a commit that referenced this pull request Oct 29, 2026
…ork, thanks @cavi21 (backport #12461 to v1.6)

neon 1.1.1 frees N-API async work inside `debug_assert_eq!`, so release
builds never call `napi_delete_async_work`. neon 1.1.2 fixes it upstream
(neon-bindings/neon#1145).

On v1.6 the shipped addon (packages/cubejs-backend-native/Cargo.lock) is
still on neon 1.0.0, which is not affected: the bump to 1.1.1 came with
#12170 (first released in v1.8.3). This backport only moves the rust/cube
workspace lockfile off 1.1.1 and switches `get_cubestore_result` to
`compute_scoped`, which neon 1.0.0 also provides.

(cherry picked from commit 62dbc3f)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr:community Contribution from Cube.js community members. rust Pull requests that update Rust code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

⌂ Proxy