feat(planning): report a lost server connection as connection-lost
CI / policy (pull_request) Successful in 8s
CI / validate (pull_request) Successful in 31s
CI / build (pull_request) Successful in 31s
CI / benchmark (pull_request) Successful in 1m25s
CI / security (pull_request) Successful in 1m41s
CI / test (pull_request) Successful in 2m54s
CI / images (pull_request) Successful in 1m14s
CI / required (pull_request) Successful in 1s
CI / policy (push) Successful in 20s
CI / validate (push) Successful in 34s
CI / build (push) Successful in 26s
CI / security (push) Successful in 56s
CI / benchmark (push) Successful in 1m45s
CI / test (push) Successful in 2m41s
CI / images (push) Successful in 54s
CI / required (push) Successful in 1s

A planning socket that closes after the server's first message now gives
a connection-lost incomplete calculation, shown as a warning with the
best valid plan kept, instead of the planner error alert. Closes the
server sends for a failed worker or a protocol violation (1003, 1007,
1008, 1009, 1011) and unparseable messages stay worker-error. Only the
close event decides, since an error event always precedes it and carries
no code. The liveness watchdog is unchanged.

Refs #330

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit was merged in pull request #328.
This commit is contained in:
nessarandClaude Opus 5.5 committed 2026-10-30 19:10:45 +01:00
1 parent 99d1b9c2ec
commit 3175dcc55b
12 files changed
+70 -11

No files matched your search

+1 -1
View File
@@ -67,7 +67,7 @@ Leave calculation runs on the server by default, for every device, so the wait d
4. `leave-planner.worker.ts` runs the framework-free core in the server's Bun Worker (or in the browser fallback), sends progress and valid checkpoints, publishes the outcome first, then delivers its stable explanation and final state.
5. `CalendarYear` ignores stale calculations, renders the selected dates, reports remaining balances or errors, and records successful request-to-rendered-calendar timing for duration refinement.
Calculations run until all objectives complete or the user cancels; there is no automatic elapsed-time cutoff. During preparation and optimization, Cancel interrupts the worker cooperatively and preserves its best jointly valid candidate as a cancelled, incomplete calculation. A cancellation before a valid candidate reports no plan. The final calendar is delivered before the stable explanation, whose later arrival or failure cannot change the retained plan. Worker heartbeats distinguish responsive long phases from a worker that stops responding. A connection lost after the first server message gives an incomplete calculation with the best valid plan already received, without an automatic retry; the person can calculate again. See [the cancellation mechanism and checks](docs/planner-cancellation.md).
Calculations run until all objectives complete or the user cancels; there is no automatic elapsed-time cutoff. During preparation and optimization, Cancel interrupts the worker cooperatively and preserves its best jointly valid candidate as a cancelled, incomplete calculation. A cancellation before a valid candidate reports no plan. The final calendar is delivered before the stable explanation, whose later arrival or failure cannot change the retained plan. Worker heartbeats distinguish responsive long phases from a worker that stops responding. A connection lost after the first server message gives an incomplete calculation with the best valid plan already received, without an automatic retry; it shows as a warning (`connection-lost`), not a planner error, and the person can calculate again. A close the server sends for a worker failure or a protocol violation (codes 1003, 1007, 1008, 1009 and 1011) stays a `worker-error`. See [the cancellation mechanism and checks](docs/planner-cancellation.md).
Technical callers may explicitly supply `deadlineMs`, a finite non-negative planning-work budget of any size. Omission means no deadline; the calendar and benchmark never supply one. This opt-in budget starts after calendar preparation and excludes observer callbacks and post-outcome explanation work. Expiry returns `PlanningIncomplete` with the latest valid checkpoint, if any, rather than a conflict. It is independent of worker liveness monitoring.
+1 -1
View File
@@ -10,7 +10,7 @@ The core exposes resumable generator steps. `calculatePlanningAsyncInternal` dri
The synchronous `calculatePlanningInternal` adapter drains the same steps without pauses for existing direct core callers. The public non-browser calculation context uses the asynchronous driver so its cancellation method also works.
User cancellation is distinct from replacement by another calculation (`stale-calculation`) and isolated worker failure (`worker-error` or `worker-unavailable`). Replacement retains the existing termination and stale-response protection. User cancellation leaves the producing worker alive until its outcome and explanation data have been delivered.
User cancellation is distinct from replacement by another calculation (`stale-calculation`) and isolated worker failure (`worker-error` or `worker-unavailable`), and from a lost server connection (`connection-lost`). Replacement retains the existing termination and stale-response protection. User cancellation leaves the producing worker alive until its outcome and explanation data have been delivered.
## Retaining a valid plan
@@ -2786,6 +2786,34 @@ describe('CalendarYear planning outcome boundary', () => {
expect(date.getAttribute('aria-label')).toContain('Paid Leave');
});
it('shows a lost connection as a warning that keeps the plan, not as a planner error', async () => {
const outcome: PlanningIncompleteOutcome = {
...incomplete,
incumbent: plan,
reasons: [{ code: 'connection-lost', message: 'The connection was lost.' }],
};
const { calendar } = calendarFor(outcome);
await TestBed.configureTestingModule({
imports: [CalendarYear],
providers: [
provideZonelessChangeDetection(),
{ provide: CalendarService, useValue: calendar },
],
}).compileComponents();
const fixture = TestBed.createComponent(CalendarYear);
fixture.detectChanges();
await fixture.whenStable();
await new Promise<void>((resolve) => setTimeout(resolve, 0));
fixture.detectChanges();
const root = fixture.nativeElement as HTMLElement;
const status = root.querySelector('.planning-status');
expect(status?.getAttribute('role')).toBe('status');
expect(status?.classList.contains('warning')).toBe(true);
expect(status?.textContent).toContain('Connection to the server lost.');
expect(root.querySelectorAll('button.selected')).toHaveLength(2);
});
it('keeps an incomplete incumbent visible and exposes its interrupted-stage details', async () => {
const outcome: PlanningIncompleteOutcome = {
kind: 'PlanningIncomplete',
@@ -950,6 +950,8 @@ export class CalendarYear {
return outcome.incumbent
? this.tr().planning.cancelledPartial
: this.tr().planning.cancelled;
if (outcome.reasons.some((reason) => reason.code === 'connection-lost'))
return this.tr().planning.connectionLost;
return this.hasPlannerError() ? this.tr().planning.error : this.tr().planning.incomplete;
}
}
+14 -1
View File
@@ -217,7 +217,7 @@ describe('remote planning job', () => {
expect(await calculation.outcome).toMatchObject({
kind: 'PlanningIncomplete',
incumbent: plan,
reasons: [{ code: 'worker-error' }],
reasons: [{ code: 'connection-lost' }],
});
expect(FakeWorker.all).toHaveLength(0);
const sentTypes = sockets().flatMap((candidate) => candidate.sentTypes());
@@ -225,6 +225,19 @@ describe('remote planning job', () => {
expect(socket.sentTypes()).toEqual(['plan']);
});
it('keeps a worker error when the server closes for its own fault', async () => {
const calculation = createPlanningCalculation(request);
const [socket] = sockets();
socket.accept();
socket.emit({ type: 'checkpoint', plan, state });
socket.drop(1011);
expect(await calculation.outcome).toMatchObject({
kind: 'PlanningIncomplete',
incumbent: plan,
reasons: [{ code: 'worker-error' }],
});
});
it('reports a lost connection once and ignores later events', async () => {
const progress = vi.fn();
const calculation = createPlanningCalculation({ ...request, progress });
+18 -7
View File
@@ -350,6 +350,12 @@ function startLocalJob(
}
const PLANNING_CONNECT_TIMEOUT_MS = 5_000;
// The server's closes for a failed worker or a protocol violation, and Bun's for an oversized message.
const SERVER_FAULT_CLOSES = [1003, 1007, 1008, 1009, 1011];
const CONNECTION_LOST: PlanningReason = {
code: 'connection-lost',
message: 'The connection to the planning server was lost.',
};
// Dates go out as Paris calendar dates: the core reads the leading date of the ISO string, which is UTC.
function encodePlanningMessage(message: WorkerRequest): string {
@@ -373,7 +379,7 @@ function startRemoteJob(
build: string,
supersede: () => void,
onMessage: (message: WorkerResponse) => void,
onError: () => void,
onError: (reason?: PlanningReason) => void,
): WorkerJob {
let socket: WebSocket;
try {
@@ -427,12 +433,12 @@ function startRemoteJob(
queue = [];
for (const { message, onFailure } of replay) local.post(message, onFailure);
};
const lose = () => {
const lose = (reason?: PlanningReason) => {
if (!heard) return fallBack();
if (released || ended) return;
ended = true;
closeSocket();
onError();
onError(reason);
};
socket.onopen = () => {
clearTimeout(connectTimer);
@@ -457,8 +463,9 @@ function startRemoteJob(
}
onMessage(parsed as WorkerResponse);
};
socket.onerror = lose;
socket.onclose = lose;
// A close always follows an error event, and only the close carries the code.
socket.onclose = (event: CloseEvent) =>
lose(SERVER_FAULT_CLOSES.includes(event.code) ? undefined : CONNECTION_LOST);
latestWorkerCancels.add(supersede);
return {
post(message, onFailure) {
@@ -483,7 +490,7 @@ function startRemoteJob(
function startWorkerJob(
supersede: () => void,
onMessage: (message: WorkerResponse) => void,
onError: () => void,
onError: (reason?: PlanningReason) => void,
): WorkerJob {
// Without a build identifier (development, tests) no server can match, so skip the socket.
const build = planningBuild();
@@ -524,7 +531,11 @@ function planInWorker(snapshot: TransportSnapshot): PlanningRun {
const job = startWorkerJob(
() => supersede(),
(message) => handleMessage(message),
() => fail('worker-error', 'Planning worker failed before returning explanation data.'),
(reason) =>
fail(
reason?.code ?? 'worker-error',
reason?.message ?? 'Planning worker failed before returning explanation data.',
),
);
let outcomeSettled = false;
let cancellationRequested = false;
+1
View File
@@ -251,6 +251,7 @@ export interface AppTranslations {
};
cancelled: string;
cancelledPartial: string;
connectionLost: string;
error: string;
complete: string;
whyPlacement: string;
+1
View File
@@ -214,6 +214,7 @@
},
"cancelled": "Berechnung abgebrochen",
"cancelledPartial": "Berechnung abgebrochen — Teilplan",
"connectionLost": "Verbindung zum Server verloren. Mit „Plan berechnen“ erneut versuchen.",
"error": "Bei der Planung ist ein unerwarteter Fehler aufgetreten.",
"complete": "Plan berechnet.",
"whyPlacement": "Ihre Urlaubstage verstehen",
+1
View File
@@ -214,6 +214,7 @@
},
"cancelled": "Calculation cancelled",
"cancelledPartial": "Calculation cancelled — partial plan",
"connectionLost": "Connection to the server lost. Use “Calculate plan” to try again.",
"error": "The planner encountered an unexpected error.",
"complete": "Plan calculated.",
"whyPlacement": "Understand your leave days",
+1
View File
@@ -214,6 +214,7 @@
},
"cancelled": "Cálculo cancelado",
"cancelledPartial": "Cálculo cancelado — plan parcial",
"connectionLost": "Se perdió la conexión con el servidor. Use «Calcular plan» para intentarlo de nuevo.",
"error": "El planificador encontró un error inesperado.",
"complete": "Plan calculado.",
"whyPlacement": "Entender tus días de permiso",
+1
View File
@@ -214,6 +214,7 @@
},
"cancelled": "Calcul annulé",
"cancelledPartial": "Calcul annulé — plan partiel",
"connectionLost": "Connexion au serveur perdue. Utilisez « Calculer le planning » pour réessayer.",
"error": "Le planificateur a rencontré une erreur inattendue.",
"complete": "Plan calculé.",
"whyPlacement": "Comprendre vos jours de congé",
+1 -1
View File
@@ -298,7 +298,7 @@ describe('server-side planning equivalence', () => {
const outcome = await calculation.outcome;
expect(outcome).toMatchObject({
kind: 'PlanningIncomplete',
reasons: [{ code: 'worker-error' }],
reasons: [{ code: 'connection-lost' }],
});
// Closing detaches the client, so no checkpoint arrives after the one it last saw.
const checkpoint = socket.received