Repository navigation
perf: serialize bulk load rows with an async generator, coalesced into packet-sized chunks - #1778
arthurschreiber wants to merge 35 commits into
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
ReviewI read through Correctness The core mechanism checks out. Since The One pre-existing (not introduced by this PR) subtlety worth a mental note: on a mid-row validation/serialization error, Performance The approach (accumulate into one long-lived Code quality
Security Nothing of concern — pure binary serialization, no new external input handling. Test coverage The two new tests are well targeted: one confirms coalescing actually reduces chunk count and respects One gap that might be worth a small test (not blocking): a row (or Overall this looks like a solid, well-reasoned change with byte-for-byte output preserved (per the hashing verification mentioned in the description) and good measurements backing the perf claim. Nice work. |
ReviewNice, focused change — coalescing Correctness of the flush scheduling — I traced through the interaction between the three flush triggers (
This all checks out — I don't see a way to lose bytes, duplicate a flush, or push after end. Good use of Minor nitpick: Test coverage looks solid for the new behavior: chunking under a size threshold, the idle-flush path (mirroring what the cancellation tests already exercise), and the synchronous large-row flush path, including the fiddly PLP-terminator byte accounting. The described byte-identical hashing validation (20k rows across several types, by-reference large values) between base and this branch is good extra assurance but isn't captured as a repo test — might be worth a lightweight regression test that asserts byte-for-byte equality between old-style per-row pushes and the new coalesced output for a representative row, so a future refactor here can't silently corrupt bytes while still passing the shape-based assertions (chunk count/size, boundary bytes). Not blocking, just a suggestion. Security / behavior: bytes on the wire are unchanged and no new user input handling is introduced, so no security concerns. The by-reference (no-copy) behavior for large buffers already existed in Overall this looks correct and well-reasoned; the measurements in the description (700k vs 470k rows/s, 4-5 orders of magnitude fewer chunks) match what I'd expect from this change. Nice work. |
ReviewNicely scoped perf change — reusing one CorrectnessI traced through the buffer lifecycle ( One thing worth a closer look or an explicit test: I believe this is actually fine — Node's writable-side error handling sets Minor
TestsThe three new tests cover the important behaviors well: coalescing into Security / otherNo security concerns — this only touches internal wire-format serialization, no new user-controlled sizing or trust boundary changes. Nothing else stood out in |
|
Reviewed the diff ( CorrectnessTraced through the trickiest interaction this change introduces: That said, it looks safe: once
Everything else checks out:
Test coverageThe three new unit tests cover the important behavioral contracts well (coalescing, immediate flush on chunk-filling row, idle flush of a single small row). One gap: no test for the mid-row-error case described above — given that's the one place the new persistent-buffer design changes the failure-mode reasoning versus the old per-row-buffer design, a regression there wouldn't be caught by the existing suite or by the cancellation tests. Minor / non-blocking
Performance & securityBenchmarks in the description are convincing and the reduced chunk count (874 vs 25,000 for 200k rows) lines up with the fewer-buffer-allocations goal. No security concerns — this is purely a buffering/chunking change with no new trust boundaries, and large values still avoid being copied. Overall this looks solid and well-tested; the mid-row-error interaction is the only thing I'd want either a comment or a test for before merging. |
|
Reviewed the diff ( CorrectnessReliance on Node's This is only safe because Writable's error handling ( Minor
Test coverageThe four new tests are solid: chunking behavior, immediate flush when a row alone exceeds Performance / designThe idle-detection trick ( No security concerns — this only touches internal buffer/chunking logic, not parsing of untrusted input. 🤖 Generated with Claude Code |
ReviewReviewed the diff, the surrounding CorrectnessTraced through the trickier scenarios and didn't find a bug:
Test coverageGood breadth — packet-sized chunking, large-row synchronous flush, byte-for-byte equivalence with the old per-row serialization, the error-during-pending-flush race, and the idle-flush path itself are all covered directly. The reliance on the idle flush is also implicitly exercised by the existing Minor/non-blocking observations
Performance & securityThe benchmark numbers (874 vs 25,000 chunks, +16% end-to-end) are convincing and the approach (coalesce until idle or chunk-sized, flush immediately once either condition hits) is sound. No security concerns — no new user-controlled sizes/paths, and the large-buffer-by-reference behavior is unchanged pre-existing behavior from Nothing here blocks merging as far as I can tell. |
ReviewNicely scoped perf change, with thorough before/after byte-equality testing and clear reasoning in the PR description. A few notes below, nothing blocking. Design / correctness
Tests
Minor
Overall: solid perf work, byte-identical output verified, and the trickiest part (idle-flush vs. error-destroy race) is both reasoned through carefully and covered by a test. LGTM, modulo the maintainer decision on whether the COLMETADATA/prior-row drop-on-error behavior change needs a callout in the description. |
RowTransform pushed COLMETADATA, every row token, every cell's length prefix and every data chunk downstream as its own buffer, so a bulk load of small rows reached the packetizer as many tiny chunks per row. Rows are now serialized into one WritableTrackingBuffer that lives for the whole bulk load and is handed downstream once it holds a chunk's worth (8 KB), or as soon as the row source goes idle, so a source that pauses waiting on something does not have its rows held back. The bytes are unchanged. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01Fxv5h4UMCGJEpjgCKcAxug
4d2948a to
f49967c
Compare
Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01Fxv5h4UMCGJEpjgCKcAxug
ReviewWent through Correctness
Test coverageGood coverage of the behaviors that matter: chunking threshold, single-row-fills-a-chunk (sync flush), byte-for-byte equivalence against per-row serialization, the error-drops-pending-bytes case, and the idle-flush case backed by the existing cancellation integration tests. I didn't find a gap worth blocking on. One thing that's implicitly but not explicitly covered: a row whose cells alone push the buffer past Minor / non-blocking
Performance & securityBenchmarks in the description are consistent with what the diff implies (fewer, larger Nice work on the concurrency reasoning here (the idle-detection via |
|
CI on bf3a0a9: the SQL Server 2022 Windows / Node.js 22.x job (job) failed inside the SQL Server 2022 installer step ( Generated by Claude Code |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #1778 +/- ##
==========================================
+ Coverage 81.89% 82.53% +0.63%
==========================================
Files 92 93 +1
Lines 4950 5074 +124
Branches 933 964 +31
==========================================
+ Hits 4054 4188 +134
+ Misses 601 593 -8
+ Partials 295 293 -2 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…ransform `RowTransform` is replaced by `BulkLoad.serializeRows`, an async generator that writes COLMETADATA, the rows and DONE into one `WritableTrackingBuffer` and yields its contents in packet-sized chunks. `BulkLoadPayload` takes the rows and returns that generator, so the bulk load payload reaches the outgoing message the same way RPC payloads do: `Readable.from(payload).pipe(message)`. This removes the `Readable.from(rows).pipe(transform)` plumbing and the error handlers wired between the two streams. Rows from a synchronous source are serialized without awaiting in between; rows from an asynchronous source are raced against a `setImmediate` so that what has accumulated goes downstream as soon as the source waits on something. Rows are not read before the server has accepted the `INSERT BULK` statement, and the row source is closed when a row fails or the consumer stops early (a canceled bulk load). Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01Fxv5h4UMCGJEpjgCKcAxug
|
873af2e replaces Generated by Claude Code |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 873af2eb2e
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
Review Nicely done overall -- this is a clean simplification as well as a real perf win: dropping the Transform/pipe plumbing in favor of an async generator that writes directly into a WritableTrackingBuffer removes a lot of moving parts (two streams, cross-wired error handlers, a nextTick per row) while also coalescing output into CHUNK_SIZE packets. I read through bulk-load.ts, bulk-load-payload.ts, connection.ts, and the new unit tests, and compared against masters RowTransform/pipe implementation. Correctness:
Minor / non-blocking:
Test coverage: Coverage is thorough for the new code path: chunking behavior, lazy pulling, oversized-row flush, byte-for-byte equivalence (both sync and async sources), error-path row dropping plus source closing, early-consumer-stop closing, idle-flush, and the "no event-loop turn for a sync source" perf property. I do not see gaps here -- the error-path and cancellation tests in particular are exactly the kind of thing that is easy to regress silently in a rewrite like this. Security / perf: No security concerns -- this is internal serialization logic with no new external input surface. Perf claims in the description are backed by the "hands rows downstream in packet-sized chunks" and "without touching the event loop" tests, and the measurements table is a nice touch for a perf PR. Overall: solid refactor, well-tested, and the documented behavior changes (rows not read until INSERT BULK is accepted; row source closed on error/early-stop) are genuine improvements over the old pipe-based version. Nothing here blocks merging. |
A `Readable` attaches its own error handling only once it is iterated, which no longer happens before the `INSERT BULK` statement has been accepted. An `'error'` emitted in the meantime was unhandled. The payload now attaches a listener when it is created; the stream keeps the error and iterating it later rejects with it, so it reaches the bulk load's callback as before. Also select the async iterator only when it is callable, so a synchronous iterable carrying an `undefined` `Symbol.asyncIterator` property is accepted, export the `Row` type instead of declaring it twice, and create the payload's generator once rather than on every `Symbol.asyncIterator` call. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01Fxv5h4UMCGJEpjgCKcAxug
|
40e6ffd addresses the two Codex findings (an error listener is attached to a stream row source as soon as the payload is created, and the async iterator is only selected when callable) and the type duplication and generator caching notes from the review comment above. On 873af2e, both Generated by Claude Code |
There was a problem hiding this comment.
💡 Codex Review
Lines 2852 to 2854 in 40e6ffd
When the preliminary INSERT BULK statement fails—for example because the table is missing or its schema is incompatible—the payload generator is never pulled, so its finally block never obtains or closes the supplied iterator. This branch invokes the callback and returns without calling return()/destroy() on rows, leaving an already-open Readable (such as a file-backed parser) or other resource-owning iterable alive after the bulk load has completed with an error.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
test comment with |
ReviewNice piece of work — replacing the A few things worth a look: Code quality
Potential fragility
Pre-existing dead code (not introduced by this PR, but adjacent)
CorrectnessTraced through the SecurityNo concerns — this is internal wire-format serialization with no new external input surface. The "large buffers are referenced rather than copied" behavior is inherited from Test coverageVery thorough for the new code path. One gap: I didn't see a test exercising the duck-typed Note: I wasn't able to execute the test suite in this sandbox (no installed |
… close failures `BulkLoadPayload` now owns the row source's iterator. When the `INSERT BULK` statement is rejected, or the bulk load is canceled before its request message is sent, the payload is closed unread: the source's iterator is returned, a stream source is destroyed, and the payload's `'error'` listener comes off. That listener also comes off once the rows have been read, so a reusable event-emitting source does not accumulate listeners across bulk loads. While closing the source after a row failed, a rejection from the source's `return()` no longer replaces the row error; without a row error (the consumer stopped pulling) the close failure is what the consumer gets. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01Fxv5h4UMCGJEpjgCKcAxug
|
39531c3 addresses the three findings on 40e6ffd. The one from the review summary (row source left open when Unit suite 475 passing, bulk load integration suite passing, lint clean. Generated by Claude Code |
…type The payload's error listener goes on a row source only when it is an `EventEmitter`, not on anything with a method that happens to be called `on`. `execBulkLoad` uses the exported `Row` type instead of spelling it out twice. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01Fxv5h4UMCGJEpjgCKcAxug
|
be1f4cc takes the two points from the review comment above:
Generated by Claude Code |
|
On 39531c3, Generated by Claude Code |
…signals late An error an emitting source reports once its final chunk is with the consumer still fails the bulk load; the message can still be marked ignored. A source closed unread whose iterator and destruction both finish late stays guarded until the slower one is done. Both were implied, neither was pinned. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01Fxv5h4UMCGJEpjgCKcAxug
|
Reviewed the diff plus the final state of OverallThis is a very well-engineered change. The 25-commit history shows the tricky edge cases (empty bulk loads, cancellation mid-stream, event-emitter sources that don't replay errors through their iterator, streams with CorrectnessI traced through the trickiest parts and didn't find a live bug:
One maintainability concern worth flagging rather than a bug: Also, Code quality
PerformanceThe benchmarks in the description are convincing (sync sources: +60–110% rows/s depending on row shape; async sources see a small ~1µs/row cost from the SecurityNo concerns — this is purely an internal serialization/backpressure refactor with unchanged wire bytes for the non-empty case (pinned by the byte-for-byte comparison test), and it doesn't touch input validation or trust boundaries. Test coverageThorough on both sides:
Nothing blocking from my read. The one thing I'd want a second pair of eyes on before merge is the |
isPromiseLike moves to its own module so the bulk load and its payload use one copy (the bulk load module cannot export it: it ends with a module.exports assignment for its default export). The doc comment on close() now lays out the order of releases and what guards the source while each is still running. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01Fxv5h4UMCGJEpjgCKcAxug
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ebc3120bcb
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Review: perf: serialize bulk load rows with an async generator, coalesced into packet-sized chunksI read through Strengths
Concerns worth a second pair of eyes before merge
Security / correctnessNo security concerns — this is internal wire-serialization logic, no new untrusted-input handling, and column validation ( Test coverageExcellent — probably the standout part of this PR. The unit suite systematically covers: chunk coalescing, the zero-row case, "don't read before consumed," sync-iterable-with-undefined- Overall: solid, well-justified change with strong test backing. My main ask is for a maintainer familiar with the bulk-load cancellation paths to specifically re-read |
A Readable that failed and closed before the payload closed it emits nothing when destroyed again, and the completion check required a clean destruction, so the listeners put on it stayed forever. A closed stream that carries an error now counts as destroyed once its 'error' has had its turn: right away when it was emitted long ago, one turn later when the stream was destroyed with an error on this very tick. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01Fxv5h4UMCGJEpjgCKcAxug
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 755d0bfa29
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Review: perf: serialize bulk load rows with an async generator, coalesced into packet-sized chunksThis is a substantial, well-engineered rewrite of the bulk-load row pipeline. Overall the change is an improvement over Correctness (mostly positive)I traced through
Code quality / maintainability
Performance
SecurityNo concerns — this is transport-layer TDS byte serialization with no new parsing of untrusted input, no new external calls, and no changes to authentication/encryption paths. Test coverageThis is the strongest part of the PR. The unit suite covers: byte-for-byte equivalence with per-row serialization (array and async source), chunk-boundary behavior (including the wide-row-mid-cell-flush case and the null-text case), zero-row bulk loads, early-consumer-stop cleanup, TYPE_INFO failures, and a long list of cancellation/error-race scenarios for both plain iterators and Minor
Nice work — the amount of edge-case reasoning here (and the tests backing it) is well above what I'd expect for a change this size. |
Any emitter with a destroy method was destroyed, and the guard put on it waited for a completion signal only a Node stream gives; another emitter's destroy could finish silently and keep the guard on for good, piling listeners up across bulk loads over the same source. Only a stream is destroyed now; any other source is released through its iterator's return alone. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01Fxv5h4UMCGJEpjgCKcAxug
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f2d331fc82
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
ReviewI read through the full diff ( Strengths
Suggestions
Nice work on the measurement section in the PR description, by the way — having both isolated serializer throughput and end-to-end numbers against real SQL Server makes the performance claim much easier to trust than microbenchmarks alone. |
A stream created with emitClose: false whose _destroy succeeds on a later tick emits nothing about its destruction at all, so the guard put on it when the payload closed it unread stayed forever. The one signal every stream gives is _destroy calling back: it is watched for the length of the payload's own destroy() call, and the guard comes off a turn after it, once anything the stream emits about the destruction is out. The stream is left with its own _destroy afterwards. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01Fxv5h4UMCGJEpjgCKcAxug
ReviewThis is a large, carefully engineered change ( CorrectnessI walked through the scenarios that worried me most and didn't find a live bug:
I didn't find a case where rows get silently dropped, double-sent, or where a source is left open when it shouldn't be. Code quality / maintainability
PerformanceThe measurements are a highlight — honest about the one regression (async sources pay ~1µs/row for the API surface
Test coverageVery thorough — chunk-boundary behavior (including the null- SecurityNo concerns — no new external input parsing, no change to how untrusted data reaches the wire beyond the chunking mechanics. Overall: this is a well-justified, well-tested change to some genuinely hard async lifecycle code. My comments above are minor (mostly maintainability/documentation), not blockers. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 86f2f90944
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Wrapping the stream's _destroy missed a destruction deferred until the stream is constructed, since the wrapper was taken off again as soon as destroy() returned, and could not be installed at all on a stream whose _destroy is not writable, which threw out of the request callback. Node's destroy() takes a callback of its own that it runs once _destroy has called back, deferred or not, so that is what the payload passes now, and the stream is not touched. A stream destroyed before gets no callback, since destroy() would run it at once while the destruction may still be going on; it is waited for through its events as before. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01Fxv5h4UMCGJEpjgCKcAxug
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5157b52f13
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
…read A stream its owner had destroyed while the INSERT BULK statement was in flight is not destroyed again by the payload, so Node's completion callback never fires for it, and with emitClose: false a clean completion emits nothing either. The payload now watches such a stream's closed flag, set once its _destroy has called back, on a timer that does not keep the process alive and backs off, and lets go of it a turn after that; its events, when it has them, still come sooner. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01Fxv5h4UMCGJEpjgCKcAxug
ReviewThis is a very well-engineered change. The core idea — replacing the A few observations, roughly in order of importance: Complexity / maintainability of
|
ignoreError joins isPromiseLike in the helper module both files import from, instead of one copy per file. On the consumer-stopped path a synchronous return() has already completed by the time it is checked, so awaiting its result did nothing. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01Fxv5h4UMCGJEpjgCKcAxug
ReviewThis is a well-engineered, thoroughly tested change. Highlights:
A few things worth a second look before merging:
Nothing here blocks approval from my read — the design is sound, the edge cases are deliberate rather than accidental, and the test suite gives strong confidence. Nice work. |
Rows given as objects, a text value with its pointer and timestamp, the shorter DONE token before TDS 7.2, the payload's description for the debug log, synchronous sources closed early with and without a return, and an emitting source with a synchronous iterator closed unread. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01Fxv5h4UMCGJEpjgCKcAxug
Review: bulk load row serialization rewriteThis is a substantial, well-executed refactor. Overview of what I checked: Strengths
Things worth a look
SecurityNo concerns — this is purely a serialization/plumbing change on an already-trusted internal path (table/column names and SQL construction are unrelated to this diff), and no new external input handling is introduced. Test coverageExcellent for the new concurrency-sensitive code; see point 1 above for a pre-existing gap unrelated to this diff. I'd still recommend running the full suite ( |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d1c6d18c70
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
It can be reported both through destroy()'s callback and through 'close', and the second report took the no-op listener off the emitter a second time, which is the one guarding the iterator's own close if that is still running; an error that close then reported was unhandled. The cleanup now runs once. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01Fxv5h4UMCGJEpjgCKcAxug
ReviewThis is a well-engineered change. Replacing the Correctness
Code quality / maintainability
Test coverageExcellent — probably the most thorough part of the PR. Unit tests cover chunk coalescing, immediate hand-off once an async source goes idle, empty bulk loads, array/object row shapes, text/ntext/image pointer handling, the TDS 7.1 vs 7.2+ DONE token length, row-validation failures closing the source, sync vs async sources, and event-emitter error surfacing in every timing permutation (before rows are read, mid-read, after the last row, after the final chunk is already with the consumer), plus the full matrix of stream-destruction edge cases. Integration tests add zero-row bulk loads and cancel-before/immediately-after-execute cases. One thing I couldn't verify in this sandbox: no Security / performance
Overall: solid change, backed by real benchmarks and unusually thorough tests for the tricky concurrency/cancellation edge cases. My only suggestions are the two maintainability notes above — neither blocks merging. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6706970e16
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Before the serializer read its source directly, the rows were piped through `Readable.from`, which awaits a promised element before handing it on. The serializer looked at such a `Promise<Row>` as if it were the row itself, so a source yielding promises for rows produced null cells instead of the rows. A promised row is now waited for the same way a pending read is: the idle flush hands what is already serialized downstream while it is pending, a cancel abandons it, and its rejection fails the bulk load and closes the source. The wait stays on the hot path rather than in a delegated generator, so the throughput of an async source is unchanged. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01Fxv5h4UMCGJEpjgCKcAxug
ReviewThis is a substantial and impressively careful rewrite of bulk-load row serialization, replacing the Code quality / minor issues
Performance
Correctness (traced, no bugs found)I traced several of the trickier invariants and they check out:
Test coverageExcellent — the unit test additions in SecurityNo concerns — this is internal serialization/stream-lifecycle plumbing; no new user input handling or injection surface. Nice work — this is a big, gnarly piece of stream/async lifecycle code, and it's rare to see this level of edge-case coverage in a PR of this size. |
Problem
RowTransformpushes COLMETADATA, every row token, every cell's length prefix and every data chunk downstream as its own buffer. A bulk load of small rows therefore reaches the packetizer as many tiny chunks per row, and each row passes throughReadable.from(rows),pipe, aTransformwith anextTickcallback, that transform's async iterator, andReadable.from(payload)before it gets there.Change
RowTransformis replaced byBulkLoad.serializeRows(iterator), an async generator. It writes COLMETADATA, a ROW token per row, and the DONE token into oneWritableTrackingBufferthat lives for the whole bulk load, and yields the buffer's contents:WritableTrackingBuffer.CHUNK_SIZE(8 KB), checked after every cell so that a wide row of large cells goes downstream as it is serialized, orBulkLoadPayloadtakes the rows, obtains their iterator, and returns that generator, so the bulk load payload reaches the outgoing message the way RPC payloads do:Readable.from(payload).pipe(message). TheReadable.from(rows).pipe(transform)plumbing inexecBulkLoad, and the error handlers wired between the two streams, are gone, and so isstreamingMode, which only existed to keep the transform open for rows written after the call.Rows from a synchronous source (an array, a generator) are serialized without touching the event loop in between:
iterator.next()returns a plain result and nothing is awaited until the next chunk is yielded. Rows from an asynchronous source are awaited one at a time; eachnext()is raced against asetImmediateso that, when the source waits on something, what has accumulated goes downstream instead of being held back until 8 KB have arrived. The immediate is armed once per stall, not once per row.Behaviour changes that fall out of pulling rows instead of piping them:
masterthe transform wrote COLMETADATA lazily before the first row, so an empty bulk load sent only DONE, which SQL Server rejects with "While reading current row from host, a premature end-of-message was encountered". A unit test pins the bytes and an integration test loads zero rows.INSERT BULKstatement. Previously the row source was piped, and pulled up to the stream's high-water mark, as soon asexecBulkLoadwas called.Readable.fromsettled a promised element before handing it on. It is waited for the same way a pending read is: the idle flush hands what is already serialized downstream while it is pending, a cancel abandons it, and its rejection fails the bulk load and closes the source.return()) when a row fails validation or serialization, when a column fails to write its TYPE_INFO, and when the consumer stops early because the bulk load was canceled. A source that fails while closing does not hide the row error. Previously the source was left dangling.INSERT BULKstatement was rejected, the bulk load was canceled before it was executed, or the connection is no longer logged in when the rows would be sent, is released: its iterator is returned and a Node stream source is destroyed. Onmasterthe piped stream was left open in that case.masterthe transform was destroyed but the pending read stayed pending.EventEmittersource (aReadable) gets an error listener from the payload while theINSERT BULKstatement is in flight, so an error it emits before the rows are read is not an unhandled'error'event. AReadablereplays the error through its iterator; an emitter that does not gets it surfaced by the payload, which ends the bulk load with it before the next chunk goes out, even when it arrives once the final chunk is already with the consumer. The payload's listener comes off once the rows have been read or the payload is closed unread. While a source closed early is still closing (itsreturn()pending, or a stream still destroying itself), a standalone no-op listener that holds nothing but the source stays on it, so a failure the close reports on a later tick cannot crash the process, and a source that never finishes closing does not keep the payload or the rows alive through it. For a stream the end of its destruction is taken from the completion callback Node'sdestroy()accepts, which runs once_destroyhas called back, deferred construction included, the one signal every stream gives (one created withemitClose: falseemits nothing about a clean destruction); nothing on the stream is touched. A stream that was destroyed before is not destroyed again; itsclosedflag is watched on a backing-off timer that does not keep the process alive, and its'close'and'error'events, when it has them, let go of it sooner.The bytes for a bulk load with rows are unchanged: COLMETADATA, rows and DONE are written in the same order, and large values are still referenced rather than copied. A unit test serializes 300 rows of
int, nullablenvarcharandvarbinary(values above and below the by-reference threshold) once per row through the samegenerate*methods and once through the generator, from an array and from an async source, and asserts the byte streams are identical.One observable difference on the error path: when a row fails, rows serialized before it that were still coalescing in the buffer are dropped rather than having already been pushed downstream. The bulk load is aborted either way, so nothing downstream depends on those bytes, and a failed row's partial bytes never leave the buffer. A unit test pins this.
rowToPacketTransformno longer exists. It was@private, and there was no supported way to feed it rows directly.Measurements
Serializer in isolation, in the pipeline shape
makeRequestuses (rows → serializer →Readable.from(payload)→ sink), 200,000 rows from an array, againstmaster's transform and against the first version of this PR (the same transform, coalescing into 8 KB chunks):masterint,nvarchar(50),floatintEnd to end against SQL Server 2022, 50 bulk loads of 10,000 rows each:
masterintcolumn, arrayThe async-source case is slower by about a microsecond per row: that is the
Promise.racefor the idle flush. Without it (flush only at 8 KB) async sources reach ~141–157k rows/s and the integration suite still passes, but the fake-server cancellation tests inconnection-cancel-test.tsdeadlock, because their row source waits for a server response to bytes that never left the buffer. That ordering guarantee is kept. For real asynchronous sources (files, cursors, network) the cost is noise next to the source itself.Event-loop starvation was checked as well: for a synchronous source, both the transform pipeline and the generator are driven by microtasks and
nextTickuntil socket backpressure forces a turn, so neither yields to the loop between rows on its own. Measured on a 500,000-row array load, the distribution of gaps between event-loop turns is the same for both (99th percentile 3–4 ms, a couple of hundred gaps over 1 ms, one or two over 10 ms, a maximum of 50–75 ms that is garbage collection of the row array and shows up identically with a forced turn every 1 MB of output).The wide-row case is still dominated by the per-cell
generateParameterLength/generateParameterDataallocations, which #1774 removes; the two changes compound.Validation
CHUNK_SIZEand far fewer than one per row; a bulk load with no rows sends COLMETADATA and DONE, and the shorter DONE of TDS versions before 7.2; rows given as objects serialize the same as rows given as arrays; rows given as promises serialize the same as plain rows, what is already serialized goes downstream while a promised row is pending, and a promised row's rejection fails the bulk load and closes the source; atextvalue is written behind its pointer and timestamp, and a null one as a null pointer; rows are not read before the bytes are consumed; a row that fills a chunk by itself is handed downstream before the next row is read, and a wide row hands a chunk downstream before its last cell is serialized; a single small row goes downstream once an async source goes idle; the output equals per-row serialization byte for byte, from an array and from an async source; nothing goes downstream after a row fails and the source is closed; the source, synchronous or not, and with or without areturn(), is closed when the consumer stops early, when a row fails, and when a column fails to write its TYPE_INFO; a source that fails to close does not hide the row error, and is reported when there is none; a synchronous source is serialized without an event-loop turn; an iterable with anundefinedSymbol.asyncIteratorproperty is accepted; an error aReadablesource emits before the rows are read comes out of the iteration, and so does one anEventEmittersource emits without failing its iterator, after its last row, or once its final chunk is with the consumer; the error listener comes off anEventEmittersource after the load, and an unrelatedonmethod is never called; only a stream source closed unread is destroyed, and closing never throws even when a synchronous source'sfinallydoes or the stream's_destroycannot be replaced.'close', on'error', whendestroy()throws, once its destruction has completed for a stream created withemitClose: false(synchronously, later, only after an asynchronous construction, or when its owner had already started destroying it), and for a stream that had already failed once its'error'has had its turn, with nothing of the payload left on it; the payload's cancel listener comes off the bulk load once the rows are read or the payload is closed unread; a bulk load whose connection is not logged in when its rows would be sent releases its source.INSERT BULKstatement is rejected, one canceled immediately afterexecBulkLoad, and one canceled beforeexecBulkLoadall destroy theirReadablesource by the time the callback runs.should not leave any dangling sockets after connection timeout. Lint and typecheck clean.Targets
masterdirectly; it only needs #1773'sWritableTrackingBuffer, which is already there. #1774 changes the cell serialization in the same place (cells are written throughwriteValue), so whichever of the two lands second gets a small merge ofserializeRows; the resolution is mechanical (keep the generator, write cells throughwriteValue).🤖 Generated with Claude Code
https://claude.ai/code/session_01Fxv5h4UMCGJEpjgCKcAxug