1515
1616from __future__ import annotations
1717
18+ import asyncio
1819import logging
1920from collections .abc import Awaitable , Callable
20- from functools import partial
2121from typing import TYPE_CHECKING , Any
2222
2323from pg_partsmith .aio .services .execution import LOCK_NOT_GRANTED
3535if TYPE_CHECKING :
3636 from pg_partsmith .aio .protocols import PartitionMetadataProvider , PartitionRepository
3737 from pg_partsmith .aio .services .execution import PlanExecutor
38- from pg_partsmith .entities import TablePartitionConfig
38+ from pg_partsmith .entities import PartitionInfo , TablePartitionConfig
3939 from pg_partsmith .topology import ActualTree , DetachedPartition
4040
4141logger = logging .getLogger (__name__ )
@@ -119,30 +119,20 @@ async def partition_data(
119119 moved_before = tally .rows_moved
120120 bounds = op .bounds
121121 assert isinstance (bounds , RangeBounds )
122- fill = partial (self ._drain_window , default .name , root .key , bounds , batch_rows , tally )
123122 try :
124- if isinstance (op , CreatePartition ):
125- attached = await self ._executor .create_partition (config , plan , op , issues = tally .issues , fill = fill )
126- else :
127- attached = await self ._executor .attach_partition (config , plan , op , issues = tally .issues , fill = fill )
123+ attached = await self ._fill_and_attach (config , plan , op , default , root .key , bounds , batch_rows , tally )
128124 except (RowMoveRefusedError , PartitionTopologyError ) as exc :
129125 # A window this run cannot finish -- rows a foreign key holds
130126 # down, a DEFAULT partition it could not clear, a name taken by
131127 # a relation with other bounds. The caller asked for a drain,
132128 # not for an exception: what stayed behind and why is on the
133129 # result, and the loop stops rather than re-planning the same
134130 # window forever.
135- tally .issue (
136- default .name , f"rows for { boundaries .describe (window )} stay in { default .name } : { exc .detail } "
137- )
138- return tally .result (complete = False )
131+ return tally .unfinished (default .name , boundaries .describe (window ), exc .detail )
139132 except Exception as exc :
140133 if pg_sqlstate (exc ) != LOCK_NOT_AVAILABLE_SQLSTATE :
141134 raise
142- tally .issue (
143- default .name , f"rows for { boundaries .describe (window )} stay in { default .name } : { LOCK_NOT_GRANTED } "
144- )
145- return tally .result (complete = False )
135+ return tally .unfinished (default .name , boundaries .describe (window ), LOCK_NOT_GRANTED )
146136 if not attached :
147137 logger .info (
148138 "Batch budget exhausted; the partition stays detached until the next call" ,
@@ -170,6 +160,88 @@ def _window_operation(plan: MaintenancePlan) -> CreatePartition | AttachPartitio
170160 return create
171161 return next ((a for a in plan .attaches if isinstance (a .bounds , RangeBounds )), None )
172162
163+ async def _fill_and_attach (
164+ self ,
165+ config : TablePartitionConfig ,
166+ plan : MaintenancePlan ,
167+ op : CreatePartition | AttachPartition ,
168+ default : PartitionInfo ,
169+ key_columns : tuple [str , ...],
170+ bounds : RangeBounds ,
171+ batch_rows : int ,
172+ tally : _Tally ,
173+ ) -> bool :
174+ """Give the window its partition, filled from DEFAULT before it is attached.
175+
176+ Every batch of the fill commits on its own, but the rows it moves are
177+ visible through the parent only once the partition is attached. When
178+ the attach does not happen -- refused, out of lock_timeout, cut off --
179+ they go back to DEFAULT: readers see them again, and the next run finds
180+ the window where it looks for one, rather than in a detached table
181+ nothing ever revisits.
182+
183+ Returns:
184+ Whether the partition was attached. False when the batch budget ran
185+ out first, which leaves it detached and part-filled on purpose.
186+ """
187+ filled : list [tuple [str , int | None ]] = []
188+ moved_before = tally .rows_moved
189+
190+ async def fill (target : str , target_oid : int | None ) -> bool :
191+ filled .append ((target , target_oid ))
192+ return await self ._drain_window (default .name , key_columns , bounds , batch_rows , tally , target , target_oid )
193+
194+ try :
195+ if isinstance (op , CreatePartition ):
196+ return await self ._executor .create_partition (config , plan , op , issues = tally .issues , fill = fill )
197+ return await self ._executor .attach_partition (config , plan , op , issues = tally .issues , fill = fill )
198+ except BaseException :
199+ if tally .rows_moved > moved_before :
200+ await asyncio .shield (self ._give_back (filled , default , key_columns , bounds , tally ))
201+ raise
202+
203+ async def _give_back (
204+ self ,
205+ filled : list [tuple [str , int | None ]],
206+ default : PartitionInfo ,
207+ key_columns : tuple [str , ...],
208+ bounds : RangeBounds ,
209+ tally : _Tally ,
210+ ) -> None :
211+ """Return the rows a fill moved to the DEFAULT partition they came from (best effort).
212+
213+ Both ends are pinned to the identities the fill used, so a relation
214+ swapped in at either name neither gives nor receives them. A failure
215+ is logged and the table the rows are left in is remembered for the
216+ report, never raised: the attach's own error stays the one the caller
217+ sees.
218+ """
219+ for target , target_oid in filled :
220+ try :
221+ returned = await self ._repo .reconcile_default_rows (
222+ default_partition_name = target ,
223+ target_partition_name = default .name ,
224+ key_columns = key_columns ,
225+ from_value = bounds .from_value ,
226+ to_value = bounds .to_value ,
227+ expected_source_oid = target_oid ,
228+ expected_target_oid = default .oid ,
229+ )
230+ except (asyncio .CancelledError , KeyboardInterrupt , SystemExit ):
231+ raise
232+ except Exception :
233+ logger .exception (
234+ "Could not return the window's rows to DEFAULT; they are in a detached table" ,
235+ extra = {"partition_name" : target , "default_partition" : default .name },
236+ )
237+ tally .stranded .append (target )
238+ else :
239+ tally .rows_moved -= returned
240+ logger .warning (
241+ "The partition was not attached; its rows are back in DEFAULT" ,
242+ extra = {"partition_name" : target , "default_partition" : default .name , "returned_rows" : returned },
243+ )
244+
173245 async def _drain_window (
174246 self ,
175247 default_name : str ,
@@ -398,6 +470,7 @@ def __init__(self, max_batches: int | None) -> None:
398470 self .batches = 0
399471 self .partitions : list [str ] = []
400472 self .issues : list [MaintenanceIssue ] = []
473+ self .stranded : list [str ] = []
401474
402475 @property
403476 def exhausted (self ) -> bool :
@@ -410,6 +483,18 @@ def batch(self, moved: int) -> None:
410483 def issue (self , partition_name : str , error : str ) -> None :
411484 self .issues .append (MaintenanceIssue (step = MaintenanceIssueStep .MOVE , error = error , partition_name = partition_name ))
412485
486+ def unfinished (self , default_name : str , window : str , reason : str ) -> MigrationResult :
487+ """Report a window this run could not finish, saying where its rows are."""
488+ if self .stranded :
489+ where = (
490+ f"are in { ', ' .join (self .stranded )} , which is not attached; they could not be returned to "
491+ f"{ default_name } , and no query through the parent sees them until it is attached"
492+ )
493+ else :
494+ where = f"stay in { default_name } "
495+ self .issue (default_name , f"rows for { window } { where } : { reason } " )
496+ return self .result (complete = False )
497+
413498 def result (self , * , complete : bool ) -> MigrationResult :
414499 return MigrationResult (
415500 rows_moved = self .rows_moved ,
0 commit comments