Skip to content

perf(native): Cut N-API round-trips in NativeSerdeDeserializer - #12170

Merged
ovr merged 11 commits into
masterfrom
ovr/nativestruct-entries-add
Oct 8, 2026
Merged

ovr merged 11 commits into
masterfrom
ovr/nativestruct-entries-add

Conversation

@ovr

@ovr ovr commented Oct 8, 2026 •

Copy link
Copy Markdown
Member

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
  • Docs have been added / updated if required

Description of Changes Made

Cuts N-API round-trips in NativeSerdeDeserializer (cubenativeutils neon wrappers, using neon's sys feature):

  • One napi_typeof per value instead of an is_a probe per candidate type; ASCII strings are read with a single copy and non-ASCII ones into an exactly sized buffer.
  • Objects and arrays are read in one with_context; values are looked up by the original key handle; keys come from a cached JS Object.keys (N-API's napi_get_all_property_names always takes V8's slow KeyAccumulator path).
  • deserialize_struct reads only the fields serde declares, so e.g. CubeDefinitionStatic no longer fetches and roots a compiled cube's measures, dimensions and sql functions.

Behaviour changes: non-enumerable properties are skipped (as in JSON.stringify); Symbol/BigInt values fail with the field/element path instead of leaking a TypeError; #[serde(deny_unknown_fields)] isn't honoured by deserialize_struct (no bridged struct uses it). backend-native's Cargo.lock moves neon 1.0.0 → 1.1.1 to match rust/cube.

Release build, master vs this PR (78cb37c), interleaved A/B, median of 7 rounds:

case master this PR speedup
CubeDefinitionStatic from a compiled cube 5.23 µs 0.96 µs 5.45x
MeasureDefinitionStatic from a measure 2.25 µs 0.66 µs 3.41x
PostgresQuery sqlTemplates() 86.5 µs 49.8 µs 1.74x
wide object, 1000 string fields 436 µs 222 µs 1.96x
wide object, 1000 non-ASCII string fields 456 µs 311 µs 1.47x
array of 10k numbers 833 µs 584 µs 1.43x
200 nested member-like objects 1263 µs 776 µs 1.63x

🤖 Generated with Claude Code

Speeds up NativeSerdeDeserializer by another 1.6-1.8x by removing N-API
calls from the neon wrappers (uses neon's `sys` feature):
- RootHolder::new_in resolves a value's type with one napi_typeof instead
  of an is_a probe per candidate type plus a re-check in downcast.
- Strings are read with one N-API call: the UTF-16 length is O(1) and
  bounds the buffer, with an exact-size fast path for ASCII.
- NativeStruct::entries() reads keys and values in one with_context and
  looks values up by the original (already internalized) key handle,
  replacing get_field_by_key.
- NeonArray::to_vec reads all elements in one with_context; SeqAccess
  gets a size_hint.

A Symbol/BigInt value now fails with the field/element path instead of
a leaked "Cannot convert a Symbol value to a string" TypeError.
backend-native's lock moves neon 1.0.0 -> 1.1.1 (already used by
rust/cube): the raw bindings return Result<(), Status> there.

Release build, `yarn bench`, master vs this change, mean of two runs:

| case | before | after | speedup |
| --- | --- | --- | --- |
| PostgresQuery sqlTemplates(), 1 call | 0.090 ms | 0.054 ms | 1.67x |
| PostgresQuery sqlTemplates(), x100 in Rust | 8.83 ms | 5.32 ms | 1.66x |
| wide object, 1000 string fields | 0.435 ms | 0.244 ms | 1.79x |
| array of 10k numbers | 0.901 ms | 0.571 ms | 1.58x |
| 200 nested member-like objects | 1.31 ms | 0.80 ms | 1.63x |

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@ovr
ovr requested a review from a team as a code owner October 8, 2026 08:33
@github-actions github-actions Bot added rust Pull requests that update Rust code javascript Pull requests that update Javascript code labels Oct 8, 2026
@claude

claude Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 2m 43s —— View job


Looks good: 0 high, 0 medium, 1 low.

Review details
  • Gather diff and context
  • Review neon wrappers / deserializer
  • Review threads
  • Post review

Findings

  • Low (simplification): neon_struct.rs:73: entries() passes the failing key out through a failed_key side variable and adds the error prefix later in a map_err. NeonArray::to_vec adds the same prefix inline. Doing it inline in entries() too removes the variable and its comment. Posted as an inline comment.

Checked and found sound

  • read_js_string (primitive_root_holder.rs): when written == utf16_len, the is_ascii() check is enough to prove nothing was cut off. If the first utf16_len bytes are all ASCII, all utf16_len UTF-16 units were written. The fallback buffer of utf16_len * 3 + 1 bytes covers both lone surrogates (3 bytes) and surrogate pairs (4 bytes for 2 units). The new éa, abcé and lone-surrogate tests cover the edge cases.
  • RootHolder::new_in: the napi_typeof match covers the same types the old is_a chain did. Arrays are still told apart with napi_is_array. JsBox still goes through neon's type-tag downcast, not from_raw. Symbol and BigInt values no longer leave a pending TypeError behind, because unsupported wraps to_string in try_catch.
  • entries(): the SAFETY note that every key is a string depends on neon's get_own_property_names requesting SKIP_SYMBOLS and NumbersToStrings. That matches neon 1.x as far as I know. I couldn't open the cargo registry here to confirm it.
  • Re-entrancy: new_in and both holder constructors only use the cx passed in, never with_context. On the error path, the roots already collected are dropped inside the closure. Their Drop then gets a failed nested with_context, so cleanup falls back to neon's deferred drop (napi-6 is enabled). Nothing leaks.
  • Key deserialization now goes through &str (StrDeserializer → visit_str). That is fine for struct field identifiers and String keys.

Notes, no action needed

  • A getter that throws during entries() or to_vec() still leaves the JS exception pending after it has been turned into a CubeError. The old get_field_by_key and get paths did the same, so this is not new.
  • to_vec reads the whole array before deserializing it. A tuple consumer that stops early will now fail if an unread trailing element is a Symbol or BigInt. Nothing in-tree relies on reading only part of an array.

Review threads

The listing returned no prior threads of mine (0). None were resolved or re-affirmed.

@codecov

codecov Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 81.31%. Comparing base (22fc5eb) to head (e283d08).
⚠️ Report is 9 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master   #12170      +/-   ##
==========================================
- Coverage   85.15%   81.31%   -3.85%     
==========================================
  Files         264      515     +251     
  Lines       89211   109723   +20512     
  Branches        0     4281    +4281     
==========================================
+ Hits        75966    89217   +13251     
- Misses      13245    19880    +6635     
- Partials        0      626     +626     
Flag Coverage Δ
cube-backend 64.60% <ø> (?)
cubesql 85.15% <ø> (ø)

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.

- deserialize_struct reads only the fields serde declares (aliases
  included) instead of every own property: values of other properties
  are never fetched, so no Get, typeof or Root for them, and keys are
  matched through a stack buffer without allocating. A compiled cube
  has 13 own properties (5 functions, 5 objects) while
  CubeDefinitionStatic needs only `name`.
- Object keys come from a cached JS `Object.keys` instead of
  napi_get_all_property_names: v8::Object::GetPropertyNames always
  collects keys through KeyAccumulator's hash set, while Object.keys
  copies the map's enum cache. Non-enumerable properties are now
  skipped, as in JSON.stringify.

Adds CubeDefinitionStatic / MeasureDefinitionStatic cases to the
deserializer benchmark.

Release build, interleaved A/B against the previous commit, median of 7:

| case | before | after | speedup |
| --- | --- | --- | --- |
| CubeDefinitionStatic from a compiled cube | 2.66 us | 0.88 us | 3.02x |
| MeasureDefinitionStatic from a measure | 1.23 us | 0.64 us | 1.92x |
| wide object, 1000 string fields | 246 us | 220 us | 1.12x |
| PostgresQuery sqlTemplates() | 53.3 us | 51.0 us | 1.05x |
| 200 nested member-like objects | 820 us | 781 us | 1.05x |
| array of 10k numbers | 579 us | 582 us | 1.00x |

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@claude

claude Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 2m 57s —— View job


Approve-level: no blocking issues. 2 low, plus 1 earlier thread that still applies.

Review details
  • Gather context (diff + changed files)
  • Review neon wrappers (root_holder, primitive_root_holder, neon_struct, neon_array)
  • Review deserializer + tests
  • Resolve stale threads / dedupe
  • Post review

Findings (inline)

  • Low (perf): rust/cube/cubenativeutils/src/wrappers/neon/object/primitive_root_holder.rs:147. For non-ASCII strings, read_js_string makes 3 N-API calls and copies the string twice into a 3× buffer, then reallocates it with shrink_to_fit. Neon's JsString::value makes 2 calls. The benchmark only covers ASCII.
  • Low (latent): rust/cube/cubenativeutils/src/wrappers/serializer/deserializer.rs:97. deserialize_struct filters keys down to fields, so a future #[serde(deny_unknown_fields)] struct would silently accept unknown keys. No struct uses that attribute today.

What I checked and found correct

  • Type detection: RootHolder::new_in handles every napi_typeof variant. Function is checked before Object, Array is detected with is_a, and JsBox still goes through neon's tag-checked downcast. A Symbol now reaches unsupported, where try_catch contains the TypeError that toString throws. Behaviour matches the old is_a chain otherwise: Date, RegExp and Proxy are still treated as structs.
  • String reads:
    • The ASCII fast path is sound. written == utf16_len && is_ascii() is the only way to accept the first read, so cases like "éa" filling the buffer go to the fallback. The tests added for multibyte-first, multibyte-last and lone-surrogate strings cover this.
    • The fallback's utf16_len * 3 + 1 bound holds: a surrogate pair is 4 bytes for 2 units, and a lone surrogate becomes 3 bytes.
  • entries_for_fields: the 128-byte key check written + 4 < buf.len() is exact. N-API writes at most 127 bytes, so a cut key always has written ≥ 124.
  • Object.keys vs napi_get_all_property_names: both return own, enumerable string keys with numeric indices as strings and symbols skipped. Proxy ownKeys / getOwnPropertyDescriptor traps still run, as the new throwing-trap test shows.
  • Serde behaviour:
    • deserialize_struct only sees structs with no flatten field. Structs with flatten, untagged enums and internally tagged enums all go through deserialize_map/deserialize_any → entries(), so they still see every key.
    • FIELDS in serde_derive 1.0.228/229 includes aliases.
  • Error paths: a nested failure like {a: {s: Symbol()}} produces field `a`: field `s`: failed to read value: …. For arrays, the prefix comes from to_vec once, before any element is visited, so it isn't doubled.
  • Trait change: NeonStruct is the only NativeStruct impl, so dropping get_field_by_key breaks no other implementers.

Review threads

The listing returned 1 of my threads. I resolved 0 and re-affirmed 1: neon_struct.rs (outdated, originalLine 73). That thread suggests building the error prefix inline instead of passing the key out through the failed_key side variable. collect_entries still uses that pattern (neon_struct.rs:56, :86-91); the code only moved.

Addresses review comments on #12170:
- read_js_string's non-ASCII fallback asks N-API for the UTF-8 length
  and reads once into an exact buffer, instead of reading into a
  3 * utf16_len buffer and shrinking it.
- NeonStruct::collect_entries prefixes the failing field inline, like
  NeonArray::to_vec, instead of passing it out through a side variable.
- Documents that deserialize_struct / entries_for_fields can't honour
  #[serde(deny_unknown_fields)].

Adds a non-ASCII case to the deserializer benchmark. Interleaved A/B,
median of 7:

| case | 3x buffer | exact buffer | speedup |
| --- | --- | --- | --- |
| wide object, 1000 non-ASCII string fields | 306 us | 285 us | 1.08x |
| wide object, 1000 string fields | 206 us | 206 us | 1.00x |
| PostgresQuery sqlTemplates() | 45.2 us | 45.3 us | 1.00x |

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@claude

claude Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 2m 3s —— View job


Looks good to merge: 0 high, 0 medium, 3 low. No correctness regressions found.

Review details
  • Gather context (diff, changed files)
  • Review neon wrappers (root_holder, primitive_root_holder, neon_struct, neon_array)
  • Review deserializer + tests/bench
  • Reconcile prior review threads
  • Post review

Findings (posted inline)

Severity Location Issue
low rust/cube/cubenativeutils/src/wrappers/neon/object/neon_struct.rs:34 Wraps the result of the global Object.keys (cached on first use) with JsArray::from_raw without checking it. If Object.keys was replaced before that first call, a non-array is wrapped as JsArray. One downcast per struct would cost almost nothing.
low rust/cube/cubenativeutils/src/wrappers/neon/object/root_holder.rs:142 napi_coerce_to_string always throws for a Symbol, so the new Symbol error always ends in Unsupported JsValue: <unprintable>. Print the value_type instead.
low rust/cube/cubenativeutils/src/wrappers/serializer/deserializer.rs:92-94 This comment repeats the deny_unknown_fields caveat already in the trait doc at object.rs:53-54.

Checked and fine

  • read_js_string ASCII fast path (primitive_root_holder.rs:137-162): if written == utf16_len and the buffer is ASCII, those bytes stand for exactly utf16_len ASCII code units, so the whole string was read. Any non-ASCII character, including a lone surrogate replaced by U+FFFD, either fails is_ascii or makes written shorter than utf16_len. The new éa, abcé and lone-surrogate cases test this.
  • entries_for_fields 128-byte key buffer (neon_struct.rs:125-134): N-API writes at most 127 bytes and cuts only on a character boundary. A cut key therefore has written >= 124, which fails written + 4 < 128 and goes to the full read. No false matches.
  • deserialize_struct filtering keys by fields: nothing on the native path uses deny_unknown_fields. The only alias/flatten attributes are in the YAML test fixtures. flatten goes through deserialize_map in any case.
  • Object.keys vs get_own_property_names: both return own, enumerable, string keys, with integer keys turned into strings. The new non-enumerable test confirms this.
  • Getter, element and ownKeys exceptions: these still return early with the JS exception pending, as before. No further N-API calls run on that path, and the existing rethrow tests plus the new ownKeys test cover it.
  • Map keys as &str through into_deserializer: a String key visitor accepts visit_str. Non-string keys failed before too.
  • Tests: the new cases cover Symbol and BigInt, element paths, undeclared getters not being read, and non-enumerable properties.

Review threads

The listing returned 0 of my own unresolved threads, so there were none to resolve or re-affirm.

I did not build or run the tests in this round. These findings come from reading the code.

Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
@claude

claude Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 2m 8s —— View job


Changes requested: the latest commit doesn't compile. 1 high, plus 2 earlier threads that still apply

Review details
  • Gather diff and changed files
  • Review code
  • Reconcile prior review threads
  • Post findings

High

  • rust/cube/cubenativeutils/src/wrappers/serializer/deserializer.rs:91-93: the applied suggestion in 61595a1 deleted the { that opens deserialize_struct's body. match now follows the where clause directly, which is a syntax error, so cubenativeutils, cubesqlplanner and backend-native no longer build. The same edit removed the deny_unknown_fields caveat from the comment. An inline suggestion restores both.

Checked, nothing to raise

  • read_js_string: the ASCII fast path is correct. Truncation on a multibyte first character is caught by the is_ascii check, and the tests cover éa, abcé and a lone surrogate.
  • entries_for_fields: N-API writes at most 127 bytes and a character is at most 4, so written + 4 < 128 proves the key wasn't cut.
  • collect_entries / NeonArray::to_vec: a throwing getter returns immediately with the NeonThrow cause intact, so no further N-API calls run while the exception is pending.
  • RootHolder::new_in: the single napi_typeof plus is_a::<JsArray> covers every ValueType. Externals still go through neon's tagged downcast.
  • I couldn't compile or run the tests locally (cargo needed approval in this run). The compile error is visible from the source.

Review threads

The listing returned 2 of my threads. I resolved 0 and re-affirmed 2, because the code at both sites is unchanged:

  • neon_struct.rs:34: JsArray::from_raw / JsString::from_raw trust whatever the cached global Object.keys returns.
  • root_holder.rs:142: a Symbol value is reported as <unprintable>, because to_string throws on Symbols.

The applied review suggestion in 61595a1 replaced one line too many:
it dropped the `{` that opens deserialize_struct's body, breaking the
cubenativeutils build, and left half of the old comment behind.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@claude

claude Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Reviewing PR #12170

  • Read diff and changed files
  • Analyze correctness / safety / perf / tests / comments
  • Resolve stale review threads (in progress)
  • Post review

View job run

Addresses review comments on #12170:
- The cached `Object.keys` may have been replaced by a polyfill, so its
  result is downcast to an array and each key to a string instead of
  being wrapped with `from_raw`. The per-key check costs 7-11% on
  struct deserialization (CubeDefinitionStatic 0.87 -> 0.98 us, still
  5.5x faster than master) and nothing measurable on maps.
- An unsupported value is reported by its type
  (`Unsupported JsValue of type Symbol`) instead of `<unprintable>`:
  coercing a Symbol to a string throws.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@claude

claude Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 2m 24s —— View job


LGTM, no blocking issues. 0 high, 0 medium, 1 low (test coverage). 1 earlier thread is still open.

Review details
  • Read diff and changed files
  • Analyze findings
  • Review threads (stale resolution / dedupe)
  • Post inline comments and summary

Finding

  • Low, test coverage (rust/cube/cubenativeutils/src/wrappers/neon/object/neon_struct.rs:131): no test reaches the long-key fallback in entries_for_fields, which handles keys of 124+ UTF-8 bytes. The Object.keys result check at neon_struct.rs:35 is also never exercised. Posted inline with a test case to add.

Checked and found correct

  • entries_for_fields truncation bound: N-API writes at most 127 bytes and only cuts on a character boundary (≤4 bytes). So written ≤ 123 proves the key was read whole, and longer keys fall back to the full read.
  • read_js_string ASCII fast path: a result that is all ASCII and utf16_len bytes long means the whole string was read. Truncated non-ASCII input such as "éa" fails the ASCII check and is re-read.
  • JS exceptions: when a getter throws, collect_entries and NeonArray::to_vec return right away and keep CubeErrorCauseType::NeonThrow, so into_cube_error passes the pending exception to JS unchanged. No other N-API call is made while it is pending.
  • Non-enumerable properties are now skipped. The only non-enumerable property found on members passed to Rust is maskSql (CubeEvaluator.ts:874), and Tesseract reads it through mask_sql() / get_field, not serde. So the change doesn't affect it.
  • deserialize_struct only receives the declared fields. Derived structs with #[serde(flatten)] go through deserialize_map, and untagged enums go through deserialize_any. Both still get every key from entries().

Review threads

The listing returned 1 thread of mine. I resolved 0 and re-affirmed 1: neon_struct.rs:128 asking for named constants instead of the bare 128 / 4, which are still in the code. The new finding isn't a duplicate of it.

Not run

The repo wasn't built and its tests weren't run locally. This is a review only.

Addresses review comments on #12170:
- Tests keys that don't fit, or end too close to the end of, the
  128-byte stack buffer entries_for_fields matches keys in.
- Tests that a replaced Object.keys returning no array or non-string
  keys fails with a TypeError, in a fresh process each since Object.keys
  is cached per addon instance. Before the checks both cases panicked
  ("internal error in Neon module").
- Spells the buffer bound with char::MAX_LEN_UTF8 instead of a bare 4.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@claude

claude Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 2m 38s —— View job


Looks good: 0 high, 0 medium, 1 low. One dead trait method remains; no correctness or safety issues found.

Review details
  • Read the diff and changed files
  • Analyse correctness, safety, perf, tests, comments
  • Reconcile prior review threads
  • Post review

Findings

  • Low: NativeStruct::get_own_property_names (rust/cube/cubenativeutils/src/wrappers/object.rs:62) has no callers left. It still uses the slow N-API path, which also returns non-enumerable keys, so its key set no longer matches entries. Posted inline.

Checked and found sound

  • read_js_string (primitive_root_holder.rs:114):
    • The ASCII fast path is correct. If written == utf16_len and every byte is ASCII, each byte came from exactly one UTF-16 unit, so the string was not truncated.
    • The fallback sizes the buffer from the real UTF-8 length.
    • from_utf8_unchecked relies on N-API replacing invalid UTF-8 and truncating only on a character boundary, the same assumption neon makes.
  • The 128-byte key buffer (neon_struct.rs:128): for N-API to truncate, the next character must not fit in the space left, so written > 123. That means written + 4 < 128 correctly proves the key is whole.
  • JS exceptions:
    • A throwing getter, a throwing ownKeys trap, or a non-array result from Object.keys keeps its NeonThrow cause through map_err(CubeError::from). Only the message gets the field prefix, so the pending exception still reaches JS unchanged (lifetime_guard.rs:82).
  • RootHolder::new_in: every from_raw is backed by the napi_typeof result (plus is_a for arrays). JsBox still goes through neon's tag-checked downcast.
  • deserialize_struct:
    • serde's FIELDS includes aliases.
    • #[serde(flatten)] containers go through deserialize_map, which still reads every entry.
    • An array passed for a struct still reaches visit_seq.
    • The deny_unknown_fields caveat is documented on the trait.
  • Lockfiles: neon is 1.1.1 in the root, rust/cube and backend-native Cargo.lock, and the sys feature is enabled in cubenativeutils/Cargo.toml.
  • Tests: they cover:
    • the truncation edge cases ('éa', 'abcé', a lone surrogate)
    • long keys and keys near the buffer boundary
    • a replaced Object.keys (each case in a fresh process, because the function is cached)
    • non-enumerable keys
    • Symbol and BigInt values
    • a throwing ownKeys trap
    • undeclared getters never being called
  • Comments: all within 3 lines, and each explains a reason a later edit could otherwise break.

Review threads

The listing returned 0 of my own unresolved threads, so there was nothing to resolve or re-affirm. The earlier threads on this PR were opened by @ovr and were left alone.

Not run: no Rust build or bridge tests in this job. The review is from reading the code.

Flatten native error handling for batched array and object reads while preserving field and element context. Reserve filtered entries for at most the number of declared fields.

Add deserializer benchmarks for long ASCII and Unicode strings and medium-length Unicode strings.

Validated with a release bridge build, 194 bridge tests, 11 Rust tests, Clippy, TypeScript, oxlint, and rustfmt.
@claude

claude Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 1m 43s —— View job


Verdict: no blocking issues. 0 high, 0 medium, 1 low (nit), plus 1 earlier thread that still applies.

Review details
  • Read diff and changed files
  • Analyze for issues
  • Handle prior review threads
  • Post review

Findings

Low (benchmark only, no inline comment): the array of 1000 Unicode strings around 128 UTF-8 bytes case in packages/cubejs-backend-native/benchmarks/deserializer.bench.ts doesn't measure the 128-byte path. It runs through the json loop, so these strings are values read by read_js_string, which has no 128-byte threshold. The 128-byte stack buffer is only used for keys in entries_for_fields (rust/cube/cubenativeutils/src/wrappers/neon/object/neon_struct.rs:122). As written, the case is just another non-ASCII value benchmark. To measure the boundary, run a cubeStatic/measureStatic loop over an object whose keys are about 120–130 bytes long. Otherwise, rename the case.

Checked and found correct

  • entries_for_fields: written + char::MAX_LEN_UTF8 < buf.len() means the key wasn't truncated. N-API stops only on a character boundary, so a truncated key is at least 124 bytes and always takes the fallback.
  • read_js_string: for ASCII strings, the UTF-16 length bounds the buffer. A non-ASCII string either fails the is_ascii check or gives written != utf16_len, and then gets an exactly sized second read. Lone surrogates are covered by a test.
  • RootHolder::new_in: the arms that build from raw values each depend on a single napi_typeof. The External arm still goes through neon's type-tagged downcast, so an external that isn't a JsBox is rejected.
  • Errors: when a getter or ownKeys throws, the error keeps its NeonThrow cause after the field/element prefix is added, and NativeObjSerializerError::context keeps it intact, so the JS exception still propagates.
  • deserialize_struct filtering: deserialize_struct is only reached through derived impls. #[serde(flatten)] structs go through deserialize_map instead, and the only flatten uses are in YAML test fixtures. alias and rename names are included in fields.
  • The subprocess tests for a replaced Object.keys resolve dist/js the same way helpers.ts does.

Review threads

The listing returned 1 thread of mine. I resolved 0 and re-affirmed 1. Thread rust/cube/cubenativeutils/src/wrappers/object.rs:50 still applies: NativeStruct::get_own_property_names (object.rs:62, implemented at neon_struct.rs:155) has no callers left now that get_field_by_key is gone.

ovr and others added 2 commits October 8, 2026 16:21
read_js_string_into now decides itself whether the copy is complete and returns a
Cow over the caller's buffer, so entries_for_fields no longer repeats the
truncation check. The buffer is MaybeUninit, avoiding a 128-byte zero fill per key,
and read_js_string shares the same copy helper.

Tests cover embedded NUL and unknown keys whose length straddles the 128-byte buffer.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The deserializer was its only caller and now uses entries. It also returned
non-enumerable keys through napi_get_all_property_names, so a future caller would
see a different key set than entries.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@claude

claude Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 2m 1s —— View job


No issues found. 0 high, 0 medium, 0 low.

Review details
  • Read the diff and changed files
  • Review for correctness, safety, performance, tests, comments
  • Reconcile prior review threads
  • Post findings

Checked and found sound

  • Detecting a truncated key (primitive_root_holder.rs:145): N-API stops before any character that doesn't fit and also reserves a byte for the NUL. So when at least char::MAX_LEN_UTF8 bytes are still free after the copy, the key wasn't cut off. The test runs prefixes of 123–128 and 200 bytes, each followed by é, 世, 🙂, NUL and a lone surrogate, which covers every place the 128-byte buffer could split a key.
  • ASCII fast path (primitive_root_holder.rs:124): the check needs both len == utf16_len and is_ascii. That is what rejects "éa", where the 2-byte copy has the expected length but holds only é. A lone surrogate becomes 3 bytes, fails the check, and falls back to neon's exact-length read.
  • napi_typeof dispatch (root_holder.rs:85): each from_raw is justified by the type N-API reported, plus is_a for arrays. External values still go through neon's tag-checked downcast, so a foreign external can't be mistaken for a JsBox<NativeRustHandle>.
  • deserialize_struct reading only declared fields (deserializer.rs:93): #[serde(flatten)] structs go through deserialize_map and so still get every entry. No struct bridged from JS uses deny_unknown_fields.
  • Skipping non-enumerable properties: the only non-enumerable property the schema compiler defines on bridged objects is maskSql (CubeEvaluator.ts:874). Tesseract reads it through the bridge trait's mask_sql accessor, not through entries, so this change doesn't affect it.
  • Subprocess test (deserializer.test.ts:147): jest-bridge.config.js runs the tests from dist/test/bridge, so ../../js resolves to dist/js/index.js.
  • Cargo.lock: the neon 1.0.0 → 1.1.1 bump only brings in linkme/either and drops syn-mid, which matches what rust/cube already locks.

Review threads

The listing returned 1 of my own threads. I resolved it (NativeStruct::get_own_property_names had no callers left, and 3aa0e92 removed it) and re-affirmed none.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@claude

claude Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 1m 37s —— View job


LGTM: no issues found (0 high, 0 medium, 0 low)

Review details
  • Read the diff and changed files
  • Analyze correctness, safety, perf, tests, comments
  • Handle prior review threads
  • Post review

What I checked

  • read_js_string ASCII fast path (rust/cube/cubenativeutils/src/wrappers/neon/object/primitive_root_holder.rs:115): this is correct. Any non-ASCII character makes the UTF-8 length strictly larger than the UTF-16 length. So if a copy into utf16_len + 1 bytes yields utf16_len ASCII bytes, it must be the whole string. The is_ascii check is what rules out cases like "éa". Lone surrogates become U+FFFD and take the fallback path.
  • read_js_string_into boundary (primitive_root_holder.rs:144): written + MAX_LEN_UTF8 < capacity is tight. When written ≤ 123, at least 4 bytes stay free before the NUL, so no character can have been dropped. At 124 a 4-byte character could have been cut, and the code correctly falls back. char::MAX_LEN_UTF8 is stable on the pinned 1.98.1 toolchain. The 123–200-byte prefix × multibyte-suffix test covers both sides of the boundary.
  • unsafe blocks: each has a // SAFETY: comment that holds. The from_raw calls in root_holder.rs:85-127 are all guarded by napi_typeof, plus is_a::<JsArray> for arrays. JsBox still goes through neon's tag-checked downcast.
  • Exception propagation: when a getter or the ownKeys trap throws, the code returns a NeonThrow and stops at the first ?. into_cube_error then passes it through unchanged, so the pending JS exception is never overwritten. The Symbol/BigInt errors are internal, with no exception pending.
  • deserialize_struct field filtering: serde's derived FIELDS includes aliases. Structs with #[serde(flatten)] go through deserialize_map, so they still see every key. The deny_unknown_fields caveat is documented on NativeStruct::entries_for_fields.
  • Object.keys caching: LocalKey is per addon instance, and the result is checked with downcast_or_throw / get::<JsString>. The tests that replace Object.keys run in fresh node processes. They load dist/js relative to dist/test/bridge, which matches where test:bridge runs.
  • Comments: all are 3 lines or fewer, and none just restates the code below it.

Review threads

The listing returned 0 of my own threads, so there was nothing to resolve or re-affirm.

@ovr
ovr merged commit 7f6d197 into master Oct 8, 2026
16 checks passed
@ovr
ovr deleted the ovr/nativestruct-entries-add branch October 8, 2026 14:38
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

javascript Pull requests that update Javascript code rust Pull requests that update Rust code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

⌂ Proxy