Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,29 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## 1.7.0 — rows a stopped backfill hid are found and attached

A backfill moves a window's rows out of DEFAULT into a partition it attaches last. If the
process died after the move and before the attach, the rows sat in a table no query
through the parent sees, DEFAULT held nothing that would bring a later backfill back to the
window, and `plan` and `validate` both said the table was fine
([#76](https://github.com/bedrock-python/pg-partsmith/issues/76)). 1.6.3 covered an attach
that fails; this covers a process that never gets to fail.

`plan` now reports such a table as `unattached_rows`, a WARNING, so `plan --check` exits 3
and `apply` carries it in `result.issues`. `partition_data` — `backfill` — attaches it once
DEFAULT is drained, through the same 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:
`metrics_remote__2025_01` beside `metrics` reads as January, and is not a partition of it.
Its rows are read only after that, so a table that merely shares the prefix is never read
and needs no grant. `validate` is unchanged: it checks the document against the table's
shape, not the table's contents.

`get_unattached_tables(table_name)` is a method of `PartitionMetadataProvider` in both
mirrors, answering with the tables named under the root, attached to nothing and carrying
no orphan marker; a provider of your own now has to answer it. `ActualTree.unattached` and
`UnattachedTable` carry what it found.

## [1.6.3](https://github.com/bedrock-python/pg-partsmith/compare/pg-partsmith-v1.6.2...pg-partsmith-v1.6.3) (2026-09-29)


Expand Down
5 changes: 4 additions & 1 deletion docs/agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,10 @@ lifecycle units — partitions directly under the root — never once per leaf o
batch *and* goes live in one transaction, so a window the application is writing into
is attached like any other; writers wait at the parent for that commit and are then
routed into the new partition. A window that still cannot be attached comes back as a
`move` issue with `complete=False` — `partition_data` does not raise for it.
`move` issue with `complete=False`, its rows moved back to DEFAULT — `partition_data`
does not raise for it. If the process dies between the fill and the attach, the rows
stay in the unattached table: `plan` reports it as `unattached_rows`, and the next
`partition_data` attaches it once DEFAULT is drained.
11. **Flat and composed spellings do not mix**, and `extra="forbid"` means a misspelled
keyword raises rather than being ignored.
12. **`schema=` goes in, `config.db_schema` comes out** — the field is aliased to avoid
Expand Down
1 change: 1 addition & 0 deletions docs/concepts/execution.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ one of a small number of states, each of which the next run converges:
| Cut off during | Left behind | Next run |
|---|---|---|
| creating a partition or its subtree | a detached, unmarked table, unreachable by writers | completes the subtree, attaches it |
| 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 |
| a detach | a marked table, attached or pending | finishes the detach (`FINALIZE` if pending), then proceeds |
| a drop | either the table or nothing | drops it, or finds nothing to do |

Expand Down
2 changes: 1 addition & 1 deletion docs/design/api-cheatsheet-1.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ Executor (`aio/services/execution.py` `PlanExecutor(repo, metadata, hooks)`): `a

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.

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`.
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`.

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.

Expand Down
3 changes: 2 additions & 1 deletion docs/guide/extending.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,8 @@ The protocol's reads: `get_partition_type`, `get_partition_columns`, `get_actual
`is_partition_attached`, `get_relation_oid`, `get_relation_kind`,
`get_unique_constraint_columns`, `get_key_high_water_mark`, `get_leading_key_minimum`,
`list_partitions`, `is_partition_closed`, which a provider of your own answers with
False rather than an exception when it cannot read the bound, and `current_time`, the
False rather than an exception when it cannot read the bound, `get_unattached_tables`, the
tables named under the root and attached to nothing, and `current_time`, the
database's clock a plan is made against when the caller names no instant.

## A lock manager
Expand Down
4 changes: 3 additions & 1 deletion docs/guide/partition-existing-table.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,9 @@ Each call:
same pass as a quiet one, and what the lock covers is a tail and a scan rather than a
month;
5. moves on to the next window, until DEFAULT holds only rows no window can take (rows
with a NULL key), or `max_batches` is spent.
with a NULL key), or `max_batches` is spent;
6. with DEFAULT drained, attaches any window's partition a previous run filled and never
attached — the process died in between — which `plan` reports as `unattached_rows`.

`result.complete` says whether DEFAULT is drained; `result.partitions` lists what was
created; `result.issues` explains anything that could not be handled. A call that runs out
Expand Down
13 changes: 13 additions & 0 deletions docs/guide/troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,19 @@ A partition was not created because part of its subtree could not be planned —
refused, a group in conflict. Attaching a branch with a hole in its child set would reject
rows, so the whole partition waits. The findings for the subtree say why.

## `unattached_rows` — rows no query through the table sees

```text
[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.
```

A backfill creates a window's partition, moves the window's rows into it from DEFAULT and
attaches it last. If the process died after the move and before the attach, the rows are in
that table and nowhere else, and DEFAULT no longer holds anything that would bring a later
backfill back to the window. Run `backfill`: once DEFAULT is drained it looks for exactly
these tables and attaches them. Only a table whose name is the one the scheme gives that
window under this root counts — its rows are never read otherwise.

## `grace_pending`, `drop_deferred` (INFO)

A detached orphan waiting out its grace period, or one whose `DropAfter(when=…)`
Expand Down
1 change: 1 addition & 0 deletions docs/reference/findings.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ issues too, with the exception's name in front of the message.
| `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. |
| `grace_pending` | INFO | A detached orphan still within its grace period. | Nothing. |
| `drop_deferred` | INFO | An orphan past its grace whose drop condition does not hold yet. | Nothing. |
| `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. |

## Operation reasons

Expand Down
3 changes: 2 additions & 1 deletion pg_partsmith/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@
YearPeriodCalculator,
get_period_calculator,
)
from .topology import ActualTree, DetachedPartition, FactKind, PartitionFacts, RelationKind
from .topology import ActualTree, DetachedPartition, FactKind, PartitionFacts, RelationKind, UnattachedTable
from .utils import qualify, split_qualified_name

__all__ = [
Expand Down Expand Up @@ -225,6 +225,7 @@
"TimezoneAwareCalculator",
"ToolkitOptions",
"UUIDv7BoundaryCodec",
"UnattachedTable",
"UnmanagedPartitionDropError",
"Unreferenced",
"WeekPeriodCalculator",
Expand Down
33 changes: 33 additions & 0 deletions pg_partsmith/aio/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
RELATION_OID_SQL,
SEQUENCE_LAST_VALUE_SQL,
TEXT_INSTANT_HAS_PASSED_SQL,
UNATTACHED_SQL,
UNIQUE_CONSTRAINT_COLUMNS_SQL,
)
from pg_partsmith.entities import PartitionInfo, PartitionType
Expand All @@ -45,6 +46,7 @@
PartitionNode,
PartitionTreeRow,
RelationKind,
UnattachedTable,
build_partition_tree,
)
from pg_partsmith.utils import (
Expand Down Expand Up @@ -320,6 +322,37 @@ async def _orphans_of(self, parents: list[str]) -> tuple[DetachedPartition, ...]
)
return tuple(orphans)

async def get_unattached_tables(self, table_name: str) -> tuple[UnattachedTable, ...]:
"""Tables named under ``table_name``, attached to nothing and carrying no orphan marker.

A partition is created standalone and attached last, so this is what
one looks like when whatever was filling it stopped first. Every table
in the root's schema whose name begins with the root's is a candidate;
which of them name a window is the scheme's call, and no row of any of
them is read here.
"""
async with self._engine.connect() as conn:
result = await conn.execute(
text(UNATTACHED_SQL),
{"table_name": to_regclass_argument(table_name), "marker_prefix": self._marker_prefix},
)
rows = result.fetchall()

tables: list[UnattachedTable] = []
for row in rows:
schema = coerce_str(row.partition_schema) or ""
relname = coerce_str(row.partition_name) or ""
if not is_addressable(schema, relname):
continue
tables.append(
UnattachedTable(
name=qualify(schema, relname),
oid=int(row.oid),
relkind=RelationKind.from_relkind(coerce_str(row.relkind, encoding="ascii")),
)
)
return tuple(tables)

async def _measure(
self,
root: PartitionNode,
Expand Down
10 changes: 10 additions & 0 deletions pg_partsmith/aio/protocols.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
PartitionType,
RangeBounds,
RelationKind,
UnattachedTable,
)

__all__ = [
Expand Down Expand Up @@ -439,6 +440,15 @@ async def is_partition_closed(
"""
...

async def get_unattached_tables(self, table_name: str) -> tuple[UnattachedTable, ...]:
"""Tables named under ``table_name``, attached to nothing and carrying no orphan marker.

The candidates for a partition whose creation stopped before its
attach: what a fill leaves behind when the process running it dies.
Nothing is read from them; which names are windows is the scheme's call.
"""
...

async def current_time(self) -> datetime:
"""The database's current time, timezone-aware.

Expand Down
31 changes: 29 additions & 2 deletions pg_partsmith/aio/services/inspection.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@
from typing import TYPE_CHECKING

from pg_partsmith.boundaries import Axis, CursorSource, Window
from pg_partsmith.planner import PlanMode, PlanningContext, fact_targets
from pg_partsmith.planner import PlanMode, PlanningContext, fact_targets, unattached_window
from pg_partsmith.scheme import RangePartitioning

if TYPE_CHECKING:
from pg_partsmith.aio.protocols import PartitionMetadataProvider
from pg_partsmith.entities import TablePartitionConfig
from pg_partsmith.topology import ActualTree
from pg_partsmith.topology import ActualTree, UnattachedTable


class PartitionInspector:
Expand Down Expand Up @@ -40,6 +41,9 @@ async def inspect(self, config: TablePartitionConfig, *, measure: bool = True) -
tree = await self._metadata.get_actual_tree(config.qualified_name)
if tree is None or not measure or not config.has_progression_level:
return tree
unattached = await unattached_tables(self._metadata, config)
if unattached:
tree = tree.model_copy(update={"unattached": unattached})

policy = config.lifecycle
if not policy.needs_facts:
Expand Down Expand Up @@ -94,3 +98,26 @@ async def context(
mode=mode,
explicit_windows=dict(explicit_windows or {}),
)


async def unattached_tables(
metadata: PartitionMetadataProvider, config: TablePartitionConfig
) -> tuple[UnattachedTable, ...]:
"""The tables named under the root and attached to nothing, ``holds_rows`` answered where it matters.

Only a name the root's scheme reads back as one of its windows is looked
into, so a table that merely shares the prefix -- the root's pre-migration
copy, say -- is never read and needs no grant. The question asked is
whether the table has a first row at all.
"""
root = config.scheme
if not isinstance(root, RangePartitioning):
return ()
measured: list[UnattachedTable] = []
for table in await metadata.get_unattached_tables(config.qualified_name):
if unattached_window(config, table.relname) is None:
measured.append(table)
continue
first = await metadata.get_leading_key_minimum(table.name, root.key)
measured.append(table.model_copy(update={"holds_rows": first is not None}))
return tuple(measured)
Loading
Loading