Skip to content

Commit 7e56adf

Browse files
AlexeyShalaevAlexey Shalaev
andauthored
fix: attach the window a live writer is filling, under one lock (#65)
* fix: attach the window a live writer is filling, under one lock DEFAULT reconciliation moved the window's rows out in one transaction and retried the ATTACH in another. On a table that is being written to the writer refills the window in the gap, PostgreSQL refuses the attach again, and after DEFAULT_CONFLICT_MAX_RETRIES the rows are moved back -- so the current month, the one every live table is writing into, could never be attached, and each attempt cost a full scan of DEFAULT under ACCESS EXCLUSIVE. The move and the attach now share a transaction: reconcile_and_attach takes EXCLUSIVE on the parent and ACCESS EXCLUSIVE on the partition and the DEFAULT sibling, moves what is left of the window, and attaches. Nothing can reach DEFAULT in between, and no insert is mid-routing when the partition set changes -- a writer waits at the parent and is then routed into the new partition, statement unchanged. The bulk of the window still moves first under the lighter SHARE ROW EXCLUSIVE, so the exclusive window is a tail and a scan. A window that still cannot be attached is now a default_holds_rows issue rather than the driver's exception: apply() records it and the run goes on, and partition_data returns a move issue with complete=False instead of raising out of the drain. Closes #64 * test: cover the locked move-and-attach and the branches around it Unit tests for reconcile_and_attach's lock order and statement order in both mirrors, for a tail move an incoming foreign key refuses inside it, and for an attach target swapped during the bulk reconcile; the docs the new lock level changes follow. * docs: the legacy table still owns the serial sequence when the drain ends Following the guide's last step verbatim on a BIGSERIAL table fails: the sequence is owned by the column it was declared on, so it belongs to the renamed legacy table while every partition's default draws from it, and DROP TABLE is refused. Measured on 17, with what CASCADE does instead. * docs: what a queued insert does when the partition set changes under it The measurement behind the move-and-attach's EXCLUSIVE lock on the parent, where the semantics page keeps the rest of the ATTACH lock findings. * docs: say which lock the move-and-attach takes, not that ATTACH takes it * test: let the attach race a writer that is already writing The block was entered on a task that may not have had the loop yet, so on a slow runner the attach could finish before the first insert went out. --------- Co-authored-by: Alexey Shalaev <shalaevad.alexey@gmail.com>
1 parent 0587ce8 commit 7e56adf

22 files changed

Lines changed: 1302 additions & 158 deletions

‎docs/agents.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -365,7 +365,11 @@ lifecycle units — partitions directly under the root — never once per leaf o
365365
10. **During `partition_data`, a window's rows are invisible through the parent** between
366366
the first batch and the attach: PostgreSQL will not attach a partition while DEFAULT
367367
still holds rows for it, so no ordering keeps them visible throughout. Rows are never
368-
in two places, and never lost.
368+
in two places, and never lost. The attach takes the rows that arrived during the last
369+
batch *and* goes live in one transaction, so a window the application is writing into
370+
is attached like any other; writers wait at the parent for that commit and are then
371+
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.
369373
11. **Flat and composed spellings do not mix**, and `extra="forbid"` means a misspelled
370374
keyword raises rather than being ignored.
371375
12. **`schema=` goes in, `config.db_schema` comes out** — the field is aliased to avoid

‎docs/concepts/execution.md‎

Lines changed: 39 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,12 @@ statements. There is no long transaction wrapping a run, because `DETACH … CON
1212
cannot run inside a transaction block at all, and because a run that creates three
1313
partitions and fails on the fourth should keep the three.
1414

15+
Two steps are exceptions, and both for the same reason: a lock has to span more than one
16+
statement or the thing it protects can change underneath. A drop takes its lock, revalidates,
17+
drains and drops in one transaction; the last step of [DEFAULT reconciliation](#default-reconciliation)
18+
moves the window's remaining rows and attaches in one transaction. `ATTACH`, unlike
19+
`DETACH … CONCURRENTLY`, may run inside a transaction block.
20+
1521
The consequence for callers: pass the service an **engine**, never a session you are
1622
using elsewhere.
1723

@@ -50,13 +56,36 @@ belong to the new window, PostgreSQL refuses the attach (`23514`). The executor:
5056

5157
1. moves those rows from DEFAULT into the new partition, naming columns on both sides
5258
(`ATTACH` matches by name, so physical column order may differ) and leaving rows with a
53-
NULL trailing key where PostgreSQL routes them;
54-
2. retries the attach.
55-
56-
If the attach still fails, the rows are returned to DEFAULT rather than left in a table
57-
no query can see. For a nested branch the moved rows are routed onward into its leaves.
58-
A DEFAULT sibling holding rows for a hash or list member is reported
59-
(`default_holds_rows`) rather than moved: only a RANGE window can be selected by its key.
59+
NULL trailing key where PostgreSQL routes them. This is one statement under
60+
`SHARE ROW EXCLUSIVE` on DEFAULT: writers wait, readers do not;
61+
2. moves whatever arrived in the meantime and attaches, **in one transaction**, under
62+
`EXCLUSIVE` on the parent and `ACCESS EXCLUSIVE` on the partition and on DEFAULT — taken
63+
in that order, and taken before the move.
64+
65+
Step 2 is what makes the window a live writer is inserting into attachable at all. Two
66+
transactions cannot do it: the move commits, DEFAULT is free again, and the next insert for
67+
the window lands in it before `ATTACH` scans — under any steady write rate that never
68+
converges, and every attempt is a full scan of DEFAULT under `ACCESS EXCLUSIVE`. Sharing one
69+
lock closes the gap. Step 1 is what keeps that exclusive window short: the bulk of the month
70+
moves before the heavy lock is taken, so what step 2 covers is a tail and a scan.
71+
72+
The parent's lock is one level above what `ATTACH` itself takes, and it is there for the
73+
writer. An INSERT picks its partition from the set it saw when it took `ROW EXCLUSIVE` on
74+
the parent: one that got that far and then queued on DEFAULT's lock would come out of the
75+
wait still aimed at DEFAULT and be rejected by the constraint the attach just narrowed — a
76+
lost write, and what a plain `ATTACH` does to a live writer. Blocking at the parent instead
77+
means no insert is ever mid-routing while the partition set changes: the writer waits,
78+
re-plans, and lands in the new partition, its statement unchanged. `EXCLUSIVE` does not
79+
conflict with `ACCESS SHARE`, so readers of the other partitions carry on.
80+
81+
If the attach still fails, the rows step 1 moved are returned to DEFAULT rather than left in
82+
a table no query can see — step 2's own move rolls back with the attach, and needs no
83+
compensation. A window that still cannot be attached is reported as `default_holds_rows`, an
84+
issue like any other: the run goes on, and `partition_data` returns it rather than raising.
85+
For a nested branch the moved rows are routed onward into its leaves. A DEFAULT sibling
86+
holding rows for a hash or list member is reported rather than moved: only a RANGE window can
87+
be selected by its key. A **foreign** DEFAULT partition cannot be locked at all, so there the
88+
race stays and the report is all there is.
6089

6190
## Detach
6291

@@ -103,6 +132,8 @@ repository).
103132
|---|---|
104133
| `CREATE TABLE … (LIKE parent)` | `ACCESS SHARE` on the parent |
105134
| `ATTACH PARTITION` | `SHARE UPDATE EXCLUSIVE` on the parent, `ACCESS EXCLUSIVE` on the child and on a DEFAULT sibling; `SHARE ROW EXCLUSIVE` on tables referencing the parent through a foreign key |
135+
| the reconciling row move ([DEFAULT reconciliation](#default-reconciliation), step 1) | `SHARE ROW EXCLUSIVE` on the DEFAULT partition and on the child: writers of DEFAULT wait, readers do not |
136+
| the move-and-attach ([DEFAULT reconciliation](#default-reconciliation), step 2) | `EXCLUSIVE` on the parent (one level above `ATTACH`'s own, so no writer is mid-routing), then `ATTACH`'s `ACCESS EXCLUSIVE` on the partition and the DEFAULT sibling — all taken before the move |
106137
| `DETACH PARTITION` (plain) | `ACCESS EXCLUSIVE` on parent, partition, and every table referencing the parent |
107138
| `DETACH PARTITION … CONCURRENTLY` | `SHARE UPDATE EXCLUSIVE` on the parent; `ACCESS EXCLUSIVE` on the partition and, in its second transaction, on referencing tables |
108139
| `DROP TABLE` of a detached table | `ACCESS EXCLUSIVE` on that table only |
@@ -117,7 +148,7 @@ it takes on `op.capabilities`.
117148

118149
| What happened | Effect on the run |
119150
|---|---|
120-
| a topology conflict at execution time — a DEFAULT sibling holding rows for a hash bucket, a name taken by a relation with other bounds, a detach PostgreSQL refuses because rows are still referenced | recorded in `result.issues`; the run goes on |
151+
| a topology conflict at execution time — a DEFAULT partition holding rows the attach could not take, a name taken by a relation with other bounds, a detach PostgreSQL refuses because rows are still referenced | recorded in `result.issues`; the run goes on |
121152
| a `PlanStaleError` — the relation is not the one the plan saw | recorded as an issue with `continue_on_error`, otherwise raised |
122153
| any other error — a connection drop, a permission denied, a `before_*` hook raising | aborts the run, unless `continue_on_error`, in which case it is recorded and the next operation runs |
123154
| validation or lock failure | fatal, always |

‎docs/design/postgresql-semantics.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,24 @@ wait is itself a period of rejected writes for that partition.
7474
Hence: create standalone with `LIKE`, attach last; never `CREATE TABLE … PARTITION OF`
7575
against a live parent; a converged tree must issue no DDL at all.
7676

77+
### A queued insert keeps the partition it chose (measured on 17, 2026-09-07)
78+
79+
An `INSERT` through the parent picks its target from the partition set it saw when it took
80+
`ROW EXCLUSIVE` on the parent. `ATTACH` takes only `SHARE UPDATE EXCLUSIVE` there, which does
81+
not conflict — so an insert can route to the DEFAULT partition, queue on the `ACCESS
82+
EXCLUSIVE` the attach holds over it, and come out of that wait still aimed at DEFAULT. The
83+
row is then rejected by the constraint the attach has just narrowed:
84+
`23514 new row for relation "events_legacy" violates partition constraint`. Nothing re-routes
85+
it; the write is lost to the caller.
86+
87+
Taking `EXCLUSIVE` on the parent instead — one level up, conflicting with `ROW EXCLUSIVE` but
88+
not with `ACCESS SHARE` — makes the insert wait *before* it chooses: it re-plans against the
89+
tree the attach left and lands in the new partition, its statement unchanged, while readers
90+
of the other partitions carry on. That is what the move-and-attach of
91+
[DEFAULT reconciliation](../concepts/execution.md#default-reconciliation) does; the
92+
integration suite asserts it on PostgreSQL 15 through 18 with a writer inserting into the
93+
window while the attach runs.
94+
7795
## Foreign tables
7896

7997
- `CREATE FOREIGN TABLE … PARTITION OF parent` and `ATTACH PARTITION` of a foreign table are

‎docs/guide/extending.md‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,20 +39,31 @@ class PartitionRepository(Protocol):
3939
async def drop_partition(self, partition_name, *, expected_oid=None) -> None: ...
4040
async def adopt_partition(self, table_name, partition_name) -> bool: ...
4141
async def reconcile_default_rows(self, *, default_partition_name, target_partition_name, key_columns, from_value, to_value, limit=None) -> int: ...
42+
async def reconcile_and_attach(self, parent_name, partition_name, bounds, *, key_columns, default_partition_name) -> int: ...
4243
async def move_rows(self, source_name, target_name, *, limit=None) -> int: ...
4344
```
4445

4546
Every method takes and returns plain domain objects (`PartitionBounds`, `PartitionBy`,
4647
`DetachMode`, `LocalLeaves`), so an implementation never needs to know how the planner
4748
works.
4849

50+
`reconcile_and_attach` is the one method with a transaction boundary in its contract: it
51+
must take the window's remaining rows out of the DEFAULT partition **and** attach in a
52+
single transaction, holding one lock across both, and roll the move back if the attach
53+
fails. Two transactions cannot do it — a writer refills the window in the gap and
54+
PostgreSQL refuses the attach every time. The bundled implementation locks the parent
55+
`EXCLUSIVE` (so no insert is mid-routing when the partition set changes) and the partition
56+
and DEFAULT sibling `ACCESS EXCLUSIVE`, then moves, then attaches. It is called only after
57+
`attach_partition` has failed on a DEFAULT conflict and the bulk of the window has been
58+
moved by `reconcile_default_rows`.
59+
4960
One thing to know about errors: the executor recognises a failed `attach_partition` by the
5061
**SQLSTATE the exception carries**, not by its type. It reads `sqlstate` or `pgcode` off
5162
the exception, or off its `orig` if it wraps one — which covers a SQLAlchemy error, a bare
5263
`psycopg.Error` and an `asyncpg.PostgresError` alike. Let the driver's exception through
5364
rather than replacing it with one of your own, and three things keep working: a lost race
5465
with another worker is treated as benign, a DEFAULT partition holding rows for the new
55-
window triggers the reconcile-and-retry, and rows already moved out of DEFAULT are put back
66+
window triggers the reconcile-and-attach, and rows already moved out of DEFAULT are put back
5667
if the attach ultimately fails. An exception carrying no SQLSTATE is still safe — the rows
5768
are restored and it propagates — but it cannot be recognised as a race or a conflict.
5869

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

Lines changed: 36 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,12 @@ await maintainer.run_maintenance_safe(config)
4848

4949
The tick creates the current month and the two after it. As each is attached, the rows
5050
of that month move out of `events_legacy` into it — ordinary DEFAULT reconciliation.
51-
From now on new rows land in real partitions; the old ones are still in the DEFAULT.
51+
The current month is the one the application is writing into, and it attaches on this
52+
first tick like the empty future ones: the bulk of its rows move first, then the rows that
53+
arrived while that ran move *and* the partition goes live in one transaction. Inserts wait
54+
at the parent for that commit and are then routed into the new partition, their statement
55+
unchanged. From now on new rows land in real partitions; the old ones are still in the
56+
DEFAULT.
5257

5358
## 3. Drain the DEFAULT partition
5459

@@ -65,7 +70,10 @@ Each call:
6570
3. moves the window's rows into it in batches of `batch_rows` — one
6671
`DELETE … RETURNING` / `INSERT` per batch, each committing on its own, so a row is in
6772
exactly one place at every commit point;
68-
4. attaches the partition once nothing of that window is left in DEFAULT;
73+
4. takes whatever landed during the last batch and attaches the partition, in one
74+
transaction and under one lock — so a window still being written to is attached on the
75+
same pass as a quiet one, and what the lock covers is a tail and a scan rather than a
76+
month;
6977
5. moves on to the next window, until DEFAULT holds only rows no window can take (rows
7078
with a NULL key), or `max_batches` is spent.
7179

@@ -80,14 +88,19 @@ finds it, finishes it and attaches it.
8088
a partition cannot be attached while DEFAULT still holds rows for it. Run the drain in
8189
a maintenance window, or with small batches during a quiet hour and readers that can
8290
tolerate a month's rows appearing a little later. Rows already in real partitions, and
83-
rows still in DEFAULT for other windows, stay visible throughout.
91+
rows still in DEFAULT for other windows, stay visible throughout. The attach that ends
92+
a window blocks writers at the parent and holds `ACCESS EXCLUSIVE` on the DEFAULT
93+
partition, for the length of the last batch's tail plus one scan of DEFAULT — so
94+
inserts stall for that long rather than fail, and readers of the partitions already
95+
drained carry on.
8496

8597
`partition_data` takes the table's lock, so it does not race the scheduled tick. It
86-
refuses a window it cannot create (an unmanaged partition overlaps it), and any move an
87-
incoming foreign key's `ON DELETE` action would corrupt, with a `move` issue and
88-
`complete=False` rather than loop. A window whose partition already exists *detached*
89-
with this library's marker — retention retired it, and late rows for it landed in
90-
DEFAULT — is filled and re-attached rather than given up on.
98+
refuses a window it cannot create (an unmanaged partition overlaps it), any move an
99+
incoming foreign key's `ON DELETE` action would corrupt, and a DEFAULT partition it could
100+
not clear, with a `move` issue and `complete=False` rather than loop — and never by
101+
raising at the caller. A window whose partition already exists *detached* with this
102+
library's marker — retention retired it, and late rows for it landed in DEFAULT — is
103+
filled and re-attached rather than given up on.
91104

92105
## 4. Afterwards
93106

@@ -103,6 +116,21 @@ DROP TABLE events_legacy;
103116
Without a DEFAULT partition, `DETACH … CONCURRENTLY` becomes available, which is what
104117
`DetachMode.AUTO` prefers.
105118

119+
!!! note "A `serial` key's sequence still belongs to the old table"
120+
`BIGSERIAL` makes the sequence **owned by** the column it was declared on, so after the
121+
swap it belongs to `events_legacy` — while every partition's `id` default draws from it.
122+
`DROP TABLE events_legacy` is refused for exactly that (`2BP01`, *other objects depend
123+
on it*, listing one default per partition). Move the ownership to the live parent first:
124+
125+
```sql
126+
ALTER SEQUENCE events_id_seq OWNED BY events.id;
127+
```
128+
129+
Then the drop goes through and the ids carry on where they were. Do **not** reach for
130+
`DROP TABLE … CASCADE` here: measured on 17, it takes the sequence with the table and
131+
every default that drew from it, and the next insert fails
132+
`null value in column "id" … violates not-null constraint`.
133+
106134
## The way back
107135

108136
`unpartition` empties every partition into one plain table, oldest first, in the same

‎pg_partsmith/aio/protocols.py‎

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,15 @@
2323
from pg_partsmith.leaves import LocalLeaves
2424
from pg_partsmith.lifecycle import DetachMode, SqlPredicate
2525
from pg_partsmith.plan import PartitionBy
26-
from pg_partsmith.topology import ActualTree, FactKind, PartitionBounds, PartitionNode, PartitionType, RelationKind
26+
from pg_partsmith.topology import (
27+
ActualTree,
28+
FactKind,
29+
PartitionBounds,
30+
PartitionNode,
31+
PartitionType,
32+
RangeBounds,
33+
RelationKind,
34+
)
2735

2836
__all__ = [
2937
"LockManager",
@@ -239,6 +247,45 @@ async def reconcile_default_rows(
239247
"""
240248
...
241249

250+
async def reconcile_and_attach(
251+
self,
252+
parent_name: str,
253+
partition_name: str,
254+
bounds: RangeBounds,
255+
*,
256+
key_columns: tuple[str, ...],
257+
default_partition_name: str,
258+
expected_oid: int | None = None,
259+
expected_parent_oid: int | None = None,
260+
expected_default_oid: int | None = None,
261+
) -> int:
262+
"""Take the window's last rows out of DEFAULT and attach, in one transaction.
263+
264+
The pair cannot be two transactions on a table that is being written
265+
to: the move commits, the DEFAULT partition is free again, and a row
266+
for the window lands in it before ``ATTACH`` scans -- which fails the
267+
attach with the very conflict the move was clearing. An implementation
268+
must hold one lock across both, and must roll the move back with a
269+
failed attach.
270+
271+
Args:
272+
parent_name: Partitioned relation to attach to.
273+
partition_name: Table to attach.
274+
bounds: The RANGE window the partition owns, and the rows to take.
275+
key_columns: The parent's partition key, leading column first. Rows
276+
with a NULL in a trailing column stay in DEFAULT, where
277+
PostgreSQL routes them.
278+
default_partition_name: Qualified name of DEFAULT partition.
279+
expected_oid: The catalog identity of the partition, checked the
280+
way ``attach_partition`` checks it.
281+
expected_parent_oid: The catalog identity of the parent.
282+
expected_default_oid: The catalog identity the rows must come from.
283+
284+
Returns:
285+
Number of rows moved out of the DEFAULT partition.
286+
"""
287+
...
288+
242289
async def move_rows(self, source_name: str, target_name: str, *, limit: int | None = None) -> int:
243290
"""Move rows from one relation into another, whatever their keys.
244291

0 commit comments

Comments
 (0)