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(warehouse-sources): spill large cdc transactions to disk instead of failing (#104729)

Daniel RC76ffd3d02840
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
index 1675d5048044..030f18801a62 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
@@ -150,9 +150,8 @@ CDC_BACKPRESSURE_STUCK_AGE = dt.timedelta(hours=2)
# re-decodes from the slot start on every retry. The slot advances after each pass, so the next
# peek resumes where this one stopped.
CDC_MAX_CHANGES_PER_READ = 100_000
-# Ceiling for the adaptive growth below. The decoder's MAX_TX_BUFFER_EVENTS (500k) is the real
-# bound on an oversized single transaction — it trips before the window doubles far past it — so
-# this only needs a little headroom above that guard.
+# Ceiling for the adaptive growth below. A peek never splits a transaction, so this window does not
+# bound a large one; the decoder spills it to disk, capped by MAX_TX_BUFFER_EVENTS and MAX_TX_SPILL_BYTES.
CDC_MAX_CHANGES_LIMIT_CAP = 800_000
# Stop starting new peeks past this wall-clock so the final flush + slot advance fit inside the
# activity's 2h start-to-close timeout (see CDCExtractionWorkflow). The remainder is picked up on
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.py
index 5ead31b49853..fa34fa52b98a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/errors.py
@@ -49,7 +49,7 @@ class CDCErrorInfo:
class CDCTransactionTooLargeError(Exception):
- """A single source transaction exceeded the in-memory decode budget.
+ """A single source transaction exceeded the decoder's per-transaction caps (changes, spill bytes or decode time).
Non-retryable: re-decoding replays the same oversized transaction. The decoder guard
that raises this lives in the source-specific decoder; the type is defined here so the
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py
index 6a21da38d863..c39b8ceb758e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py
@@ -10,7 +10,7 @@ References:
Message types handled:
B (Begin) - Start of a transaction
- C (Commit) - End of a transaction; flushes buffered events
+ C (Commit) - End of a transaction; yields its buffered or spilled events
R (Relation) - Schema metadata for a relation (table)
I (Insert) - New row
U (Update) - Updated row
@@ -20,15 +20,21 @@ Message types handled:
from __future__ import annotations
+import json
+import time
+import shutil
import struct
import logging
+import tempfile
+import threading
+from collections.abc import Iterable, Iterator, Mapping
from dataclasses import (
dataclass,
field,
replace as dataclass_replace,
)
from datetime import UTC, datetime
-from typing import Any
+from typing import IO, Any
import pyarrow as pa
@@ -38,11 +44,83 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.c
logger = logging.getLogger(__name__)
-# A transaction is buffered entirely in memory until its COMMIT, when every event is yielded
-# at once. Cap the buffer so a single pathologically large transaction can't OOM the worker;
-# the orchestration layer classifies CDCTransactionTooLargeError as a non-retryable failure.
-# Spill-to-disk is out of scope.
-MAX_TX_BUFFER_EVENTS = 500_000
+# A transaction's position is its COMMIT end LSN, which pgoutput sends only after the last change,
+# so every change of a transaction is held until then. The decoder keeps up to this many changes in
+# memory and writes each full chunk to a local temporary file. A bulk INSERT, UPDATE or DELETE then
+# costs worker disk, not worker memory, and COMMIT streams the chunks back one at a time.
+TX_SPILL_CHUNK_EVENTS = 50_000
+# Both bound the temporary file on the worker's local disk: the byte cap covers wide rows, which
+# fill the disk long before the change count trips. The orchestration layer classifies
+# CDCTransactionTooLargeError as a non-retryable failure.
+MAX_TX_BUFFER_EVENTS = 50_000_000
+MAX_TX_SPILL_BYTES = 64 * 1024**3
+# A transaction must finish inside one capture attempt, which a timeout would retry from the start
+# forever, so decoding one that runs past this fails it as too large instead.
+MAX_TX_DECODE_SECONDS = 60 * 60
+# Every capture on a worker spills to the same scratch volume, which other warehouse activities also
+# use. Open spill files together stay under this share of the volume, so concurrent large
+# transactions cannot fill it.
+WORKER_SPILL_BUDGET_FRACTION = 0.5
+
+
+class CDCSpillBudgetExhaustedError(Exception):
+ """Other transactions on this worker hold the shared spill budget.
+
+ Retryable: the space frees when those transactions commit or fail.
+ """
+
+
+class _WorkerSpillBudget:
+ """Bytes held by open spill files across every decoder in this worker process."""
+
+ def __init__(self, limit: int | None = None) -> None:
+ self._lock = threading.Lock()
+ self._limit = limit
+ self._used = 0
+
+ @property
+ def limit(self) -> int:
+ if self._limit is None:
+ self._limit = int(shutil.disk_usage(tempfile.gettempdir()).total * WORKER_SPILL_BUDGET_FRACTION)
+ return self._limit
+
+ def reserve(self, size: int) -> bool:
+ limit = self.limit
+ with self._lock:
+ if self._used + size > limit:
+ return False
+ self._used += size
+ return True
+
+ def release(self, size: int) -> None:
+ with self._lock:
+ self._used -= size
+
+
+_worker_spill_budget = _WorkerSpillBudget()
+
+
+class _SpillFile:
+ """A transaction's spill file and its share of the worker budget, released together on close."""
+
+ def __init__(self, budget: _WorkerSpillBudget) -> None:
+ self.file: IO[bytes] = tempfile.TemporaryFile()
+ self.bytes = 0
+ self._budget = budget
+
+ def write(self, line: bytes) -> bool:
+ if not self._budget.reserve(len(line)):
+ return False
+ # Counted before the write, so close() releases the reservation even when the write fails.
+ self.bytes += len(line)
+ self.file.write(line)
+ return True
+
+ def close(self) -> None:
+ self.file.close()
+ self._budget.release(self.bytes)
+ self.bytes = 0
+
# PostgreSQL epoch: 2000-01-01 00:00:00 UTC
# Timestamps in pgoutput are microseconds since this epoch
@@ -101,8 +179,9 @@ class PgOutputDecoder:
"""Stateful decoder for pgoutput binary messages.
Maintains a relation cache (updated by R messages) and a transaction
- buffer (events collected between B and C messages). Events are only
- yielded when a Commit message is received, ensuring atomic transactions.
+ buffer (events collected between B and C messages, spilled to a temporary
+ file past TX_SPILL_CHUNK_EVENTS). Events are only yielded when a Commit
+ message is received, because only the Commit carries their position.
Usage:
decoder = PgOutputDecoder()
@@ -115,15 +194,22 @@ class PgOutputDecoder:
def __init__(self) -> None:
self._relations: dict[int, Relation] = {}
self._tx_buffer: list[ChangeEvent] = []
+ self._tx_spill: _SpillFile | None = None
+ self._tx_started_at = 0.0
+ # The spill a committed transaction is still replaying from, so close() can release it.
+ self._replay_spill: _SpillFile | None = None
+ # Column types are shared per relation, so a spilled line stores an index into this list.
+ self._tx_spill_types: list[Mapping[str, pa.DataType] | None] = []
+ self._tx_event_count = 0
self._tx_timestamp: datetime | None = None
self._truncated_tables: list[str] = []
self._last_commit_end_lsn: str | None = None
- def decode_message(self, data: bytes, lsn: str) -> list[ChangeEvent]:
+ def decode_message(self, data: bytes, lsn: str) -> Iterable[ChangeEvent]:
"""Decode a single pgoutput binary message.
- Returns a list of ChangeEvents. Only non-empty on Commit messages
- (transaction boundary), when all buffered events are flushed.
+ Returns the transaction's ChangeEvents on a Commit message and nothing otherwise. Consume
+ the result before decoding the next message: a spilled transaction is read back lazily.
"""
if not data:
return []
@@ -175,9 +261,10 @@ class PgOutputDecoder:
# xid = struct.unpack("!I", payload[16:20])[0] # not needed
self._tx_timestamp = _pg_timestamp_to_datetime(timestamp_us)
- self._tx_buffer.clear()
+ self._reset_transaction()
+ self._tx_started_at = time.monotonic()
- def _handle_commit(self, payload: bytes) -> list[ChangeEvent]:
+ def _handle_commit(self, payload: bytes) -> Iterable[ChangeEvent]:
"""C message: flags(1) + commit_lsn(8) + end_lsn(8) + timestamp(8)
Flushes the transaction buffer. Events are stamped with end_lsn — the
@@ -187,10 +274,38 @@ class PgOutputDecoder:
# end_lsn starts at byte 9: flags(1) + commit_lsn(8)
end_lsn = PgLSN.from_bytes(payload[9:17]).serialize()
self._last_commit_end_lsn = end_lsn
- events = [dataclass_replace(e, position_serialized=end_lsn) for e in self._tx_buffer]
- self._tx_buffer.clear()
+ self._check_decode_time()
+ spill, tail, types = self._tx_spill, self._tx_buffer, self._tx_spill_types
+ self._tx_spill = None
+ self._reset_transaction()
self._tx_timestamp = None
- return events
+ if spill is None:
+ return [dataclass_replace(e, position_serialized=end_lsn) for e in tail]
+ # A caller that abandoned the previous replay would otherwise keep its budget share.
+ if self._replay_spill is not None:
+ self._replay_spill.close()
+ self._replay_spill = spill
+ return _replay_spilled_transaction(spill, types, tail, end_lsn)
+
+ def _check_decode_time(self) -> None:
+ if time.monotonic() - self._tx_started_at > MAX_TX_DECODE_SECONDS:
+ self._reset_transaction()
+ raise CDCTransactionTooLargeError(f"Transaction took more than {MAX_TX_DECODE_SECONDS}s to decode")
+
+ def close(self) -> None:
+ """Release a spill file left by a read that failed before its transaction committed or finished replaying."""
+ self._reset_transaction()
+ if self._replay_spill is not None:
+ self._replay_spill.close()
+ self._replay_spill = None
+
+ def _reset_transaction(self) -> None:
+ if self._tx_spill is not None:
+ self._tx_spill.close()
+ self._tx_spill = None
+ self._tx_spill_types = []
+ self._tx_buffer = []
+ self._tx_event_count = 0
def _handle_relation(self, payload: bytes) -> None:
"""R message: relation_id(4) + namespace(str) + name(str) + replica_identity(1) + n_cols(2) + columns"""
@@ -399,11 +514,80 @@ class PgOutputDecoder:
def _buffer_event(self, event: ChangeEvent) -> None:
"""Buffer a decoded change until COMMIT, guarding against an unbounded transaction."""
- self._tx_buffer.append(event)
- if len(self._tx_buffer) > MAX_TX_BUFFER_EVENTS:
+ self._tx_event_count += 1
+ if self._tx_event_count > MAX_TX_BUFFER_EVENTS:
+ self._reset_transaction()
raise CDCTransactionTooLargeError(
f"Transaction buffered more than {MAX_TX_BUFFER_EVENTS} changes before COMMIT"
)
+ self._tx_buffer.append(event)
+ if len(self._tx_buffer) >= TX_SPILL_CHUNK_EVENTS:
+ self._spill_buffer()
+
+ def _spill_buffer(self) -> None:
+ """Append the in-memory chunk to the spill file as JSON lines, one change per line.
+
+ Decoded values are only bool, int, float, str or None, so JSON round-trips them exactly.
+ """
+ self._check_decode_time()
+ # A transaction larger than the whole worker budget can never fit, so it fails as too large
+ # instead of retrying forever.
+ spill_cap = min(MAX_TX_SPILL_BYTES, _worker_spill_budget.limit)
+ if self._tx_spill is None:
+ self._tx_spill = _SpillFile(_worker_spill_budget)
+ type_index = {id(types): i for i, types in enumerate(self._tx_spill_types)}
+ for event in self._tx_buffer:
+ key = id(event.column_types)
+ if key not in type_index:
+ type_index[key] = len(self._tx_spill_types)
+ self._tx_spill_types.append(event.column_types)
+ line = (
+ json.dumps(
+ [
+ event.operation,
+ event.table_name,
+ event.timestamp.isoformat(),
+ event.columns,
+ sorted(event.omitted_columns),
+ type_index[key],
+ ],
+ ensure_ascii=False,
+ separators=(",", ":"),
+ ).encode()
+ + b"\n"
+ )
+ if self._tx_spill.bytes + len(line) > spill_cap:
+ self._reset_transaction()
+ raise CDCTransactionTooLargeError(f"Transaction spilled more than {spill_cap} bytes before COMMIT")
+ if not self._tx_spill.write(line):
+ self._reset_transaction()
+ raise CDCSpillBudgetExhaustedError(
+ f"Worker spill budget of {_worker_spill_budget.limit} bytes is in use by other transactions"
+ )
+ self._tx_buffer = []
+
+
+def _replay_spilled_transaction(
+ spill: _SpillFile, types: list[Mapping[str, pa.DataType] | None], tail: list[ChangeEvent], end_lsn: str
+) -> Iterator[ChangeEvent]:
+ """Yield a spilled transaction in WAL order, one change at a time: the file, then the in-memory tail."""
+ try:
+ spill.file.seek(0)
+ for line in spill.file:
+ operation, table_name, timestamp, columns, omitted, type_index = json.loads(line)
+ yield ChangeEvent(
+ operation=operation,
+ table_name=table_name,
+ position_serialized=end_lsn,
+ timestamp=datetime.fromisoformat(timestamp),
+ columns=columns,
+ column_types=types[type_index],
+ omitted_columns=frozenset(omitted),
+ )
+ for event in tail:
+ yield dataclass_replace(event, position_serialized=end_lsn)
+ finally:
+ spill.close()
def _read_cstring(data: bytes, offset: int) -> tuple[str, int]:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/stream_reader.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/stream_reader.py
index cce71f669b02..ea0244c0b918 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/stream_reader.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/stream_reader.py
@@ -156,8 +156,8 @@ class PgCDCStreamReader:
``upto_nchanges`` bounds one peek: ``pg_logical_slot_peek_binary_changes`` stops once a
transaction's COMMIT pushes the decoded-change count past it. It never splits a
- transaction, so a single large transaction is still returned in full (the decoder's own
- buffer guard bounds that case). ``None`` reads the whole backlog.
+ transaction, so a single large transaction is still returned in full (the decoder spills it
+ to a temporary file rather than holding it in memory). ``None`` reads the whole backlog.
``on_row`` is invoked once per fetched WAL row so the caller can heartbeat during a long
decode — the decoder yields nothing until a COMMIT, so a big transaction would otherwise
@@ -373,6 +373,7 @@ class PgCDCStreamReader:
return self._last_rows_consumed
def close(self) -> None:
+ self._decoder.close()
if self._conn is not None:
self._conn.close()
self._conn = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py
index 7c7eb9dcd34a..971a42e05e3c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py
@@ -1,12 +1,15 @@
+import io
import struct
from datetime import UTC, datetime
import pytest
+from unittest.mock import MagicMock, patch
import pyarrow as pa
from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.cdc.errors import CDCTransactionTooLargeError
+from products.warehouse_sources.backend.temporal.data_imports.cdc.types import ChangeEvent
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.decoder import (
_OID_BOOL,
_OID_FLOAT8,
@@ -15,10 +18,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.c
_OID_JSONB,
_OID_TEXT,
PG_EPOCH_OFFSET_US,
+ CDCSpillBudgetExhaustedError,
PgOutputDecoder,
Relation,
RelationColumn,
_pg_timestamp_to_datetime,
+ _WorkerSpillBudget,
)
_DECODER_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.decoder"
@@ -148,10 +153,10 @@ class TestPgOutputDecoder:
begin = _make_begin()
commit = _make_commit()
- events = decoder.decode_message(begin, "0/100")
+ events = list(decoder.decode_message(begin, "0/100"))
assert events == []
- events = decoder.decode_message(commit, "0/200")
+ events = list(decoder.decode_message(commit, "0/200"))
assert events == []
def test_event_table_name_is_schema_qualified(self):
@@ -163,7 +168,7 @@ class TestPgOutputDecoder:
)
decoder.decode_message(_make_begin(), "0/100")
decoder.decode_message(_make_insert(7, [("t", "1")]), "0/150")
- events = decoder.decode_message(_make_commit(), "0/200")
+ events = list(decoder.decode_message(_make_commit(), "0/200"))
assert len(events) == 1
assert events[0].table_name == "public.cdc_test_orders"
@@ -177,7 +182,7 @@ class TestPgOutputDecoder:
decoder.decode_message(begin, "0/100")
decoder.decode_message(insert, "0/150")
- events = decoder.decode_message(commit, "0/200")
+ events = list(decoder.decode_message(commit, "0/200"))
assert len(events) == 1
event = events[0]
@@ -195,7 +200,7 @@ class TestPgOutputDecoder:
decoder.decode_message(begin, "0/100")
decoder.decode_message(update, "0/150")
- events = decoder.decode_message(commit, "0/200")
+ events = list(decoder.decode_message(commit, "0/200"))
assert len(events) == 1
event = events[0]
@@ -217,7 +222,7 @@ class TestPgOutputDecoder:
decoder.decode_message(begin, "0/100")
decoder.decode_message(update, "0/150")
- events = decoder.decode_message(commit, "0/200")
+ events = list(decoder.decode_message(commit, "0/200"))
assert len(events) == 1
assert events[0].operation == "U"
@@ -232,7 +237,7 @@ class TestPgOutputDecoder:
decoder.decode_message(begin, "0/100")
decoder.decode_message(delete, "0/150")
- events = decoder.decode_message(commit, "0/200")
+ events = list(decoder.decode_message(commit, "0/200"))
assert len(events) == 1
event = events[0]
@@ -252,7 +257,7 @@ class TestPgOutputDecoder:
decoder.decode_message(begin, "0/100")
decoder.decode_message(insert, "0/150")
- events = decoder.decode_message(commit, "0/200")
+ events = list(decoder.decode_message(commit, "0/200"))
assert len(events) == 1
assert events[0].columns["id"] == 1
@@ -277,7 +282,7 @@ class TestPgOutputDecoder:
decoder.decode_message(
_make_insert(1, [("t", "1"), ("t", "5"), ("t", "9.5"), ("t", "t"), ("t", "{}"), ("t", "x")]), "0/150"
)
- events = decoder.decode_message(_make_commit(), "0/200")
+ events = list(decoder.decode_message(_make_commit(), "0/200"))
assert events[0].column_types == {
"id": pa.int64(),
@@ -298,7 +303,7 @@ class TestPgOutputDecoder:
decoder.decode_message(begin, "0/100")
decoder.decode_message(update, "0/150")
- events = decoder.decode_message(commit, "0/200")
+ events = list(decoder.decode_message(commit, "0/200"))
assert len(events) == 1
assert events[0].columns["id"] == 1
@@ -320,7 +325,7 @@ class TestPgOutputDecoder:
old_marker=b"O",
)
decoder.decode_message(update, "0/150")
- events = decoder.decode_message(_make_commit(), "0/200")
+ events = list(decoder.decode_message(_make_commit(), "0/200"))
assert len(events) == 1
assert events[0].columns["big_text"] == "big toasted value"
@@ -335,13 +340,13 @@ class TestPgOutputDecoder:
insert3 = _make_insert(1, [("t", "3")])
# Events should NOT be returned until Commit
- assert decoder.decode_message(begin, "0/100") == []
- assert decoder.decode_message(insert1, "0/110") == []
- assert decoder.decode_message(insert2, "0/120") == []
- assert decoder.decode_message(insert3, "0/130") == []
+ assert list(decoder.decode_message(begin, "0/100")) == []
+ assert list(decoder.decode_message(insert1, "0/110")) == []
+ assert list(decoder.decode_message(insert2, "0/120")) == []
+ assert list(decoder.decode_message(insert3, "0/130")) == []
commit = _make_commit()
- events = decoder.decode_message(commit, "0/200")
+ events = list(decoder.decode_message(commit, "0/200"))
assert len(events) == 3
assert [e.columns["id"] for e in events] == [1, 2, 3]
@@ -352,12 +357,12 @@ class TestPgOutputDecoder:
# Transaction 1
decoder.decode_message(_make_begin(), "0/100")
decoder.decode_message(_make_insert(1, [("t", "1")]), "0/110")
- events1 = decoder.decode_message(_make_commit(), "0/200")
+ events1 = list(decoder.decode_message(_make_commit(), "0/200"))
# Transaction 2
decoder.decode_message(_make_begin(), "0/300")
decoder.decode_message(_make_insert(1, [("t", "2")]), "0/310")
- events2 = decoder.decode_message(_make_commit(), "0/400")
+ events2 = list(decoder.decode_message(_make_commit(), "0/400"))
assert len(events1) == 1
assert events1[0].columns["id"] == 1
@@ -378,7 +383,7 @@ class TestPgOutputDecoder:
_make_insert(1, [("t", "10"), ("t", "20"), ("t", "99.5")]),
"0/110",
)
- events = decoder.decode_message(_make_commit(), "0/200")
+ events = list(decoder.decode_message(_make_commit(), "0/200"))
assert len(events) == 1
assert events[0].columns["tenant_id"] == 10
@@ -393,7 +398,7 @@ class TestPgOutputDecoder:
_make_insert(1, [("t", "1"), ("t", "日本語テスト 🎉")]),
"0/110",
)
- events = decoder.decode_message(_make_commit(), "0/200")
+ events = list(decoder.decode_message(_make_commit(), "0/200"))
assert len(events) == 1
assert events[0].columns["name"] == "日本語テスト 🎉"
@@ -407,7 +412,7 @@ class TestPgOutputDecoder:
decoder.decode_message(_make_begin(), "0/100")
decoder.decode_message(_make_insert(1, [("t", "1"), ("t", "Alice")]), "0/110")
- events1 = decoder.decode_message(_make_commit(), "0/200")
+ events1 = list(decoder.decode_message(_make_commit(), "0/200"))
assert events1[0].columns == {"id": 1, "name": "Alice"}
@@ -422,7 +427,7 @@ class TestPgOutputDecoder:
_make_insert(1, [("t", "2"), ("t", "Bob"), ("t", "[email protected]")]),
"0/310",
)
- events2 = decoder.decode_message(_make_commit(), "0/400")
+ events2 = list(decoder.decode_message(_make_commit(), "0/400"))
assert events2[0].columns == {"id": 2, "name": "Bob", "email": "[email protected]"}
@@ -448,7 +453,7 @@ class TestPgOutputDecoder:
decoder.decode_message(_make_begin(), "0/100")
decoder.decode_message(_make_insert(1, [("t", "1")]), "0/110")
decoder.decode_message(_make_insert(2, [("t", "100"), ("t", "1")]), "0/120")
- events = decoder.decode_message(_make_commit(), "0/200")
+ events = list(decoder.decode_message(_make_commit(), "0/200"))
assert len(events) == 2
assert events[0].table_name == "public.users"
@@ -472,7 +477,7 @@ class TestPgOutputDecoder:
decoder.decode_message(_make_begin(), "0/100")
decoder.decode_message(_make_insert(1, [("t", text_value)]), "0/110")
- events = decoder.decode_message(_make_commit(), "0/200")
+ events = list(decoder.decode_message(_make_commit(), "0/200"))
assert events[0].columns["val"] == expected
@@ -482,18 +487,18 @@ class TestPgOutputDecoder:
decoder.decode_message(_make_begin(), "0/100")
decoder.decode_message(_make_insert(99, [("t", "1")]), "0/110")
- events = decoder.decode_message(_make_commit(), "0/200")
+ events = list(decoder.decode_message(_make_commit(), "0/200"))
assert len(events) == 0
def test_empty_message(self):
decoder = PgOutputDecoder()
- events = decoder.decode_message(b"", "0/100")
+ events = list(decoder.decode_message(b"", "0/100"))
assert events == []
def test_unknown_message_type_ignored(self):
decoder = PgOutputDecoder()
- events = decoder.decode_message(b"Z\x00\x00", "0/100")
+ events = list(decoder.decode_message(b"Z\x00\x00", "0/100"))
assert events == []
def test_mixed_operations_in_transaction(self):
@@ -503,7 +508,7 @@ class TestPgOutputDecoder:
decoder.decode_message(_make_insert(1, [("t", "1"), ("t", "Alice")]), "0/110")
decoder.decode_message(_make_update(1, [("t", "1"), ("t", "Alice Updated")]), "0/120")
decoder.decode_message(_make_delete(1, [("t", "2"), None]), "0/130")
- events = decoder.decode_message(_make_commit(), "0/200")
+ events = list(decoder.decode_message(_make_commit(), "0/200"))
assert len(events) == 3
assert events[0].operation == "I"
@@ -527,38 +532,138 @@ class TestPgTimestamp:
class TestTransactionBufferGuard:
- """A single transaction is buffered fully in memory until COMMIT; the decoder caps it so one
- pathological transaction can't OOM the worker."""
+ _COLUMNS = [("id", _OID_INT4, -1), ("name", _OID_TEXT, -1), ("active", _OID_BOOL, -1), ("score", _OID_FLOAT8, -1)]
def _decoder_with_relation(self) -> PgOutputDecoder:
decoder = PgOutputDecoder()
- decoder.decode_message(_make_relation(1, "public", "users", [("id", _OID_INT4, -1)]), "0/1")
+ decoder.decode_message(_make_relation(1, "public", "users", self._COLUMNS), "0/1")
return decoder
- def test_raises_when_transaction_exceeds_buffer_cap(self, monkeypatch):
- monkeypatch.setattr(f"{_DECODER_MODULE}.MAX_TX_BUFFER_EVENTS", 3)
- decoder = self._decoder_with_relation()
+ def _row(self, i: int) -> list[tuple[str, str] | None]:
+ return [("t", str(i)), None if i % 2 else ("t", f"用户 {i}"), ("t", "t"), ("t", f"{i}.5")]
+
+ def _decode(self, decoder: PgOutputDecoder, messages: list[bytes]) -> list[ChangeEvent]:
decoder.decode_message(_make_begin(), "0/1")
+ for message in messages:
+ assert list(decoder.decode_message(message, "0/1")) == []
+ return list(decoder.decode_message(_make_commit(end_lsn=0x500), "0/2"))
+
+ def _mixed_transaction(self) -> list[bytes]:
+ retyped = [("id", _OID_INT4, -1), ("name", _OID_TEXT, -1), ("active", _OID_BOOL, -1), ("score", _OID_TEXT, -1)]
+ return [
+ *(_make_insert(1, self._row(i)) for i in range(4)),
+ _make_update(1, [("t", "2"), ("u", ""), ("t", "f"), ("t", "9.5")]),
+ _make_relation(1, "public", "users", retyped),
+ *(_make_insert(1, self._row(i)) for i in range(4, 7)),
+ ]
- # Up to the cap buffers without yielding (events flush only on COMMIT).
- for i in range(3):
- assert decoder.decode_message(_make_insert(1, [("t", str(i))]), "0/1") == []
+ @parameterized.expand([("spills_whole_chunks", 4), ("spills_with_a_tail", 3)])
+ def test_a_spilled_transaction_comes_back_identical_at_the_commit_position(self, _name: str, chunk: int) -> None:
+ with patch(f"{_DECODER_MODULE}.TX_SPILL_CHUNK_EVENTS", 100):
+ in_memory = self._decode(self._decoder_with_relation(), self._mixed_transaction())
+ with patch(f"{_DECODER_MODULE}.TX_SPILL_CHUNK_EVENTS", chunk):
+ decoder = self._decoder_with_relation()
+ spilled = self._decode(decoder, self._mixed_transaction())
+ follow_up = self._decode(decoder, [_make_insert(1, self._row(100))])
+
+ assert spilled == in_memory
+ assert {e.position_serialized for e in spilled} == {"0/500"}
+ assert spilled[4].omitted_columns == frozenset({"name"})
+ assert spilled[0].column_types != spilled[-1].column_types
+ assert [e.columns["id"] for e in follow_up] == [100]
- # The change past the cap aborts decoding instead of growing the buffer unbounded.
- with pytest.raises(CDCTransactionTooLargeError):
- decoder.decode_message(_make_insert(1, [("t", "99")]), "0/1")
+ @parameterized.expand(
+ [
+ ("change_count", "MAX_TX_BUFFER_EVENTS", 3),
+ ("spill_bytes", "MAX_TX_SPILL_BYTES", 1),
+ ("larger_than_the_worker_budget", "_worker_spill_budget", _WorkerSpillBudget(limit=1)),
+ ]
+ )
+ def test_raises_when_transaction_exceeds_a_cap(self, _name: str, cap: str, value: object) -> None:
+ with patch(f"{_DECODER_MODULE}.{cap}", value), patch(f"{_DECODER_MODULE}.TX_SPILL_CHUNK_EVENTS", 4):
+ decoder = self._decoder_with_relation()
+ decoder.decode_message(_make_begin(), "0/1")
+ for i in range(3):
+ decoder.decode_message(_make_insert(1, [("t", str(i)), None, None, None]), "0/1")
+
+ with pytest.raises(CDCTransactionTooLargeError):
+ decoder.decode_message(_make_insert(1, [("t", "99"), None, None, None]), "0/1")
+
+ def test_concurrent_transactions_share_the_worker_spill_budget(self) -> None:
+ row = _make_insert(1, [("t", "1"), None, None, None])
+ with patch(f"{_DECODER_MODULE}.TX_SPILL_CHUNK_EVENTS", 1):
+ probe = io.BytesIO()
+ with patch(f"{_DECODER_MODULE}.tempfile.TemporaryFile", return_value=probe):
+ measured = self._decoder_with_relation()
+ measured.decode_message(_make_begin(), "0/1")
+ measured.decode_message(row, "0/1")
+ line = len(probe.getvalue())
+ measured.close()
+
+ with patch(f"{_DECODER_MODULE}._worker_spill_budget", _WorkerSpillBudget(limit=line * 5 // 2)):
+ first, second = self._decoder_with_relation(), self._decoder_with_relation()
+ first.decode_message(_make_begin(), "0/1")
+ first.decode_message(row, "0/1")
+ first.decode_message(row, "0/1")
+ second.decode_message(_make_begin(), "0/1")
+
+ with pytest.raises(CDCSpillBudgetExhaustedError):
+ second.decode_message(row, "0/1")
+
+ assert len(list(first.decode_message(_make_commit(), "0/2"))) == 2
+ assert len(self._decode(second, [row, row])) == 2
+
+ def test_a_failed_spill_write_returns_its_budget_on_close(self) -> None:
+ budget = _WorkerSpillBudget(limit=10_000)
+ full_disk = MagicMock()
+ full_disk.write.side_effect = OSError(28, "No space left on device")
+ with (
+ patch(f"{_DECODER_MODULE}.TX_SPILL_CHUNK_EVENTS", 1),
+ patch(f"{_DECODER_MODULE}._worker_spill_budget", budget),
+ patch(f"{_DECODER_MODULE}.tempfile.TemporaryFile", return_value=full_disk),
+ ):
+ decoder = self._decoder_with_relation()
+ decoder.decode_message(_make_begin(), "0/1")
+ with pytest.raises(OSError):
+ decoder.decode_message(_make_insert(1, [("t", "1"), None, None, None]), "0/1")
+
+ decoder.close()
+
+ assert budget.reserve(10_000)
- def test_cap_is_per_transaction(self, monkeypatch):
- # The buffer clears at each COMMIT, so a long stream of small transactions never trips the cap.
- monkeypatch.setattr(f"{_DECODER_MODULE}.MAX_TX_BUFFER_EVENTS", 2)
- decoder = self._decoder_with_relation()
+ @parameterized.expand([("at_a_spill", 1), ("at_commit", 100)])
+ def test_raises_when_decoding_a_transaction_outlasts_the_time_limit(self, _name: str, chunk: int) -> None:
+ clock = iter([0.0, 3601.0])
+ with (
+ patch(f"{_DECODER_MODULE}.TX_SPILL_CHUNK_EVENTS", chunk),
+ patch(f"{_DECODER_MODULE}.time.monotonic", side_effect=lambda: next(clock)),
+ ):
+ decoder = self._decoder_with_relation()
+ decoder.decode_message(_make_begin(), "0/1")
- for _ in range(3):
+ with pytest.raises(CDCTransactionTooLargeError):
+ decoder.decode_message(_make_insert(1, [("t", "1"), None, None, None]), "0/1")
+ decoder.decode_message(_make_commit(), "0/2")
+
+ @parameterized.expand([("before_commit", False), ("mid_replay", True)])
+ def test_close_releases_the_spill(self, _name: str, committed: bool) -> None:
+ spill = io.BytesIO()
+ with (
+ patch(f"{_DECODER_MODULE}.TX_SPILL_CHUNK_EVENTS", 1),
+ patch(f"{_DECODER_MODULE}.tempfile.TemporaryFile", return_value=spill),
+ ):
+ decoder = self._decoder_with_relation()
decoder.decode_message(_make_begin(), "0/1")
- decoder.decode_message(_make_insert(1, [("t", "1")]), "0/1")
- decoder.decode_message(_make_insert(1, [("t", "2")]), "0/1")
- events = decoder.decode_message(_make_commit(), "0/1")
- assert len(events) == 2
+ decoder.decode_message(_make_insert(1, [("t", "1"), None, None, None]), "0/1")
+ decoder.decode_message(_make_insert(1, [("t", "2"), None, None, None]), "0/1")
+ if committed:
+ replay = iter(decoder.decode_message(_make_commit(), "0/2"))
+ next(replay)
+ assert not spill.closed
+
+ decoder.close()
+
+ assert spill.closed
class TestReplicaIdentityKeyColumns: