Skip to content

Commit b1260c1

Browse files
AlexeyShalaevAlexey Shalaev
andauthored
fix: a backfilled window always attaches with writers held at the parent (#89)
The attach that ends a window partition_data filled tried a plain ATTACH first and fell back to reconcile_and_attach only on a DEFAULT conflict. With nothing left in DEFAULT for the window, the plain attach went through, and an insert into the window that got past the parent while it was in flight chose DEFAULT from the old tree, queued on DEFAULT's lock and was rejected by the narrowed constraint. The current month under a live writer hits that. A filled window now skips the plain attempt and attaches through reconcile_and_attach, which holds writers at the parent and takes the rows that arrived after the last batch, as the docs already describe. Co-authored-by: Alexey Shalaev <shalaevad.alexey@gmail.com>
1 parent df5d31d commit b1260c1

4 files changed

Lines changed: 109 additions & 2 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,19 @@ All notable changes to this project will be documented in this file.
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
## 1.7.2 — a backfill's last attach no longer rejects a live insert
9+
10+
The attach that ends a backfilled window is documented to hold writers at the parent, and
11+
when rows had arrived in DEFAULT during the fill it did. When none had, it ran a plain
12+
`ATTACH` first, which does not: an insert into that window that got past the parent while
13+
the attach was in flight chose DEFAULT from the tree as it was, queued on DEFAULT's lock,
14+
and was then rejected by the constraint the attach had just narrowed, `new row for
15+
relation ... violates partition constraint`. The current month, the one the application
16+
is writing into, is exactly such a window. Found against Outpost's schema with a writer at
17+
20 inserts a second: two inserts failed in one `backfill`. A window filled from DEFAULT now
18+
always attaches the documented way, writers held at the parent and whatever arrived after
19+
the last batch taken with it.
20+
821
## [1.7.1](https://github.com/bedrock-python/pg-partsmith/compare/pg-partsmith-v1.7.0...pg-partsmith-v1.7.1) (2026-10-01)
922

1023

‎pg_partsmith/aio/services/execution.py‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,7 @@ async def _create(
304304
key_columns=op.key_columns,
305305
expected_oid=target_oid,
306306
expected_parent_oid=expected_parent_oid,
307+
filled=fill is not None,
307308
)
308309

309310
if op.counts_as == "created":
@@ -437,7 +438,13 @@ async def _attach_detached(
437438
info = _attach_info(config, op)
438439
await self._fire(HookPhase.BEFORE_ATTACH, config, info, op)
439440
await self._attach_with_reconcile(
440-
config, op.parent_name, op.target, op.bounds, key_columns=op.key_columns, expected_oid=op.oid
441+
config,
442+
op.parent_name,
443+
op.target,
444+
op.bounds,
445+
key_columns=op.key_columns,
446+
expected_oid=op.oid,
447+
filled=fill is not None,
441448
)
442449
tally.attached += 1
443450
await self._fire(HookPhase.AFTER_ATTACH, config, info.model_copy(update={"is_attached": True}), op)
@@ -453,6 +460,7 @@ async def _attach_with_reconcile(
453460
key_columns: tuple[str, ...],
454461
expected_oid: int | None = None,
455462
expected_parent_oid: int | None = None,
463+
filled: bool = False,
456464
) -> None:
457465
"""Attach a partition, moving DEFAULT rows out of the way for a RANGE window.
458466
@@ -467,6 +475,13 @@ async def _attach_with_reconcile(
467475
lighter transaction, so what the exclusive lock covers is the rows
468476
that arrived while it ran, plus the scan.
469477
478+
A window just filled from DEFAULT (``filled``) skips the plain attempt.
479+
Its rows were written into DEFAULT until moments ago, so writers may be
480+
routing into it now, and a plain ``ATTACH`` leaves them free to get past
481+
the parent, choose DEFAULT from the tree as it was, and be rejected by
482+
the constraint the attach narrows. ``reconcile_and_attach`` holds them
483+
at the parent instead, and takes whatever landed after the last batch.
484+
470485
If the attach ultimately fails after rows were reconciled out of the
471486
DEFAULT partition, the moved rows are returned to DEFAULT (best effort)
472487
so they do not end up stranded in a table that is invisible through the
@@ -481,6 +496,8 @@ async def _attach_with_reconcile(
481496
reconciled_from: tuple[str, int | None] | None = None
482497
window = bounds if isinstance(bounds, RangeBounds) else None
483498
default_partition: PartitionInfo | None = None
499+
if filled and window is not None:
500+
default_partition = await self._metadata.get_default_partition(parent_name)
484501

485502
for attempt in range(1, DEFAULT_CONFLICT_MAX_RETRIES + 1):
486503
try:

‎pg_partsmith/sync/services/execution.py‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,7 @@ def _create(
303303
key_columns=op.key_columns,
304304
expected_oid=target_oid,
305305
expected_parent_oid=expected_parent_oid,
306+
filled=fill is not None,
306307
)
307308

308309
if op.counts_as == "created":
@@ -436,7 +437,13 @@ def _attach_detached(
436437
info = _attach_info(config, op)
437438
self._fire(HookPhase.BEFORE_ATTACH, config, info, op)
438439
self._attach_with_reconcile(
439-
config, op.parent_name, op.target, op.bounds, key_columns=op.key_columns, expected_oid=op.oid
440+
config,
441+
op.parent_name,
442+
op.target,
443+
op.bounds,
444+
key_columns=op.key_columns,
445+
expected_oid=op.oid,
446+
filled=fill is not None,
440447
)
441448
tally.attached += 1
442449
self._fire(HookPhase.AFTER_ATTACH, config, info.model_copy(update={"is_attached": True}), op)
@@ -452,6 +459,7 @@ def _attach_with_reconcile(
452459
key_columns: tuple[str, ...],
453460
expected_oid: int | None = None,
454461
expected_parent_oid: int | None = None,
462+
filled: bool = False,
455463
) -> None:
456464
"""Attach a partition, moving DEFAULT rows out of the way for a RANGE window.
457465
@@ -466,6 +474,13 @@ def _attach_with_reconcile(
466474
lighter transaction, so what the exclusive lock covers is the rows
467475
that arrived while it ran, plus the scan.
468476
477+
A window just filled from DEFAULT (``filled``) skips the plain attempt.
478+
Its rows were written into DEFAULT until moments ago, so writers may be
479+
routing into it now, and a plain ``ATTACH`` leaves them free to get past
480+
the parent, choose DEFAULT from the tree as it was, and be rejected by
481+
the constraint the attach narrows. ``reconcile_and_attach`` holds them
482+
at the parent instead, and takes whatever landed after the last batch.
483+
469484
If the attach ultimately fails after rows were reconciled out of the
470485
DEFAULT partition, the moved rows are returned to DEFAULT (best effort)
471486
so they do not end up stranded in a table that is invisible through the
@@ -480,6 +495,8 @@ def _attach_with_reconcile(
480495
reconciled_from: tuple[str, int | None] | None = None
481496
window = bounds if isinstance(bounds, RangeBounds) else None
482497
default_partition: PartitionInfo | None = None
498+
if filled and window is not None:
499+
default_partition = self._metadata.get_default_partition(parent_name)
483500

484501
for attempt in range(1, DEFAULT_CONFLICT_MAX_RETRIES + 1):
485502
try:

‎tests/integration/aio/test_migration.py‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
from pg_partsmith.aio.hooks import BasePartitionLifecycleHooks
2323
from pg_partsmith.aio.metadata import PostgresMetadataProvider
2424
from pg_partsmith.aio.repositories import PostgresPartitionRepository
25+
from pg_partsmith.aio.repositories.creator import PartitionCreator
2526
from pg_partsmith.entities import MaintenanceIssueStep, Period
2627
from pg_partsmith.events import PartitionEvent
2728
from pg_partsmith.exceptions import InvalidPartitionConfigError, PlanStaleError
@@ -220,6 +221,65 @@ async def test__partition_data__attach_not_granted_its_lock__rows_stay_visible_a
220221
assert await _count(db_engine, events) == 25
221222

222223

224+
# sync-mirror: skip
225+
async def test__partition_data__an_insert_arriving_during_the_attach__lands_in_the_new_partition(
226+
db_engine: AsyncEngine, events: str
227+
) -> None:
228+
"""The attach that ends a window keeps writers out at the parent, even with nothing left to move.
229+
230+
An insert that got past the parent while the attach was in flight would
231+
have chosen DEFAULT from the tree as it was, queued on DEFAULT's lock, and
232+
been rejected by the constraint the attach had just narrowed.
233+
"""
234+
# Arrange: March in DEFAULT, and the window's attach held open once it has run
235+
default = await _default_with_rows(db_engine, events, months=(3,), per_month=10)
236+
config = monthly_config(events, create_ahead=1)
237+
march = f"{events}__2026_03"
238+
attaching = asyncio.Event()
239+
release = asyncio.Event()
240+
original = PartitionCreator._clear_orphan_marker
241+
242+
async def held_open(self: PartitionCreator, conn: object, partition_name: str) -> None:
243+
attaching.set()
244+
await release.wait()
245+
await original(self, conn, partition_name) # type: ignore[arg-type]
246+
247+
async def insert_into_march() -> None:
248+
await attaching.wait()
249+
await exec_sql(
250+
db_engine,
251+
f'INSERT INTO "{events}" (created_at, payload) ' # noqa: S608
252+
"VALUES (make_timestamptz(2026, 3, 15, 12, 0, 0, 'UTC'), 'live')",
253+
)
254+
255+
async def release_once_the_insert_waits() -> None:
256+
await attaching.wait()
257+
for _ in range(200):
258+
await asyncio.sleep(0.05)
259+
if await scalar(
260+
db_engine,
261+
"SELECT count(*) FROM pg_locks WHERE NOT granted "
262+
"AND relation IN (to_regclass(:parent), to_regclass(:default))",
263+
parent=events,
264+
default=default,
265+
):
266+
break
267+
release.set()
268+
269+
# Act
270+
with patch.object(PartitionCreator, "_clear_orphan_marker", held_open):
271+
result, _, _ = await asyncio.gather(
272+
make_service(db_engine).partition_data(config),
273+
insert_into_march(),
274+
release_once_the_insert_waits(),
275+
)
276+
277+
# Assert
278+
assert result.complete
279+
assert await _only_count(db_engine, default) == 0
280+
assert await _count(db_engine, march) == 11
281+
282+
223283
async def test__partition_data__a_fill_the_process_died_after__is_reported_then_attached(
224284
db_engine: AsyncEngine, events: str
225285
) -> None:

0 commit comments

Comments
 (0)