11import type { InternalSessionEntry as SessionEntry } from "../config/sessions.js" ;
22import { mergeRestartRecoveryTerminalRunIds } from "../config/sessions/restart-recovery-state.js" ;
3+ import { retryAsync } from "../infra/retry.js" ;
34import {
45 buildMainSessionRecoveryClearPatch ,
56 type MainRecoveryStateFields ,
67} from "./main-session-recovery-clear.js" ;
78
8- const MAIN_RESTART_RECOVERY_WEDGED_FALLBACK_REASON =
9- "main-session restart recovery is tombstoned for this session" ;
9+ const MAIN_SESSION_RECOVERY_RETRY_DELAY_MS = 1_000 ;
10+ const MAIN_SESSION_RECOVERY_RETRY_MAX_DELAY_MS = 30_000 ;
1011
1112type MainRecoveryLifecycleEvent = {
1213 runId ?: string ;
1314 lifecycleGeneration ?: string ;
1415 data ?: { error ?: unknown ; phase ?: unknown ; stopReason ?: unknown } ;
1516} ;
1617
17- export function inspectMainSessionRecoveryHealth ( entry : SessionEntry ) :
18- | { status : "none" }
19- | { status : "active" }
20- | {
21- status : "tombstoned" ;
22- reason : string ;
23- repair : "clear_stale_abort" | null ;
24- } {
25- const state = entry . mainRestartRecovery ;
26- if ( ! state ) {
27- return { status : "none" } ;
28- }
29- if ( ! state . tombstone ) {
30- return { status : "active" } ;
18+ export async function retryMainSessionRecoveryMutation < T > ( mutation : ( ) => Promise < T > ) : Promise < T > {
19+ return await retryAsync ( mutation , 3 , 25 ) ;
20+ }
21+
22+ /** Retries now, then leaves an exact idempotent repair queued after transient failure. */
23+ export async function repairMainSessionRecoveryMutation < T > ( params : {
24+ mutation : ( ) => Promise < T > ;
25+ onDeferredSuccess : ( result : T ) => void | Promise < void > ;
26+ onError : ( error : unknown ) => void ;
27+ } ) : Promise < T | undefined > {
28+ try {
29+ return await retryMainSessionRecoveryMutation ( params . mutation ) ;
30+ } catch ( error ) {
31+ params . onError ( error ) ;
32+ scheduleMainSessionRecoveryMutation ( {
33+ mutation : ( ) => retryMainSessionRecoveryMutation ( params . mutation ) ,
34+ onSuccess : params . onDeferredSuccess ,
35+ } ) ;
36+ return undefined ;
3137 }
32- return {
33- status : "tombstoned" ,
34- reason : state . tombstone . reason . trim ( ) || MAIN_RESTART_RECOVERY_WEDGED_FALLBACK_REASON ,
35- repair : entry . abortedLastRun === true ? "clear_stale_abort" : null ,
36- } ;
38+ }
39+
40+ /** Keeps an idempotent durable-state repair alive until it succeeds or restart retires it. */
41+ export function scheduleMainSessionRecoveryMutation < T > ( params : {
42+ mutation : ( ) => Promise < T > ;
43+ onError ?: ( error : unknown ) => void ;
44+ onSuccess : ( result : T ) => void | Promise < void > ;
45+ delayMs ?: number ;
46+ } ) : void {
47+ const delayMs = params . delayMs ?? MAIN_SESSION_RECOVERY_RETRY_DELAY_MS ;
48+ setTimeout ( ( ) => {
49+ void params . mutation ( ) . then ( params . onSuccess , ( error : unknown ) => {
50+ params . onError ?.( error ) ;
51+ scheduleMainSessionRecoveryMutation ( {
52+ ...params ,
53+ delayMs : Math . min ( delayMs * 2 , MAIN_SESSION_RECOVERY_RETRY_MAX_DELAY_MS ) ,
54+ } ) ;
55+ } ) ;
56+ } , delayMs ) . unref ?.( ) ;
3757}
3858
3959function lifecyclePhase ( event : MainRecoveryLifecycleEvent ) : "start" | "end" | "error" | null {
@@ -61,6 +81,47 @@ export function isMainSessionRecoveryLifecycleEvent(params: {
6181 ) ;
6282}
6383
84+ function settleForegroundOwner (
85+ entry : MainRecoveryStateFields ,
86+ runId : string ,
87+ lifecycleGeneration : string ,
88+ currentLifecycleGeneration : string ,
89+ ) {
90+ const state = entry . mainRestartRecovery ;
91+ const claims = state ?. foregroundClaims ;
92+ const claimId =
93+ lifecycleGeneration === currentLifecycleGeneration &&
94+ claims ?. lifecycleGeneration === lifecycleGeneration
95+ ? claims . tokens . find ( ( token ) => claims . runIdsByClaimId ?. [ token ] === runId )
96+ : undefined ;
97+ if ( ! state || ! claims || ! claimId ) {
98+ return {
99+ hasCurrentOwner :
100+ Boolean (
101+ claims ?. lifecycleGeneration === currentLifecycleGeneration && claims . tokens . length ,
102+ ) || state ?. reservation ?. lifecycleGeneration === currentLifecycleGeneration ,
103+ } ;
104+ }
105+ const tokens = claims . tokens . filter ( ( token ) => token !== claimId ) ;
106+ const runIdsByClaimId = Object . fromEntries (
107+ Object . entries ( claims . runIdsByClaimId ?? { } ) . filter ( ( [ token ] ) => token !== claimId ) ,
108+ ) ;
109+ const foregroundClaims = tokens . length
110+ ? {
111+ lifecycleGeneration : claims . lifecycleGeneration ,
112+ tokens,
113+ ...( Object . keys ( runIdsByClaimId ) . length ? { runIdsByClaimId } : { } ) ,
114+ }
115+ : undefined ;
116+ return {
117+ claimId,
118+ state : { ...state , revision : state . revision + 1 , foregroundClaims } ,
119+ hasCurrentOwner :
120+ Boolean ( foregroundClaims ) ||
121+ state . reservation ?. lifecycleGeneration === currentLifecycleGeneration ,
122+ } ;
123+ }
124+
64125export function projectMainSessionRecoveryLifecycle ( params : {
65126 currentLifecycleGeneration : string ;
66127 entry ?:
@@ -73,19 +134,17 @@ export function projectMainSessionRecoveryLifecycle(params: {
73134 event : MainRecoveryLifecycleEvent ;
74135 snapshotPatch : Partial < SessionEntry > ;
75136} ) : { action : "suppress" } | { action : "apply" ; patch : Partial < SessionEntry > } {
137+ const apply = ( patch : Partial < SessionEntry > ) => ( { action : "apply" as const , patch } ) ;
76138 if ( params . entry ?. mainRestartRecovery ?. tombstone ) {
77139 // Keep the operator boundary while allowing unrelated lifecycle status to settle.
78140 return isMainSessionRecoveryLifecycleEvent ( params )
79141 ? { action : "suppress" }
80- : {
81- action : "apply" ,
82- patch : {
83- ...params . snapshotPatch ,
84- abortedLastRun : params . entry . abortedLastRun ,
85- restartRecoveryRuns : params . entry . restartRecoveryRuns ,
86- mainRestartRecovery : params . entry . mainRestartRecovery ,
87- } ,
88- } ;
142+ : apply ( {
143+ ...params . snapshotPatch ,
144+ abortedLastRun : params . entry . abortedLastRun ,
145+ restartRecoveryRuns : params . entry . restartRecoveryRuns ,
146+ mainRestartRecovery : params . entry . mainRestartRecovery ,
147+ } ) ;
89148 }
90149 if ( isMainSessionRecoveryLifecycleEvent ( params ) ) {
91150 return { action : "suppress" } ;
@@ -113,8 +172,13 @@ export function projectMainSessionRecoveryLifecycle(params: {
113172 )
114173 : runs ;
115174 if ( settlesRecovery ) {
175+ if ( ! matchesFence || ! runId || ! lifecycleGeneration ) {
176+ // No terminal snapshot may settle a recovery row it cannot identify.
177+ return params . entry ?. mainRestartRecovery || runs ?. length
178+ ? { action : "suppress" }
179+ : apply ( patch ) ;
180+ }
116181 if (
117- matchesFence &&
118182 lifecycleGeneration !== params . currentLifecycleGeneration &&
119183 remaining ?. some (
120184 ( run ) =>
@@ -123,88 +187,34 @@ export function projectMainSessionRecoveryLifecycle(params: {
123187 ) {
124188 // Older generations share the live owner's run id. Consume only their
125189 // fence; recording that id as terminal would also tombstone its replacement.
126- return { action : " apply" , patch : { restartRecoveryRuns : remaining } } ;
190+ return apply ( { restartRecoveryRuns : remaining } ) ;
127191 }
128- const foregroundClaims = params . entry ?. mainRestartRecovery ?. foregroundClaims ;
129- const foregroundOwnerClaimId =
130- runId &&
131- lifecycleGeneration &&
132- lifecycleGeneration === params . currentLifecycleGeneration &&
133- foregroundClaims ?. lifecycleGeneration === lifecycleGeneration
134- ? foregroundClaims . tokens . find (
135- ( claimId ) => foregroundClaims . runIdsByClaimId ?. [ claimId ] === runId ,
136- )
137- : undefined ;
138- const remainingForegroundClaimIds = foregroundOwnerClaimId
139- ? foregroundClaims ! . tokens . filter ( ( claimId ) => claimId !== foregroundOwnerClaimId )
140- : foregroundClaims ?. tokens ;
141- const remainingForegroundRunIds = foregroundOwnerClaimId
142- ? Object . fromEntries (
143- Object . entries ( foregroundClaims ?. runIdsByClaimId ?? { } ) . filter (
144- ( [ claimId ] ) => claimId !== foregroundOwnerClaimId ,
145- ) ,
146- )
147- : foregroundClaims ?. runIdsByClaimId ;
148- const remainingForegroundClaims = remainingForegroundClaimIds ?. length
149- ? {
150- lifecycleGeneration : foregroundClaims ! . lifecycleGeneration ,
151- tokens : remainingForegroundClaimIds ,
152- ...( remainingForegroundRunIds && Object . keys ( remainingForegroundRunIds ) . length > 0
153- ? { runIdsByClaimId : remainingForegroundRunIds }
154- : { } ) ,
155- }
156- : undefined ;
157- const recoveryStateAfterForegroundSettlement = foregroundOwnerClaimId
158- ? {
159- ...params . entry ! . mainRestartRecovery ! ,
160- revision : params . entry ! . mainRestartRecovery ! . revision + 1 ,
161- foregroundClaims : remainingForegroundClaims ,
162- }
163- : params . entry ?. mainRestartRecovery ;
164- const hasForegroundOwners = Boolean (
165- remainingForegroundClaims ?. lifecycleGeneration === params . currentLifecycleGeneration &&
166- remainingForegroundClaims . tokens . length ,
192+ const foreground = settleForegroundOwner (
193+ params . entry ?? { } ,
194+ runId ,
195+ lifecycleGeneration ,
196+ params . currentLifecycleGeneration ,
167197 ) ;
168- const reservation = params . entry ?. mainRestartRecovery ?. reservation ;
169- const hasCurrentReservation =
170- reservation ?. lifecycleGeneration === params . currentLifecycleGeneration ;
171- const hasCurrentOwner = hasForegroundOwners || hasCurrentReservation ;
172- if ( ! matchesFence ) {
173- // No terminal snapshot may settle a recovery row it cannot identify.
174- return params . entry ?. mainRestartRecovery || runs ?. length
175- ? { action : "suppress" }
176- : { action : "apply" , patch } ;
177- }
178- if ( hasCurrentOwner ) {
198+ if ( foreground . hasCurrentOwner ) {
179199 // A terminal event may consume its own claim. Another owner still keeps
180200 // the aggregate live until that owner's terminal event or release.
181- return {
182- action : "apply" ,
183- patch : {
184- restartRecoveryRuns : remaining ?. length ? remaining : undefined ,
185- restartRecoveryTerminalRunIds : mergeRestartRecoveryTerminalRunIds (
186- params . entry ?. restartRecoveryTerminalRunIds ,
187- [ runId ] ,
188- ) ,
189- ...( foregroundOwnerClaimId
190- ? { mainRestartRecovery : recoveryStateAfterForegroundSettlement }
191- : { } ) ,
192- } ,
193- } ;
201+ return apply ( {
202+ restartRecoveryRuns : remaining ?. length ? remaining : undefined ,
203+ restartRecoveryTerminalRunIds : mergeRestartRecoveryTerminalRunIds (
204+ params . entry ?. restartRecoveryTerminalRunIds ,
205+ [ runId ] ,
206+ ) ,
207+ ...( foreground . claimId ? { mainRestartRecovery : foreground . state } : { } ) ,
208+ } ) ;
194209 }
195- if ( foregroundOwnerClaimId ) {
210+ if ( foreground . claimId ) {
196211 // This exact foreground run completed while its release lease was still
197212 // active. Its terminal snapshot is authoritative and consumes the cycle.
198213 Object . assign ( patch , buildMainSessionRecoveryClearPatch ( params . entry ) ) ;
199- return { action : " apply" , patch } ;
214+ return apply ( patch ) ;
200215 }
201- if (
202- ! hasForegroundOwners &&
203- ! hasCurrentReservation &&
204- params . entry ?. abortedLastRun === true &&
205- ( remaining ?. length ?? 0 ) > 0
206- ) {
207- return { action : "apply" , patch : { restartRecoveryRuns : remaining } } ;
216+ if ( params . entry ?. abortedLastRun === true && ( remaining ?. length ?? 0 ) > 0 ) {
217+ return apply ( { restartRecoveryRuns : remaining } ) ;
208218 }
209219 const recoveryDeliveryRunId =
210220 typeof params . entry ?. restartRecoveryDeliveryRunId === "string"
@@ -216,19 +226,19 @@ export function projectMainSessionRecoveryLifecycle(params: {
216226 patch . abortedLastRun = false ;
217227 patch . restartRecoveryRuns = remaining ;
218228 patch . mainRestartRecovery = params . entry ?. mainRestartRecovery ;
219- return { action : " apply" , patch } ;
229+ return apply ( patch ) ;
220230 }
221231 // An admitted recovery clears the interruption flag before it runs. With
222232 // no live owner left, that exact delivery run is the durable cleanup boundary.
223233 Object . assign ( patch , buildMainSessionRecoveryClearPatch ( params . entry ) ) ;
224- return { action : " apply" , patch } ;
234+ return apply ( patch ) ;
225235 }
226236 if ( phase === "start" || ! matchesFence || ! remaining ) {
227- return { action : " apply" , patch } ;
237+ return apply ( patch ) ;
228238 }
229239 if ( params . entry ?. abortedLastRun === true && remaining . length > 0 ) {
230- return { action : " apply" , patch : { restartRecoveryRuns : remaining } } ;
240+ return apply ( { restartRecoveryRuns : remaining } ) ;
231241 }
232242 patch . restartRecoveryRuns = remaining . length > 0 ? remaining : undefined ;
233- return { action : " apply" , patch } ;
243+ return apply ( patch ) ;
234244}
0 commit comments