Skip to content

perf: serialize bulk load rows with an async generator, coalesced into packet-sized chunks - #1778

Closed
arthurschreiber wants to merge 35 commits into
masterfrom
claude/bulk-load-coalesce
Closed

arthurschreiber wants to merge 35 commits into
masterfrom
claude/bulk-load-coalesce

Conversation

@arthurschreiber

@arthurschreiber arthurschreiber commented Sep 3, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

RowTransform pushes 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 through Readable.from(rows), pipe, a Transform with a nextTick callback, that transform's async iterator, and Readable.from(payload) before it gets there.

Change

RowTransform is replaced by BulkLoad.serializeRows(iterator), an async generator. It writes COLMETADATA, a ROW token per row, and the DONE token into one WritableTrackingBuffer that lives for the whole bulk load, and yields the buffer's contents:

  • once it holds a chunk's worth, WritableTrackingBuffer.CHUNK_SIZE (8 KB), checked after every cell so that a wide row of large cells goes downstream as it is serialized, or
  • as soon as an asynchronous row source goes idle.

BulkLoadPayload takes 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). The Readable.from(rows).pipe(transform) plumbing in execBulkLoad, and the error handlers wired between the two streams, are gone, and so is streamingMode, 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; each next() is raced against a setImmediate so 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:

  • A bulk load with no rows now works. COLMETADATA is written before the rows are read, so an empty source sends COLMETADATA followed by DONE. On master the 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.
  • Rows are not read before the server has accepted the INSERT BULK statement. Previously the row source was piped, and pulled up to the stream's high-water mark, as soon as execBulkLoad was called.
  • A row given as a promise is settled before it is serialized, as Readable.from settled 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.
  • The row source is closed (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.
  • A row source that is never read, because the INSERT BULK statement 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. On master the piped stream was left open in that case.
  • A bulk load canceled while its rows are being sent abandons a row read that is pending in the source at that moment, and does not wait for a source stuck in such a read to close, so a source that never delivers that row does not keep the bulk load's resources open. On master the transform was destroyed but the pending read stayed pending.
  • An EventEmitter source (a Readable) gets an error listener from the payload while the INSERT BULK statement is in flight, so an error it emits before the rows are read is not an unhandled 'error' event. A Readable replays 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 (its return() 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's destroy() accepts, which runs once _destroy has called back, deferred construction included, the one signal every stream gives (one created with emitClose: false emits nothing about a clean destruction); nothing on the stream is touched. A stream that was destroyed before is not destroyed again; its closed flag 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, nullable nvarchar and varbinary (values above and below the by-reference threshold) once per row through the same generate* 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.

rowToPacketTransform no longer exists. It was @private, and there was no supported way to feed it rows directly.

Measurements

Serializer in isolation, in the pipeline shape makeRequest uses (rows → serializer → Readable.from(payload) → sink), 200,000 rows from an array, against master's transform and against the first version of this PR (the same transform, coalescing into 8 KB chunks):

rows master transform, coalescing generator
int, nvarchar(50), float ~490k rows/s ~490–520k rows/s ~790–860k rows/s
40 × int ~77k rows/s ~136–146k rows/s ~154–158k rows/s

End to end against SQL Server 2022, 50 bulk loads of 10,000 rows each:

source master transform, coalescing generator
one int column, array ~166k rows/s ~180k rows/s ~200–210k rows/s
three columns, array ~139k rows/s ~151k rows/s ~166k rows/s
three columns, async generator ~141–146k rows/s ~125–135k rows/s

The async-source case is slower by about a microsecond per row: that is the Promise.race for 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 in connection-cancel-test.ts deadlock, 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 nextTick until 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/generateParameterData allocations, which #1774 removes; the two changes compound.

Validation

  • New unit tests: rows are handed downstream in chunks of at most CHUNK_SIZE and 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; a text value 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 a return(), 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 an undefined Symbol.asyncIterator property is accepted; an error a Readable source emits before the rows are read comes out of the iteration, and so does one an EventEmitter source emits without failing its iterator, after its last row, or once its final chunk is with the consumer; the error listener comes off an EventEmitter source after the load, and an unrelated on method is never called; only a stream source closed unread is destroyed, and closing never throws even when a synchronous source's finally does or the stream's _destroy cannot be replaced.
  • New unit tests for the cancel and release paths: a pending row read is abandoned when the bulk load is canceled; a bulk load canceled with a chunk already downstream closes without waiting for a source stuck in a read; a source whose close reports an error on a later tick stays guarded until that close has settled, whether it was being read or is closed unread, and until both its iterator and its destruction have finished when both are late; the guard on a stream closed unread comes off on 'close', on 'error', when destroy() throws, once its destruction has completed for a stream created with emitClose: 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.
  • New integration tests: a bulk load with no rows completes with a row count of zero; a bulk load whose INSERT BULK statement is rejected, one canceled immediately after execBulkLoad, and one canceled before execBulkLoad all destroy their Readable source by the time the callback runs.
  • Unit suite: 517 passing. Full integration suite against SQL Server 2022 passes except the pre-existing environment-only should not leave any dangling sockets after connection timeout. Lint and typecheck clean.

Targets master directly; it only needs #1773's WritableTrackingBuffer, which is already there. #1774 changes the cell serialization in the same place (cells are written through writeValue), so whichever of the two lands second gets a small merge of serializeRows; the resolution is mechanical (keep the generator, write cells through writeValue).

🤖 Generated with Claude Code

https://claude.ai/code/session_01Fxv5h4UMCGJEpjgCKcAxug

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 3, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-05T03:30:45.953953Z 66fcbe9 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@claude

claude Bot commented Sep 3, 2026

Copy link
Copy Markdown

Review

I read through src/bulk-load.ts and the new tests in test/unit/bulk-load-test.ts, plus the WritableTrackingBuffer contract this builds on.

Correctness

The core mechanism checks out. Since flushBuffer() operates on the same shared this.buffer instance from both _transform (chunk-size trigger) and _flush (end-of-stream), byte ordering is preserved even when a setImmediate flush is still pending when _flush runs directly: _flush writes the DONE token into whatever is already sitting in the buffer and flushes it all at once, and the stale setImmediate callback later finds buffer.length === 0 and no-ops. I traced a few of the trickier interleavings (synchronous CHUNK_SIZE flush racing a scheduled idle flush, _flush running before a pending setImmediate fires) and didn't find a duplicate-push or reordering case.

The !this.destroyed guard in the setImmediate callback is a reasonable defensive check against pushing after the stream has been torn down (e.g., on cancellation), even though by the time the immediate fires autoDestroy should normally have already marked the stream destroyed in the same tick group.

One pre-existing (not introduced by this PR) subtlety worth a mental note: on a mid-row validation/serialization error, callback(error) is invoked before the row's already-written bytes for that row (and possibly other fully-formed but not-yet-flushed rows sitting in the shared buffer) get flushed downstream. Previously each row had its own buffer that was only pushed after a full successful row, so a failed row never touched the push path. Now, partially-written row bytes live in the shared buffer and are simply abandoned when the stream errors/destroys. This doesn't look like an observable bug (the connection aborts the whole bulk load on error either way), but flagging it since it's a subtle behavioral shift from "push after each successful row" to "push on a delay" — worth a quick confirmation that no code path relies on already-pushed bytes existing at the moment an error is raised.

Performance

The approach (accumulate into one long-lived WritableTrackingBuffer, flush at CHUNK_SIZE or on idle via setImmediate) is a sound way to get packetizer-sized chunks without sacrificing latency for slow/streamed row sources. The measurements in the description (25,000 → ~874 chunks for 200k simple rows, +16% end-to-end) make the win concrete. Using nextTick-driven row delivery vs. setImmediate-driven flush to detect "source went idle" is a neat trick and is explained well in the inline comment.

Code quality

  • Matches the existing style in the file (declare fields assigned in the constructor, @private JSDoc tags on internal members).
  • flushBuffer() is a clean extraction; the comment on the setImmediate branch explains why the idle-detection trick works, which is exactly the kind of non-obvious rationale worth documenting.
  • No this.push() return-value / backpressure handling here, but that matches the pre-existing pattern in this file, so not a regression.

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 CHUNK_SIZE, the other specifically exercises the idle-flush path with a single row plus a separate assertion that the DONE token is flushed on end(). Combined with the existing connection-cancel-test.ts coverage of the idle-flush path against a real connection, this feels adequately covered for the change being made.

One gap that might be worth a small test (not blocking): a row (or _transform call) large enough by itself to push buffer.length over CHUNK_SIZE in one shot, to explicitly confirm the synchronous flush branch (as opposed to the idle/setImmediate branch) fires and flushes immediately without waiting for more rows or idle.

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.

@claude

claude Bot commented Sep 3, 2026

Copy link
Copy Markdown

Review

Nice, focused change — coalescing RowTransform output into WritableTrackingBuffer.CHUNK_SIZE-sized pushes instead of one push per row is a sensible fix for the allocation/growth-step overhead, and the "flush when idle" fallback via setImmediate is a thoughtful way to avoid regressing latency for slow/streamed sources.

Correctness of the flush scheduling — I traced through the interaction between the three flush triggers (_transform's size check, the scheduled setImmediate, and _flush) for edge cases:

  • A synchronous chunk-size flush while an idle-flush is already scheduled (flushScheduled stays true, but that's fine — the pending immediate re-checks buffer.length live at fire time, so it just becomes a no-op or flushes newly-arrived rows).
  • _flush racing the scheduled immediate: _flush unconditionally drains buffer itself, so even if the immediate hasn't fired yet, there's nothing left for it to flush when it eventually runs, and the !this.destroyed guard covers the case where the stream is already gone by then.
  • The "push after EOF" risk from a stale immediate firing post-_flush: can't happen, because _flush already zeroes buffer.length before the DONE token's push, so the immediate's buffer.length > 0 check will always be false in that scenario.

This all checks out — I don't see a way to lose bytes, duplicate a flush, or push after end. Good use of getBuffers()/consume() as an atomic snapshot-then-drain pair.

Minor nitpick: flushScheduled is only ever cleared inside the setImmediate callback itself, so if a caller destroys the stream (e.g., on cancellation) mid-flight and then somehow reuses flushScheduled's state... this isn't actually reachable since RowTransform instances aren't reused across bulk loads, so no real bug here, just noting the coupling for future readers.

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 WritableTrackingBuffer and its "caller must not modify until consumed" contract is unaffected by this change since rows aren't mutated after being handed to writeValue.

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.

@claude

claude Bot commented Sep 3, 2026

Copy link
Copy Markdown

Review

Nicely scoped perf change — reusing one WritableTrackingBuffer for the life of a RowTransform instead of allocating one per row, with an idle-triggered setImmediate flush so streamed sources (and the cancellation tests) don't get their rows held back. The byte-for-byte hash comparison against base for mixed by-reference/by-value payloads is a good way to build confidence that serialization order is unchanged, and the benchmark numbers back up the motivation.

Correctness

I traced through the buffer lifecycle (_seal/consume/getBuffers in WritableTrackingBuffer) and the flush paths and didn't find a byte-ordering or aliasing bug — sealed chunks are views onto buffers that are never written to again once sealed, and push() hands ownership downstream exactly as before.

One thing worth a closer look or an explicit test: _transform can bail out mid-row via return callback(error) (from c.type.validate or writeValue), after already having written some of that row's bytes (e.g. rowTokenBuffer, or preceding columns) into the now-long-lived this.buffer. In the old code that partial data lived in a per-row-local buffer that was simply discarded on error. Now it's sitting in shared state, and if a previously-scheduled idle setImmediate fired after the error, it would flush that partial/corrupt row downstream unless something prevents it.

I believe this is actually fine — Node's writable-side error handling sets destroyed = true synchronously as part of processing the callback(error) call, well before any setImmediate gets a turn, and flushBuffer's scheduled callback already guards on !this.destroyed. But since the blast radius of getting this wrong changed with this PR (from "row buffer thrown away" to "row buffer is shared and long-lived"), it'd be worth adding a small regression test: write a valid small row (so an idle flush gets scheduled), then a row that fails validate/writeValue, and assert nothing extra/corrupt reaches the 'data' listener afterward. Cheap insurance for a path the existing tests don't exercise.

Minor

  • flushScheduled isn't reset to false when the synchronous buffer.length >= CHUNK_SIZE flush fires while an idle flush is already scheduled from an earlier, smaller row. It's harmless today (the deferred callback re-checks buffer.length > 0 before pushing, so there's no double-send), but it does mean the flag doesn't always reflect "is a setImmediate actually pending." A one-line comment noting that would save a future reader from assuming it's a precise pending-timer flag.

Tests

The three new tests cover the important behaviors well: coalescing into CHUNK_SIZE-bounded chunks, synchronous flush when a single row already fills a chunk, and the idle flush for a lone small row. Given the PR body's manual hash-comparison against base was a big part of the confidence here, it might be worth turning that into a committed fixture-based regression test (hash or byte-compare of serialized output for a small representative row set) so future edits to _transform's serialization order get caught automatically rather than relying on someone re-running that comparison by hand.

Security / other

No security concerns — this only touches internal wire-format serialization, no new user-controlled sizing or trust boundary changes. Nothing else stood out in bulk-load.ts or the test file.

@claude

claude Bot commented Sep 3, 2026

Copy link
Copy Markdown

Reviewed the diff (src/bulk-load.ts, test/unit/bulk-load-test.ts). Nice write-up in the description — the benchmark numbers and the "why setImmediate, not nextTick" reasoning made this easy to verify.

Correctness

Traced through the trickiest interaction this change introduces: this.buffer is now a persistent, instance-level buffer instead of a fresh one per row, so a mid-row failure (c.type.validate or writeValue throwing) now leaves partial/corrupt bytes sitting in this.buffer when callback(error) is called — unlike before, where the discarded row-local buffer just vanished.

That said, it looks safe: once _transform's callback receives an error, Node's stream internals call destroy(err) synchronously (before returning to the event loop), which flips this.destroyed to true immediately. Since setImmediate always fires strictly after the current synchronous call stack and any nextTick/microtask work, the !this.destroyed guard in the scheduled flush (bulk-load.ts:242-248) will correctly see destroyed === true and skip pushing the corrupted buffer. Good — but this correctness now depends on that ordering guarantee holding, which is a bit implicit. Worth either:

  • a one-line comment noting why !this.destroyed is load-bearing for the error path (not just the idle/cancel path it's documented for), or
  • an explicit unit test that triggers a validation error mid-row and asserts nothing extra is pushed downstream after the error.

Everything else checks out:

  • flushBuffer()'s getBuffers() + consume(buffer.length) pairing is correct — no data loss/duplication since nothing can append to the buffer between the two calls (synchronous).
  • Ordering (COLMETADATA → rows → DONE) is preserved through the shared buffer regardless of which path (size-triggered vs. idle-triggered vs. _flush) does the actual push.
  • The flushScheduled guard correctly prevents redundant timers piling up while rows arrive back-to-back, and doesn't need explicit resetting on the size-triggered or _flush paths since the buffer is empty by the time the stale immediate fires.
  • Large (>= CHUNK_SIZE) by-reference values still flush immediately and in the right position relative to surrounding row bytes (consistent with the hashing check mentioned in the PR description).

Test coverage

The 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

  • flushBuffer (bulk-load.ts:264) has no explicit private modifier (JSDoc @private only), but that matches the existing style of _transform/_flush in this class, so not a real inconsistency.
  • The stale setImmediate from the last row (when _flush beats it to the punch) still fires and does a no-op destroyed-check afterward. Harmless, but if you wanted to be tidy you could track the timer with clearImmediate in _flush/on destroy — not worth the added complexity for one no-op callback per bulk load.

Performance & security

Benchmarks 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.

@claude

claude Bot commented Sep 3, 2026

Copy link
Copy Markdown

Reviewed the diff (src/bulk-load.ts, test/unit/bulk-load-test.ts). Overall this is a clean, well-motivated perf change with good before/after measurements and a byte-for-byte equivalence test against the old per-row serialization. A few notes:

Correctness

Reliance on Node's nextTick-before-setImmediate ordering for data integrity. When a row's writeValue/validate throws partway through writing a row into the shared this.buffer (e.g. after rowTokenBuffer and some columns are written but before the row is complete), _transform calls callback(error) synchronously and returns, leaving the corrupted partial row sitting in this.buffer alongside any already-buffered valid rows. If a setImmediate flush was scheduled by a previous, successful row (flushScheduled), it's still pending at that point.

This is only safe because Writable's error handling (onwriteError) is deferred via process.nextTick, which drains before the setImmediate "check" phase runs — so this.destroyed becomes true before the scheduled flush's if (!this.destroyed && ...) guard is checked, and the corrupted buffer never gets pushed. That reasoning holds today, but it's an implicit dependency on Node stream internals rather than something enforced by the code, and it isn't exercised by a dedicated test (the cancellation tests cover the idle-flush path but not "error occurs while a flush is already scheduled"). Worth adding a unit test that triggers a validation/write error on a row after a prior row has scheduled a pending flush, asserting no partial/corrupt bytes are ever pushed — this would also act as a regression guard if Node's scheduling behavior or the Transform internals ever change.

Minor

  • flushBuffer() is a plain method (not prefixed _) on a class where every other method/property is @private-annotated; it's fine functionally (used only internally) but slightly inconsistent with the file's convention — might be worth the @private tag for consistency, and/or making it a #private or naming it _flushBuffer per the existing pattern (_transform, _flush).
  • The setImmediate callback captures this.buffer by reference (this.buffer.length) rather than the local buffer closed over earlier in _transform — harmless since this.buffer is never reassigned, but worth double-checking that invariant holds (i.e., nothing ever replaces this.buffer with a new instance) since the mixed style (local buffer var vs. this.buffer) could get out of sync if that ever changes.

Test coverage

The four new tests are solid: chunking behavior, immediate flush when a row alone exceeds CHUNK_SIZE, byte-for-byte equivalence with the old per-row approach, and the idle-flush timing. As noted above, the one gap is a test around the interaction between a scheduled idle-flush and a mid-row error on a subsequent row.

Performance / design

The idle-detection trick (setImmediate only firing once the row source stops producing, because rows are fed through nextTick/microtasks) is a nice, well-explained solution to the streaming-source-must-not-be-delayed constraint. The WritableTrackingBuffer growth/seal/consume design (chunks doubling up to CHUNK_SIZE, large buffers referenced rather than copied) looks correct and match the documented reference-vs-copy semantics — getBuffers()/consume() interaction is safe against the previously-returned array being mutated (new array via slice()), so no aliasing hazard from the shared long-lived buffer.

No security concerns — this only touches internal buffer/chunking logic, not parsing of untrusted input.

🤖 Generated with Claude Code

@claude

claude Bot commented Sep 3, 2026

Copy link
Copy Markdown

Review

Reviewed the diff, the surrounding RowTransform/WritableTrackingBuffer code, and how the transform's output is consumed downstream (bulk-load-payload.ts, connection.ts). Overall this is a clean, well-targeted perf change — nice work.

Correctness

Traced through the trickier scenarios and didn't find a bug:

  • Error mid-row: when c.type.validate/writeValue throws and callback(error) is called with a partially-written row still sitting in this.buffer, the pending setImmediate flush correctly no-ops because this.destroyed is set synchronously by the stream's internal destroy() path before the setImmediate macrotask ever runs — well before any queued microtasks/nextTicks finish. The "hands nothing downstream after a row fails, even with a flush pending" test nails exactly this race.
  • Flush-then-schedule-fires-anyway: when a synchronous CHUNK_SIZE flush drains the buffer while an idle setImmediate is still outstanding, the immediate's buffer.length > 0 check makes it a no-op, as the comment describes.
  • Chunk boundaries changing (COLMETADATA now coalesced into the first row's chunk instead of being its own push()): confirmed downstream code (BulkLoadPayload, the packetizer) treats the transform's output as an opaque byte stream with no assumption that a push() call aligns to a token boundary, so this is safe.
  • Buffer reuse across the whole bulk load (rather than a fresh WritableTrackingBuffer per row) is safe with consume()/getBuffers() as implemented — _seal() only pushes non-empty open segments, so consume(buffer.length) always fully drains after a flush.

Test coverage

Good 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 connection-cancel-test.ts cases (single row well under CHUNK_SIZE, stream goes idle waiting on the server) — worth noting in review even though that file wasn't touched, since it's load-bearing for this change.

Minor/non-blocking observations

  • flushBuffer() is currently only ever called when buffer.length > 0 (callers all guard it), so it has no empty-buffer guard of its own. Not a bug today, just something to keep in mind if another call site is added later.
  • The local const buffer = this.buffer; aliasing in both _transform and flushBuffer shadows the field name — consistent with the pre-existing style in this file, but worth a glance if it ever causes confusion during future edits.
  • As noted in the PR description, this stacks on refactor: resolve parameters once and serialize them through a write contract #1774 for the writeValue contract and targets claude/parameter-contract rather than master — just flagging so the merge order is tracked.

Performance & security

The 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 WritableTrackingBuffer, not something this PR introduces.

Nothing here blocks merging as far as I can tell.

@claude

claude Bot commented Sep 3, 2026

Copy link
Copy Markdown

Review

Nicely 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

  • The idle-flush mechanism (setImmediate gated by flushScheduled) is a neat way to avoid holding back a lone row while still coalescing back-to-back writes. I traced the ordering guarantee the error-path comment relies on (the "!this.destroyed" check in the scheduled flush, racing against a synchronous "callback(error)" in _transform): Node fully drains the process.nextTick queue -- including any nextTicks that stream error propagation itself schedules -- before advancing to the "check" phase where setImmediate callbacks run. So "destroyed" is guaranteed to be set before the scheduled flush fires, even though errorOrDestroy may itself hop through nextTick internally. That guarantee holds up, and it is good that it is pinned down by a test ("hands nothing downstream after a row fails...") rather than left as an unstated assumption.

  • One behavior change worth calling out explicitly, even though it looks intentional and harmless: previously COLMETADATA and each successfully-serialized row were pushed downstream synchronously, in the same tick as their own _transform call -- so if row N later failed validation, rows 1..N-1 (and COLMETADATA) had already been handed to the packetizer. Now they can still be sitting in the shared buffer when the failure happens, and get silently dropped (per the new "hands nothing downstream after a row fails, even with a flush pending" test). Functionally this should be fine since an aborted bulk load never sends a DONE token either way and the request gets torn down, but it is a real difference in what hits the wire before an error -- worth a one-line mention in the PR description for future readers diffing behavior against the previous implementation.

Tests

  • Good coverage: chunk-size flush, idle flush, byte-for-byte equivalence against per-row serialization, and the drop-on-error case. The "assert.isBelow(chunks.length, rowCount / 20)" bound in the first test looks safe given 2000 tiny rows queued synchronously (they get processed through chained nextTicks well before any setImmediate gets a turn, and 2000 x ~60 bytes only produces on the order of 15 chunk-size flushes), but it is timing-sensitive by nature -- if it ever flakes in CI, that bound is the first place to look.

Minor

  • flushBuffer() could note in its doc comment that it is a no-op on an empty buffer (harmless today since callers already guard on buffer.length > 0, but it would save a re-derivation next time someone reads it).
  • Not a regression from this PR, but RowTransform never checks the return value of this.push(), so backpressure signaling from the packetizer downstream is still effectively ignored (same as before this change) -- the _transform callback fires on nextTick regardless of whether the consumer wants more data. Out of scope here, just flagging as useful context for a possible follow-up.

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
@arthurschreiber
arthurschreiber force-pushed the claude/bulk-load-coalesce branch from 4d2948a to f49967c Compare September 3, 2026 20:25
@arthurschreiber
arthurschreiber changed the base branch from claude/parameter-contract to master September 3, 2026 20:25
@claude

claude Bot commented Sep 3, 2026

Copy link
Copy Markdown

Review

Went through src/bulk-load.ts and the new tests in test/unit/bulk-load-test.ts in detail. Overall this is a clean, well-reasoned change — the coalescing logic and its interaction with the idle-flush (setImmediate) and error/destroy paths hold up under close reading.

Correctness

  • Ordering is preserved. _flush only runs after the last _transform's callback has fired (Node defers it via process.nextTick), so by the time _flush writes the DONE token, all row bytes are already in buffer. No reordering risk.
  • The destroyed guard in the scheduled flush is load-bearing, not just an optimization. If a row fails, callback(error) synchronously sets destroyed = true (even though the 'error' event itself is deferred), so the pending setImmediate correctly no-ops instead of pushing partial/stale bytes — and this doubles as protection against a push() after the stream has already ended via _flush's own synchronous flushBuffer() call. The dedicated test for this (hands nothing downstream after a row fails, even with a flush pending) is a good one to have pinned given how easy this would be to regress silently.
  • flushScheduled correctly prevents duplicate setImmediate scheduling without needing to be cleared when a chunk-sized synchronous flush happens in between — the stale scheduled callback just finds buffer.length === 0 and does nothing. I traced through the interleavings I could think of (sync flush mid-stream, sync flush racing the idle flush, end-of-stream racing the idle flush) and didn't find a case where bytes get double-pushed or dropped.
  • Buffer reference semantics (WritableTrackingBuffer.writeBuffer referencing rather than copying buffers ≥ CHUNK_SIZE) are unaffected by this change — getColMetaData()/createDoneToken() and the per-cell generated buffers are all freshly allocated per call, so there's no aliasing/mutation hazard introduced by holding onto them longer in the shared buffer.

Test coverage

Good 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 CHUNK_SIZE twice while processing a single row (e.g. two ~5 KB cells) — not a bug (the row is still flushed as a unit after the loop, same as before), just noting it's exercised only indirectly.

Minor / non-blocking

  • flushBuffer() isn't underscore-prefixed like _transform/_flush, which is correct (it's not a Transform stream API method), but worth double-checking it reads unambiguously next to the two that are.
  • this.push()'s boolean return value (backpressure signal) is still ignored, same as before this PR — not a regression, just calling it out since the new buffering strategy makes it a little more likely a slow consumer accumulates a larger internal readable buffer before backpressure would otherwise kick in. Not something this PR needs to fix, but a candidate for separate follow-up if bulk loads against slow consumers become a concern.

Performance & security

Benchmarks in the description are consistent with what the diff implies (fewer, larger push() calls per bulk load). No security concerns — this is purely a serialization/buffering restructuring with no change to what bytes go on the wire, which the byte-equivalence test enforces.

Nice work on the concurrency reasoning here (the idle-detection via setImmediate vs. nextTick/microtask ordering is subtle and well explained in both the code comments and the PR description).

Copy link
Copy Markdown
Collaborator Author

CI on bf3a0a9: the SQL Server 2022 Windows / Node.js 22.x job (job) failed inside the SQL Server 2022 installer step (setup.exe exited with 2233073689 after the bootstrap engine returned -2061893607), before npm ci or any test ran. This is the same installer failure that hit #1774 and #1777 on other Windows jobs today; the other 2022 Windows jobs on this commit installed fine. Nothing in this PR reaches the installer, so it needs a re-run of that job from the Actions UI; the re-run API is not available to this integration. The rest of the matrix is still running.


Generated by Claude Code

@codecov

codecov Bot commented Sep 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.21429% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.53%. Comparing base (daa8e77) to head (66fcbe9).

Files with missing lines Patch % Lines
src/bulk-load-payload.ts 98.92% 0 Missing and 1 partial ⚠️
src/bulk-load.ts 98.57% 0 Missing and 1 partial ⚠️
src/connection.ts 75.00% 0 Missing and 1 partial ⚠️
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.
📢 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.

…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
@arthurschreiber arthurschreiber changed the title perf: coalesce bulk load rows into packet-sized chunks perf: serialize bulk load rows with an async generator, coalesced into packet-sized chunks Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

873af2e replaces RowTransform with an async generator (BulkLoad.serializeRows), keeping the 8 KB coalescing and the idle flush from the first version. The PR description is rewritten for the new design and carries the updated measurements: about +10–15% end to end over the transform version for array sources, and the same event-loop turn profile. Earlier review threads that pointed at _transform/flushBuffer now refer to code that no longer exists.


Generated by Claude Code

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread src/connection.ts Resolved
Comment thread src/bulk-load.ts Resolved
@claude

claude Bot commented Sep 4, 2026

Copy link
Copy Markdown

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:

  • The core Promise.race([result, idle]) idle-detection logic in serializeRows (src/bulk-load.ts:518-620) checks out: the idle promise is only recreated once it actually fires (idle = undefined only happens on the winner === IDLE branch), so a fast-resolving async source does not get a fresh setImmediate armed on every row -- matches the "armed once per stall" description and is a nice touch.
  • The try { ... } finally { if (!done) iterator.return(); } correctly closes the row source both on a thrown validation/serialization error and on early consumer termination (a for await break or explicit .return()), and this is well covered by the two new tests for those paths.
  • Buffering semantics (getBuffers()/consume()) look right for the chunk-size-boundary case (a single oversized row is flushed immediately) and the idle-flush case (a small row emitted before the source is asked for the next one). The "produces the same bytes as serializing each row on its own" test is a good belt-and-suspenders check that the refactor is byte-for-byte compatible with the old per-row path.
  • execBulkLoads removal of the else if (!bulkLoad.streamingMode) { bulkLoad.rowToPacketTransform.end() } branch is safe: rows ?? [] reproduces the same "immediately end with just COLMETADATA+DONE" behavior for a no-rows call. Side note, not something this PR needs to fix: streamingMode/firstRowWritten appear to already be dead flags on master -- streamingMode is never set to true anywhere in src/, and firstRowWritten is never set to true either, so the if (!this.firstRowWritten) validate-once guard in serializeRows is effectively always taken, same as it was in RowTransform. Pre-existing, just flagging in case it is a signal of a half-removed streaming-write API that could be cleaned up separately.

Minor / non-blocking:

  • type Row = unknown[] | { [colName: string]: unknown }; is now duplicated verbatim in both bulk-load.ts and bulk-load-payload.ts. Might be worth exporting it from one module (or a shared types file) so the two definitions cannot drift apart later.
  • BulkLoadPayload[Symbol.asyncIterator]() now calls this.bulkLoad.serializeRows(this.rows) fresh each time it is invoked, whereas the old code cached a single iterator in the constructor. In current usage Readable.from(payload) only pulls the async iterator once, so this is not a live bug, but it is a slight behavior change: if something ever called [Symbol.asyncIterator]() twice on the same payload, an array-backed rows would now be replayed from the start (double COLMETADATA/rows) rather than continuing/exhausting like before. Probably fine given the single call site, just noting the reduced robustness.
  • The dangling idle setImmediate when the loop finishes (done = true) or throws before that timer fires is harmless (it just resolves an orphaned promise on its next tick) but could be avoided with clearImmediate if you want the generator to be fully tidy on exit -- very low priority given the cost is a single no-op macrotask.

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

Copy link
Copy Markdown
Collaborator Author

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 Azure SQL Server / Node.js 22.x jobs failed with connection timeouts only: the before each hooks of inserting binary data, Browse mode and BulkLoad timed out while connecting, and should connect by port / should be bad credentials / .connect in connection-test.ts hit Failed to connect to ...:1433 in 15000ms. Every test that got a connection passed, including the bulk load suite on the other jobs. That is the Azure connectivity flake seen on #1777 as well, not this change; the push re-runs the matrix, and I cannot trigger a re-run from here if it recurs.


Generated by Claude Code

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

tedious/src/connection.ts

Lines 2852 to 2854 in 40e6ffd

bulkLoad.error = error;
bulkLoad.callback(error);
return;

P2 Badge Close the row source when INSERT BULK is rejected

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".

Comment thread src/bulk-load.ts Resolved
Comment thread src/bulk-load-payload.ts Resolved
@claude

claude Bot commented Sep 4, 2026

Copy link
Copy Markdown

test comment with code backticks

@claude

claude Bot commented Sep 4, 2026

Copy link
Copy Markdown

Review

Nice piece of work — replacing the Transform/pipe plumbing with a single async generator that coalesces rows into packet-sized chunks is a solid design, backed by measurements and a thorough set of unit tests for the tricky timing behavior (idle-flush, chunk-boundary, cancellation, sync-vs-async sourcing, byte-for-byte equivalence with the old per-row serialization). The PR description is exemplary in explaining the tradeoffs.

A few things worth a look:

Code quality

  • connection.ts's execBulkLoad overloads still inline the row type twice (AsyncIterable<unknown[] | { [columnName: string]: unknown }> | Iterable<...>), duplicating the newly-exported Row type in bulk-load.ts (and even using a different field name — columnName vs. colName — for the same shape). One of the commits states the intent was to "export the Row type instead of declaring it twice"; connection.ts seems to have been missed. Worth importing Row there too so there's one definition to keep in sync.

Potential fragility

  • In bulk-load-payload.ts, the decision to attach an 'error' listener is based purely on duck-typing: typeof source.on === 'function'. Since rows is typed as an arbitrary Iterable<Row> | AsyncIterable<Row>, a custom row source that happens to expose an unrelated method literally named on (not an EventEmitter) would have that method invoked as on('error', ignoreError) inside the constructor — which could throw (if the method validates its arguments) or otherwise misbehave for a source that was never meant to be treated as an event emitter. Might be safer to check rows instanceof EventEmitter (or instanceof Readable) rather than duck-typing on .on.
  • Relatedly, the ignoreError listener that's attached is never removed. Harmless here since it captures no state, but it silently swallows 'error' events on that emitter for its entire lifetime, not just the window before iteration starts.

Pre-existing dead code (not introduced by this PR, but adjacent)

  • BulkLoad#streamingMode and #firstRowWritten appear to already be unreachable/always-false on master (nothing sets either to true, and rowToPacketTransform — the only thing streamingMode gated — was confirmed @private with "no supported way to feed it rows directly"). Since this PR removes the one branch in connection.ts that referenced streamingMode, it might be a good opportunity for a follow-up to confirm and remove these fields entirely if truly dead.

Correctness

Traced through the Promise.race/idle-flush logic in serializeRows (armed-once-per-stall, re-awaiting the original next() promise rather than calling next() again, finally-based iterator.return() on early exit/failure) and it looks correct, including the edge case where a chunk-size flush already empties the buffer while an idle timer from a prior iteration is still outstanding (that's a harmless no-op flush). The Readable.from(payload).pipe(message) cancellation path mirrors the existing RPC payload mechanism, so relying on Readable.from's iterator cleanup on stream destruction is consistent with already-proven behavior elsewhere in the codebase.

Security

No 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 WritableTrackingBuffer (#1773), not new to this PR.

Test coverage

Very thorough for the new code path. One gap: I didn't see a test exercising the duck-typed .on check against a non-stream object that also happens to define an unrelated on method — the scenario flagged above. Worth a regression test either way (asserting it's handled safely, or tightening the check first).

Note: I wasn't able to execute the test suite in this sandbox (no installed node_modules, and tool approvals blocked npm/npx), so this is a static review; the PR description's reported 469 passing unit tests and clean integration run stand as-is.

… 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

Copy link
Copy Markdown
Collaborator Author

39531c3 addresses the three findings on 40e6ffd. The one from the review summary (row source left open when INSERT BULK is rejected) was also the behaviour on master, where the piped row stream was never destroyed either, but the payload now owns the source so it is cheap to do right: BulkLoadPayload.close() returns the source's iterator, destroys a stream source, and drops the error listener, and execBulkLoad calls it when the INSERT BULK statement fails or the bulk load was canceled before its request is sent. An integration test bulk loads into a missing table from a Readable and checks the stream is destroyed when the callback runs.

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

Copy link
Copy Markdown
Collaborator Author

be1f4cc takes the two points from the review comment above: execBulkLoad now uses the exported Row type instead of spelling the shape out twice, and the payload attaches its error listener only to a real EventEmitter (instanceof), with a unit test passing a source whose unrelated on/removeListener methods would throw if called. The listener removal was already in 39531c3.

streamingMode and firstRowWritten are indeed dead on master (nothing sets either); left for a separate cleanup so this PR stays about serialization.


Generated by Claude Code

Copy link
Copy Markdown
Collaborator Author

On 39531c3, SQL Server Linux / Node.js 22.x failed its TDS 7.4 pass after 11 seconds with every test reporting Connection lost - socket hang up or ECONNRESET, i.e. the SQL Server container on that runner was closing connections from the start of the run. It is not this change: the Node.js 24.x and Node.js 26.x Linux jobs on the same commit passed the TDS 7.4, 7.3B and 7.3A passes against the same container setup, and the full integration suite passes locally on be1f4cc against SQL Server 2022 (453 passing, only the known environment-only socket test failing). I cannot re-run the job from here; be1f4cc has since started a fresh matrix.


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
@claude

claude Bot commented Sep 5, 2026

Copy link
Copy Markdown

Reviewed the diff plus the final state of src/bulk-load.ts, src/bulk-load-payload.ts, src/connection.ts, and the unit/integration test additions.

Overall

This 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 emitClose: false, synchronous finally throwing) were found and fixed one by one, and each fix is backed by a unit test with a clear name explaining what it pins. The design mirrors the existing RPC payload pattern (Readable.from(payload).pipe(message)), which is a good consistency win and removes a whole stream/transform/pipe/error-listener plumbing layer.

Correctness

I traced through the trickiest parts and didn't find a live bug:

  • serializeRows's per-cell chunk-boundary check (now unconditional, including the null-text-pointer branch) correctly avoids the earlier bug where an all-null-text-column source would buffer whole.
  • The idle promise reuse ("armed once per stall, not once per row") can occasionally win a race spuriously once a previously-armed timer fires after the source resumed being fast — but this is explicitly called out in the comment as producing at worst one smaller-than-necessary chunk, never wrong bytes. Agreed that's fine.
  • execBulkLoad's payload.close() before the not-logged-in/canceled branches lines up correctly with makeRequest, which returns before ever touching payload in those same two branches — so there's no risk of the async generator being iterated after its source was already released.
  • The abort race (Promise.race([read, idle, abort]) / Promise.race([read, abort])) and the "don't wait for a stuck source's return() once aborted" logic in the finally block match the description and the cancellation integration tests.

One maintainability concern worth flagging rather than a bug: BulkLoadPayload.close()'s bookkeeping for "keep the guard on an emitter until its return() and its stream destruction have both settled" is intricate (nested pending-counter + multiple listener-removal paths). It's correct as far as I can tell and is exercised by dedicated tests, but it took several commits to get right, which suggests it'll be easy for a future change to silently reintroduce one of the fixed edge cases. Might be worth a short block comment at the top of close() summarizing the state machine (started → releasing iterator / destroying stream → both settled → unguard), since the reasoning is currently spread across many inline comments.

Also, close()'s reliance on "a Readable's Symbol.asyncIterator only attaches once the iterator is first pulled, so destroy() on the stream itself is needed to release it when unread" is real but undocumented Node.js internal behavior rather than a documented contract. It's good that a unit test pins this against a Node behavior change, but it's a forward-compat risk worth keeping an eye on across Node versions.

Code quality

  • isPromiseLike is duplicated verbatim in bulk-load.ts and bulk-load-payload.ts. The comment explains why ignoreError has to stay local (no named export from bulk-load.ts), but that reasoning doesn't apply to isPromiseLike — it could live in a small shared internal helper module.
  • Removal of RowTransform, rowToPacketTransform, and streamingMode is clean — grepped for leftover references and found none.
  • The doc comment on serializeRows is excellent: it states the idle-flush behavior as a guarantee (not just an optimization) and points at the specific tests that pin it, which will save the next reader a lot of archaeology.

Performance

The 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 Promise.race idle check, justified against the cancellation deadlock it prevents). The event-loop-starvation comparison against the old transform pipeline is a nice extra diligence step.

Security

No 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 coverage

Thorough on both sides:

  • Unit: chunk coalescing, empty bulk load bytes, lazy row reads, error-then-close-source ordering, TYPE_INFO failures, guarded-emitter lifecycle (including the emitClose: false case), cancellation abandoning a pending read, and a byte-identical comparison against per-row serialization from both an array and an async source.
  • Integration: zero-row bulk load, INSERT BULK rejection, cancel-before-exec, and cancel-immediately-after-exec all assert the Readable source is actually destroyed by the time the callback runs — good, since that's exactly the kind of resource leak that's easy to introduce silently.

Nothing blocking from my read. The one thing I'd want a second pair of eyes on before merge is the close()/guard lifecycle in bulk-load-payload.ts given how many iterations it took to land, but the test suite around it looks like it would catch a regression there.

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread src/bulk-load-payload.ts Resolved
@claude

claude Bot commented Sep 5, 2026

Copy link
Copy Markdown

Review: perf: serialize bulk load rows with an async generator, coalesced into packet-sized chunks

I read through src/bulk-load-payload.ts, src/bulk-load.ts, src/connection.ts, src/promise-like.ts, and the new unit/integration tests. This is a large, carefully worked change (30 incremental commits, each fixing one edge case with a pinning test), and overall it's in good shape. Notes below.

Strengths

  • Byte-for-byte equivalence is proven, not assumed. The 'produces the same bytes as serializing each row on its own' unit test asserts the generator output equals per-row WritableTrackingBuffer serialization for both a synchronous array and an async source. That's exactly the right way to validate a serializer rewrite.
  • Real, measured perf gains with a clear methodology (isolated serializer benchmark + end-to-end against SQL Server 2022), and an honest accounting of the one regression (async sources pay ~1µs/row for the Promise.race idle check) with a measured event-loop-starvation comparison against master. Good practice.
  • Genuine bug fixes fall out of this, not just a perf refactor: the empty-bulk-load case (master sends bare DONE, which SQL Server rejects), the dangling Readable when INSERT BULK is rejected/canceled, and the previously-unhandled 'error' on a stream source that fails before it's ever iterated. These are documented with tests.
  • I traced the cancellation/rejection interplay between execBulkLoad's payload.close() calls and Connection.makeRequest (which checks state !== LOGGED_IN / request.canceled before ever doing Readable.from(payload)), and confirmed there's no double-read of an already-closed source. That was my biggest worry going in and it holds up.

Concerns worth a second pair of eyes before merge

  1. Concurrency/close-lifecycle complexity is high, and its surface area is now large. BulkLoadPayload.close() and guardWhileClosing juggle: the bulk-load cancel listener, the source's own 'error' guard, the iterator's return() settling, and (for stream sources) destroy()/'close'/'error' — each potentially finishing on a different tick, with a comment explaining the exact ordering. It's well tested (the "keeps guarding ... until both ... have finished" tests are great), but this is the kind of code where a future refactor can silently reintroduce a listener leak or an unhandled rejection without a test catching it immediately. Consider a short comment block at the top of the class summarizing the state machine (when guarded is set/cleared, what started/closing mean together), so a future reader doesn't have to reconstruct it from the method-level comments.

  2. streamingMode removal — please double-check it was never public. BulkLoad.streamingMode and rowToPacketTransform are gone entirely, along with the ability to call execBulkLoad(bulkLoad) (no rows) and then write rows directly into the transform afterward. The fields were only JSDoc'd @private (not enforced by TS, no leading underscore/#), and there's no README mention of this pattern or prior test exercising it, so it looks safe to remove — but since it changes behavior for anyone who did rely on it (execBulkLoad(bulkLoad) with no rows now immediately completes a 0-row load instead of waiting for manual writes), it'd be worth calling out explicitly as a breaking change in the changelog/release notes rather than only in the commit body.

  3. Minor duplication: the "flush the buffer and yield its chunks" pattern (for (const chunk of buffer.getBuffers()) yield chunk; buffer.consume(buffer.length);) appears three times in serializeRows (idle flush, per-cell chunk-boundary flush, final DONE flush). Pulling it into a small local generator forwarded with yield* would remove the repetition without changing behavior — purely a readability nit.

  4. ignoreError duplication across bulk-load-payload.ts and bulk-load.ts: isPromiseLike was correctly extracted to promise-like.ts for reuse, but function ignoreError() {} is still duplicated in both files (with a comment explaining bulk-load.ts can't export it because it ends with a module.exports default-export assignment). Reasonable tradeoff, just flagging it as intentional rather than an oversight.

Security / correctness

No security concerns — this is internal wire-serialization logic, no new untrusted-input handling, and column validation (c.type.validate) is unchanged. I didn't find a case where the new code reads from or writes to a released/destroyed source (the started flag on BulkLoadPayload guards against close() and the consumer both touching the source).

Test coverage

Excellent — 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-Symbol.asyncIterator, wide-row mid-row flush, byte-equivalence, source-close on row failure/early-stop/TYPE_INFO failure, EventEmitter source error surfacing (before/during/after reads, before/after the last chunk), cancellation races (pending read abandonment, close-without-waiting-for-a-stuck-source), and the guard lifecycle for both plain iterators and streams (including emitClose: false). The integration tests add the zero-row, cancel-before/after-exec, and INSERT-BULK-rejected scenarios. I don't have a runnable environment here (no network access to npm ci), so I read the diff rather than executing the suite, but the PR description states 497 unit tests passing and a clean integration run against SQL Server 2022.

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 BulkLoadPayload.close()/guardWhileClosing line by line before merging, given how much of this PR's iteration history is fixing races in exactly that area — not because I found a bug, but because that's where any remaining one would hide.

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread src/bulk-load-payload.ts Resolved
@claude

claude Bot commented Sep 5, 2026

Copy link
Copy Markdown

Review: perf: serialize bulk load rows with an async generator, coalesced into packet-sized chunks

This is a substantial, well-engineered rewrite of the bulk-load row pipeline. Overall the change is an improvement over master in both correctness and throughput, and it is backed by an unusually thorough test suite. A few observations below, roughly in order of importance.

Correctness (mostly positive)

I traced through BulkLoad.serializeRows, BulkLoadPayload (construction, serialize(), close()), and the execBulkLoad changes in connection.ts, cross-checked against the new unit/integration tests. The logic held up under scrutiny:

  • The empty-bulk-load fix (COLMETADATA written eagerly, before any row is pulled) correctly addresses the "premature end-of-message" issue described in the PR body.
  • The chunk-boundary check after every cell (including the null text/image/ntext pointer byte) is necessary and correctly implemented — an earlier version of this PR reportedly missed the null-text case, and there's now a dedicated test (hands rows of null text cells downstream in chunks) pinning it.
  • The idle/abort race in serializeRows (armed once per stall, not once per row) matches the documented guarantee and is exercised by both the idle-flush test and the cancellation deadlock tests.
  • The resource-release bookkeeping in BulkLoadPayload (guarding an EventEmitter source's 'error' while close()/return() is still in flight, releasing the guard once both the iterator's return() and a stream's destroy() have settled) is intricate but each branch I checked (double registration of the shared ignoreError listener via both guardWhileClosing and the inline destroy-guard, the emitClose: false case, the "already failed before close" case) is backed by a specific unit test and matches the inline comments.

Code quality / maintainability

  • BulkLoadPayload.close() in particular concentrates a lot of subtle, order-dependent state (two independent "guard" mechanisms that both register the same ignoreError function reference on the same emitter/event, relying on each being removed independently). It's correct and well-commented, but it's the kind of code that's easy to break "cleaning it up" later without realizing why the apparent duplication exists. Consider whether a small ref-counted guard helper (increment/decrement instead of two independent listener registrations of the same function) would make the invariant more self-evident to a future editor, even if functionally equivalent.
  • Nice cleanup: removing RowTransform, streamingMode, and the Readable.from(rows).pipe(transform) plumbing simplifies execBulkLoad noticeably, and sharing isPromiseLike via src/promise-like.ts (rather than duplicating it) is the right call given bulk-load.ts's module.exports default-export style prevents named exports.
  • RowSource/Row are now properly exported/shared types instead of being declared twice — good.

Performance

  • The core win (coalescing into ~8 KB chunks instead of per-row/per-cell buffers) is well justified by the included benchmarks, and pulling rows lazily (not reading them until INSERT BULK is accepted) is a real behavior improvement, not just a perf one.
  • The tradeoff called out in the PR body is worth flagging explicitly here too: for asynchronous row sources, each row now costs a Promise.race against a setImmediate-based idle promise while a read is pending, and the PR's own end-to-end numbers show the async-generator case (~125–135k rows/s) landing below both master and the "coalescing transform" intermediate version (~141–146k rows/s) in one of the two scenarios measured. That's an accepted tradeoff to preserve the deadlock-avoidance guarantee for sources that block on server round-trips (and it's justified in the PR body), but it means the perf win is asymmetric: synchronous/array sources get a large win, real async sources get a smaller one or occasionally a slight regression. Might be worth a callout in the changelog/release notes so downstream users bulk-loading from async sources (cursors, files) aren't surprised if they benchmark before/after.

Security

No 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 coverage

This 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 EventEmitter/Readable sources. The integration tests add real end-to-end coverage for the empty-bulk-load and source-release-on-cancel/rejection cases. I don't see an obvious gap here.

Minor

  • package.json requires Node >=22, so relying on stream.errored/stream.closed in close()'s duck-typing (this.rows as { destroy?, closed?, errored? }) is safe — those have been stable for a long time before Node 22, just flagging that I checked it rather than assuming.
  • The one observable behavior change on the error path (bytes for rows serialized before a failing row are dropped instead of already having been pushed downstream) is called out clearly in the PR description and pinned by a test — good practice for a change like this.

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread src/bulk-load-payload.ts Resolved
@claude

claude Bot commented Sep 5, 2026

Copy link
Copy Markdown

Review

I read through the full diff (bulk-load.ts, bulk-load-payload.ts, connection.ts, promise-like.ts, and both test files) and traced the cancellation/close races by hand against makeRequest in connection.ts. Overall this is a well-executed, carefully-tested change. Notes below are suggestions, not blockers.

Strengths

  • Correctness fixes are real and well-targeted. I confirmed against makeRequest (connection.ts:3212) that for a canceled bulk load or a connection that's no longer LOGGED_IN, the payload is never iterated (makeRequest returns via request.callback(...) before ever calling Readable.from(payload)), so payload.close() in execBulkLoad is exactly the right place to release an unread row source — no double-consumption risk.
  • The "flush on idle" mechanism is sound. Racing iterator.next() against a setImmediate and only re-arming the immediate when it hasn't already fired (idle ??= …) correctly limits the immediate to "once per stall" rather than "once per row" for synchronous/fast sources, and the getBuffers()/consume() handoff from WritableTrackingBuffer means yielded chunks are stable views that later writes can't mutate.
  • Byte-for-byte regression test (produces the same bytes as serializing each row on its own) is a good guard against subtly changing wire format while refactoring the serialization path.
  • Test coverage of the listener/stream lifecycle (guarding a source while an async return()/destroy() is still in flight, emitClose: false, a stream that already failed, etc.) is unusually thorough for this kind of change.

Suggestions

  1. Maintainability risk in BulkLoadPayload's cleanup bookkeeping (close() / serialize() / guardWhileClosing). The listener-guard logic relies on some pretty subtle invariants — e.g. registering the same ignoreError function reference twice and relying on removeListener removing only one instance per completion signal as a de-facto 2-holder refcount (there's already a comment calling this out, which helps). This is clever and is backed by tests, but it's the kind of code where a future one-line "simplification" could silently reintroduce an unhandled 'error' crash or a leaked listener. Since correctness here is essentially only demonstrated by the unit tests rather than being structurally obvious from the code, it might be worth a short block comment at the top of the class summarizing the invariant ("every path that can emit 'error' asynchronously must be guarded until its own completion signal, and guards are independent — see close()'s doc comment for the ordering"), so a reviewer of a future PR knows to re-run/extend that specific test file rather than reasoning from the diff alone.

  2. Duplicated ignoreError no-op in both bulk-load.ts and bulk-load-payload.ts, with a comment explaining bulk-load.ts can't export it (it ends with a module.exports assignment). That's true for exporting, but nothing stops moving ignoreError into src/promise-like.ts (which already exists as a shared, dependency-free helper module for exactly this kind of cross-cutting utility) and having both files import it from there — avoiding the duplication without touching bulk-load.ts's export shape.

  3. Pre-existing, unrelated observation: firstRowWritten (used to gate c.type.validate() to only the first row) is set to false in the constructor and, as far as I can tell on both master and this branch, never set to true anywhere. So every row is always re-validated — the intended "validate once" optimization looks like it's never actually activated. This isn't introduced by this PR and is out of scope here, but since this PR already touches this exact line for a performance goal, it might be worth a quick follow-up look.

  4. Since I couldn't run npm ci/the test suite in this sandbox (no registry access), I relied on static reading rather than executing the 1000+ new lines of unit tests — worth double-checking CI is green (the PR description says unit suite 501 passing, full integration suite passing, lint/typecheck clean) before merging.

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
@claude

claude Bot commented Sep 5, 2026

Copy link
Copy Markdown

Review

This is a large, carefully engineered change (RowTransform → BulkLoad.serializeRows async generator), and it shows — 29 iterative commits each closing a specific edge case, ~1,100 lines of new unit tests, plus new integration tests. I traced through the trickiest parts of the design rather than just skimming; notes below.

Correctness

I walked through the scenarios that worried me most and didn't find a live bug:

  • Cancel-before-exec / not-logged-in release (connection.ts execBulkLoad): payload.close() is always called before makeRequest in the canceled/not-logged-in branch, and makeRequest never touches payload at all in those states (it only builds Readable.from(payload) in the else branch) — so there's no race where a "closed" payload gets read anyway.
  • The ignoreError double-bookkeeping in BulkLoadPayload.close(): two separate on('error', ignoreError) registrations (one from guardWhileClosing for the iterator's return(), one for the stream's destroy()) can be removed "out of order" relative to which one logically finished first, since removeListener just removes the first matching instance. This looks alarming at first glance, but since both listeners are the same no-op function reference, the pairing doesn't actually matter — the count just needs to reach zero once both releases finish, and it does (confirmed against the "keeps guarding a source closed unread until both its iterator and its destruction have finished" test).
  • firstRowWritten / old streamingMode: I checked — both were already permanently dead on master before this PR (firstRowWritten is never set true anywhere, streamingMode is never set true anywhere), so validation already ran on every row and streamingMode's check was already unreachable. Removing streamingMode/rowToPacketTransform here is safe cleanup, not a behavior change.
  • The idle/flush race (Promise.race([read, idle, abort]), re-arming the setImmediate only once per stall rather than per row) checks out: microtask-resolved reads always beat the macrotask idle timer, so a fast async source is coalesced exactly as described, and a stalling one flushes promptly.

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

  • The BulkLoadPayload close/guard state machine (guarded, sourceError, aborted/rejectAborted, guardWhileClosing, the stream-destroy branch in close()) is dense — a lot of state to hold in your head at once, even with the doc comments. It's clearly correct by the test suite, but it's the kind of code where a future "small" edit could easily break an invariant that isn't obvious from local context. Might be worth a short state-machine summary comment at the top of the class for the next person touching it, beyond what's already there.
  • ignoreError() is defined twice (once in bulk-load.ts, once in bulk-load-payload.ts), with a comment explaining bulk-load.ts can't export it because of its trailing module.exports default export. Since isPromiseLike already got its own module for exactly this sharing problem, ignoreError could move there too and drop the duplication — very minor.
  • Good instinct pulling isPromiseLike out into its own module rather than exporting it awkwardly from bulk-load.ts.

Performance

The measurements are a highlight — honest about the one regression (async sources pay ~1µs/row for the Promise.race against setImmediate), and justify it as a correctness guarantee (avoiding deadlock with a source that's waiting on the server's reaction to bytes still sitting in the buffer) rather than hand-waving it away. The event-loop-starvation check for synchronous sources is a nice touch given the removal of the nextTick-per-row that the old transform had.

API surface

Connection.execBulkLoad's public overload now requires rows (previously it was effectively optional to support the old streaming-via-addRow pattern). Since streamingMode was already dead code and rowToPacketTransform was @private, this isn't a functional break for anyone using documented APIs, but it's a public type signature change — worth a line in the release notes for anyone who was calling execBulkLoad(bulkLoad) with no second argument (even though, per the above, that path was already non-functional for streaming purposes).

Test coverage

Very thorough — chunk-boundary behavior (including the null-text-cell fix), zero-row bulk loads, byte-for-byte equivalence against the old per-row serialization, and a long list of cancellation/close/error-ordering permutations. Nice that the byte-equivalence test drives both an array and an async source through the same assertion.

Security

No 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread src/bulk-load-payload.ts Resolved
Comment thread src/bulk-load-payload.ts Resolved
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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread src/bulk-load-payload.ts Resolved
…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
@claude

claude Bot commented Sep 5, 2026

Copy link
Copy Markdown

Review

This is a very well-engineered change. The core idea — replacing the Readable.from(rows).pipe(RowTransform) plumbing with a single async generator that pulls rows and coalesces them into CHUNK_SIZE buffers — is sound, and the PR does an unusually thorough job of chasing down the resource-lifecycle edge cases that fall out of pulling rows instead of piping them (empty sources, cancellation mid-read, unread sources, EventEmitter sources that don't replay errors through their iterator, streams created with emitClose: false, deferred _construct, etc.). The benchmark numbers and the byte-for-byte equivalence test against the old per-row serialization give good confidence the wire format is unchanged.

A few observations, roughly in order of importance:

Complexity / maintainability of BulkLoadPayload.close()

The stream-release path in close() (guarding 'error' while an async return()/destroy() is still settling, detecting whether a stream already finished destroying, handling emitClose: false, etc.) is the most intricate part of the change, and its correctness leans on fairly subtle Node.js stream internals — e.g. that destroy()'s own callback fires strictly after any 'error'/'close' the destruction emits, and that calling destroy() on an already-destroyed stream never invokes the callback. That's true today, but it's the kind of guarantee that has shifted between Node major versions before (the PR's own history shows this logic was rewritten twice for exactly this reason). Since none of this complexity applies to the common case (an array or plain generator as the row source — the whole block is gated on rows instanceof EventEmitter/instanceof Stream), it might be worth:

  • a one-line comment pinning the Node.js version(s) this was verified against, so a future contributor investigating a report on a newer/older Node knows where to look first, and
  • double-checking the CI matrix actually exercises these tests (the emitClose: false / deferred-destroy ones especially) across every supported Node major version, since that's exactly where this kind of behavior tends to diverge.

This isn't a request to simplify — the complexity looks load-bearing given the guarantees being made — just a maintainability note for whoever has to touch this next.

Minor readability nit in bulk-load.ts

In serializeRows's finally block:

const closing = iterator.return();
if (!isPromiseLike(closing)) {
  await closing;
} else {
  ...
}

Awaiting closing when it's known not to be promise-like is a no-op (aside from a microtask tick). It's harmless, but reads like it could be a mistake at a glance — a short comment on why the await is kept (e.g. to normalize control flow with the promise branch) would save the next reader a double-take.

API removal

RowTransform, rowToPacketTransform, and streamingMode are gone. All three were @private/undocumented, and a repo grep turns up no public docs referencing them, so this looks safe — just flagging it explicitly in case any downstream consumer had discovered bulkLoad.streamingMode despite it not being public API.

Test coverage

Coverage is exceptionally thorough — empty bulk loads, cancellation at every stage (before exec, mid-flight, with a chunk already downstream), unread-source release, EventEmitter sources that do/don't replay errors through their iterator, and the byte-equivalence test. I didn't find a gap worth calling out.

Performance & security

The measurements in the description show consistent wins over both master and the intermediate "transform, coalescing" version, with reasonable analysis of the async-source overhead (the Promise.race idle check) and event-loop starvation. No security concerns — this is internal wire-format serialization and stream lifecycle management with no new handling of untrusted input.

Nice work on the edge-case hunting here — the commit history shows real rigor in chasing down each of these scenarios rather than leaving them as known gaps.

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
@claude

claude Bot commented Sep 5, 2026

Copy link
Copy Markdown

Review

This is a well-engineered, thoroughly tested change. Highlights:

  • Correctness improvements over master: fixing the "empty bulk load" premature-EOM bug, closing row sources that used to be left dangling, and abandoning pending row reads on cancel instead of leaving them stuck are all real bug fixes, not just perf work.
  • Test coverage is exceptional — ~1,230 lines of new unit tests pin byte-for-byte equivalence with the old per-row serialization, the idle-flush guarantee, the chunk-boundary checks (including the easy-to-miss null-text-cell case), and a long tail of source-lifecycle edge cases (streams destroyed early/late, emitClose: false, _destroy that can't be wrapped, etc.). That's exactly the kind of coverage this amount of async-generator/event-emitter interleaving needs to be trustworthy.
  • Performance claims are backed by numbers (both isolated serializer throughput and end-to-end against SQL Server), and the event-loop-starvation concern was explicitly checked rather than assumed away.
  • No security concerns — this is purely wire-format serialization/stream-lifecycle plumbing; no new parsing of untrusted input, no SQL string construction changes.

A few things worth a second look before merging:

  1. BulkLoadPayload.close() complexity (src/bulk-load-payload.ts). The stream-destruction handling — tracking destroyed/closed/errored, wrapping destroy()'s callback, and an exponential-backoff setTimeout poll for streams built with emitClose: false that were already destroying themselves — is a lot of intricate state for a best-effort cleanup path that only runs when rows are never read (canceled/rejected INSERT BULK, not-logged-in connection). It's clearly correct per the tests, but it's dense enough that a future bug fix here will be hard without re-deriving the same reasoning. Consider whether a short summary comment (the current one is good) plus maybe extracting the "wait for a stream to finish destroying itself" bit into a small named helper would make it easier to reason about in isolation from the rest of close().

  2. Duplicated close conditions between execBulkLoad and makeRequest (src/connection.ts). execBulkLoad pre-emptively calls payload.close() when bulkLoad.canceled || this.state !== this.STATE.LOGGED_IN, mirroring the two conditions under which makeRequest rejects a request without ever reading its payload. That mirroring is currently correct and commented, but it's a coupling that only holds by convention — if makeRequest's rejection conditions ever change, the row-source-leak bug this PR fixes could silently come back. Not asking for a change, just flagging it as something to keep in mind (maybe worth a comment on the makeRequest side pointing back at execBulkLoad, mirroring the comment that already exists in the other direction).

  3. Comment density/style. Many of the new comments are quite long and narrative (multi-sentence paragraphs explaining why, sometimes cross-referencing specific Node.js stream internals). Given how subtle this code is, the verbosity is arguably earned here, but it's a notable departure from the terser comment style elsewhere in the codebase — worth a style pass if the maintainers prefer a leaner default.

  4. Dead flag, pre-existing (not introduced here): firstRowWritten is checked in serializeRows (if (!this.firstRowWritten) { value = c.type.validate(...) }) but is never set to true anywhere in bulk-load.ts, on master or in this PR. So every row is always validated, and addColumn's "can't add columns after the first row" guard is unreachable. Out of scope for this PR since the behavior is unchanged, but flagging in case it's useful context.

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
@claude

claude Bot commented Sep 5, 2026

Copy link
Copy Markdown

Review: bulk load row serialization rewrite

This is a substantial, well-executed refactor. Overview of what I checked: src/bulk-load.ts (serializeRows), src/bulk-load-payload.ts, src/tracking-buffer/writable-tracking-buffer.ts, src/connection.ts (execBulkLoad), and both unit/integration test files. I did not have npm install available in this sandbox, so this is a static review, not a test run.

Strengths

  • Removing RowTransform/the pipe() plumbing and unifying bulk load with the same Readable.from(payload) path used by RPC payloads is a nice simplification, and the "coalesce into ~8KB chunks, but flush early when the source goes idle" strategy is a good fix for the tiny-buffer-per-row problem without sacrificing responsiveness for slow/streamed sources.
  • The idle/abort race in serializeRows (bulk-load.ts:552-578) is subtle but looks correct: reusing the same idle promise across iterations until it actually fires (rather than creating a new setImmediate per row) correctly avoids flushing after every row for a fast synchronous-ish async source, while still guaranteeing prompt delivery when the source genuinely stalls (relying on microtasks draining before the setImmediate/check-phase callback runs, which is the correct Node ordering).
  • Resource cleanup (bulk-load-payload.ts) is unusually thorough: closing the row source on early consumer stop, on row failure, on cancel with a pending read, on the stream-destroy path, and not letting a slow/never-finishing return() hang the bulk load. The unit tests exercise essentially every one of these paths (chunk boundaries, empty bulk load, mid-row cancel, source-emits-error-while-read-pending, stream destroy races, etc.) — this is exceptional test coverage for concurrency-sensitive code.
  • The behavior-change list in the PR description (empty bulk load now works, rows not read before INSERT BULK is accepted, source always closed) is each backed by a dedicated test.

Things worth a look

  1. Pre-existing, not introduced here: firstRowWritten (bulk-load.ts:593, connection.ts:2828) is still never set to true anywhere in the codebase (verified this was already the case on master before this PR), so c.type.validate(...) runs unconditionally on every row rather than only "before the first row was written" as the field name/original intent implies. Not a regression from this PR, but since you were already in this code, might be worth a follow-up issue to either remove the dead flag or fix whatever it was originally meant to gate.

  2. WritableTrackingBuffer.CHUNK_SIZE is a fixed 8KB constant, decoupled from the connection's actual/negotiated packetSize (default 4KB, configurable up to 32767 — see DEFAULT_PACKET_SIZE in connection.ts). The PR description frames this as "packet-sized chunks", but the chunks aren't actually sized to the negotiated packet size, so with default settings each ~8KB chunk still gets split again downstream, and with a larger configured packetSize you might still emit smaller-than-packet chunks. Not a bug, just worth double-checking the naming/intent, or considering deriving the coalescing threshold from options.packetSize if that was the actual goal.

  3. writeBuffer now stores buffers >= CHUNK_SIZE by reference instead of copying (writable-tracking-buffer.ts:285-297), which is a nice memory win for large VarBinary/Image/Text cell values, but it's an observable contract change: such a buffer must not be mutated by the caller until it's been flushed downstream. Since this can now include a user-supplied row value (e.g., a large Buffer passed in a bulk-loaded row), it might be worth a one-line doc note (either near addColumn/row typing, or in the bulk-load class docs) warning against reusing/mutating large buffers passed into binary columns after handing them to execBulkLoad.

  4. Minor: the integration test 'should not throw in _transform function' (test/integration/bulk-load-test.ts:1650, pre-existing/untouched by this PR) now references a method (_transform) that no longer exists anywhere in the implementation. Not something this PR needs to fix, but a rename would avoid future confusion since it's easy to assume it's testing something that's still there.

Security

No 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 coverage

Excellent 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 (npm run test-all) plus a real bulk-load-heavy workload before merging, given how much of the correctness here rests on Node's microtask/setImmediate ordering guarantees.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread src/bulk-load-payload.ts Resolved
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
@claude

claude Bot commented Sep 5, 2026

Copy link
Copy Markdown

Review

This is a well-engineered change. Replacing the Readable.from(rows).pipe(RowTransform) plumbing with BulkLoad.serializeRows, an async generator that writes directly into a single long-lived WritableTrackingBuffer and yields ~8 KB chunks, removes several layers of indirection (extra Transform, extra Readable.from, nextTick round-trips per row), and the benchmark numbers in the description back that up (up to ~2x throughput for narrow, many-column rows).

Correctness

  • The empty-bulk-load fix (COLMETADATA written eagerly before rows are read, so an empty source still produces a valid COLMETADATA … DONE message) is a real, well-diagnosed bug fix — master sends only DONE, which SQL Server rejects. Good catch, pinned with both a unit test and an integration test.
  • The idle-flush logic (Promise.race([read, idle, abort]), arming a single setImmediate per stall rather than per row) looks correct: a synchronous source never touches the event loop, an asynchronous source that stalls flushes what it has, and a source that keeps producing coalesces up to CHUNK_SIZE. Checking the flush condition after every cell (not only after every row) is a nice detail for wide rows with large cells.
  • The cancellation/close bookkeeping in BulkLoadPayload (guardWhileClosing, the stream-destruction watcher with the backing-off closed poll, the release()/unguard() split) is intricate but each piece is exercised by a dedicated unit test — coverage of "guard stays on until both the iterator's return() and the stream's destruction have settled" is particularly thorough (including emitClose: false and double-destroy()-report cases).
  • In connection.ts's execBulkLoad, the bulkLoad.canceled || this.state !== LOGGED_IN check before makeRequest mirrors exactly the condition under which makeRequest bails without touching the payload, so payload.close() fires precisely when the payload would otherwise leak unread. That symmetry is duplicated across two places and could silently drift apart in a future edit — might be worth a comment cross-referencing makeRequest's early-return conditions, or extracting a shared check.

Code quality / maintainability

  • BulkLoadPayload.close() is quite dense (~100 lines) with polling/backoff for streams that give no destruction signal (emitClose: false). It's justified by the comments and tests, but it's the kind of code that's hard to safely modify without re-reading the whole block plus its ~15 associated tests. A short doc-comment at the top of the class flagging why this complexity exists (supporting the "unread source" cancellation paths) would help future readers know where to look before touching it.
  • Several fields on BulkLoadPayload (started, guarded, sourceError, onSourceError, aborted, rejectAborted, onCancel, source) are internal state exposed as plain public declare fields rather than private. That looks like a deliberate trade-off to allow the white-box unit tests (e.g. payload.onSourceError, payload.guarded) to assert on listener identity, but nothing stops external code from poking at them. Worth confirming that's intentional rather than an oversight.
  • promise-like.ts is a nice small extraction; isPromiseLike correctly narrows on .then rather than instanceof Promise, which matters since thenables (e.g. some cursor/driver row sources) need to work too.

Test coverage

Excellent — 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 node_modules were installed, so I reviewed by inspection only rather than running npm run lint / npm test. Worth keeping an eye on CI given how much of this is timing-sensitive (setImmediate/backing-off timers in the new tests) — the reasoning behind each looks sound, but that's exactly the kind of code that can occasionally flake in CI even when logically correct.

Security / performance

  • No security concerns — this is internal serialization/stream-lifecycle code with no new external input handling.
  • The performance measurements included in the description (transform-pipeline vs. generator, sync vs. async sources, event-loop-starvation check) are a nice touch. The one caveat called out — async sources are ~1µs/row slower due to the idle Promise.race — is well-reasoned, and correctness (avoiding the cancellation deadlock) is clearly the right tradeoff to make.

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread src/bulk-load.ts Resolved
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
@claude

claude Bot commented Sep 5, 2026

Copy link
Copy Markdown

Review

This is a substantial and impressively careful rewrite of bulk-load row serialization, replacing the RowTransform/pipe-based pipeline with an async generator (BulkLoad.serializeRows) driven directly by BulkLoadPayload. I read through src/bulk-load-payload.ts, src/bulk-load.ts, src/connection.ts, src/promise-like.ts, and the new tests. Overall this looks correct and very thoroughly tested — the commit history shows each edge case (cancellation mid-read, source errors during close, emitClose: false streams, promised rows, etc.) was found and pinned with a dedicated unit test. A few notes:

Code quality / minor issues

  • Dead field: src/bulk-load-payload.ts:262 declares errored?: Error | null on the inline stream type cast, but it's never read anywhere in close(). Either it's a leftover from an earlier iteration of the destroy logic, or it was meant to short-circuit the polling loop for a stream that's already errored — worth double-checking which, and removing it if it's genuinely unused.

  • Duplicate ignoreError listeners on the same emitter: In close(), when the source is a Stream, guardWhileClosing() (for the iterator's return()) and the stream-destroy block can both register emitter.on('error', ignoreError) with the same function reference. This works today because each side removes exactly one instance of ignoreError when its own condition settles (Node lets the same listener be registered/removed independently per call), but it's a subtle pattern — a future reader inspecting emitter.listeners('error') can't tell which guard installed which entry. A short comment already partially explains this (line 278-280); might be worth being a bit more explicit that this is intentional and safe, since it's easy to mistake for a bug at a glance.

  • Complexity vs. likely benefit: The exponential-backoff polling for stream.closed (close(), lines ~303-322) exists to handle a stream created with emitClose: false that was already being destroyed by its owner before the payload gets to it — a very narrow scenario. It's correct and well-tested, but it's also some of the densest code in the PR (unref'd timers with backoff, multiple listener-cleanup paths). Given tedious's real-world bulk-load sources are almost always arrays, plain generators, or DB-cursor-backed Readables, it might be worth a maintainer gut-check on whether this corner case is worth the maintenance cost, even though the tests demonstrate it works. Not blocking — just flagging for discussion.

Performance

  • The PR's own benchmark table shows the final generator design is measurably slower for async sources (three-column async generator: ~125–135k rows/s) than the intermediate "transform, coalescing" design tried earlier in the same PR (~141–146k rows/s), because of the per-read Promise.race against the idle setImmediate. This is explained and justified (removing the race causes the cancellation tests to deadlock, since a source can be legitimately waiting on the server's reaction to bytes not yet flushed), and it's still a large win over master for synchronous/array sources. Just want to make sure this async-source tradeoff is a deliberate, accepted one rather than something to revisit — it could matter for users bulk-loading from async cursors/streams rather than arrays.

Correctness (traced, no bugs found)

I traced several of the trickier invariants and they check out:

  • execBulkLoad's payload.close() calls (on INSERT BULK rejection, on cancel, on not-logged-in) are only reachable through code paths in makeRequest that never construct Readable.from(payload), so there's no risk of close() and serialize() racing to read/destroy the same source.
  • The promised-row handling (added late in the PR, commit 66fcbe98) correctly treats a Promise<Row> the same as a pending iterator read for idle-flush/cancel purposes, and the fix is well-targeted (it was previously silently producing null cells for sources that hand back promises for rows, a real behavior gap versus the old Readable.from pipe).
  • RowTransform/rowToPacketTransform/streamingMode are fully removed with no dangling references left in src/ or test/; streamingMode was already dead code on master (declared and initialized but never set to true anywhere), so this isn't a breaking change despite the public-sounding name.

Test coverage

Excellent — the unit test additions in test/unit/bulk-load-test.ts systematically cover the byte-level serialization (parity with old per-row serialization), chunk-boundary edge cases (wide rows, null text cells), and an unusually complete matrix of source-lifecycle scenarios (sync/async/emitter sources, closed-early, close-fails, destroy-throws, double-reported destruction, emitClose: false). The integration tests cover the zero-row bulk load and the three cancel/reject paths that release the row source. I didn't spot a gap worth calling out.

Security

No 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.

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.

2 participants