From 976928869d4e9fecca0fb21f2e844501d0ecdf4a Mon Sep 17 00:00:00 2001 From: "Dmitry S." <1832518+nuzayets@users.noreply.github.com> Date: Tue, 10 Nov 2026 04:48:33 -0500 Subject: [PATCH 1/3] perf: write string table bytes at encode time instead of buffering each string StringTable encoded every new string into its own Uint8Array as it was added. A profile with thousands of distinct file paths and function names made thousands of small allocations, and every array over V8's 64-byte on-heap typed array limit got its own off-heap backing store, which adds to V8's external memory. Track each string's UTF-8 length instead and write the bytes straight into the output buffer when the table is encoded. Strings read by decode keep their original bytes so re-encoding stays byte-for-byte identical. --- src/index.test.ts | 16 +++++++++ src/string-table.ts | 84 ++++++++++++++++++++++++++++++++++----------- 2 files changed, 80 insertions(+), 20 deletions(-) diff --git a/src/index.test.ts b/src/index.test.ts index 26c8764..72c9826 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -466,6 +466,22 @@ test('StringTable', async (t) => { table.dedup('hello') assert.strictEqual(bufToHex(table.encode()), encodings[''] + encodings['hello']) }) + + await t.test('encodes non-ASCII strings as TextEncoder does', async () => { + const strings = ['é', '日本語', '😀 emoji', 'lone \uD800 high', 'lone \uDC00 low', 'x'.repeat(200) + 'ü'] + const table = new StringTable() + for (const s of strings) table.dedup(s) + const encoded = table.encode() + assert.strictEqual(encoded.length, table.encodedLength) + assert.strictEqual(bufToHex(encoded), encodeStringTable(table)) + }) + + await t.test('re-encodes decoded strings byte for byte', async () => { + // 0xff is not valid UTF-8, so the decoded string alone can't reproduce it + const raw = hexToBuf('3200' + '3203' + '61ff62') + const decoded = Profile.decode(raw).stringTable + assert.strictEqual(bufToHex(decoded.encode()), bufToHex(raw)) + }) }) function profileToObject(profile: any): object { diff --git a/src/string-table.ts b/src/string-table.ts index d099c5b..bf6e61e 100644 --- a/src/string-table.ts +++ b/src/string-table.ts @@ -29,14 +29,51 @@ function encodeLengthDelimited(utf8: Uint8Array | Buffer): Uint8Array { return buffer } +// The UTF-8 length of a string, counting a lone surrogate as U+FFFD the way +// Buffer and TextEncoder write it +function utf8Length(value: string): number { + let length = value.length + for (let i = 0; i < value.length; i++) { + const code = value.charCodeAt(i) + if (code < 0x80) continue + if (code < 0x800) { + length += 1 + } else if (code >= 0xd800 && code <= 0xdbff && i + 1 < value.length && + (value.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { + length += 2 + i++ + } else { + length += 2 + } + } + return length +} + +const utf8ByteLength = typeof Buffer === 'undefined' + ? utf8Length + : (value: string) => Buffer.byteLength(value, 'utf8') + +// Writes a string's UTF-8 bytes into `buffer` at `offset` +function utf8Writer(buffer: Uint8Array): (value: string, offset: number) => void { + if (typeof Buffer === 'undefined') { + const encoder = new TextEncoder() + return (value, offset) => { encoder.encodeInto(value, buffer.subarray(offset)) } + } + const view = Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength) + return (value, offset) => { view.write(value, offset, 'utf8') } +} + /** - * The strings of a profile, each encoded once as it is added. The enclosing - * message supplies the field number when it encodes the table, so one table - * type serves both pprof and OTel. + * The strings of a profile. A string's UTF-8 bytes are written straight into + * the output when the table is encoded, so adding a string allocates no + * buffer. The enclosing message supplies the field number when it encodes the + * table, so one table type serves both pprof and OTel. */ export class StringTable { strings = new Array() - #encodings = new Array() + #byteLengths = new Array() + // The bytes of strings read from a profile, which re-encoding reproduces exactly + #decoded = new Array() #positions = new Map() #encodedLength = 0 @@ -54,15 +91,23 @@ export class StringTable { /** Measures the strings as the repeated string field `field`. */ _measure(field: number): number { - return this.#encodings.length * measureTag(field) + this.#encodedLength + return this.#byteLengths.length * measureTag(field) + this.#encodedLength } /** Encodes the strings as the repeated string field `field`. */ _encodeToBuffer(buffer: Uint8Array, offset: number, field: number): number { - for (const encoded of this.#encodings) { + const writeUtf8 = utf8Writer(buffer) + for (let i = 0; i < this.#byteLengths.length; i++) { + const byteLength = this.#byteLengths[i] offset = encodeTag(buffer, offset, field, kTypeLengthDelim) - buffer.set(encoded, offset) - offset += encoded.length + offset = encodeNumber(buffer, offset, byteLength) + const decoded = this.#decoded[i] + if (decoded !== undefined) { + buffer.set(decoded, offset) + } else if (byteLength > 0) { + writeUtf8(this.strings[i], offset) + } + offset += byteLength } return offset } @@ -89,22 +134,21 @@ export class StringTable { if (typeof value === 'number') return value let position = this.#positions.get(value) if (position === undefined) { - position = this.strings.push(value) - 1 - this.#positions.set(value, position) - - // Encode strings on insertion - const encoded = encodeLengthDelimited(toUtf8(value)) - this.#encodings.push(encoded) - this.#encodedLength += encoded.length + position = this.#add(value, utf8ByteLength(value)) } return position } _decodeString(buffer: Uint8Array) { - const value = decodeString(buffer) - this.#positions.set(value, this.strings.push(value) - 1) - const encoded = encodeLengthDelimited(buffer) - this.#encodings.push(encoded) - this.#encodedLength += encoded.length + const position = this.#add(decodeString(buffer), buffer.length) + this.#decoded[position] = buffer.slice() + } + + #add(value: string, byteLength: number): number { + const position = this.strings.push(value) - 1 + this.#positions.set(value, position) + this.#byteLengths.push(byteLength) + this.#encodedLength += varintLength(byteLength) + byteLength + return position } } From 28c605c1424357c254a331c6a080cba81db34a86 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Tue, 17 Nov 2026 20:48:09 +0100 Subject: [PATCH 2/3] fix(string-table): preserve buffer ownership and capacity checks Buffer.slice() shares the caller's storage, so later input changes corrupt re-encoded string tables. Keep an independent copy of decoded bytes. Buffer.write() and TextEncoder.encodeInto() can truncate strings without throwing. Validate output capacity before encoding. --- src/index.test.ts | 55 ++++++++++++++++++++++++++++++++++++++++++++- src/string-table.ts | 29 ++++++------------------ 2 files changed, 61 insertions(+), 23 deletions(-) diff --git a/src/index.test.ts b/src/index.test.ts index 72c9826..9202dd7 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -7,10 +7,14 @@ import { test } from 'node:test' import type { TestContext } from 'node:test' import assert from 'node:assert' +import { Buffer as NodeBuffer } from 'node:buffer' +import { spawnSync } from 'node:child_process' +import { fileURLToPath } from 'node:url' import { gunzipSync } from 'zlib' import * as fs from 'fs' import proto from '../testing/proto/profile.js' +import { ProfilesDictionary } from './otel.js' const {decode, toObject} = proto.perftools.profiles.Profile @@ -470,7 +474,9 @@ test('StringTable', async (t) => { await t.test('encodes non-ASCII strings as TextEncoder does', async () => { const strings = ['é', '日本語', '😀 emoji', 'lone \uD800 high', 'lone \uDC00 low', 'x'.repeat(200) + 'ü'] const table = new StringTable() - for (const s of strings) table.dedup(s) + for (const value of strings) { + table.dedup(value) + } const encoded = table.encode() assert.strictEqual(encoded.length, table.encodedLength) assert.strictEqual(bufToHex(encoded), encodeStringTable(table)) @@ -482,6 +488,53 @@ test('StringTable', async (t) => { const decoded = Profile.decode(raw).stringTable assert.strictEqual(bufToHex(decoded.encode()), bufToHex(raw)) }) + + await t.test('owns decoded string bytes after the input changes', () => { + for (const ArrayType of [Uint8Array, NodeBuffer]) { + for (const length of [0, 1, 64, 65]) { + const bytes = new Uint8Array(length).fill(0xff) + const expected = Uint8Array.of(0x32, 0, 0x32, length, ...bytes) + for (const [MessageType, field] of [[Profile, 0x32], [ProfilesDictionary, 0x2a]] as const) { + const input = ArrayType.from([0xaa, field, 0, field, length, ...bytes, 0xaa]) + const decoded = MessageType.decode(input.subarray(1, -1)) + input.fill(0) + assert.deepStrictEqual(decoded.stringTable.encode(), expected, `${ArrayType.name}, ${length} bytes`) + } + } + } + }) + + await t.test('checks the capacity of supplied buffers', () => { + for (const value of ['', 'hello', 'é日本😀\uD800', 'x'.repeat(127), 'x'.repeat(128)]) { + const table = new StringTable() + table.dedup(value) + const expected = encodeStringTable(table) + for (const ArrayType of [Uint8Array, NodeBuffer]) { + for (const length of [0, table.encodedLength - 1]) { + assert.throws(() => table.encode(new ArrayType(length)), { name: 'RangeError' }) + } + for (const extra of [0, 1]) { + const backing = new ArrayType(table.encodedLength + extra + 2).fill(0xaa) + const target = backing.subarray(1, -1) + assert.strictEqual(table.encode(target), target) + assert.strictEqual(bufToHex(target.subarray(0, table.encodedLength)), expected) + assert.strictEqual(backing[0], 0xaa) + assert.strictEqual(backing[backing.length - 1], 0xaa) + if (extra) { + assert.strictEqual(target[table.encodedLength], 0xaa) + } + } + } + } + }) + + await t.test('works without the Buffer global', { skip: typeof globalThis.Buffer === 'undefined' }, () => { + const result = spawnSync(process.execPath, [ + '--import', 'data:text/javascript,globalThis.Buffer=undefined', + '--test', '--test-name-pattern=StringTable', fileURLToPath(import.meta.url), + ], { encoding: 'utf8', env: { ...process.env, NODE_TEST_CONTEXT: undefined } }) + assert.strictEqual(result.status, 0, result.stderr || result.stdout) + }) }) function profileToObject(profile: any): object { diff --git a/src/string-table.ts b/src/string-table.ts index bf6e61e..14a495c 100644 --- a/src/string-table.ts +++ b/src/string-table.ts @@ -10,7 +10,9 @@ import { encodeTag, kTypeLengthDelim, measureTag, + prepareBuffer, toUtf8, + utf8Length, varintLength, } from './protobuf.js' @@ -29,26 +31,6 @@ function encodeLengthDelimited(utf8: Uint8Array | Buffer): Uint8Array { return buffer } -// The UTF-8 length of a string, counting a lone surrogate as U+FFFD the way -// Buffer and TextEncoder write it -function utf8Length(value: string): number { - let length = value.length - for (let i = 0; i < value.length; i++) { - const code = value.charCodeAt(i) - if (code < 0x80) continue - if (code < 0x800) { - length += 1 - } else if (code >= 0xd800 && code <= 0xdbff && i + 1 < value.length && - (value.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { - length += 2 - i++ - } else { - length += 2 - } - } - return length -} - const utf8ByteLength = typeof Buffer === 'undefined' ? utf8Length : (value: string) => Buffer.byteLength(value, 'utf8') @@ -113,7 +95,8 @@ export class StringTable { } /** Encodes the strings as pprof's string_table. */ - encode(buffer = new Uint8Array(this.encodedLength)): Uint8Array { + encode(buffer?: Uint8Array): Uint8Array { + buffer = prepareBuffer(buffer, this.encodedLength) this._encodeToBuffer(buffer, 0, pprofStringTableField) return buffer } @@ -141,7 +124,9 @@ export class StringTable { _decodeString(buffer: Uint8Array) { const position = this.#add(decodeString(buffer), buffer.length) - this.#decoded[position] = buffer.slice() + this.#decoded[position] = buffer.length <= 64 || typeof Buffer === 'undefined' + ? new Uint8Array(buffer) + : Buffer.from(buffer) } #add(value: string, byteLength: number): number { From 2c1009999b766e0691375691ffc07ffcf92fa5e3 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Tue, 17 Nov 2026 23:44:26 +0100 Subject: [PATCH 3/3] perf(protobuf): pre-count code units when measuring UTF-8 strings For mixed ASCII names and paths, Node 22.23.4 (V8 12.4.254.21-node.57) takes 113-115 ns per call instead of 133-143 ns. Each of two fresh processes uses seven trials of 262,144 calls, discarding the fastest and slowest. --- src/otel.test.ts | 6 +++++- src/protobuf.ts | 13 +++++++------ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/otel.test.ts b/src/otel.test.ts index a0e5790..8ef243b 100644 --- a/src/otel.test.ts +++ b/src/otel.test.ts @@ -332,7 +332,11 @@ test('ProfilesDictionary', async (t) => { }) test('string fields are encoded as UTF-8', () => { - for (const key of ['plain', 'café', '✓', '😀', 'lone \ud800 surrogate']) { + for (const key of [ + 'plain', 'café', '✓', '😀', 'lone \ud800 surrogate', + '\u007f', '\u0080', '\u07ff', '\u0800', '\ud7ff', '\ud800', '\udbff', '\udc00', '\udfff', '\ue000', '\uffff', + '\ud800\udc00', '\udbff\udfff', '\ud800\ud800', '\ud800\ue000', '\udc00\ud800', + ]) { const utf8 = Buffer.from(key, 'utf8') const encoded = new KeyValue({ key }).encode() assert.strictEqual(hex(encoded), '0a' + utf8.length.toString(16).padStart(2, '0') + utf8.toString('hex'), key) diff --git a/src/protobuf.ts b/src/protobuf.ts index 6207ac0..fd44957 100644 --- a/src/protobuf.ts +++ b/src/protobuf.ts @@ -446,19 +446,20 @@ export function encodeBytesField(buffer: Uint8Array, offset: number, field: numb /** UTF-8 byte length; lone surrogates become U+FFFD (3 bytes), as in TextEncoder. */ export function utf8Length(string: string): number { - let length = 0 + let length = string.length for (let i = 0; i < string.length; i++) { const code = string.charCodeAt(i) if (code < 0x80) { + continue + } + if (code < 0x800) { length += 1 - } else if (code < 0x800) { + } else if (code >= 0xd800 && code <= 0xdbff && i + 1 < string.length && + (string.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { length += 2 - } else if ((code & 0xfc00) === 0xd800 && (string.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { - // A surrogate pair encodes one code point in 4 bytes - length += 4 i++ } else { - length += 3 + length += 2 } } return length