Skip to content

Commit f57ee1d

Browse files
author
Alexey Shalaev
committed
feat: find and attach the partitions a stopped backfill left unattached
A backfill moves a window's rows out of DEFAULT into a partition it attaches last. If the process died between the two, the rows sat in a table no query through the parent sees, DEFAULT held nothing to bring a later backfill back to the window, and plan and validate said all was well. plan now reports such a table as unattached_rows (WARNING), and partition_data attaches it once DEFAULT is drained, through the path a window out of DEFAULT takes. A table counts only when its name is the very name the scheme gives a window under this root, checked both ways, so metrics_remote__2025_01 beside metrics is not taken for January; its rows are read only after that, so a table that merely shares the prefix is never read and needs no grant. A table under a window's name holding rows outside that window was not left by a backfill; partition_data reports it and leaves it as it is rather than raising the check violation ATTACH gives. get_unattached_tables(table_name) is a method of PartitionMetadataProvider in both mirrors: the tables in the root's schema named under it, attached to nothing and unmarked. It is its own query rather than part of get_actual_tree, so list_partitions and get_default_partition do not pay for it. ActualTree.unattached and UnattachedTable carry what it found. Closes #76
1 parent 921b938 commit f57ee1d

32 files changed

Lines changed: 837 additions & 34 deletions

‎CHANGELOG.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,29 @@ 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.0 — rows a stopped backfill hid are found and attached
9+
10+
A backfill moves a window's rows out of DEFAULT into a partition it attaches last. If the
11+
process died after the move and before the attach, the rows sat in a table no query
12+
through the parent sees, DEFAULT held nothing that would bring a later backfill back to the
13+
window, and `plan` and `validate` both said the table was fine
14+
([#76](https://github.com/bedrock-python/pg-partsmith/issues/76)). 1.6.3 covered an attach
15+
that fails; this covers a process that never gets to fail.
16+
17+
`plan` now reports such a table as `unattached_rows`, a WARNING, so `plan --check` exits 3
18+
and `apply` carries it in `result.issues`. `partition_data` — `backfill` — attaches it once
19+
DEFAULT is drained, through the same path a window out of DEFAULT takes. A table counts
20+
only when its name is the very name the scheme gives a window under this root:
21+
`metrics_remote__2025_01` beside `metrics` reads as January, and is not a partition of it.
22+
Its rows are read only after that, so a table that merely shares the prefix is never read
23+
and needs no grant. `validate` is unchanged: it checks the document against the table's
24+
shape, not the table's contents.
25+
26+
`get_unattached_tables(table_name)` is a method of `PartitionMetadataProvider` in both
27+
mirrors, answering with the tables named under the root, attached to nothing and carrying
28+
no orphan marker; a provider of your own now has to answer it. `ActualTree.unattached` and
29+
`UnattachedTable` carry what it found.
30+
831
## [1.6.3](https://github.com/bedrock-python/pg-partsmith/compare/pg-partsmith-v1.6.2...pg-partsmith-v1.6.3) (2026-09-29)
932

1033

‎docs/agents.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -369,7 +369,10 @@ lifecycle units — partitions directly under the root — never once per leaf o
369369
batch *and* goes live in one transaction, so a window the application is writing into
370370
is attached like any other; writers wait at the parent for that commit and are then
371371
routed into the new partition. A window that still cannot be attached comes back as a
372-
`move` issue with `complete=False` — `partition_data` does not raise for it.
372+
`move` issue with `complete=False`, its rows moved back to DEFAULT — `partition_data`
373+
does not raise for it. If the process dies between the fill and the attach, the rows
374+
stay in the unattached table: `plan` reports it as `unattached_rows`, and the next
375+
`partition_data` attaches it once DEFAULT is drained.
373376
11. **Flat and composed spellings do not mix**, and `extra="forbid"` means a misspelled
374377
keyword raises rather than being ignored.
375378
12. **`schema=` goes in, `config.db_schema` comes out** — the field is aliased to avoid

‎docs/concepts/execution.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,7 @@ one of a small number of states, each of which the next run converges:
183183
| Cut off during | Left behind | Next run |
184184
|---|---|---|
185185
| creating a partition or its subtree | a detached, unmarked table, unreachable by writers | completes the subtree, attaches it |
186+
| a backfill, between the fill and the attach | a detached, unmarked table holding its window's rows, which DEFAULT no longer has | `plan` reports `unattached_rows`; `backfill` attaches it |
186187
| a detach | a marked table, attached or pending | finishes the detach (`FINALIZE` if pending), then proceeds |
187188
| a drop | either the table or nothing | drops it, or finds nothing to do |
188189

‎docs/design/api-cheatsheet-1.0.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ Executor (`aio/services/execution.py` `PlanExecutor(repo, metadata, hooks)`): `a
5252

5353
Repository protocol (`PartitionRepository`): `create_table_like(template_name, table_name, partition_by: PartitionBy | None, *, physical: LocalLeaves | None = None)`, `create_foreign_table_like(template_name, table_name, *, server, options)`, `move_rows(source, target, *, limit=None) -> int`, `attach_partition(parent, partition, bounds: PartitionBounds, *, key_arity=1)`, `detach_partition(parent, partition, *, mode=DetachMode.AUTO)`, `drop_partition(partition, *, expected_oid=None)`, `adopt_partition(table, partition) -> bool`, `reconcile_default_rows(*, default_partition_name, target_partition_name, key_columns, from_value, to_value, limit=None) -> int`. Old `create_partition/create_branch/create_subpartition_table/attach_subpartition/attach_composite_partition` are gone.
5454

55-
Metadata protocol (`PartitionMetadataProvider`): `get_partition_type`, `get_partition_columns`, `get_actual_tree(table) -> ActualTree | None`, `measure(tree, *, targets, facts, sql_predicates) -> ActualTree`, `get_partition_tree(name) -> PartitionNode | None`, `get_default_partition`, `partition_exists`, `is_partition_attached`, `get_relation_oid(name)`, `get_relation_kind(name)`, `get_unique_constraint_columns`, `get_key_high_water_mark(table, column, *, sequence=False)`, `get_leading_key_minimum(table, key_columns)`, `list_partitions`, `is_partition_closed(partition_name, *, settle_seconds=0, boundaries=None)` (on the protocol since 1.4.0), `current_time()` (since 1.6.0; the database's clock, what `plan()` uses when `now` is not given). Plus on the Postgres implementation: `get_partition_column` (single-column only), `get_partition_boundaries`, `evaluate_sql_predicate`.
55+
Metadata protocol (`PartitionMetadataProvider`): `get_partition_type`, `get_partition_columns`, `get_actual_tree(table) -> ActualTree | None`, `measure(tree, *, targets, facts, sql_predicates) -> ActualTree`, `get_partition_tree(name) -> PartitionNode | None`, `get_default_partition`, `partition_exists`, `is_partition_attached`, `get_relation_oid(name)`, `get_relation_kind(name)`, `get_unique_constraint_columns`, `get_key_high_water_mark(table, column, *, sequence=False)`, `get_leading_key_minimum(table, key_columns)`, `list_partitions`, `is_partition_closed(partition_name, *, settle_seconds=0, boundaries=None)` (on the protocol since 1.4.0), `current_time()` (since 1.6.0; the database's clock, what `plan()` uses when `now` is not given), `get_unattached_tables(table) -> tuple[UnattachedTable, ...]` (since 1.7.0; tables named under the root, attached to nothing and unmarked). Plus on the Postgres implementation: `get_partition_column` (single-column only), `get_partition_boundaries`, `evaluate_sql_predicate`.
5656

5757
Hooks: in 1.0 `before_create(config, partition: PartitionInfo)` (was `(config, name, from_value, to_value)`) and the other five unchanged. **Superseded in 1.1**: every method takes one `PartitionEvent`, and there are eight phases plus `on_event` — see the changelog. Hooks fire for partitions directly under the root only (lifecycle units / root set members), never per leaf of a subtree.
5858

‎docs/guide/extending.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,8 @@ The protocol's reads: `get_partition_type`, `get_partition_columns`, `get_actual
9494
`is_partition_attached`, `get_relation_oid`, `get_relation_kind`,
9595
`get_unique_constraint_columns`, `get_key_high_water_mark`, `get_leading_key_minimum`,
9696
`list_partitions`, `is_partition_closed`, which a provider of your own answers with
97-
False rather than an exception when it cannot read the bound, and `current_time`, the
97+
False rather than an exception when it cannot read the bound, `get_unattached_tables`, the
98+
tables named under the root and attached to nothing, and `current_time`, the
9899
database's clock a plan is made against when the caller names no instant.
99100

100101
## A lock manager

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,9 @@ Each call:
7575
same pass as a quiet one, and what the lock covers is a tail and a scan rather than a
7676
month;
7777
5. moves on to the next window, until DEFAULT holds only rows no window can take (rows
78-
with a NULL key), or `max_batches` is spent.
78+
with a NULL key), or `max_batches` is spent;
79+
6. with DEFAULT drained, attaches any window's partition a previous run filled and never
80+
attached — the process died in between — which `plan` reports as `unattached_rows`.
7981

8082
`result.complete` says whether DEFAULT is drained; `result.partitions` lists what was
8183
created; `result.issues` explains anything that could not be handled. A call that runs out

‎docs/guide/troubleshooting.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,19 @@ A partition was not created because part of its subtree could not be planned —
100100
refused, a group in conflict. Attaching a branch with a hole in its child set would reject
101101
rows, so the whole partition waits. The findings for the subtree say why.
102102

103+
## `unattached_rows` — rows no query through the table sees
104+
105+
```text
106+
[warning] unattached_rows: public.events__2026_03 holds rows of 2026_03 but is attached to nothing, so no query through public.events sees them; backfill (partition_data) attaches it.
107+
```
108+
109+
A backfill creates a window's partition, moves the window's rows into it from DEFAULT and
110+
attaches it last. If the process died after the move and before the attach, the rows are in
111+
that table and nowhere else, and DEFAULT no longer holds anything that would bring a later
112+
backfill back to the window. Run `backfill`: once DEFAULT is drained it looks for exactly
113+
these tables and attaches them. Only a table whose name is the one the scheme gives that
114+
window under this root counts — its rows are never read otherwise.
115+
103116
## `grace_pending`, `drop_deferred` (INFO)
104117

105118
A detached orphan waiting out its grace period, or one whose `DropAfter(when=…)`

‎docs/reference/findings.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ issues too, with the exception's name in front of the message.
3030
| `detach_pending` | INFO | An interrupted `DETACH CONCURRENTLY`; the partition rejects its rows until finalized. `maintain()` completes it with `DETACH … FINALIZE` and re-plans in the same call. | Nothing; check that the run went through. |
3131
| `grace_pending` | INFO | A detached orphan still within its grace period. | Nothing. |
3232
| `drop_deferred` | INFO | An orphan past its grace whose drop condition does not hold yet. | Nothing. |
33+
| `unattached_rows` | WARNING | A table under a window's partition name holds rows but was never attached — a fill that stopped before its attach — so no query through the root sees them. | Run `backfill` (`partition_data`); it attaches the table. |
3334

3435
## Operation reasons
3536

‎pg_partsmith/__init__.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@
113113
YearPeriodCalculator,
114114
get_period_calculator,
115115
)
116-
from .topology import ActualTree, DetachedPartition, FactKind, PartitionFacts, RelationKind
116+
from .topology import ActualTree, DetachedPartition, FactKind, PartitionFacts, RelationKind, UnattachedTable
117117
from .utils import qualify, split_qualified_name
118118

119119
__all__ = [
@@ -225,6 +225,7 @@
225225
"TimezoneAwareCalculator",
226226
"ToolkitOptions",
227227
"UUIDv7BoundaryCodec",
228+
"UnattachedTable",
228229
"UnmanagedPartitionDropError",
229230
"Unreferenced",
230231
"WeekPeriodCalculator",

‎pg_partsmith/aio/metadata.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
RELATION_OID_SQL,
2727
SEQUENCE_LAST_VALUE_SQL,
2828
TEXT_INSTANT_HAS_PASSED_SQL,
29+
UNATTACHED_SQL,
2930
UNIQUE_CONSTRAINT_COLUMNS_SQL,
3031
)
3132
from pg_partsmith.entities import PartitionInfo, PartitionType
@@ -45,6 +46,7 @@
4546
PartitionNode,
4647
PartitionTreeRow,
4748
RelationKind,
49+
UnattachedTable,
4850
build_partition_tree,
4951
)
5052
from pg_partsmith.utils import (
@@ -320,6 +322,37 @@ async def _orphans_of(self, parents: list[str]) -> tuple[DetachedPartition, ...]
320322
)
321323
return tuple(orphans)
322324

325+
async def get_unattached_tables(self, table_name: str) -> tuple[UnattachedTable, ...]:
326+
"""Tables named under ``table_name``, attached to nothing and carrying no orphan marker.
327+
328+
A partition is created standalone and attached last, so this is what
329+
one looks like when whatever was filling it stopped first. Every table
330+
in the root's schema whose name begins with the root's is a candidate;
331+
which of them name a window is the scheme's call, and no row of any of
332+
them is read here.
333+
"""
334+
async with self._engine.connect() as conn:
335+
result = await conn.execute(
336+
text(UNATTACHED_SQL),
337+
{"table_name": to_regclass_argument(table_name), "marker_prefix": self._marker_prefix},
338+
)
339+
rows = result.fetchall()
340+
341+
tables: list[UnattachedTable] = []
342+
for row in rows:
343+
schema = coerce_str(row.partition_schema) or ""
344+
relname = coerce_str(row.partition_name) or ""
345+
if not is_addressable(schema, relname):
346+
continue
347+
tables.append(
348+
UnattachedTable(
349+
name=qualify(schema, relname),
350+
oid=int(row.oid),
351+
relkind=RelationKind.from_relkind(coerce_str(row.relkind, encoding="ascii")),
352+
)
353+
)
354+
return tuple(tables)
355+
323356
async def _measure(
324357
self,
325358
root: PartitionNode,

0 commit comments

Comments
 (0)