diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e7e894..e3cb33b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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) diff --git a/docs/agents.md b/docs/agents.md index 5f966f8..0b7ff70 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -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 diff --git a/docs/concepts/execution.md b/docs/concepts/execution.md index a755d87..9daeb62 100644 --- a/docs/concepts/execution.md +++ b/docs/concepts/execution.md @@ -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 | diff --git a/docs/design/api-cheatsheet-1.0.md b/docs/design/api-cheatsheet-1.0.md index 7c20c7e..7acc60c 100644 --- a/docs/design/api-cheatsheet-1.0.md +++ b/docs/design/api-cheatsheet-1.0.md @@ -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. diff --git a/docs/guide/extending.md b/docs/guide/extending.md index c1b19da..cc12300 100644 --- a/docs/guide/extending.md +++ b/docs/guide/extending.md @@ -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 diff --git a/docs/guide/partition-existing-table.md b/docs/guide/partition-existing-table.md index f576f29..8b17073 100644 --- a/docs/guide/partition-existing-table.md +++ b/docs/guide/partition-existing-table.md @@ -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 diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.md index 98353e7..972f2f5 100644 --- a/docs/guide/troubleshooting.md +++ b/docs/guide/troubleshooting.md @@ -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=…)` diff --git a/docs/reference/findings.md b/docs/reference/findings.md index b37e2fa..5f634c6 100644 --- a/docs/reference/findings.md +++ b/docs/reference/findings.md @@ -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 diff --git a/pg_partsmith/__init__.py b/pg_partsmith/__init__.py index 1b59a86..d5ea51b 100644 --- a/pg_partsmith/__init__.py +++ b/pg_partsmith/__init__.py @@ -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__ = [ @@ -225,6 +225,7 @@ "TimezoneAwareCalculator", "ToolkitOptions", "UUIDv7BoundaryCodec", + "UnattachedTable", "UnmanagedPartitionDropError", "Unreferenced", "WeekPeriodCalculator", diff --git a/pg_partsmith/aio/metadata.py b/pg_partsmith/aio/metadata.py index c94facb..633f566 100644 --- a/pg_partsmith/aio/metadata.py +++ b/pg_partsmith/aio/metadata.py @@ -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 @@ -45,6 +46,7 @@ PartitionNode, PartitionTreeRow, RelationKind, + UnattachedTable, build_partition_tree, ) from pg_partsmith.utils import ( @@ -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, diff --git a/pg_partsmith/aio/protocols.py b/pg_partsmith/aio/protocols.py index beb2a6f..3cae828 100644 --- a/pg_partsmith/aio/protocols.py +++ b/pg_partsmith/aio/protocols.py @@ -32,6 +32,7 @@ PartitionType, RangeBounds, RelationKind, + UnattachedTable, ) __all__ = [ @@ -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. diff --git a/pg_partsmith/aio/services/inspection.py b/pg_partsmith/aio/services/inspection.py index 5ea970c..3316a9d 100644 --- a/pg_partsmith/aio/services/inspection.py +++ b/pg_partsmith/aio/services/inspection.py @@ -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: @@ -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: @@ -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) diff --git a/pg_partsmith/aio/services/migration.py b/pg_partsmith/aio/services/migration.py index 9bd78d9..bcdf884 100644 --- a/pg_partsmith/aio/services/migration.py +++ b/pg_partsmith/aio/services/migration.py @@ -21,16 +21,17 @@ from typing import TYPE_CHECKING, Any from pg_partsmith.aio.services.execution import LOCK_NOT_GRANTED +from pg_partsmith.aio.services.inspection import unattached_tables from pg_partsmith.boundaries import Window -from pg_partsmith.constants import DEFAULT_MOVE_BATCH_ROWS, LOCK_NOT_AVAILABLE_SQLSTATE +from pg_partsmith.constants import DEFAULT_MOVE_BATCH_ROWS, LOCK_NOT_AVAILABLE_SQLSTATE, PG_CHECK_VIOLATION from pg_partsmith.entities import MaintenanceIssue, MaintenanceIssueStep, MigrationResult from pg_partsmith.exceptions import InvalidPartitionConfigError, PartitionTopologyError, RowMoveRefusedError from pg_partsmith.lifecycle import DropAfter from pg_partsmith.plan import AttachPartition, CreatePartition, DetachPartition, DropPartition, MaintenancePlan, Reason -from pg_partsmith.planner import to_maintenance_issue +from pg_partsmith.planner import to_maintenance_issue, unattached_window from pg_partsmith.scheme import RangePartitioning from pg_partsmith.topology import DefaultBounds, PartitionNode, RangeBounds, RelationKind -from pg_partsmith.utils import pg_sqlstate +from pg_partsmith.utils import is_default_partition_conflict, pg_sqlstate if TYPE_CHECKING: from pg_partsmith.aio.protocols import PartitionMetadataProvider, PartitionRepository @@ -100,11 +101,17 @@ async def partition_data( tally = _Tally(max_batches) while True: probe = await self._metadata.get_leading_key_minimum(default.name, root.key) - if probe is None: - return tally.result(complete=True) - - position = boundaries.decode(str(probe)) - window = boundaries.window_at(probe if position is None else position) + stranded = probe is None + if stranded: + # DEFAULT is drained. A partition whose fill finished and whose + # attach never happened -- the process died in between -- holds + # its window's rows where no probe of DEFAULT will find them. + window = await self._stranded_window(config) + if window is None: + return tally.result(complete=True) + else: + position = boundaries.decode(str(probe)) + window = boundaries.window_at(probe if position is None else position) plan = await plan_for(window) tally.issues.extend(to_maintenance_issue(f) for f in plan.actionable_findings) op = self._window_operation(plan) @@ -130,6 +137,15 @@ async def partition_data( # window forever. return tally.unfinished(default.name, boundaries.describe(window), exc.detail) except Exception as exc: + if stranded and pg_sqlstate(exc) == PG_CHECK_VIOLATION and not is_default_partition_conflict(exc): + # The table's own rows do not fit its window, so no fill of + # this library's put them there: it only takes a window's rows. + tally.issue( + op.target, + f"{op.target} holds rows outside {boundaries.describe(window)}, so it cannot become that " + "window's partition; it was not left by a backfill, and it is left as it is", + ) + return tally.result(complete=False) if pg_sqlstate(exc) != LOCK_NOT_AVAILABLE_SQLSTATE: raise return tally.unfinished(default.name, boundaries.describe(window), LOCK_NOT_GRANTED) @@ -141,7 +157,7 @@ async def partition_data( return tally.result(complete=False) tally.partitions.append(op.target) - if tally.rows_moved == moved_before: + if not stranded and tally.rows_moved == moved_before: # The probe found a row this window's literals do not select # -- a bound rendered in another timezone, say. Looping would # create the same partition forever. @@ -152,6 +168,11 @@ async def partition_data( ) return tally.result(complete=False) + async def _stranded_window(self, config: TablePartitionConfig) -> Window | None: + """The window of a partition a stopped fill left unattached with rows in it, if there is one.""" + tables = await unattached_tables(self._metadata, config) + return next((unattached_window(config, t.relname) for t in tables if t.holds_rows), None) + @staticmethod def _window_operation(plan: MaintenancePlan) -> CreatePartition | AttachPartition | None: """The operation that gives the window its partition: a creation, or a matching orphan's re-attach.""" diff --git a/pg_partsmith/catalog_queries.py b/pg_partsmith/catalog_queries.py index f4ff377..128d7fd 100644 --- a/pg_partsmith/catalog_queries.py +++ b/pg_partsmith/catalog_queries.py @@ -125,6 +125,38 @@ ORDER BY ns.nspname, c.relname """ +# Tables in the root's schema whose names begin with the root's, attached to +# nothing and carrying no orphan marker. A partition is created standalone and +# attached last, so that is exactly what one looks like when whatever was +# filling it stopped before the attach. The root itself is excluded, and which +# of the rest are partitions at all is the scheme's call: their names are read +# back against it, and no row of any of them is read here. +UNATTACHED_SQL = """ + SELECT + c.oid AS oid, + c.relkind AS relkind, + ns.nspname AS partition_schema, + c.relname AS partition_name + FROM pg_class root + JOIN pg_class c ON c.relnamespace = root.relnamespace + JOIN pg_namespace ns ON ns.oid = c.relnamespace + WHERE root.oid = to_regclass(:table_name) + AND c.oid <> root.oid + AND c.relkind IN ('r', 'p') + AND c.relispartition = false + AND left(c.relname, length(root.relname)) = root.relname + AND NOT EXISTS (SELECT 1 FROM pg_inherits inh WHERE inh.inhrelid = c.oid) + AND NOT EXISTS ( + SELECT 1 + FROM pg_description d + WHERE d.objoid = c.oid + AND d.classoid = 'pg_class'::regclass + AND d.objsubid = 0 + AND left(d.description, length(:marker_prefix)) = :marker_prefix + ) + ORDER BY c.relname +""" + # Size and row estimate of each relation in ``:oids``, subtree included. # # ``pg_total_relation_size`` of a partitioned relation is 0 -- it has no diff --git a/pg_partsmith/plan.py b/pg_partsmith/plan.py index 2d62d64..dc56b59 100644 --- a/pg_partsmith/plan.py +++ b/pg_partsmith/plan.py @@ -160,6 +160,9 @@ class FindingReason(StrEnum): GRACE_PENDING: A detached orphan still within its grace period. DROP_DEFERRED: A detached orphan past its grace whose drop condition does not hold yet. + UNATTACHED_ROWS: A partition named for a window of the root holds rows + but was never attached -- a fill stopped before its attach -- so no + query through the root sees them. ``partition_data`` attaches it. """ LEGACY_LEAF = "legacy_leaf" @@ -182,6 +185,7 @@ class FindingReason(StrEnum): DETACH_PENDING = "detach_pending" GRACE_PENDING = "grace_pending" DROP_DEFERRED = "drop_deferred" + UNATTACHED_ROWS = "unattached_rows" # Reasons that describe a healthy, deliberate state (policy evolution, a diff --git a/pg_partsmith/planner.py b/pg_partsmith/planner.py index f459e6c..09b03c7 100644 --- a/pg_partsmith/planner.py +++ b/pg_partsmith/planner.py @@ -127,6 +127,23 @@ def plan_maintenance(config: TablePartitionConfig, actual: ActualTree, context: ) +def unattached_window(config: TablePartitionConfig, relname: str) -> Window | None: + """The root window ``relname`` is the partition for, or None. + + The name has to read back as a window *and* be the very name the scheme + gives that window under this root: ``metrics_remote__2025_01`` beside + ``metrics`` reads as January, but it is not a partition of ``metrics``. + """ + root = config.scheme + if not isinstance(root, RangePartitioning): + return None + boundaries = root.range_boundaries + window = boundaries.parse_child_name(relname) + if window is None or boundaries.child_name(config.table_name, window) != relname: + return None + return window + + def fact_targets(config: TablePartitionConfig, actual: ActualTree) -> tuple[str, ...]: """Names the lifecycle policy may need facts about. @@ -228,6 +245,29 @@ def _owns(self, relkind: RelationKind) -> bool: def run(self) -> None: self._plan_level(self.config.scheme, self.actual.root, depth=0) + self._report_unattached() + + def _report_unattached(self) -> None: + """A partition that was filled and never attached holds rows no query through the root sees. + + Not when this plan creates the window anyway: the executor finds the + table under that name and attaches it. + """ + root = self.config.scheme + if not isinstance(root, RangePartitioning): + return + boundaries = root.range_boundaries + planned = {op.target.rpartition(".")[2] for op in self.creates} + for table in self.actual.unattached: + window = unattached_window(self.config, table.relname) + if not table.holds_rows or window is None or table.relname in planned: + continue + self._record( + table.name, + FindingReason.UNATTACHED_ROWS, + f"{table.name} holds rows of {boundaries.describe(window)} but is attached to nothing, so no query " + f"through {self.config.qualified_name} sees them; backfill (partition_data) attaches it.", + ) # ── Dispatch ──────────────────────────────────────────────────────────────── diff --git a/pg_partsmith/sync/metadata.py b/pg_partsmith/sync/metadata.py index cdb0e3a..91e183c 100644 --- a/pg_partsmith/sync/metadata.py +++ b/pg_partsmith/sync/metadata.py @@ -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 @@ -45,6 +46,7 @@ PartitionNode, PartitionTreeRow, RelationKind, + UnattachedTable, build_partition_tree, ) from pg_partsmith.utils import ( @@ -320,6 +322,37 @@ def _orphans_of(self, parents: list[str]) -> tuple[DetachedPartition, ...]: ) return tuple(orphans) + 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. + """ + with self._engine.connect() as conn: + result = 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) + def _measure( self, root: PartitionNode, diff --git a/pg_partsmith/sync/protocols.py b/pg_partsmith/sync/protocols.py index ef6eccd..3d2311a 100644 --- a/pg_partsmith/sync/protocols.py +++ b/pg_partsmith/sync/protocols.py @@ -32,6 +32,7 @@ PartitionType, RangeBounds, RelationKind, + UnattachedTable, ) __all__ = [ @@ -439,6 +440,15 @@ def is_partition_closed( """ ... + 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. + """ + ... + def current_time(self) -> datetime: """The database's current time, timezone-aware. diff --git a/pg_partsmith/sync/services/inspection.py b/pg_partsmith/sync/services/inspection.py index 6ee4b11..30c28f7 100644 --- a/pg_partsmith/sync/services/inspection.py +++ b/pg_partsmith/sync/services/inspection.py @@ -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.entities import TablePartitionConfig from pg_partsmith.sync.protocols import PartitionMetadataProvider - from pg_partsmith.topology import ActualTree + from pg_partsmith.topology import ActualTree, UnattachedTable class PartitionInspector: @@ -40,6 +41,9 @@ def inspect(self, config: TablePartitionConfig, *, measure: bool = True) -> Actu tree = self._metadata.get_actual_tree(config.qualified_name) if tree is None or not measure or not config.has_progression_level: return tree + unattached = unattached_tables(self._metadata, config) + if unattached: + tree = tree.model_copy(update={"unattached": unattached}) policy = config.lifecycle if not policy.needs_facts: @@ -94,3 +98,24 @@ def context( mode=mode, explicit_windows=dict(explicit_windows or {}), ) + + +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 metadata.get_unattached_tables(config.qualified_name): + if unattached_window(config, table.relname) is None: + measured.append(table) + continue + first = metadata.get_leading_key_minimum(table.name, root.key) + measured.append(table.model_copy(update={"holds_rows": first is not None})) + return tuple(measured) diff --git a/pg_partsmith/sync/services/migration.py b/pg_partsmith/sync/services/migration.py index 29a34fc..c531412 100644 --- a/pg_partsmith/sync/services/migration.py +++ b/pg_partsmith/sync/services/migration.py @@ -20,16 +20,17 @@ from typing import TYPE_CHECKING, Any from pg_partsmith.boundaries import Window -from pg_partsmith.constants import DEFAULT_MOVE_BATCH_ROWS, LOCK_NOT_AVAILABLE_SQLSTATE +from pg_partsmith.constants import DEFAULT_MOVE_BATCH_ROWS, LOCK_NOT_AVAILABLE_SQLSTATE, PG_CHECK_VIOLATION from pg_partsmith.entities import MaintenanceIssue, MaintenanceIssueStep, MigrationResult from pg_partsmith.exceptions import InvalidPartitionConfigError, PartitionTopologyError, RowMoveRefusedError from pg_partsmith.lifecycle import DropAfter from pg_partsmith.plan import AttachPartition, CreatePartition, DetachPartition, DropPartition, MaintenancePlan, Reason -from pg_partsmith.planner import to_maintenance_issue +from pg_partsmith.planner import to_maintenance_issue, unattached_window from pg_partsmith.scheme import RangePartitioning from pg_partsmith.sync.services.execution import LOCK_NOT_GRANTED +from pg_partsmith.sync.services.inspection import unattached_tables from pg_partsmith.topology import DefaultBounds, PartitionNode, RangeBounds, RelationKind -from pg_partsmith.utils import pg_sqlstate +from pg_partsmith.utils import is_default_partition_conflict, pg_sqlstate if TYPE_CHECKING: from pg_partsmith.entities import PartitionInfo, TablePartitionConfig @@ -99,11 +100,17 @@ def partition_data( tally = _Tally(max_batches) while True: probe = self._metadata.get_leading_key_minimum(default.name, root.key) - if probe is None: - return tally.result(complete=True) - - position = boundaries.decode(str(probe)) - window = boundaries.window_at(probe if position is None else position) + stranded = probe is None + if stranded: + # DEFAULT is drained. A partition whose fill finished and whose + # attach never happened -- the process died in between -- holds + # its window's rows where no probe of DEFAULT will find them. + window = self._stranded_window(config) + if window is None: + return tally.result(complete=True) + else: + position = boundaries.decode(str(probe)) + window = boundaries.window_at(probe if position is None else position) plan = plan_for(window) tally.issues.extend(to_maintenance_issue(f) for f in plan.actionable_findings) op = self._window_operation(plan) @@ -129,6 +136,15 @@ def partition_data( # window forever. return tally.unfinished(default.name, boundaries.describe(window), exc.detail) except Exception as exc: + if stranded and pg_sqlstate(exc) == PG_CHECK_VIOLATION and not is_default_partition_conflict(exc): + # The table's own rows do not fit its window, so no fill of + # this library's put them there: it only takes a window's rows. + tally.issue( + op.target, + f"{op.target} holds rows outside {boundaries.describe(window)}, so it cannot become that " + "window's partition; it was not left by a backfill, and it is left as it is", + ) + return tally.result(complete=False) if pg_sqlstate(exc) != LOCK_NOT_AVAILABLE_SQLSTATE: raise return tally.unfinished(default.name, boundaries.describe(window), LOCK_NOT_GRANTED) @@ -140,7 +156,7 @@ def partition_data( return tally.result(complete=False) tally.partitions.append(op.target) - if tally.rows_moved == moved_before: + if not stranded and tally.rows_moved == moved_before: # The probe found a row this window's literals do not select # -- a bound rendered in another timezone, say. Looping would # create the same partition forever. @@ -151,6 +167,11 @@ def partition_data( ) return tally.result(complete=False) + def _stranded_window(self, config: TablePartitionConfig) -> Window | None: + """The window of a partition a stopped fill left unattached with rows in it, if there is one.""" + tables = unattached_tables(self._metadata, config) + return next((unattached_window(config, t.relname) for t in tables if t.holds_rows), None) + @staticmethod def _window_operation(plan: MaintenancePlan) -> CreatePartition | AttachPartition | None: """The operation that gives the window its partition: a creation, or a matching orphan's re-attach.""" diff --git a/pg_partsmith/topology.py b/pg_partsmith/topology.py index 721544b..1f4f4b8 100644 --- a/pg_partsmith/topology.py +++ b/pg_partsmith/topology.py @@ -44,6 +44,7 @@ "PartitionType", "RangeBounds", "RelationKind", + "UnattachedTable", "build_partition_tree", "hash_keyspace_covered", "missing_remainders", @@ -379,18 +380,51 @@ def relname(self) -> str: return relname or self.name +class UnattachedTable(BaseModel): + """A table named under the root that is attached to nothing and carries no orphan marker. + + A partition is created standalone and attached last, so this is what one + looks like in between -- and what it stays when whatever was filling it + stopped before the attach. Found by name, since no marker says whose it + is; only a name that is a window of the scheme makes it a partition at all. + + Attributes: + name: Schema-qualified relation name. + oid: ``pg_class.oid``. + relkind: What the relation physically is. + holds_rows: Whether it holds any row. None until something looked, + which only happens for a name that is a window of the scheme. + """ + + model_config = ConfigDict(frozen=True) + + name: StrippedNonEmptyStr + oid: int | None = None + relkind: RelationKind = RelationKind.TABLE + holds_rows: bool | None = None + + @property + def relname(self) -> str: + """Bare relation name without the schema qualifier.""" + _, _, relname = self.name.rpartition(".") + return relname or self.name + + class ActualTree(BaseModel): """Everything below one root that maintenance may act on. Attributes: root: The partitioned table and its whole attached subtree. orphans: Marker-tagged detached tables whose marker names the root. + unattached: Tables named under the root, attached to nothing and + unmarked: partitions whose creation stopped before their attach. """ model_config = ConfigDict(frozen=True) root: PartitionNode orphans: tuple[DetachedPartition, ...] = () + unattached: tuple[UnattachedTable, ...] = () def find(self, name: str) -> PartitionNode | None: """Return the attached node with schema-qualified ``name``, or None.""" diff --git a/tests/integration/aio/test_migration.py b/tests/integration/aio/test_migration.py index 51f13ac..f64ee55 100644 --- a/tests/integration/aio/test_migration.py +++ b/tests/integration/aio/test_migration.py @@ -25,6 +25,7 @@ from pg_partsmith.entities import MaintenanceIssueStep, Period from pg_partsmith.events import PartitionEvent from pg_partsmith.exceptions import InvalidPartitionConfigError, PlanStaleError +from pg_partsmith.plan import FindingReason from tests.integration.aio.support import ( child_count, exec_sql, @@ -219,6 +220,63 @@ async def test__partition_data__attach_not_granted_its_lock__rows_stay_visible_a assert await _count(db_engine, events) == 25 +async def test__partition_data__a_fill_the_process_died_after__is_reported_then_attached( + db_engine: AsyncEngine, events: str +) -> None: + # Arrange -- March was filled and never attached: DEFAULT is empty, the rows sit in a + # standalone table under March's name. A table that only shares the prefix sits beside it. + await _default_with_rows(db_engine, events, months=(3,), per_month=0) + march = f"{events}__2026_03" + await exec_sql(db_engine, f'CREATE TABLE "{march}" (LIKE "{events}" INCLUDING ALL)') + await exec_sql( + db_engine, + f'INSERT INTO "{march}" (created_at, payload) ' # noqa: S608 + "SELECT '2026-03-01 00:00+00'::timestamptz + g * interval '1 hour', 'x' FROM generate_series(0, 24) g", + ) + await exec_sql(db_engine, f'CREATE TABLE "{events}__archive" (LIKE "{events}" INCLUDING ALL)') + await exec_sql(db_engine, f"INSERT INTO \"{events}__archive\" (created_at) VALUES ('2026-03-02')") # noqa: S608 + config = monthly_config(events, create_ahead=1) + service = make_service(db_engine) + now = datetime(2026, 8, 26, tzinfo=UTC) + + # Act + before = await service.plan(config, now=now) + result = await service.partition_data(config) + after = await service.plan(config, now=now) + + # Assert -- reported while hidden, attached by the backfill, and nothing else touched + assert [(f.partition_name, f.reason) for f in before.actionable_findings] == [ + (f"public.{march}", FindingReason.UNATTACHED_ROWS) + ] + assert result.complete + assert result.partitions == (f"public.{march}",) + assert await is_attached(db_engine, march) + assert await _count(db_engine, events) == 25 + assert after.actionable_findings == () + assert not await is_attached(db_engine, f"{events}__archive") + assert await _count(db_engine, f"{events}__archive") == 1 + + +async def test__partition_data__a_window_named_table_with_other_rows__is_reported_and_left_alone( + db_engine: AsyncEngine, events: str +) -> None: + # Arrange -- a table under March's name holding February's rows: not something a fill leaves + await _default_with_rows(db_engine, events, months=(3,), per_month=0) + march = f"{events}__2026_03" + await exec_sql(db_engine, f'CREATE TABLE "{march}" (LIKE "{events}" INCLUDING ALL)') + await exec_sql(db_engine, f"INSERT INTO \"{march}\" (created_at) VALUES ('2026-02-20 00:00+00')") # noqa: S608 + + # Act + result = await make_service(db_engine).partition_data(monthly_config(events, create_ahead=1)) + + # Assert + assert not result.complete + assert [issue.partition_name for issue in result.issues] == [f"public.{march}"] + assert "holds rows outside 2026_03" in result.issues[0].error + assert not await is_attached(db_engine, march) + assert await _count(db_engine, march) == 1 + + async def test__partition_data__nested_scheme__rows_land_in_the_buckets(db_engine: AsyncEngine, tenants: str) -> None: # Arrange default = f"{tenants}_legacy" diff --git a/tests/integration/sync/test_migration.py b/tests/integration/sync/test_migration.py index 314f532..72c1a8a 100644 --- a/tests/integration/sync/test_migration.py +++ b/tests/integration/sync/test_migration.py @@ -17,6 +17,7 @@ from pg_partsmith.entities import MaintenanceIssueStep, Period from pg_partsmith.events import PartitionEvent from pg_partsmith.exceptions import InvalidPartitionConfigError +from pg_partsmith.plan import FindingReason from pg_partsmith.sync.hooks import BasePartitionLifecycleHooks from pg_partsmith.sync.metadata import PostgresMetadataProvider from pg_partsmith.sync.repositories import PostgresPartitionRepository @@ -170,6 +171,63 @@ def test__partition_data__attach_not_granted_its_lock__rows_stay_visible_and_the assert _count(sync_db_engine, events) == 25 +def test__partition_data__a_fill_the_process_died_after__is_reported_then_attached( + sync_db_engine: Engine, events: str +) -> None: + # Arrange -- March was filled and never attached: DEFAULT is empty, the rows sit in a + # standalone table under March's name. A table that only shares the prefix sits beside it. + _default_with_rows(sync_db_engine, events, months=(3,), per_month=0) + march = f"{events}__2026_03" + exec_sql(sync_db_engine, f'CREATE TABLE "{march}" (LIKE "{events}" INCLUDING ALL)') + exec_sql( + sync_db_engine, + f'INSERT INTO "{march}" (created_at, payload) ' # noqa: S608 + "SELECT '2026-03-01 00:00+00'::timestamptz + g * interval '1 hour', 'x' FROM generate_series(0, 24) g", + ) + exec_sql(sync_db_engine, f'CREATE TABLE "{events}__archive" (LIKE "{events}" INCLUDING ALL)') + exec_sql(sync_db_engine, f"INSERT INTO \"{events}__archive\" (created_at) VALUES ('2026-03-02')") # noqa: S608 + config = monthly_config(events, create_ahead=1) + service = make_service(sync_db_engine) + now = datetime(2026, 8, 26, tzinfo=UTC) + + # Act + before = service.plan(config, now=now) + result = service.partition_data(config) + after = service.plan(config, now=now) + + # Assert -- reported while hidden, attached by the backfill, and nothing else touched + assert [(f.partition_name, f.reason) for f in before.actionable_findings] == [ + (f"public.{march}", FindingReason.UNATTACHED_ROWS) + ] + assert result.complete + assert result.partitions == (f"public.{march}",) + assert is_attached(sync_db_engine, march) + assert _count(sync_db_engine, events) == 25 + assert after.actionable_findings == () + assert not is_attached(sync_db_engine, f"{events}__archive") + assert _count(sync_db_engine, f"{events}__archive") == 1 + + +def test__partition_data__a_window_named_table_with_other_rows__is_reported_and_left_alone( + sync_db_engine: Engine, events: str +) -> None: + # Arrange -- a table under March's name holding February's rows: not something a fill leaves + _default_with_rows(sync_db_engine, events, months=(3,), per_month=0) + march = f"{events}__2026_03" + exec_sql(sync_db_engine, f'CREATE TABLE "{march}" (LIKE "{events}" INCLUDING ALL)') + exec_sql(sync_db_engine, f"INSERT INTO \"{march}\" (created_at) VALUES ('2026-02-20 00:00+00')") # noqa: S608 + + # Act + result = make_service(sync_db_engine).partition_data(monthly_config(events, create_ahead=1)) + + # Assert + assert not result.complete + assert [issue.partition_name for issue in result.issues] == [f"public.{march}"] + assert "holds rows outside 2026_03" in result.issues[0].error + assert not is_attached(sync_db_engine, march) + assert _count(sync_db_engine, march) == 1 + + def test__partition_data__nested_scheme__rows_land_in_the_buckets(sync_db_engine: Engine, tenants: str) -> None: # Arrange default = f"{tenants}_legacy" diff --git a/tests/unit/sync/test_inspection.py b/tests/unit/sync/test_inspection.py index e6b9904..5c49262 100644 --- a/tests/unit/sync/test_inspection.py +++ b/tests/unit/sync/test_inspection.py @@ -22,8 +22,8 @@ ) from pg_partsmith.planner import PlanMode from pg_partsmith.scheme import HashPartitioning, RangePartitioning -from pg_partsmith.sync.services.inspection import PartitionInspector -from pg_partsmith.topology import ActualTree, DetachedPartition, FactKind +from pg_partsmith.sync.services.inspection import PartitionInspector, unattached_tables +from pg_partsmith.topology import ActualTree, DetachedPartition, FactKind, UnattachedTable NOW = datetime(2024, 3, 15, 12, 0, tzinfo=UTC) @@ -33,6 +33,8 @@ @pytest.fixture def metadata() -> MagicMock: metadata = MagicMock() + metadata.get_unattached_tables = MagicMock(return_value=()) + metadata.get_leading_key_minimum = MagicMock(return_value=None) metadata.get_actual_tree = MagicMock(return_value=_tree()) metadata.measure = MagicMock(side_effect=lambda tree, **kwargs: tree) metadata.get_key_high_water_mark = MagicMock(return_value=None) @@ -239,6 +241,69 @@ def test__inspect__nested_progression_level__measures_members_below_the_root( assert metadata.measure.call_args.kwargs["targets"] == ("events__h0__2024_02",) +# ── unattached tables ─────────────────────────────────────────────────────────── + + +def test__unattached_tables__only_a_window_name_is_looked_into(metadata: MagicMock) -> None: + # Arrange -- March's table, one that merely shares the prefix, and one that looks like a window + # of another table whose name starts with the root's + march, archive = UnattachedTable(name="events__2024_03"), UnattachedTable(name="events__archive") + remote = UnattachedTable(name="events_remote__2024_03") + metadata.get_unattached_tables.return_value = (march, archive, remote) + metadata.get_leading_key_minimum.return_value = datetime(2024, 3, 5, tzinfo=UTC) + + # Act + tables = unattached_tables(metadata, _config()) + + # Assert -- the archive's rows are never read, so it needs no grant + assert [(t.name, t.holds_rows) for t in tables] == [ + ("events__2024_03", True), + ("events__archive", None), + ("events_remote__2024_03", None), + ] + metadata.get_leading_key_minimum.assert_called_once_with("events__2024_03", ("created_at",)) + + +def test__unattached_tables__an_empty_window_table__holds_no_rows(metadata: MagicMock) -> None: + # Arrange + metadata.get_unattached_tables.return_value = (UnattachedTable(name="events__2024_03"),) + metadata.get_leading_key_minimum.return_value = None + + # Act + tables = unattached_tables(metadata, _config()) + + # Assert + assert [t.holds_rows for t in tables] == [False] + + +def test__inspect__unattached_window_tables__are_on_the_tree( + inspector: PartitionInspector, metadata: MagicMock +) -> None: + # Arrange + metadata.get_actual_tree.return_value = _tree() + metadata.get_unattached_tables.return_value = (UnattachedTable(name="events__2024_03"),) + metadata.get_leading_key_minimum.return_value = datetime(2024, 3, 5, tzinfo=UTC) + + # Act + tree = inspector.inspect(_config()) + + # Assert + assert tree is not None + assert [(t.name, t.holds_rows) for t in tree.unattached] == [("events__2024_03", True)] + + +def test__unattached_tables__a_root_that_is_not_range__is_not_searched(metadata: MagicMock) -> None: + # Arrange + config = TablePartitionConfig(table_name="tasks", scheme=HashPartitioning(key="task_id", modulus=4)) + + # Act + tables = unattached_tables(metadata, config) + + # Assert + assert tables == () + metadata.get_unattached_tables.assert_not_called() + + # ── context ───────────────────────────────────────────────────────────────────── diff --git a/tests/unit/sync/test_metadata.py b/tests/unit/sync/test_metadata.py index d7150e7..746cf38 100644 --- a/tests/unit/sync/test_metadata.py +++ b/tests/unit/sync/test_metadata.py @@ -25,6 +25,7 @@ PartitionNode, RangeBounds, RelationKind, + UnattachedTable, ) from pg_partsmith.utils import DETACHED_AT_MARKER, orphan_table_comment @@ -456,6 +457,27 @@ def test__get_actual_tree__orphan_query__carries_a_marker_for_every_partitioned_ assert orphan_call.args[1] == {"markers": ["myapp:parent=public.events", "myapp:parent=public.events__2024_02"]} +def test__get_unattached_tables__rows__become_qualified_tables_and_the_unaddressable_are_left_out() -> None: + # Arrange + rows = [ + _orphan_row("events__2024_03", None, oid=600), + _orphan_row("events__2024_04", None, oid=601, relkind="p"), + _orphan_row("events__2024_05", None, oid=602, schema="bad.schema"), + ] + engine = _make_engine(rows) + provider = PostgresMetadataProvider(engine, marker_prefix="acme:") + + # Act + tables = provider.get_unattached_tables("events") + + # Assert -- the root is resolved by the server, the marker prefix keeps orphans out + assert tables == ( + UnattachedTable(name="public.events__2024_03", oid=600, relkind=RelationKind.TABLE), + UnattachedTable(name="public.events__2024_04", oid=601, relkind=RelationKind.PARTITIONED), + ) + assert _conn(engine).execute.call_args.args[1] == {"table_name": '"events"', "marker_prefix": "acme:"} + + def test__get_actual_tree__orphans__are_parsed_with_their_detach_instant() -> None: # Arrange marker = orphan_table_comment("public.events") diff --git a/tests/unit/sync/test_migration.py b/tests/unit/sync/test_migration.py index e828c2a..1eadfe5 100644 --- a/tests/unit/sync/test_migration.py +++ b/tests/unit/sync/test_migration.py @@ -34,7 +34,7 @@ ) from pg_partsmith.scheme import HashPartitioning, ListGroup, ListPartitioning from pg_partsmith.sync.services.migration import DataMover -from pg_partsmith.topology import ActualTree, DetachedPartition, RelationKind +from pg_partsmith.topology import ActualTree, DetachedPartition, RelationKind, UnattachedTable NOW = datetime(2026, 8, 28, tzinfo=UTC) ROOT = "public.events" @@ -55,6 +55,7 @@ def repo() -> MagicMock: @pytest.fixture def metadata() -> MagicMock: metadata = MagicMock() + metadata.get_unattached_tables = MagicMock(return_value=()) metadata.get_default_partition = MagicMock(return_value=_default_info()) metadata.get_leading_key_minimum = MagicMock(return_value=None) metadata.get_actual_tree = MagicMock(return_value=None) @@ -128,6 +129,12 @@ def create_partition(config: Any, plan: Any, op: Any, *, issues: Any, fill: Any return create_partition +class _CheckViolationError(Exception): + """What a driver raises when ATTACH finds a row outside the partition's bounds.""" + + sqlstate = "23514" + + class _LockNotAvailableError(Exception): """What a driver raises when lock_timeout runs out, whichever driver it is.""" @@ -577,6 +584,60 @@ def test__partition_data__move_refused_by_a_foreign_key_action__issue_and_incomp assert "ON DELETE CASCADE" in result.issues[0].error +def test__partition_data__default_drained_and_a_window_left_unattached__finishes_that_window( + mover: DataMover, metadata: MagicMock, repo: MagicMock +) -> None: + # Arrange -- DEFAULT is empty; March's table holds rows and was never attached + metadata.get_unattached_tables.side_effect = [(UnattachedTable(name=f"{ROOT}__2026_03"),), ()] + metadata.get_leading_key_minimum.side_effect = [None, datetime(2026, 3, 5, tzinfo=UTC), None] + plan_for = _plans(_plan(_create_op(3))) + + # Act + result = mover.partition_data(_config(), plan_for, batch_rows=10) + + # Assert -- March goes through the path a window out of DEFAULT takes, and then there is nothing left + assert result.complete + assert result.partitions == (f"{ROOT}__2026_03",) + assert result.issues == () + assert plan_for.call_args.args[0] == _window(3) + + +def test__partition_data__a_window_table_whose_rows_do_not_fit__is_left_as_it_is( + mover: DataMover, metadata: MagicMock, executor: MagicMock +) -> None: + # Arrange -- March's name, rows that are not March's: no fill of ours put them there + metadata.get_unattached_tables.return_value = (UnattachedTable(name=f"{ROOT}__2026_03"),) + metadata.get_leading_key_minimum.side_effect = [None, datetime(2026, 2, 20, tzinfo=UTC)] + executor.create_partition.side_effect = _CheckViolationError( + f'partition constraint of relation "{ROOT}__2026_03" is violated by some row' + ) + plan_for = _plans(_plan(_create_op(3))) + + # Act + result = mover.partition_data(_config(), plan_for, batch_rows=10) + + # Assert -- reported, not raised, and not retried in a loop + assert not result.complete + assert [issue.partition_name for issue in result.issues] == [f"{ROOT}__2026_03"] + assert "holds rows outside 2026_03" in result.issues[0].error + assert executor.create_partition.call_count == 1 + + +def test__partition_data__default_drained_and_nothing_left_unattached__is_complete( + mover: DataMover, metadata: MagicMock +) -> None: + # Arrange -- the fixture's defaults: an empty DEFAULT, nothing unattached + plan_for = _plans() + + # Act + result = mover.partition_data(_config(), plan_for, batch_rows=10) + + # Assert + assert result.complete + assert result.partitions == () + plan_for.assert_not_called() + + def test__partition_data__a_lock_not_granted_in_time__issue_and_incomplete( mover: DataMover, metadata: MagicMock, executor: MagicMock ) -> None: diff --git a/tests/unit/sync/test_service.py b/tests/unit/sync/test_service.py index 5236dfb..7b65cd5 100644 --- a/tests/unit/sync/test_service.py +++ b/tests/unit/sync/test_service.py @@ -88,6 +88,7 @@ def repo() -> MagicMock: @pytest.fixture def metadata() -> MagicMock: metadata = MagicMock() + metadata.get_unattached_tables = MagicMock(return_value=()) metadata.get_partition_type = MagicMock(return_value=PartitionType.RANGE) metadata.get_partition_columns = MagicMock(return_value=("created_at",)) metadata.get_actual_tree = MagicMock(return_value=_tree()) diff --git a/tests/unit/test_inspection.py b/tests/unit/test_inspection.py index 8a27e8a..d4e301f 100644 --- a/tests/unit/test_inspection.py +++ b/tests/unit/test_inspection.py @@ -8,7 +8,7 @@ import pytest -from pg_partsmith.aio.services.inspection import PartitionInspector +from pg_partsmith.aio.services.inspection import PartitionInspector, unattached_tables from pg_partsmith.boundaries import CursorSource, NumericBoundaries, TimeBoundaries, Window from pg_partsmith.entities import PartitionGranularity, PartitionNode, PartitionType, RangeBounds, TablePartitionConfig from pg_partsmith.lifecycle import ( @@ -23,7 +23,7 @@ ) from pg_partsmith.planner import PlanMode from pg_partsmith.scheme import HashPartitioning, RangePartitioning -from pg_partsmith.topology import ActualTree, DetachedPartition, FactKind +from pg_partsmith.topology import ActualTree, DetachedPartition, FactKind, UnattachedTable NOW = datetime(2024, 3, 15, 12, 0, tzinfo=UTC) @@ -33,6 +33,8 @@ @pytest.fixture def metadata() -> MagicMock: metadata = MagicMock() + metadata.get_unattached_tables = AsyncMock(return_value=()) + metadata.get_leading_key_minimum = AsyncMock(return_value=None) metadata.get_actual_tree = AsyncMock(return_value=_tree()) metadata.measure = AsyncMock(side_effect=lambda tree, **kwargs: tree) metadata.get_key_high_water_mark = AsyncMock(return_value=None) @@ -239,6 +241,69 @@ async def test__inspect__nested_progression_level__measures_members_below_the_ro assert metadata.measure.call_args.kwargs["targets"] == ("events__h0__2024_02",) +# ── unattached tables ─────────────────────────────────────────────────────────── + + +async def test__unattached_tables__only_a_window_name_is_looked_into(metadata: MagicMock) -> None: + # Arrange -- March's table, one that merely shares the prefix, and one that looks like a window + # of another table whose name starts with the root's + march, archive = UnattachedTable(name="events__2024_03"), UnattachedTable(name="events__archive") + remote = UnattachedTable(name="events_remote__2024_03") + metadata.get_unattached_tables.return_value = (march, archive, remote) + metadata.get_leading_key_minimum.return_value = datetime(2024, 3, 5, tzinfo=UTC) + + # Act + tables = await unattached_tables(metadata, _config()) + + # Assert -- the archive's rows are never read, so it needs no grant + assert [(t.name, t.holds_rows) for t in tables] == [ + ("events__2024_03", True), + ("events__archive", None), + ("events_remote__2024_03", None), + ] + metadata.get_leading_key_minimum.assert_awaited_once_with("events__2024_03", ("created_at",)) + + +async def test__unattached_tables__an_empty_window_table__holds_no_rows(metadata: MagicMock) -> None: + # Arrange + metadata.get_unattached_tables.return_value = (UnattachedTable(name="events__2024_03"),) + metadata.get_leading_key_minimum.return_value = None + + # Act + tables = await unattached_tables(metadata, _config()) + + # Assert + assert [t.holds_rows for t in tables] == [False] + + +async def test__inspect__unattached_window_tables__are_on_the_tree( + inspector: PartitionInspector, metadata: MagicMock +) -> None: + # Arrange + metadata.get_actual_tree.return_value = _tree() + metadata.get_unattached_tables.return_value = (UnattachedTable(name="events__2024_03"),) + metadata.get_leading_key_minimum.return_value = datetime(2024, 3, 5, tzinfo=UTC) + + # Act + tree = await inspector.inspect(_config()) + + # Assert + assert tree is not None + assert [(t.name, t.holds_rows) for t in tree.unattached] == [("events__2024_03", True)] + + +async def test__unattached_tables__a_root_that_is_not_range__is_not_searched(metadata: MagicMock) -> None: + # Arrange + config = TablePartitionConfig(table_name="tasks", scheme=HashPartitioning(key="task_id", modulus=4)) + + # Act + tables = await unattached_tables(metadata, config) + + # Assert + assert tables == () + metadata.get_unattached_tables.assert_not_awaited() + + # ── context ───────────────────────────────────────────────────────────────────── diff --git a/tests/unit/test_metadata.py b/tests/unit/test_metadata.py index 8f6e416..d90f53d 100644 --- a/tests/unit/test_metadata.py +++ b/tests/unit/test_metadata.py @@ -25,6 +25,7 @@ PartitionNode, RangeBounds, RelationKind, + UnattachedTable, ) from pg_partsmith.utils import DETACHED_AT_MARKER, orphan_table_comment @@ -456,6 +457,27 @@ async def test__get_actual_tree__orphan_query__carries_a_marker_for_every_partit assert orphan_call.args[1] == {"markers": ["myapp:parent=public.events", "myapp:parent=public.events__2024_02"]} +async def test__get_unattached_tables__rows__become_qualified_tables_and_the_unaddressable_are_left_out() -> None: + # Arrange + rows = [ + _orphan_row("events__2024_03", None, oid=600), + _orphan_row("events__2024_04", None, oid=601, relkind="p"), + _orphan_row("events__2024_05", None, oid=602, schema="bad.schema"), + ] + engine = _make_engine(rows) + provider = PostgresMetadataProvider(engine, marker_prefix="acme:") + + # Act + tables = await provider.get_unattached_tables("events") + + # Assert -- the root is resolved by the server, the marker prefix keeps orphans out + assert tables == ( + UnattachedTable(name="public.events__2024_03", oid=600, relkind=RelationKind.TABLE), + UnattachedTable(name="public.events__2024_04", oid=601, relkind=RelationKind.PARTITIONED), + ) + assert _conn(engine).execute.call_args.args[1] == {"table_name": '"events"', "marker_prefix": "acme:"} + + async def test__get_actual_tree__orphans__are_parsed_with_their_detach_instant() -> None: # Arrange marker = orphan_table_comment("public.events") diff --git a/tests/unit/test_migration.py b/tests/unit/test_migration.py index 641f127..766d46c 100644 --- a/tests/unit/test_migration.py +++ b/tests/unit/test_migration.py @@ -35,7 +35,7 @@ Reason, ) from pg_partsmith.scheme import HashPartitioning, ListGroup, ListPartitioning -from pg_partsmith.topology import ActualTree, DetachedPartition, RelationKind +from pg_partsmith.topology import ActualTree, DetachedPartition, RelationKind, UnattachedTable NOW = datetime(2026, 8, 28, tzinfo=UTC) ROOT = "public.events" @@ -56,6 +56,7 @@ def repo() -> MagicMock: @pytest.fixture def metadata() -> MagicMock: metadata = MagicMock() + metadata.get_unattached_tables = AsyncMock(return_value=()) metadata.get_default_partition = AsyncMock(return_value=_default_info()) metadata.get_leading_key_minimum = AsyncMock(return_value=None) metadata.get_actual_tree = AsyncMock(return_value=None) @@ -129,6 +130,12 @@ async def create_partition(config: Any, plan: Any, op: Any, *, issues: Any, fill return create_partition +class _CheckViolationError(Exception): + """What a driver raises when ATTACH finds a row outside the partition's bounds.""" + + sqlstate = "23514" + + class _LockNotAvailableError(Exception): """What a driver raises when lock_timeout runs out, whichever driver it is.""" @@ -580,6 +587,60 @@ async def test__partition_data__move_refused_by_a_foreign_key_action__issue_and_ assert "ON DELETE CASCADE" in result.issues[0].error +async def test__partition_data__default_drained_and_a_window_left_unattached__finishes_that_window( + mover: DataMover, metadata: MagicMock, repo: MagicMock +) -> None: + # Arrange -- DEFAULT is empty; March's table holds rows and was never attached + metadata.get_unattached_tables.side_effect = [(UnattachedTable(name=f"{ROOT}__2026_03"),), ()] + metadata.get_leading_key_minimum.side_effect = [None, datetime(2026, 3, 5, tzinfo=UTC), None] + plan_for = _plans(_plan(_create_op(3))) + + # Act + result = await mover.partition_data(_config(), plan_for, batch_rows=10) + + # Assert -- March goes through the path a window out of DEFAULT takes, and then there is nothing left + assert result.complete + assert result.partitions == (f"{ROOT}__2026_03",) + assert result.issues == () + assert plan_for.call_args.args[0] == _window(3) + + +async def test__partition_data__a_window_table_whose_rows_do_not_fit__is_left_as_it_is( + mover: DataMover, metadata: MagicMock, executor: MagicMock +) -> None: + # Arrange -- March's name, rows that are not March's: no fill of ours put them there + metadata.get_unattached_tables.return_value = (UnattachedTable(name=f"{ROOT}__2026_03"),) + metadata.get_leading_key_minimum.side_effect = [None, datetime(2026, 2, 20, tzinfo=UTC)] + executor.create_partition.side_effect = _CheckViolationError( + f'partition constraint of relation "{ROOT}__2026_03" is violated by some row' + ) + plan_for = _plans(_plan(_create_op(3))) + + # Act + result = await mover.partition_data(_config(), plan_for, batch_rows=10) + + # Assert -- reported, not raised, and not retried in a loop + assert not result.complete + assert [issue.partition_name for issue in result.issues] == [f"{ROOT}__2026_03"] + assert "holds rows outside 2026_03" in result.issues[0].error + assert executor.create_partition.call_count == 1 + + +async def test__partition_data__default_drained_and_nothing_left_unattached__is_complete( + mover: DataMover, metadata: MagicMock +) -> None: + # Arrange -- the fixture's defaults: an empty DEFAULT, nothing unattached + plan_for = _plans() + + # Act + result = await mover.partition_data(_config(), plan_for, batch_rows=10) + + # Assert + assert result.complete + assert result.partitions == () + plan_for.assert_not_called() + + async def test__partition_data__a_lock_not_granted_in_time__issue_and_incomplete( mover: DataMover, metadata: MagicMock, executor: MagicMock ) -> None: diff --git a/tests/unit/test_planner.py b/tests/unit/test_planner.py index 6430c52..4cd4db9 100644 --- a/tests/unit/test_planner.py +++ b/tests/unit/test_planner.py @@ -62,6 +62,7 @@ PartitionType, RangeBounds, RelationKind, + UnattachedTable, ) from pg_partsmith.utils import qualify, split_qualified_name @@ -246,9 +247,12 @@ def _plan( root: PartitionNode, *, orphans: tuple[DetachedPartition, ...] = (), + unattached: tuple[UnattachedTable, ...] = (), context: PlanningContext | None = None, ) -> MaintenancePlan: - return plan_maintenance(config, ActualTree(root=root, orphans=orphans), context or _context()) + return plan_maintenance( + config, ActualTree(root=root, orphans=orphans, unattached=unattached), context or _context() + ) def _reasons(plan: MaintenancePlan) -> list[FindingReason]: @@ -2461,3 +2465,53 @@ def test__plan_maintenance__records_the_configuration_it_planned_under() -> None # Assert: what makes a plan read back from a file answerable assert plan.config_fingerprint == config.fingerprint + + +# ── Partitions whose attach never happened ────────────────────────────────────── + + +def test__plan_maintenance__unattached_window_holding_rows__is_reported() -> None: + # Arrange -- March was filled and never attached + config = _config(lifecycle=_policy(creation=CreateAhead(count=2))) + root = _root(_month(2026, 8, oid=1), _month(2026, 9, oid=2)) + march = UnattachedTable(name=f"{ROOT}__2026_03", holds_rows=True) + + # Act + plan = _plan(config, root, unattached=(march,)) + + # Assert + assert [(f.partition_name, f.reason, f.severity) for f in plan.findings] == [ + (march.name, FindingReason.UNATTACHED_ROWS, Severity.WARNING) + ] + assert "attached to nothing" in plan.findings[0].detail + + +def test__plan_maintenance__unattached_tables_that_hide_nothing__are_not_reported() -> None: + # Arrange -- an empty one, one whose name is no window, and a look-alike of another table's + config = _config(lifecycle=_policy(creation=CreateAhead(count=2))) + root = _root(_month(2026, 8, oid=1), _month(2026, 9, oid=2)) + tables = ( + UnattachedTable(name=f"{ROOT}__2026_03", holds_rows=False), + UnattachedTable(name=f"{ROOT}__archive"), + UnattachedTable(name=f"{ROOT}_remote__2026_03", holds_rows=True), + ) + + # Act + plan = _plan(config, root, unattached=tables) + + # Assert + assert plan.findings == () + + +def test__plan_maintenance__unattached_window_this_plan_creates__is_left_to_the_create() -> None: + # Arrange -- the executor attaches whatever it finds under a name it creates + config = _config(lifecycle=_policy(creation=CreateAhead(count=2))) + root = _root(_month(2026, 8, oid=1)) + september = UnattachedTable(name=f"{ROOT}__2026_09", holds_rows=True) + + # Act + plan = _plan(config, root, unattached=(september,)) + + # Assert + assert _targets(plan.creates) == [september.name] + assert plan.findings == () diff --git a/tests/unit/test_service.py b/tests/unit/test_service.py index 1111c3c..7f61ab1 100644 --- a/tests/unit/test_service.py +++ b/tests/unit/test_service.py @@ -88,6 +88,7 @@ def repo() -> MagicMock: @pytest.fixture def metadata() -> MagicMock: metadata = MagicMock() + metadata.get_unattached_tables = AsyncMock(return_value=()) metadata.get_partition_type = AsyncMock(return_value=PartitionType.RANGE) metadata.get_partition_columns = AsyncMock(return_value=("created_at",)) metadata.get_actual_tree = AsyncMock(return_value=_tree())