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.

fix(ai-research): compress ML blocks with the native brotli encoder (#110653)

Robbie8e31d5d3cc07
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-compression.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-compression.test.ts
new file mode 100644
index 000000000000..2052dc397be1
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-compression.test.ts
@@ -0,0 +1,40 @@
+import { brotliCompressSync, constants } from 'node:zlib'
+
+import { logger } from '~/common/utils/logger'
+import { compressBlock } from '~/ingestion/pipelines/sessionreplay/sessions/block-compression'
+
+import { ML_BLOCK_COMPRESSION } from './block-compression'
+
+let addonLoaded = false
+try {
+ require('@posthog/replay-anonymizer')
+ addonLoaded = true
+} catch (e) {
+ if (process.env.CI) {
+ throw new Error(`replay-anonymizer addon failed to load; the ML block compression test cannot run in CI: ${e}`)
+ }
+ logger.warn('🙈', 'replay_anonymizer_addon_not_built_skipping_ml_block_compression_test')
+}
+
+const describeAddon = addonLoaded ? describe : describe.skip
+describeAddon('ML block compression', () => {
+ it('writes the same bytes as zlib at the same quality', async () => {
+ const block = Buffer.from(
+ Array.from({ length: 3000 }, (_, i) =>
+ JSON.stringify({
+ type: 3,
+ timestamp: 1_700_000_000_000 + i * 16,
+ data: { source: 1, positions: [{ x: (i * 37) % 1280, y: (i * 91) % 720, id: i % 53 }] },
+ })
+ ).join('\n')
+ )
+
+ const zlibBytes = brotliCompressSync(block, {
+ params: {
+ [constants.BROTLI_PARAM_QUALITY]: ML_BLOCK_COMPRESSION.level,
+ [constants.BROTLI_PARAM_SIZE_HINT]: block.length,
+ },
+ })
+ expect(Buffer.compare(await compressBlock(block, ML_BLOCK_COMPRESSION), zlibBytes)).toBe(0)
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-compression.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-compression.ts
index a52e4faa58a0..dc2b21710c3d 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-compression.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-compression.ts
@@ -1,9 +1,18 @@
import { BlockCompression } from '~/ingestion/pipelines/sessionreplay/sessions/block-compression'
+import { getRustAnonymizer } from './rust-anonymizer'
+
/**
* Measured 2026-09-19 on 1500 production blocks: quality 9 stores 0.53 of snappy for 25 times its CPU, and beats zstd
* level 19 on both counts. Quality 5 stores 6% more for 46% of the CPU. Quality 11 stores 6% less, but costs 47 times
* quality 9 and needs more packing throughput than the threadpool gives. This lane reads a block rarely and keeps it
* for months, so it takes the bytes.
+ *
+ * The addon runs the same C encoder as zlib and writes the same bytes. zlib reports the encoder's working memory at
+ * quality 9 to V8 as external memory, which caused most of this lane's full GCs in October 2026.
*/
-export const ML_BLOCK_COMPRESSION = { codec: 'brotli', level: 9 } as const satisfies BlockCompression
+export const ML_BLOCK_COMPRESSION = {
+ codec: 'brotli',
+ level: 9,
+ encoder: (data, quality) => getRustAnonymizer().compressBrotli(data, quality),
+} as const satisfies BlockCompression
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/block-compression.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/block-compression.ts
index 483eb0e8c693..bb1338e5d727 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/block-compression.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/block-compression.ts
@@ -1,16 +1,22 @@
import { brotliCompress, constants } from 'node:zlib'
import snappy from 'snappy'
-export type BlockCompression = { codec: 'brotli'; level: number } | { codec: 'snappy' }
+export type BrotliEncoder = (data: Buffer, quality: number) => Promise<Buffer>
+
+/** A brotli `encoder` replaces Node's zlib and must write a stream that zlib can decompress. */
+export type BlockCompression = { codec: 'brotli'; level: number; encoder?: BrotliEncoder } | { codec: 'snappy' }
export const DEFAULT_BLOCK_COMPRESSION: BlockCompression = { codec: 'snappy' }
/** Both codecs pack on the libuv threadpool, not on the event loop. */
-export function compressBlock(data: Buffer, compression: BlockCompression): Promise<Buffer> {
+export async function compressBlock(data: Buffer, compression: BlockCompression): Promise<Buffer> {
switch (compression.codec) {
case 'snappy':
return snappy.compress(data)
case 'brotli':
+ if (compression.encoder) {
+ return compression.encoder(data, compression.level)
+ }
return new Promise((resolve, reject) => {
// We tried setting LGWIN:24, but this performed worse than leaving it unset. Just leave this unset
// and let Brotli choose a good enough value.
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index bd6b2e7285b0..a96bbc916774 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2026,6 +2026,24 @@ dependencies = [
"alloc-stdlib 0.3.0",
]
+[[package]]
+name = "brotlic"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f552f56f302af0006c32b50bfa2bdb4696fd6ba33c3ab9f6225fefdb1efdc680"
+dependencies = [
+ "brotlic-sys",
+]
+
+[[package]]
+name = "brotlic-sys"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "afdec5c62bc97b56349053cf66ba503af5c2448591be61c3ad70a5f11b57e574"
+dependencies = [
+ "cc",
+]
+
[[package]]
name = "brownstone"
version = "3.0.0"
@@ -10767,6 +10785,7 @@ checksum = "51743d3e274e2b18df81c4dc6caf8a5b8e15dbe799e0dca05c7617380094e884"
name = "replay-anonymizer-node"
version = "0.0.1"
dependencies = [
+ "brotlic",
"lru",
"neon",
"posthog-replay-anonymizer",
diff --git a/rust/replay-anonymizer-node/Cargo.toml b/rust/replay-anonymizer-node/Cargo.toml
index 854f610e5a38..daa37e6458af 100644
--- a/rust/replay-anonymizer-node/Cargo.toml
+++ b/rust/replay-anonymizer-node/Cargo.toml
@@ -15,6 +15,7 @@ crate-type = ["cdylib"]
neon = { workspace = true, features = ["external-buffers"] }
# default-features = false: the offline typed-parse module has no place in the ingestion cdylib.
posthog-replay-anonymizer = { path = "../replay-anonymizer", default-features = false }
+brotlic = "0.8"
lru = "0.12"
serde = { workspace = true }
serde_json = { workspace = true }
diff --git a/rust/replay-anonymizer-node/src/brotli.rs b/rust/replay-anonymizer-node/src/brotli.rs
new file mode 100644
index 000000000000..5d47f59f179a
--- /dev/null
+++ b/rust/replay-anonymizer-node/src/brotli.rs
@@ -0,0 +1,51 @@
+use brotlic::{CompressionMode, Quality, WindowSize};
+
+/// Node's zlib default window, so the output matches `zlib.brotliCompress` byte for byte.
+const WINDOW_BITS: u8 = 22;
+
+pub fn compress(input: &[u8], quality: u8) -> Result<Vec<u8>, String> {
+ let invalid_quality = || format!("brotli quality must be from 2 to 11, got {quality}");
+ let quality = Quality::new(quality).map_err(|_| invalid_quality())?;
+ let max_compressed_size =
+ brotlic::compress_bound(input.len(), quality).ok_or_else(invalid_quality)?;
+
+ let mut output = vec![0u8; max_compressed_size];
+ let written = brotlic::compress(
+ input,
+ &mut output,
+ quality,
+ WindowSize::new(WINDOW_BITS).expect("22 is a valid brotli window"),
+ CompressionMode::Generic,
+ )
+ .map_err(|error| format!("brotli compression failed: {error}"))?;
+ output.truncate(written);
+ output.shrink_to_fit();
+ Ok(output)
+}
+
+#[cfg(test)]
+mod tests {
+ use std::io::Read;
+
+ use super::*;
+
+ #[test]
+ fn incompressible_input_round_trips() {
+ let mut state = 0x9E37_79B9_7F4A_7C15u64;
+ let incompressible: Vec<u8> = (0..200_000)
+ .map(|_| {
+ state ^= state << 13;
+ state ^= state >> 7;
+ state ^= state << 17;
+ (state >> 56) as u8
+ })
+ .collect();
+ let compressed = compress(&incompressible, 9).unwrap();
+
+ let mut decoded = Vec::new();
+ brotlic::DecompressorReader::new(compressed.as_slice())
+ .read_to_end(&mut decoded)
+ .unwrap();
+ assert_eq!(decoded, incompressible);
+ }
+}
diff --git a/rust/replay-anonymizer-node/src/index.ts b/rust/replay-anonymizer-node/src/index.ts
index cba2ffbfbba8..8aea491d0f70 100644
--- a/rust/replay-anonymizer-node/src/index.ts
+++ b/rust/replay-anonymizer-node/src/index.ts
@@ -315,3 +315,8 @@ export function canonicalizeUrl(url: string): CanonicalUrl | null {
const verdict = tryCanonicalizeUrl(url)
return verdict.ok ? verdict.url : null
}
+
+/** The same bytes as `zlib.brotliCompress` at this quality with a size hint of `data.length`. */
+export function compressBrotli(data: Buffer, quality: number): Promise<Buffer> {
+ return native.compressBrotli(data, quality)
+}
diff --git a/rust/replay-anonymizer-node/src/lib.rs b/rust/replay-anonymizer-node/src/lib.rs
index ea5e33a70847..019caff0caa6 100644
--- a/rust/replay-anonymizer-node/src/lib.rs
+++ b/rust/replay-anonymizer-node/src/lib.rs
@@ -11,6 +11,7 @@
//! inputs in place in typed arrays that the sidecar allocates, and the produce lanes' ref dedup
//! caches (`dedup`), which hold their entries outside the V8 heap.
+mod brotli;
mod dedup;
mod pixels;
@@ -606,6 +607,23 @@ fn ref_dedup_cache_stats(mut cx: FunctionContext) -> JsResult<JsObject> {
Ok(result)
}
+fn compress_brotli_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {
+ let input = cx.argument::<JsBuffer>(0)?.as_slice(&cx).to_vec();
+ let quality = cx.argument::<JsNumber>(1)?.value(&mut cx);
+ if !(quality.fract() == 0.0 && (2.0..=11.0).contains(&quality)) {
+ return cx.throw_range_error(format!(
+ "brotli quality must be an integer from 2 to 11, got {quality}"
+ ));
+ }
+ let promise = cx
+ .task(move || brotli::compress(&input, quality as u8))
+ .promise(|mut cx, compressed| match compressed {
+ Ok(compressed) => Ok(JsBuffer::external(&mut cx, compressed)),
+ Err(error) => cx.throw_error(error),
+ });
+ Ok(promise)
+}
+
#[neon::main]
fn main(mut cx: ModuleContext) -> NeonResult<()> {
cx.export_function("initAnonymizer", init_anonymizer)?;
@@ -628,6 +646,7 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> {
ref_dedup_cache_release_transport_urls,
)?;
cx.export_function("refDedupCacheStats", ref_dedup_cache_stats)?;
+ cx.export_function("compressBrotli", compress_brotli_ffi)?;
Ok(())
}