@@ -473,7 +473,7 @@ async def _settle_charge(self, name: str, run: Run) -> None:
473473
474474 charged_usd = Decimal (str (run .usage_total_usd ))
475475 if run .finished_at is not None and datetime .now (UTC ) - run .finished_at >= _CHARGE_SETTLE_TIME :
476- await self ._save (name , record .model_copy (update = {'charged_usd' : charged_usd }))
476+ await self ._save (name , record .model_copy (update = {'charged_usd' : charged_usd }), if_unchanged = record )
477477 self ._unsettled_charges .pop (name , None )
478478 else :
479479 self ._unsettled_charges [name ] = charged_usd
@@ -575,13 +575,22 @@ async def _load(self) -> dict[str, ChildRunRecord]:
575575 ) from exc
576576 return self ._records
577577
578- async def _save (self , name : str , record : ChildRunRecord ) -> None :
578+ async def _save (self , name : str , record : ChildRunRecord , * , if_unchanged : ChildRunRecord | None = None ) -> None :
579+ """Record `record` under `name`.
580+
581+ With `if_unchanged`, the write is skipped when `name` no longer holds that record, and a reservation of a start
582+ or resurrection in flight is left alone.
583+ """
579584 records = await self ._load ()
580585 key_value_store = await self ._open_key_value_store ()
581586 async with self ._write_lock :
587+ if if_unchanged is not None :
588+ if records .get (name ) is not if_unchanged :
589+ return
590+ else :
591+ # The record carries the limit reserved for a start or resurrection in flight from here on.
592+ self ._reserving .pop (name , None )
582593 records [name ] = record
583- # The record carries the limit reserved for a start or resurrection in flight from here on.
584- self ._reserving .pop (name , None )
585594 await key_value_store .set_value (
586595 CHILD_RUNS_KEY , _records_adapter .dump_python (records , by_alias = True , mode = 'json' )
587596 )
0 commit comments