Skip to content

Commit cee0f67

Browse files
fix: a backfill that cannot attach gives the rows back to DEFAULT (#83)
partition_data moves a window's rows out of DEFAULT in batches that each commit, into a partition it attaches last. When the attach failed, the rows stayed in that detached table, where no query through the parent sees them, and if the fill had taken the last of them nothing revisited the window. 1.6.1's lock timeout made that easy to reach -- a reader holding the table for three seconds -- and the issue then said the rows stayed in DEFAULT and nothing had changed. Whatever stops the attach, the rows the fill moved now go back to DEFAULT, pinned to both relations' identities, so the issue is true and the next run takes the window again. When they cannot be returned, the issue says which table holds them. A fill that moved nothing has nothing to give back. A process killed between the fill and the attach can still leave rows behind; finding and finishing such tables is #76.
1 parent a4f222d commit cee0f67

9 files changed

Lines changed: 499 additions & 37 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,24 @@ 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.6.3 — a backfill that cannot attach gives the rows back
9+
10+
`partition_data` moves a window's rows out of DEFAULT in batches, each committed on its own,
11+
into a partition it attaches last; until the attach, those rows are visible through no
12+
query. When the attach failed, the rows stayed in that detached table, and if the fill had
13+
already taken the last of them, nothing ever looked at the window again: the next
14+
`backfill` reported DEFAULT drained, `validate` said ok, and the rows were gone from every
15+
read. 1.6.1 made that easy to reach. Its lock timeout refuses an attach after 3 s instead of
16+
waiting out the 30-second budget, so a reader holding the table for a few seconds was
17+
enough, and the issue then claimed the rows stayed in DEFAULT and nothing had changed.
18+
19+
Now whatever stops the attach, the rows the fill moved go back to DEFAULT, pinned to both
20+
tables' identities, and the issue is true: the rows are where readers see them, and the
21+
next run takes the window again. If they cannot be returned, the issue names the table they
22+
are in instead. A process killed between the fill and the attach can still leave them there,
23+
with nobody to move them back; finding and finishing such tables is
24+
[#76](https://github.com/bedrock-python/pg-partsmith/issues/76).
25+
826
## [1.6.2](https://github.com/bedrock-python/pg-partsmith/compare/pg-partsmith-v1.6.1...pg-partsmith-v1.6.2) (2026-09-29)
927

1028

‎docs/concepts/execution.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,8 +137,10 @@ partition, so a reader holding the table for a minute would otherwise stop write
137137
minute.
138138

139139
Past the timeout the statement fails, its transaction rolls back having changed nothing,
140-
and the step is recorded in `result.issues` — `partition_data` reports the window as not
141-
finished. The run goes on with its other steps, and the next run tries again. A drop has
140+
and the step is recorded in `result.issues`. The run goes on with its other steps, and the
141+
next run tries again. `partition_data` reports the window as not finished, and the rows its
142+
fill had already moved go back to DEFAULT: readers see them again, and the next call finds
143+
the window where it looks for one. A drop has
142144
its own timeout and retries (see [Drop](#drop)); `DETACH … CONCURRENTLY` does not hold up
143145
writers and runs without one.
144146

‎docs/guide/partition-existing-table.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,9 @@ Each call:
8080
`result.complete` says whether DEFAULT is drained; `result.partitions` lists what was
8181
created; `result.issues` explains anything that could not be handled. A call that runs out
8282
of budget mid-window leaves that partition detached and filled so far; the next call
83-
finds it, finishes it and attaches it.
83+
finds it, finishes it and attaches it. A window whose attach fails instead — refused, out
84+
of `ddl_lock_timeout_ms`, cut off by an error — has its rows moved back to DEFAULT, where
85+
readers see them and the next call takes the window again.
8486

8587
!!! warning "What a batch cannot hide"
8688
While a window's rows are being moved, they sit in a partition that is not yet

‎pg_partsmith/aio/services/migration.py‎

Lines changed: 100 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@
1515

1616
from __future__ import annotations
1717

18+
import asyncio
1819
import logging
1920
from collections.abc import Awaitable, Callable
20-
from functools import partial
2121
from typing import TYPE_CHECKING, Any
2222

2323
from pg_partsmith.aio.services.execution import LOCK_NOT_GRANTED
@@ -35,7 +35,7 @@
3535
if TYPE_CHECKING:
3636
from pg_partsmith.aio.protocols import PartitionMetadataProvider, PartitionRepository
3737
from pg_partsmith.aio.services.execution import PlanExecutor
38-
from pg_partsmith.entities import TablePartitionConfig
38+
from pg_partsmith.entities import PartitionInfo, TablePartitionConfig
3939
from pg_partsmith.topology import ActualTree, DetachedPartition
4040

4141
logger = logging.getLogger(__name__)
@@ -119,30 +119,20 @@ async def partition_data(
119119
moved_before = tally.rows_moved
120120
bounds = op.bounds
121121
assert isinstance(bounds, RangeBounds)
122-
fill = partial(self._drain_window, default.name, root.key, bounds, batch_rows, tally)
123122
try:
124-
if isinstance(op, CreatePartition):
125-
attached = await self._executor.create_partition(config, plan, op, issues=tally.issues, fill=fill)
126-
else:
127-
attached = await self._executor.attach_partition(config, plan, op, issues=tally.issues, fill=fill)
123+
attached = await self._fill_and_attach(config, plan, op, default, root.key, bounds, batch_rows, tally)
128124
except (RowMoveRefusedError, PartitionTopologyError) as exc:
129125
# A window this run cannot finish -- rows a foreign key holds
130126
# down, a DEFAULT partition it could not clear, a name taken by
131127
# a relation with other bounds. The caller asked for a drain,
132128
# not for an exception: what stayed behind and why is on the
133129
# result, and the loop stops rather than re-planning the same
134130
# window forever.
135-
tally.issue(
136-
default.name, f"rows for {boundaries.describe(window)} stay in {default.name}: {exc.detail}"
137-
)
138-
return tally.result(complete=False)
131+
return tally.unfinished(default.name, boundaries.describe(window), exc.detail)
139132
except Exception as exc:
140133
if pg_sqlstate(exc) != LOCK_NOT_AVAILABLE_SQLSTATE:
141134
raise
142-
tally.issue(
143-
default.name, f"rows for {boundaries.describe(window)} stay in {default.name}: {LOCK_NOT_GRANTED}"
144-
)
145-
return tally.result(complete=False)
135+
return tally.unfinished(default.name, boundaries.describe(window), LOCK_NOT_GRANTED)
146136
if not attached:
147137
logger.info(
148138
"Batch budget exhausted; the partition stays detached until the next call",
@@ -170,6 +160,88 @@ def _window_operation(plan: MaintenancePlan) -> CreatePartition | AttachPartitio
170160
return create
171161
return next((a for a in plan.attaches if isinstance(a.bounds, RangeBounds)), None)
172162

163+
async def _fill_and_attach(
164+
self,
165+
config: TablePartitionConfig,
166+
plan: MaintenancePlan,
167+
op: CreatePartition | AttachPartition,
168+
default: PartitionInfo,
169+
key_columns: tuple[str, ...],
170+
bounds: RangeBounds,
171+
batch_rows: int,
172+
tally: _Tally,
173+
) -> bool:
174+
"""Give the window its partition, filled from DEFAULT before it is attached.
175+
176+
Every batch of the fill commits on its own, but the rows it moves are
177+
visible through the parent only once the partition is attached. When
178+
the attach does not happen -- refused, out of lock_timeout, cut off --
179+
they go back to DEFAULT: readers see them again, and the next run finds
180+
the window where it looks for one, rather than in a detached table
181+
nothing ever revisits.
182+
183+
Returns:
184+
Whether the partition was attached. False when the batch budget ran
185+
out first, which leaves it detached and part-filled on purpose.
186+
"""
187+
filled: list[tuple[str, int | None]] = []
188+
moved_before = tally.rows_moved
189+
190+
async def fill(target: str, target_oid: int | None) -> bool:
191+
filled.append((target, target_oid))
192+
return await self._drain_window(default.name, key_columns, bounds, batch_rows, tally, target, target_oid)
193+
194+
try:
195+
if isinstance(op, CreatePartition):
196+
return await self._executor.create_partition(config, plan, op, issues=tally.issues, fill=fill)
197+
return await self._executor.attach_partition(config, plan, op, issues=tally.issues, fill=fill)
198+
except BaseException:
199+
if tally.rows_moved > moved_before:
200+
await asyncio.shield(self._give_back(filled, default, key_columns, bounds, tally))
201+
raise
202+
203+
async def _give_back(
204+
self,
205+
filled: list[tuple[str, int | None]],
206+
default: PartitionInfo,
207+
key_columns: tuple[str, ...],
208+
bounds: RangeBounds,
209+
tally: _Tally,
210+
) -> None:
211+
"""Return the rows a fill moved to the DEFAULT partition they came from (best effort).
212+
213+
Both ends are pinned to the identities the fill used, so a relation
214+
swapped in at either name neither gives nor receives them. A failure
215+
is logged and the table the rows are left in is remembered for the
216+
report, never raised: the attach's own error stays the one the caller
217+
sees.
218+
"""
219+
for target, target_oid in filled:
220+
try:
221+
returned = await self._repo.reconcile_default_rows(
222+
default_partition_name=target,
223+
target_partition_name=default.name,
224+
key_columns=key_columns,
225+
from_value=bounds.from_value,
226+
to_value=bounds.to_value,
227+
expected_source_oid=target_oid,
228+
expected_target_oid=default.oid,
229+
)
230+
except (asyncio.CancelledError, KeyboardInterrupt, SystemExit):
231+
raise
232+
except Exception:
233+
logger.exception(
234+
"Could not return the window's rows to DEFAULT; they are in a detached table",
235+
extra={"partition_name": target, "default_partition": default.name},
236+
)
237+
tally.stranded.append(target)
238+
else:
239+
tally.rows_moved -= returned
240+
logger.warning(
241+
"The partition was not attached; its rows are back in DEFAULT",
242+
extra={"partition_name": target, "default_partition": default.name, "returned_rows": returned},
243+
)
244+
173245
async def _drain_window(
174246
self,
175247
default_name: str,
@@ -398,6 +470,7 @@ def __init__(self, max_batches: int | None) -> None:
398470
self.batches = 0
399471
self.partitions: list[str] = []
400472
self.issues: list[MaintenanceIssue] = []
473+
self.stranded: list[str] = []
401474

402475
@property
403476
def exhausted(self) -> bool:
@@ -410,6 +483,18 @@ def batch(self, moved: int) -> None:
410483
def issue(self, partition_name: str, error: str) -> None:
411484
self.issues.append(MaintenanceIssue(step=MaintenanceIssueStep.MOVE, error=error, partition_name=partition_name))
412485

486+
def unfinished(self, default_name: str, window: str, reason: str) -> MigrationResult:
487+
"""Report a window this run could not finish, saying where its rows are."""
488+
if self.stranded:
489+
where = (
490+
f"are in {', '.join(self.stranded)}, which is not attached; they could not be returned to "
491+
f"{default_name}, and no query through the parent sees them until it is attached"
492+
)
493+
else:
494+
where = f"stay in {default_name}"
495+
self.issue(default_name, f"rows for {window} {where}: {reason}")
496+
return self.result(complete=False)
497+
413498
def result(self, *, complete: bool) -> MigrationResult:
414499
return MigrationResult(
415500
rows_moved=self.rows_moved,

‎pg_partsmith/sync/services/migration.py‎

Lines changed: 99 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717

1818
import logging
1919
from collections.abc import Callable
20-
from functools import partial
2120
from typing import TYPE_CHECKING, Any
2221

2322
from pg_partsmith.boundaries import Window
@@ -33,7 +32,7 @@
3332
from pg_partsmith.utils import pg_sqlstate
3433

3534
if TYPE_CHECKING:
36-
from pg_partsmith.entities import TablePartitionConfig
35+
from pg_partsmith.entities import PartitionInfo, TablePartitionConfig
3736
from pg_partsmith.sync.protocols import PartitionMetadataProvider, PartitionRepository
3837
from pg_partsmith.sync.services.execution import PlanExecutor
3938
from pg_partsmith.topology import ActualTree, DetachedPartition
@@ -119,30 +118,20 @@ def partition_data(
119118
moved_before = tally.rows_moved
120119
bounds = op.bounds
121120
assert isinstance(bounds, RangeBounds)
122-
fill = partial(self._drain_window, default.name, root.key, bounds, batch_rows, tally)
123121
try:
124-
if isinstance(op, CreatePartition):
125-
attached = self._executor.create_partition(config, plan, op, issues=tally.issues, fill=fill)
126-
else:
127-
attached = self._executor.attach_partition(config, plan, op, issues=tally.issues, fill=fill)
122+
attached = self._fill_and_attach(config, plan, op, default, root.key, bounds, batch_rows, tally)
128123
except (RowMoveRefusedError, PartitionTopologyError) as exc:
129124
# A window this run cannot finish -- rows a foreign key holds
130125
# down, a DEFAULT partition it could not clear, a name taken by
131126
# a relation with other bounds. The caller asked for a drain,
132127
# not for an exception: what stayed behind and why is on the
133128
# result, and the loop stops rather than re-planning the same
134129
# window forever.
135-
tally.issue(
136-
default.name, f"rows for {boundaries.describe(window)} stay in {default.name}: {exc.detail}"
137-
)
138-
return tally.result(complete=False)
130+
return tally.unfinished(default.name, boundaries.describe(window), exc.detail)
139131
except Exception as exc:
140132
if pg_sqlstate(exc) != LOCK_NOT_AVAILABLE_SQLSTATE:
141133
raise
142-
tally.issue(
143-
default.name, f"rows for {boundaries.describe(window)} stay in {default.name}: {LOCK_NOT_GRANTED}"
144-
)
145-
return tally.result(complete=False)
134+
return tally.unfinished(default.name, boundaries.describe(window), LOCK_NOT_GRANTED)
146135
if not attached:
147136
logger.info(
148137
"Batch budget exhausted; the partition stays detached until the next call",
@@ -170,6 +159,88 @@ def _window_operation(plan: MaintenancePlan) -> CreatePartition | AttachPartitio
170159
return create
171160
return next((a for a in plan.attaches if isinstance(a.bounds, RangeBounds)), None)
172161

162+
def _fill_and_attach(
163+
self,
164+
config: TablePartitionConfig,
165+
plan: MaintenancePlan,
166+
op: CreatePartition | AttachPartition,
167+
default: PartitionInfo,
168+
key_columns: tuple[str, ...],
169+
bounds: RangeBounds,
170+
batch_rows: int,
171+
tally: _Tally,
172+
) -> bool:
173+
"""Give the window its partition, filled from DEFAULT before it is attached.
174+
175+
Every batch of the fill commits on its own, but the rows it moves are
176+
visible through the parent only once the partition is attached. When
177+
the attach does not happen -- refused, out of lock_timeout, cut off --
178+
they go back to DEFAULT: readers see them again, and the next run finds
179+
the window where it looks for one, rather than in a detached table
180+
nothing ever revisits.
181+
182+
Returns:
183+
Whether the partition was attached. False when the batch budget ran
184+
out first, which leaves it detached and part-filled on purpose.
185+
"""
186+
filled: list[tuple[str, int | None]] = []
187+
moved_before = tally.rows_moved
188+
189+
def fill(target: str, target_oid: int | None) -> bool:
190+
filled.append((target, target_oid))
191+
return self._drain_window(default.name, key_columns, bounds, batch_rows, tally, target, target_oid)
192+
193+
try:
194+
if isinstance(op, CreatePartition):
195+
return self._executor.create_partition(config, plan, op, issues=tally.issues, fill=fill)
196+
return self._executor.attach_partition(config, plan, op, issues=tally.issues, fill=fill)
197+
except BaseException:
198+
if tally.rows_moved > moved_before:
199+
(self._give_back(filled, default, key_columns, bounds, tally))
200+
raise
201+
202+
def _give_back(
203+
self,
204+
filled: list[tuple[str, int | None]],
205+
default: PartitionInfo,
206+
key_columns: tuple[str, ...],
207+
bounds: RangeBounds,
208+
tally: _Tally,
209+
) -> None:
210+
"""Return the rows a fill moved to the DEFAULT partition they came from (best effort).
211+
212+
Both ends are pinned to the identities the fill used, so a relation
213+
swapped in at either name neither gives nor receives them. A failure
214+
is logged and the table the rows are left in is remembered for the
215+
report, never raised: the attach's own error stays the one the caller
216+
sees.
217+
"""
218+
for target, target_oid in filled:
219+
try:
220+
returned = self._repo.reconcile_default_rows(
221+
default_partition_name=target,
222+
target_partition_name=default.name,
223+
key_columns=key_columns,
224+
from_value=bounds.from_value,
225+
to_value=bounds.to_value,
226+
expected_source_oid=target_oid,
227+
expected_target_oid=default.oid,
228+
)
229+
except (KeyboardInterrupt, SystemExit):
230+
raise
231+
except Exception:
232+
logger.exception(
233+
"Could not return the window's rows to DEFAULT; they are in a detached table",
234+
extra={"partition_name": target, "default_partition": default.name},
235+
)
236+
tally.stranded.append(target)
237+
else:
238+
tally.rows_moved -= returned
239+
logger.warning(
240+
"The partition was not attached; its rows are back in DEFAULT",
241+
extra={"partition_name": target, "default_partition": default.name, "returned_rows": returned},
242+
)
243+
173244
def _drain_window(
174245
self,
175246
default_name: str,
@@ -396,6 +467,7 @@ def __init__(self, max_batches: int | None) -> None:
396467
self.batches = 0
397468
self.partitions: list[str] = []
398469
self.issues: list[MaintenanceIssue] = []
470+
self.stranded: list[str] = []
399471

400472
@property
401473
def exhausted(self) -> bool:
@@ -408,6 +480,18 @@ def batch(self, moved: int) -> None:
408480
def issue(self, partition_name: str, error: str) -> None:
409481
self.issues.append(MaintenanceIssue(step=MaintenanceIssueStep.MOVE, error=error, partition_name=partition_name))
410482

483+
def unfinished(self, default_name: str, window: str, reason: str) -> MigrationResult:
484+
"""Report a window this run could not finish, saying where its rows are."""
485+
if self.stranded:
486+
where = (
487+
f"are in {', '.join(self.stranded)}, which is not attached; they could not be returned to "
488+
f"{default_name}, and no query through the parent sees them until it is attached"
489+
)
490+
else:
491+
where = f"stay in {default_name}"
492+
self.issue(default_name, f"rows for {window} {where}: {reason}")
493+
return self.result(complete=False)
494+
411495
def result(self, *, complete: bool) -> MigrationResult:
412496
return MigrationResult(
413497
rows_moved=self.rows_moved,

0 commit comments

Comments
 (0)