
# Starting, following and stopping a solve through the API

You will learn how to start a solve (full, queued or incremental), predict what it will receive, follow its progress live, read what it leaves behind (previous plan, snapshots, A/B comparison) and avoid its traps: budget, server restart, starting point. The internal mechanics of the solver are in [how the schedule is computed](comment-le-planning-est-calcule.md).

## Four ways to start, one path

The synchronous solve, the asynchronous one from a posted problem or from the referential, and the incremental one all go through [`SolvePipeline`](repo:src/main/java/dev/sylvain/planning/service/solve/SolvePipeline.java): capture the plan about to be overwritten, build the problem, solve, persist, diagnose, feed the Planning rules screen, write the KPI line, announce the end if the edition asked. A path stopping short would leave that screen on the previous solve's analysis without error.

**The past is frozen** ([ADR 0044](repo:docs/decisions/0044-le-passe-est-fige.md)): the seats of timeslots already begun are taken from the saved plan and pinned, and count in the rules without ever being blamed ([details](horaires-et-fenetres-des-stands.md#le-passé-est-figé)), including for a problem posted in the body. A solve whose seats are all past is refused: the job ends `FAILED` with "Nothing to plan: all the timeslots have already begun…" in `error`, with no failure alert. `PASSE_FIGE=false` turns the rule off.

### One solve at a time

Only one solve job runs for the whole application. Other sessions see the active job through `GET /api/jobs/active` and get `409` on a second launch, the body carrying the running job. It is the only launch `409` whose body is a job: the hourly quota and capped queue of a public instance (`SOLVER_MAX_SOLVES_PER_HOUR`, `SOLVER_MAX_QUEUED_JOBS`, [solve settings](../installer/calcul-du-planning.md)) and the frozen referential answer `409` with a plain `{ message }`: tell them apart by the body's shape (an `id` and a `status`), not by the status.

## The budget

The budget is the **instance's** (ADR 0110), the same for all editions: `planning.solver.seconds-limit` and `planning.solver.unimproved-seconds-limit`, which `GET /api/parametres/calcul` exposes under `instance` with the launch ceiling (`maxSecondsLimit`, `SOLVER_SECONDS_LIMIT_MAX`). No write changes it: `PUT /api/parametres/calcul` sets only the end-of-solve mail. Three traps:

- **a ceiling refuses, it does not truncate**: a duration above it is refused with `400` citing the ceiling (`?seconds=` as the MCP `secondes`);
- **the plateau stays conditioned on feasibility**: the stop is "feasible AND N seconds without improvement". An explicit `?seconds=` different from the instance duration means "exactly this duration": no plateau;
- **a job keeps the budget of its launch**, resolved at submission. Incremental replanning has its own duration (60 s without `?seconds=`) and no plateau, under the same ceiling.

## Predicting what the solve will receive

`GET /api/planning/volumetrie` (MCP `consulter_besoin`, `volumetrie` section) describes the problem the next solve would build: `animateurCount`, `posteCount` (one seat per seat to fill), `contrainteAdHocCount`, `hoursToFill` (effective durations, closures deducted) and `hoursAvailable`, the legal ceiling of what staff members can work on the event days (per animateur and ISO week, at most six non-unavailable days, each at the daily ceiling of their age, all bounded by the weekly ceiling). Their ratio is a ceiling, not a forecast: competences, rest and breaks still subtract, and a rate near 1 already announces an infeasible plan. Seats depend only on stands and timeslots: counted before any animateur is entered (`hoursAvailable` is zero), all zero without stand or timeslot. `GET /api/staffing` does the same (`referentielsManquants`); `GET /api/feasibility` and `GET /api/fragilite` say instead that nothing is feasible without staff members, and `GET /api/feasibility` also says an edition without timeslots or whose stands never open: nothing to fill is not a green light.

### The staffing need

`GET /api/staffing` (MCP `consulter_besoin`, `borne` section) returns **proven minimums**: no smaller team fills the seats. Three figures read differently than they seem:

- `mineursMax` is a ceiling, computed for `effectifReference` (the minimum, or the staff members entered if more numerous): it never says how many minors to recruit, and ignores consecutive days and the minors' 4 h 30 of continuous work;
- `absentsMax` (per day) and `budgetIndisponibilites` (per week) are read against the same headcount, beyond the rest day each must already take (`indisponibilitesAuDela` counts the days declared beyond);
- `joursConsecutifsMax` is read only if `maxJoursConsecutifsTravailles` is mandatory, `null` otherwise: a preference may be breached, it must not drive recruiting.

`POST /api/staffing/verification` by default launches a seat solve with a **made-up team** (`majeurs`, sixteen-year-old `mineurs`, all available and competent everywhere) and answers `202`. With `calcul: false`, it answers **by the exact bound**: it compares the requested headcount with the exact minimum and the adults the most demanding day requires, and returns `202` with a verification already `TERMINEE` (`methode: BORNE`, `minimum`), with no solve or quota. This answer says "at least N", never "a plan exists". With nothing said, the request gets the instance default, `planning.staffing.verification-default` (`calcul`, or `borne` when the bound will equal the solve over the whole range: [ADR 0098](repo:docs/decisions/0098-la-borne-exacte-s-affiche-d-abord-le-calcul-reste-le-defaut.md)). `GET /api/staffing/verification` returns the last verification, or `204`. Without `dureeSecondes`, the duration is that of an edition solve (minimum 10 s); the solve runs on the instance's engine and stops as soon as a plan is feasible ([ADR 0071](repo:docs/decisions/0071-le-besoin-en-animateurs-un-minimum-exact-verifie-par-une-equipe-fictive.md)). To know:

- neither the plan, nor the staff members, nor the queue are written; the verification is kept (`verification_besoin`);
- one verification at a time, all editions together, and none during a solve: a second request gets `409`, and a starting solve (`SolveStarting`) interrupts it, read then as `ECHEC` with the reason. It travels in the status stream (`verification` field);
- **a failure proves nothing**: `realisable: false` says only that no complete plan was found in the allotted time. `posteDoitEtrePourvu` is always held;
- ad hoc exceptions and the published plan are left aside, since they name people the made-up team lacks. The plan in place is the starting point: each real animateur maps to a made-up member, adult to adult, minor to minor, the most loaded first.

`GET /api/solve/entrees` counts in one read what the Calculate tab announces under "This solve will take into account": `pendingDeclarations` (availability declarations **pending**, which the solve will not see, since it reads the records), `changesSinceSolve` (actions journalled since the persisted plan, 0 without a plan) and `disabledRules` (shipped rules active that the edition switched off).

## The queue

![Life cycle of a solve job](repo:docs/diagrammes/job-etats.svg)

<sub>Source: [`diagrammes/job-etats.puml`](repo:docs/diagrammes/job-etats.puml).</sub>

`enFile=true` queues the task instead of refusing it, FIFO. Statuses: `QUEUED`, `PENDING`, `RUNNING`, `COMPLETED`, `FAILED`, `CANCELLED`, `INTERROMPU`. The problem is built at **actual start**, not at the click, and a queued task does not hold the solver: entry stays open on the targeted edition. A duplicate (same edition, same type, already planned) is refused with `409`, but planning a solve of the edition being solved stays allowed ("redo it with what I just fixed").

What is persisted (`solver_job`) is the **intention** (type, budget, edition, scope), never the solver's state. A restart loses the running solve, whose job becomes `INTERROMPU`, a terminal state so as not to hold the global lock; the result not being stored, a restored job exposes `result: null`. `planning.jobs.reprise-au-demarrage=false` turns the resumption off.

**A server stop does not overwrite the plan.** When the container stops under a solve, Timefold returns its best solution as if the budget were exhausted: this is not a completed solve. The job ends `INTERROMPU`, never `COMPLETED`, and the partial plan replaces the saved plan only if it **strictly beats** it (hard, then medium, then soft) or there was none. `result.interruption: { partialPlanKept, partialScore, persistedScore }` tells a script; plan discarded, no KPI line and no end mail. A solve not respecting the few seconds left to the solver is found `RUNNING` at the next start and goes through the previous case.

## The starting point

`POST /api/solve/async/reference-data?reamorcage=AUTO|PLAN_COURANT|AUCUN` chooses where a full solve starts. `AUTO`, the default, starts from the saved plan if there is one, from zero otherwise; `PLAN_COURANT` requires it (the job fails without a plan); `AUCUN` is the cold start. An unknown value answers `400`. The choice is persisted with the job.

Starting from the plan does not pin it: each seat receives the animateur the plan gave it and stays movable, only explicit locks are frozen, which separates this restart from incremental replanning. The solver scores the starting solution first and keeps the best seen: on equal data, the result never falls below the starting plan. A seat whose holder disappeared or declared themselves unavailable starts empty. The default is not the cold start, even for a script or an assistant, since it may end below the plan already in the database; it is asked for. An infeasible starting plan buys no shortcut: the feasibility termination does not fire.

The result reports what was done:

- `reamorcage: { mode, postes, postesLiberes, postesPasses, postesPassesVides }`, `mode` being `PLAN_COURANT` or `AUCUN`, never `AUTO`; absent when the problem came in the body. `postesPasses` counts the seats already begun, pinned whatever the mode, `postesPassesVides` those holding nobody (a warning);
- `previousPlan`, see below;
- `impactPublication: { personnes, publieLe }`: how many people would see their schedule change against the last published plan, `null` while nothing is published: the count to read before publishing (the `stabiliteDuPlanPublie` rule keeps it low, [the rules](pourquoi-ces-regles.md)).

## Following a solve live

`GET /api/jobs/stream` pushes the `{ active, file }` aggregate as server-sent events. The first event arrives on connection, without waiting for a transition, and each event is a whole snapshot. A `heartbeat` every 20 s (`JOBS_STREAM_HEARTBEAT`) also carries the `:keep-alive` line, without which a proxy closes a silent connection; `EventSource` not exposing the lone comment, the browser takes over after a silence of about two heartbeats.

### The score curve

The same stream carries the `score` event: the points (elapsed time, hard, medium, soft) Timefold announces through `bestSolutionChanged`. `GET /api/jobs/score` returns the same curve in one block; nothing is persisted. Timefold announcing a better solution only when the score strictly improves, a plateauing solve stops producing points: the **duration therefore travels apart** (`dureeMs`, wall clock), the right edge where the browser extends the last value flat, the plateau. A running solve emits an event at each tick, even with no point (`points: []`); a finished curve goes silent. Sampling is bounded server-side: at most one point per second (the most recent of the window) and at most 400 points (beyond, the series is halved and the interval doubles; pace `JOBS_STREAM_SCORE`, 1 s). Announcements of an uninitialised solution are ignored: their score describes a partial assignment and would draw a cliff.

Timefold announces a best solution only when the score strictly improves: a solve that plateaus stops producing points, which is exactly the state the screen must show. The **duration therefore travels separately** (`dureeMs`, by the clock): it is the right edge, the browser extends the last value flat to it and that segment is the plateau. A solve in progress therefore emits an event at every tick, even with no new point (`points: []`); a finished curve goes quiet.

`score` events are **deltas**: `depuis` is the index of the first point sent (`0` replaces everything: new connection, new solve or halved series; otherwise append at that index), and `generation` changes as soon as the series stops being an extension of itself. Three points:

- `EventSource` sets no header, so the stream has no edition: each event carries the solve's `editionId` and the browser shows only its edition's curve. `GET /api/jobs/score` filters server-side and answers `204` for another edition;
- a `score` event **without `jobId`** means "there is no curve any more", sent once per connection (restart);
- the curve closes at the job's end (success, failure, cancellation): last score added, `dureeMs` frozen, `termine` set to `true`. A job cancelled before its solver started leaves the curve alone.

### The feasibility moment

The first feasible plan (zero hard) often arrives well before the end: the planning is then usable, the rest is quality. The job carries it in `feasibleAtSeconds` (`JobView`, `consulter_calcul`), `null` while the plan is not feasible, and pushes a status event at that instant. "Stop and keep this plan" is just the ordinary stop, the solver always keeping the best plan. A solve already starting from a zero-hard plan would say nothing (Timefold announces only changes): the complete starting plan is therefore noted once before the start (`SolveListener`).

## Incremental replanning

`POST /api/solve/incremental/async` starts from the persisted plan, pins what a late change did not invalidate and recomputes only the rest. The body is optional and **widens** the scope: `animateurIds`, `jours` and `standIds` form a union; without a body, it is what the changes invalidated plus the empty seats. The job fails without a plan to resume. Seats already begun are pinned, never reopened (`jours` naming a past day reopens nothing), counted in `statistiques.postesPasses` and `postesPassesVides`, and a replanning whose seats are all past is refused like the full solve. Mechanism: [locks, freeze and replanning](plan-verrous-et-publication.md).

## Versions and A/B comparison

Only one plan is persisted per edition; **versions** are the only persistence able to keep several ([ADR 0108](repo:docs/decisions/0108-un-seul-type-version-a-trois-origines.md)). Three origins, given by `origine`: `MANUELLE`, `AVANT_CALCUL` (taken automatically: the anti-overwrite net before each solve) and `PUBLIEE` (what the staff members received). Routes: `/api/planning/versions`; the 3.x root of the snapshots and the `automatique` field left the API in 5.0. Automatic ones are purged beyond the last N (`planning.snapshots.automatiques-conservees`, 5), hand-made ones never.

A solve's result names this snapshot and its score: `previousPlan : { snapshotId, score, degraded }`. `degraded` compares the two scores in Timefold's order (hard, medium, soft) and is `false` as soon as one is missing or unreadable: better assert nothing than a false alert. `previousPlan` is `null` at an edition's first solve.

### Freshness and restoring

A snapshot says whether it is still current (`perime`, `referenceModifieLe`): the referential carries the date of its last mutation (`edition.reference_modifie_le`, written by [`ReferenceDataChangeTracker`](repo:src/main/java/dev/sylvain/planning/service/ReferenceDataChangeTracker.java)) and a snapshot captured before it is stale. This date is persisted: in memory, a restart would read it "never modified", hence "current", and a false "current" costs most in front of *Restore* ([ADR 0038](repo:docs/decisions/0038-fraicheur-du-referentiel-persistee.md)).

`POST /api/planning/versions/{id}/restore` answers `409` **without writing anything** in three cases:

- a **reference has disappeared**: the body lists which (checked first, a snapshot most often being stale because ids disappeared);
- the snapshot is **stale**: `perime: true` and the date. The gesture is replayed with `?forcer=true` (the plan stays restorable, it just no longer describes today's referential); `forcer` lifts only this refusal;
- a solve holds **this edition's** solver: it would overwrite the restored plan. The body is the referential writes', with the job named; the guard is in the service, shared with `restaurer_version`; a solve of another edition refuses nothing.

### Publication and deletion

A snapshot may carry the "published" state (`publieLe`): the plan the staff members received, which leaves the purge. A restore puts the plan back with the dosage under which it was computed. Two `409` refusals at deletion:

- **the last publication**: the space reads it, and deleting it would silently take back what was announced. Replaced publications are deleted like any snapshot;
- **a publication measuring an elapsed day**: Realised vs planned compares each finished day to the published plan in force at its first timeslot, and deleting it would rewrite the gap afterwards. The refusal names the day's date, never a person (also for `supprimer_version`), and is evaluated before deletion, since the answer depends on the clock.

The comparison marker of a deferred person (`animateur.plan_notifie_id`) may designate one of these publications: deleting it makes them read as "never notified", and their next publication will announce their whole schedule rather than their changes.

### Comparing two plans

`GET /api/planning/versions/compare` triggers **no solve**: it reads KPIs measured at capture. `GET /api/planning/versions/comparables` crosses editions, hence `editionsDifferentes` (a variant is another edition: not an anomaly, but the interface must say so). In `diffViolations`, `null` means **not measured**, never zero, and `kpiRecalcule` marks the degraded mode of a snapshot without stored KPIs (exact coverage and volumetry, unmeasured gaps).

**Two plans computed under different dosages cannot be compared at equal weights**: `dosagesDifferents` says so when both `kpi.dosage` are known and differ. A snapshot also carries the consignes in force at capture (`consignes`, by date): `null` means **unknown**, an empty array "there were none". `consignesDifferentes` stays `false` as soon as one side does not know, and signals when a difference comes from a band an order closed rather than a solver setting ([consignes](api-planning-et-publication.md#consignes)).
