Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(ai-research): write the v4 index with zstd and sorted blocks (#124953)

Robbiebc7c9c6834f2
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/parquet-sink-v4/parquet-buffer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/parquet-sink-v4/parquet-buffer.ts
index 9c7876f4d07b..5d084030a4d9 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/parquet-sink-v4/parquet-buffer.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/parquet-sink-v4/parquet-buffer.ts
@@ -1,4 +1,4 @@
-/** Encode already-mapped records into a Snappy/Parquet buffer via an in-memory sink — parquetjs only
+/** Encode already-mapped records into a Parquet buffer via an in-memory sink — parquetjs only
* writes to a stream, so this is the openStream/collect plumbing. Schema + record shape are the caller's. */
import { ParquetSchema, ParquetWriter } from '@dsnp/parquetjs'
import { Writable } from 'stream'
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/parquet-sink-v4/parquet-writer.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/parquet-sink-v4/parquet-writer.test.ts
index 5226d36f6307..8bd528981466 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/parquet-sink-v4/parquet-writer.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/parquet-sink-v4/parquet-writer.test.ts
@@ -124,7 +124,7 @@ describe('indexRowsToParquet', () => {
expect(fields).toEqual(SCHEMAS[index])
})
- it('reads back the values it writes, in row groups of the given size, with snappy on every column', async () => {
+ it('reads back the values it writes, in row groups of the given size, with zstd on every column', async () => {
const image = {
team_id: 7,
key_month: '2026-10',
@@ -139,7 +139,7 @@ describe('indexRowsToParquet', () => {
await indexRowsToParquet('images', Array(5).fill(image), 2)
)
expect(rowGroups).toBe(3)
- expect(codecs).toEqual(Array(3 * 8).fill(CompressionCodec.SNAPPY))
+ expect(codecs).toEqual(Array(3 * 8).fill(CompressionCodec.ZSTD))
expect(rows).toEqual(Array(5).fill({ ...image, team_id: 7n, byte_start: 0n, byte_end: 99n, byte_size: 60n }))
})
@@ -168,10 +168,32 @@ describe('indexRowsToParquet', () => {
const { rows } = await describeFile(file)
expect((rows as Record<string, unknown>[])[0]).toMatchObject({ urls, urls_truncated: false })
- // Snappy cannot shrink random base64, so the file is about one copy of the value.
+ // Zstd shrinks random base64 by about a quarter, so a second copy in the statistics would break this bound.
expect(file.length).toBeLessThan(urls.length * 1.1)
})
+ it('writes blocks in (team_id, session_id, first_ts_ms) order, with a null first_ts_ms last', async () => {
+ const at = (team_id: number, session_id: string, first_ts_ms: number | null): Record<string, unknown> => ({
+ ...block([], []),
+ team_id,
+ session_id,
+ first_ts_ms,
+ })
+ const arrival = [at(10, 'a', 1), at(2, 'b', null), at(2, 'b', 30), at(2, 'a', 5), at(2, 'b', 4)]
+
+ const { rows } = await describeFile(await indexRowsToParquet('blocks', arrival, 1_000))
+
+ expect(
+ (rows as Record<string, unknown>[]).map((row) => [row.team_id, row.session_id, row.first_ts_ms ?? null])
+ ).toEqual([
+ [2n, 'a', 5n],
+ [2n, 'b', 4n],
+ [2n, 'b', 30n],
+ [2n, 'b', null],
+ [10n, 'a', 1n],
+ ])
+ })
+
it('reads moments back as a list of structs and the string lists as lists', async () => {
const moments = [
{ kind: 'click', window_id: 'w1', ts_ms: 1_000, event_index: 2 ** 31 - 1 },
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/parquet-sink-v4/parquet-writer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/parquet-sink-v4/parquet-writer.ts
index 3d23e79394c8..c4960c53a18c 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/parquet-sink-v4/parquet-writer.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/parquet-sink-v4/parquet-writer.ts
@@ -1,23 +1,36 @@
-/** Encodes v4 index rows into a Snappy-compressed Parquet buffer, with the types of the COLUMNS table. */
+/** Encodes v4 index rows into a zstd-compressed Parquet buffer, with the types of the COLUMNS table. */
import { ParquetSchema } from '@dsnp/parquetjs'
+import { PARQUET_COMPRESSION_METHODS } from '@dsnp/parquetjs/dist/lib/compression'
+import { promisify } from 'node:util'
+import { constants, zstdCompress, zstdDecompress } from 'node:zlib'
import { INDEX_COLUMNS, ParquetType, V4Column, V4Index, V4IndexRow } from './index-columns'
import { parquetRecordsToBuffer } from './parquet-buffer'
type SchemaDef = ConstructorParameters<typeof ParquetSchema>[0]
-// Snappy on every column: compression is a per-field option in parquetjs, not a writer option.
+const ZSTD_LEVEL = 9
+const zstdCompressAsync = promisify(zstdCompress)
+const zstdDecompressAsync = promisify(zstdDecompress)
+
+// parquetjs ships no zstd codec and takes compression per field, not per writer. Its codec table is open and its Thrift enum has ZSTD, so the file records the right codec.
+PARQUET_COMPRESSION_METHODS.ZSTD = {
+ deflate: (value: Buffer) =>
+ zstdCompressAsync(value, { params: { [constants.ZSTD_c_compressionLevel]: ZSTD_LEVEL } }),
+ inflate: (value: Buffer) => zstdDecompressAsync(value),
+}
+
function schemaDef(columns: readonly V4Column[]): SchemaDef {
const def: Record<string, unknown> = {}
for (const column of columns) {
if ('repeated' in column) {
def[column.name] = { repeated: true, fields: schemaDef(column.fields) }
} else if ('list' in column) {
- def[column.name] = { type: column.list, repeated: true, compression: 'SNAPPY' }
+ def[column.name] = { type: column.list, repeated: true, compression: 'ZSTD' }
} else {
def[column.name] = {
type: column.type,
- compression: 'SNAPPY',
+ compression: 'ZSTD',
...(column.optional && { optional: true }),
...(column.opaque && { statistics: false }),
}
@@ -31,6 +44,24 @@ const SCHEMAS: Record<V4Index, ParquetSchema> = {
images: new ParquetSchema(schemaDef(INDEX_COLUMNS.images)),
}
+const compareStrings = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0)
+
+const compareNumbersNullsLast = (a: number | null, b: number | null): number =>
+ a === b ? 0 : a === null ? 1 : b === null ? -1 : a - b
+
+function compareBlocks(a: V4IndexRow, b: V4IndexRow): number {
+ return (
+ (a.team_id as number) - (b.team_id as number) ||
+ compareStrings(a.session_id as string, b.session_id as string) ||
+ compareNumbersNullsLast(a.first_ts_ms as number | null, b.first_ts_ms as number | null)
+ )
+}
+
+/** Puts a session's blocks next to each other, so its repeated session and window ids compress to almost nothing. */
+function inFileOrder(index: V4Index, rows: readonly V4IndexRow[]): readonly V4IndexRow[] {
+ return index === 'blocks' ? [...rows].sort(compareBlocks) : rows
+}
+
function toValue(type: ParquetType, value: unknown): unknown {
return type === 'INT64' ? BigInt(value as number) : value
}
@@ -56,7 +87,7 @@ export function indexRowsToParquet(index: V4Index, rows: readonly V4IndexRow[],
const columns = INDEX_COLUMNS[index]
return parquetRecordsToBuffer(
SCHEMAS[index],
- rows.map((row) => toRecord(row, columns)),
+ inFileOrder(index, rows).map((row) => toRecord(row, columns)),
{ rowGroupSize }
)
}
diff --git a/products/ai_training/docs/replay-data.md b/products/ai_training/docs/replay-data.md
index 59464e038376..8bd015781d0f 100644
--- a/products/ai_training/docs/replay-data.md
+++ b/products/ai_training/docs/replay-data.md
@@ -496,7 +496,7 @@ The recorder does not write the two index prefixes itself, as in v3:
- After a flush stores its packs and blocks, the recorder sends one JSON record per index row to `ai_research_v4_index`. The record's keys are the Parquet column names.
- The recorder commits without waiting for delivery. A row that is not delivered leaves its block or image stored but not in the index.
- The v4 Parquet sink reads the topic, groups the rows by index and write day, and writes one file per group and flush as `{ms}-{random}.parquet`. A flush runs every 10 minutes, or at 128 MiB of rows or 1,000,000 rows. The sink commits its offsets only after the files are stored.
-- Index files use four column types: `INT32`, `INT64`, `UTF8` and `BOOLEAN`. Integers are signed. The recorder caps an `INT32` value at the type's range and an `INT64` value at ±(2^53 − 1), so every value is a safe JavaScript integer. It ignores an event timestamp outside the JavaScript date range. Byte counts, offsets and times are `INT64`, the other counts `INT32`. `moments` is a repeated group whose item is named `moments`; an Arrow reader sees a list of structs. `url_fingerprints` and `window_ids` are lists of `UTF8` with no null items. Row groups hold 131072 rows, and every column is snappy-compressed. The sink writes no statistics for `urls`, because a sealed value has no useful order.
+- Index files use four column types: `INT32`, `INT64`, `UTF8` and `BOOLEAN`. Integers are signed. The recorder caps an `INT32` value at the type's range and an `INT64` value at ±(2^53 − 1), so every value is a safe JavaScript integer. It ignores an event timestamp outside the JavaScript date range. Byte counts, offsets and times are `INT64`, the other counts `INT32`. `moments` is a repeated group whose item is named `moments`; an Arrow reader sees a list of structs. `url_fingerprints` and `window_ids` are lists of `UTF8` with no null items. Row groups hold 131072 rows, and every column is zstd-compressed at level 9. Older files can still be snappy-compressed and in arrival order until they expire; Parquet records the codec per column chunk, so a reader handles both. The sink writes no statistics for `urls`, because a sealed value has no useful order.
- The sink can write a row twice after a restart. The copies have the same `flush_id`, so the rule below does not remove them: readers first drop rows that repeat within one `flush_id`.
### Block index
@@ -516,6 +516,9 @@ Readers drop duplicates with one rule per (`topic`, `partition`), applied to all
A flush keeps or loses its whole range. When two flushes overlap, the reader keeps only the one it reaches first, even when their ranges differ in size, so it never merges parts of two flushes.
+Each file holds its rows in (`team_id`, `session_id`, `first_ts_ms`) order, with a null `first_ts_ms` last, so the blocks of a session in one file are adjacent and in time order.
+The order holds only within a file. The blocks of a session spread over many files and write days, and a file is usually one row group, so its min and max statistics do not narrow a lookup.
+
A reader that needs whole sessions selects them by the start time in the session UUIDv7, not by write day:
- Read the write days from the UTC day of `start - 1 day` onward. The recorder admits a session from 1 day before its start until 14 days after it, so no block of a session has an earlier write day.