Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/adr/0002-ported-rule-decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ drift, which is what settles ODD-01, ODD-05, ODD-10 (seat part) and ODD-13.
| ODD-06 | 6. accommodation floor on capacity reductions | **Keep** (`scheduling.rules.accommodation-floor: allocated`) | Capacity below `AccommodationCapacity` (or negative) is rejected with `INVALID_CAPACITY` (HTTP 409, legacy code 50005 = state 5), and nothing changes. `booked` (floor = extra-time seats in use) is opt-in and not legacy behaviour. Equal to the allocation is allowed (`CP-08`). | portal `CP-05`, `CP-08`; db `CP-06` | `022_usp_ChangeCapacity.sql` (state 5; PR 51 not in `legacy-baseline`), HB-14 | `AccommodationFloorPolicy`, `CapacityChange` |
| ODD-07 | 6a. blank accommodation code | **Keep API meaning** | Blank / missing code = no accommodation (stored NULL, no accommodation seat used), as in booking-api. The portal's silent fallback to the profile default moves into the UI, which shows the code explicitly. Unknown codes -> `VALIDATION` 400. `ET25`/`ET50` consume accommodation seats, `SR`/`RB` never do (`AC-01..AC-04`, `AC-07`, `AC-08`). | portal `AC-05`; api `AC-06` | booking-api `StringUtils.trimToNull`, portal `AccommodationCodes.cs` / `BookingService.cs` (HB-09) | `AccommodationCodes` |
| ODD-08 | 6b. reschedule onto the same session | **Keep API rule** | Refused on every channel with `SAME_SESSION` (409). The portal's cancel + re-book on the same session (new id, seat released and re-taken) is not reproduced. | portal `RS-05`; api `RS-06` | booking-api `BookingService.reschedule`, `023_usp_RescheduleBooking.sql` (HB-10, HB-11) | `ReschedulePolicy` |
| ODD-09 | - | **Keep** | Cancelling a BOOKED seat frees it but promotes nobody. Cancelling a WAITLISTED booking deletes its waitlist entry, and the other positions are not renumbered. A second cancel -> `NOT_CANCELLABLE` (409 / 50004). Automatic promotion is a product decision for a later story. | portal `CN-05`, `CN-03`, `CN-07`; api `CN-06`, `CN-04`, `CN-08` | `021_usp_CancelBooking.sql` (HB-06) | `BookingRules.checkCancellable`, `SchedulingService.cancel` |
| ODD-09 | - | **Keep** | Cancelling a BOOKED seat frees it but promotes nobody. Cancelling a WAITLISTED booking deletes its waitlist entry, and the other positions are not renumbered. A second cancel -> `NOT_CANCELLABLE` (409 / 50004). Automatic promotion is a product decision for a later story: superseded for BOOKED cancels by [ADR 0005](0005-waitlist-auto-offer.md) (MBA-3829, the freed seat is offered to the waitlist; legacy unchanged). | portal `CN-05`, `CN-03`, `CN-07`; api `CN-06`, `CN-04`, `CN-08` | `021_usp_CancelBooking.sql` (HB-06) | `BookingRules.checkCancellable`, `SchedulingService.cancel` |
| ODD-10 | - | **Change** | A rescheduled booking keeps the original `channel`, `external_ref` and accommodation code, so partner references (PX-3008) survive. | portal `RS-08` | `023_usp_RescheduleBooking.sql` (HB-10) | `ReschedulePolicy`, `SchedulingService.reschedule` |
| ODD-11 | - | **Change (mapping)** | Errors carry a symbolic `error` and `legacyCode = 50000 + proc state`: `SESSION_NOT_OPEN` 50001, `DUPLICATE_BOOKING` 50002, `NO_ACCOMMODATION_SEAT` 50003, `NOT_CANCELLABLE` 50004, `INVALID_CAPACITY` 50005, `DIFFERENT_EXAM` 50006. This is the documented 5000x table the procs never raised. | db `BK-07`, `CP-06`, `RS-07` | `db/procs/020..023` (HB-14) | `ErrorCode`, `web/ApiExceptionHandler` |
| ODD-12 | - | **Change** | Every channel gets booking-api's shape: HTTP 409 `{error, message, legacyCode}` (404 / 400 for not found / validation), never an HTTP 200 page with an alert. The UI shows these as toasts and inline errors. | portal `BK-05`, `BK-08`, `BK-10`, `CP-05`, `RS-03`; api `BK-06`, `BK-09`, `BK-11`, `RS-04` | portal controllers vs booking-api (HB-14) | `web/ApiExceptionHandler` |
Expand Down
61 changes: 61 additions & 0 deletions docs/adr/0005-waitlist-auto-offer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# ADR 0005: freed seats are offered to the waitlist (MBA-3829, A4)

Status: accepted. Deliberate behaviour change to [ADR 0002](0002-ported-rule-decisions.md) ODD-09, built on the single
writer and outbox of [ADR 0003](0003-single-writer-outbox-relay.md).

## Context

Legacy never promotes anyone: `usp_CancelBooking` frees the seat and leaves the waitlist untouched
([HB-06](../as-is/hidden-behaviours.md), [MR-12](../as-is/migration-risks.md)); centre staff promote by hand. ADR 0002
kept that behaviour (ODD-09) and left automatic promotion to a later story. Since M4 scheduling-service is the only
writer of bookings, waitlist and capacity, so the rule can change in one place and the relay carries the result to
every legacy reader.

## Decisions

1. **Trigger.** Whenever a seat frees up in an `OPEN` session (cancel of a BOOKED booking, reschedule out, capacity
increase, an offer declined, expired or withdrawn), `WaitlistOfferPolicy` offers it, in the same transaction and
under the same session lock (`UPDLOCK` on `exam_session`) as the change that freed it. Closed, delivered and
cancelled sessions make no offers.
2. **Who.** The lowest-position `WAITLISTED` entry without a pending offer whose accommodation needs fit
(`WaitlistOfferRules`, pure domain). `ET25`/`ET50` need a free accommodation seat; while none is free they are
skipped and keep their position, and the next standard entry is offered. Several free seats give several offers in
position order.
3. **Offer and hold.** A `seat_offer` row (`V3__waitlist_offers.sql`) with status `PENDING`, `expires_at = now +
scheduling.waitlist.offer-ttl` (default `PT24H`). A pending offer holds its seat (and the accommodation seat for
ET entries): `SessionCapacity.heldSeats` is subtracted from `seatsAvailable`, so a new booking is waitlisted, not
booked, and `seatsAvailable` stays 0. A filtered unique index allows one pending offer per booking, so concurrent
triggers cannot double-offer.
4. **Accept** (`POST /api/v2/offers/{offerId}/accept`, before expiry): the booking becomes `BOOKED`, its waitlist entry
is removed and later positions move up by one. **Decline** (`.../decline`) and **expiry** (`WaitlistOfferExpiryJob`,
every `scheduling.waitlist.expiry-poll`, default `PT1M`) cancel the waitlisted booking (reason `Waitlist offer
declined` / `Waitlist offer expired`), remove its entry, shift later positions, and offer the seat to the next
eligible entry; if nobody is left the seat is simply available. Accepting an expired offer answers
`409 OFFER_NOT_PENDING` even if the job has not swept it yet.
5. **Withdraw.** Cancelling or rescheduling a booking with a pending offer withdraws the offer (`WITHDRAWN`) and passes
the seat on; a capacity decrease withdraws the newest pending offers that no longer fit. Withdrawn candidates keep
their position.
6. **Outbox.** New event types `SeatOffered`, `SeatOfferAccepted`, `SeatOfferDeclined`, `SeatOfferExpired`,
`SeatOfferWithdrawn`, written in the same transaction and carrying the full resulting booking/session state like
every M4 event (state transfer). The relay needs no new code: acceptance projects as `BOOKED` in `dbo.Booking`, the
`dbo.Waitlist` row is deleted and the remaining positions are rewritten.
7. **Legacy view of a hold.** The hold exists only in scheduling-service. In legacy the offered booking stays
`WAITLISTED` and `ExamSession.SeatsAvailable` stays `Capacity - (BOOKED + ATTENDED)` (the formula
`db/checks/seat-drift.sql` checks), so reconciliation and seat drift stay at 0 during and after an offer cycle.
Legacy writes are denied (ADR 0003), so no legacy path can take the held seat.
8. **Waitlisted cancel** keeps ODD-09: cancelling a waitlisted booking without an offer deletes its entry and does not
renumber. Accept, decline and expiry renumber because the ticket requires positions 2-3 to become 1-2.

## Consequences

* Candidates see a pending offer under My bookings with Accept / Decline; the admin waitlist table shows offer state
and the session page counts held seats.
* Authorisation is the same as for the other `/api/v2` candidate writes (cancel, reschedule): none beyond the gateway.
Candidate authentication is out of scope for the scheduling slice.
* Anyone holding an offer id can accept or decline it; this is by design for now, consistent with cancel/reschedule,
because the slice has no candidate login (MR-16 in `docs/as-is/migration-risks.md`).
* The routing gateway's modern write guard covers `POST /api/v2/offers/{id}/accept|decline`: it resolves offer ->
session -> centre (`/api/v2/internal/routing/resolve?offerId=`) and refuses with `403 CENTER_NOT_MODERN` when that
centre is not on `routing.modern-centers` or cannot be resolved (fail closed).
* Rolling back a centre to legacy (runbook section 5) leaves pending offers in Scheduling only; the legacy waitlist is
intact, so staff promote by hand as before.
18 changes: 18 additions & 0 deletions docs/runbooks/scheduling-service.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,24 @@ event id in `dbo.RelayCheckpoint` ([ADR 0003](../adr/0003-single-writer-outbox-r
- While lag is high, legacy readers (portal pages, booking-api `GET`, results) show stale availability. Writes are not
affected (scheduling-service is the only writer).

### Waitlist offers stuck or not made (MBA-3829)

A seat freed in an `OPEN` session is offered to the next eligible waitlist entry and held while the offer is
`PENDING` ([ADR 0005](../adr/0005-waitlist-auto-offer.md)). Config: `scheduling.waitlist.offer-ttl`
(`SCHEDULING_WAITLIST_OFFER_TTL`, default `PT24H`), `scheduling.waitlist.expiry-enabled` (`..._EXPIRY_ENABLED`,
default `true`), `scheduling.waitlist.expiry-poll` (`..._EXPIRY_POLL`, default `PT1M`).

- Live offers: `SELECT offer_id, session_id, booking_id, position, offered_at, expires_at FROM seat_offer WHERE status =
'PENDING' ORDER BY expires_at` in `Scheduling`. `GET /api/v2/sessions/{id}` shows `heldSeats`; the waitlist endpoint
shows `offerStatus` per entry.
- Offers past `expires_at` still `PENDING`: the expiry job is off or failing. Check `expiry-enabled` and WARN logs
`offer expiry failed`. Accepting such an offer already answers `409 OFFER_NOT_PENDING`, so nobody gets an expired
seat; the job releases it on its next pass.
- Seat free but nobody offered: the waitlist only holds ET25/ET50 entries and no accommodation seat is free (they are
skipped, by design), or the session is not `OPEN`.
- Offers do not change legacy until accepted: the offered booking stays `WAITLISTED` in `dbo.Booking`, and
`SeatsAvailable` counts the held seat as free there. Reconciliation is expected to stay at 0 during offers.

### Non-zero reconciliation report

`GET /internal/reconciliation` (or `java -jar target/scheduling-service-*.jar reconcile`, exit 0 only when
Expand Down
5 changes: 3 additions & 2 deletions services/routing-gateway/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ allow-list still applies to the API rows. See [ADR 0004](../../docs/adr/0004-ret
API requests without a centre key (e.g. `/api/v1/sessions` without `centerCode`) stay on legacy. Portal pages without a modern equivalent (`/Admin/Centers`, `/Eligibility`,
`/Results`, roster CSV, capacity audit) always stay on legacy.

The centre is resolved through scheduling-service `GET /api/v2/internal/routing/resolve?centerCode=|centerId=|sessionId=|bookingId=`
The centre is resolved through scheduling-service `GET /api/v2/internal/routing/resolve?centerCode=|centerId=|sessionId=|bookingId=|offerId=`
(reads its snapshots; cached for `routing.resolve-cache-ttl`, 30 s). If the lookup fails the request goes to
legacy (writes through the v2 guard below are refused instead). `/api/v2/internal/**` (resolver, snapshot
import/reset) is never proxied: the gateway answers `404` for it. With an **empty allow-list no lookups are made and no request bodies are read**: the gateway is a
Expand All @@ -85,7 +85,8 @@ allow-list says, so rolling a centre back never orphans an in-flight modern book
rule above.

**Modern write guard.** v2 writes that reach scheduling-service through :8000 (`POST /api/v2/bookings`,
`DELETE /api/v2/bookings/{id}`, `POST /api/v2/bookings/{id}/reschedule`, `PUT /api/v2/sessions/{id}/capacity`)
`DELETE /api/v2/bookings/{id}`, `POST /api/v2/bookings/{id}/reschedule`, `PUT /api/v2/sessions/{id}/capacity`,
`POST /api/v2/offers/{id}/accept|decline` resolved offer -> session -> centre via `resolve?offerId=`)
are refused with `403 {"error":"CENTER_NOT_MODERN"}` when the centre is not allow-listed (modern-owned bookings
excepted), so the modern UI cannot take seats legacy still owns. The guard fails closed: if a centre cannot be
resolved (lookup outage, unknown id) the write is refused with the same 403. A reschedule must also land on an
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ public final class ApiRoutes {

public enum V1Op { SESSIONS, SESSION, BOOK, GET_BOOKING, CANCEL, RESCHEDULE }

public enum V2Op { BOOK, CANCEL, RESCHEDULE, CAPACITY }
public enum V2Op { BOOK, CANCEL, RESCHEDULE, CAPACITY, OFFER }

/** {@code needsBody}: the centre key is {@code sessionId} in the JSON body (POST /api/v1/bookings). */
public record V1(V1Op op, Lookup lookup, String id, boolean needsBody) {
}

/** {@code id} is the booking or session id from the path, if any. */
/** {@code id} is the booking, session or offer id from the path, if any. */
public record V2Write(V2Op op, String id) {
}

Expand Down Expand Up @@ -79,6 +79,10 @@ public static Optional<V2Write> matchV2Write(String method, String rawPath) {
return Optional.of(new V2Write(V2Op.RESCHEDULE, s[1]));
}
}
if (s[0].equals("offers") && s.length == 3 && m.equals("POST") && (s[2].equals("accept") || s[2].equals("decline"))
&& PortalRoutes.isId(s[1])) {
return Optional.of(new V2Write(V2Op.OFFER, s[1]));
}
if (s[0].equals("sessions") && s.length == 3 && s[2].equals("capacity") && m.equals("PUT") && PortalRoutes.isId(s[1])) {
return Optional.of(new V2Write(V2Op.CAPACITY, s[1]));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
public record Lookup(Kind kind, String value) {

public enum Kind {
CENTER_CODE("centerCode"), CENTER_ID("centerId"), SESSION_ID("sessionId"), BOOKING_ID("bookingId");
CENTER_CODE("centerCode"), CENTER_ID("centerId"), SESSION_ID("sessionId"), BOOKING_ID("bookingId"), OFFER_ID("offerId");

private final String param;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

/**
* Keeps the modern side from writing seat inventory it does not own: a v2 write (book, cancel, reschedule,
* capacity change) that reaches scheduling-service through the gateway is refused with
* capacity change, waitlist offer accept/decline) that reaches scheduling-service through the gateway is refused with
* {@code 403 CENTER_NOT_MODERN} when its centre is not allow-listed. Bookings at or above the modern id floor
* are always the modern side's own. Keys that cannot be resolved
* (lookup outage or unknown id) are refused: the guard fails closed.
Expand All @@ -41,6 +41,7 @@ public Mono<Optional<String>> deniedCenter(ApiRoutes.V2Write write, Map<String,
case BOOK -> denied(Lookup.of(Kind.SESSION_ID, number(body, "sessionId")));
case CANCEL -> denied(Lookup.of(Kind.BOOKING_ID, write.id()));
case CAPACITY -> denied(Lookup.of(Kind.SESSION_ID, write.id()));
case OFFER -> denied(Lookup.of(Kind.OFFER_ID, write.id()));
case RESCHEDULE -> deniedReschedule(Lookup.of(Kind.BOOKING_ID, write.id()),
Lookup.of(Kind.SESSION_ID, number(body, "newSessionId")));
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,9 @@ static Stub.Answer scheduling(Stub.Call c) {
String u = c.uri();
if (u.startsWith("/api/v2/internal/routing/resolve")) {
String center = u.contains("sessionId=154") || u.contains("bookingId=5000000") || u.contains("centerId=1&") || u.endsWith("centerId=1")
|| u.contains("centerCode=BOS01") ? "BOS01"
: u.contains("sessionId=200") || u.contains("bookingId=1200") || u.contains("centerCode=CHI01") ? "CHI01"
|| u.contains("centerCode=BOS01") || u.endsWith("offerId=7") ? "BOS01"
: u.contains("sessionId=200") || u.contains("bookingId=1200") || u.contains("centerCode=CHI01")
|| u.endsWith("offerId=8") ? "CHI01"
: u.contains("centerCode=SEA01") ? "SEA01" : null;
return center == null ? Stub.Answer.json(404, "{\"error\":\"SESSION_NOT_FOUND\"}")
: Stub.Answer.json(200, "{\"centerCode\":\"" + center + "\",\"target\":\"legacy\",\"reason\":\"x\"}");
Expand All @@ -72,6 +73,9 @@ static Stub.Answer scheduling(Stub.Call c) {
return Stub.Answer.json(200, "{\"bookingId\":50000001,\"sessionId\":154,\"candidateNumber\":\"NW00000901\","
+ "\"candidateName\":\"A\",\"status\":\"CANCELLED\",\"channel\":\"PARTNER\",\"bookedAt\":\"2026-11-10T08:00:00\"}");
}
if (c.method().equals("POST") && u.startsWith("/api/v2/offers/")) {
return Stub.Answer.json(200, "{\"offer\":{\"offerId\":7,\"status\":\"ACCEPTED\"}}");
}
if (u.startsWith("/api/v2/centers/BOS01/sessions")) {
return Stub.Answer.json(200, "[{\"sessionId\":154,\"centerCode\":\"BOS01\",\"startsAt\":\"2026-11-12T09:00:00\",\"waitlistCount\":0}]");
}
Expand Down Expand Up @@ -240,6 +244,22 @@ void v2WritesOnNonAllowListedCentresAreRefused() {
.bodyValue(Map.of("capacity", 5)).exchange().expectStatus().isForbidden();
}

@Test
void offerAcceptAndDeclineAreGuardedByTheOffersCentre() {
web.post().uri("/api/v2/offers/7/accept").exchange()
.expectStatus().isOk().expectHeader().valueEquals("X-Route", "modern")
.expectBody().jsonPath("$.offer.status").isEqualTo("ACCEPTED");
web.post().uri("/api/v2/offers/8/accept").exchange()
.expectStatus().isForbidden().expectBody().jsonPath("$.error").isEqualTo("CENTER_NOT_MODERN");
web.post().uri("/api/v2/offers/8/decline").exchange()
.expectStatus().isForbidden().expectBody().jsonPath("$.error").isEqualTo("CENTER_NOT_MODERN");
web.post().uri("/api/v2/offers/999/decline").exchange()
.expectStatus().isForbidden().expectBody().jsonPath("$.error").isEqualTo("CENTER_NOT_MODERN")
.jsonPath("$.message").value(m -> assertThat((String) m).contains("could not be resolved"));
assertThat(SCHEDULING.calls("POST", "/api/v2/offers/8")).isEmpty();
assertThat(SCHEDULING.calls("POST", "/api/v2/offers/999")).isEmpty();
}

@Test
void internalSchedulingEndpointsAreNotExposed() {
web.post().uri("/api/v2/internal/import/sessions?mode=reset").exchange()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,5 +95,10 @@ void bookingApiRoutes() {
assertThat(ApiRoutes.matchV2Write("POST", "/api/v2/bookings").orElseThrow().op()).isEqualTo(ApiRoutes.V2Op.BOOK);
assertThat(ApiRoutes.matchV2Write("PUT", "/api/v2/sessions/154/capacity").orElseThrow().id()).isEqualTo("154");
assertThat(ApiRoutes.matchV2Write("GET", "/api/v2/bookings/9")).isEmpty();
assertThat(ApiRoutes.matchV2Write("POST", "/api/v2/offers/7/accept").orElseThrow())
.isEqualTo(new ApiRoutes.V2Write(ApiRoutes.V2Op.OFFER, "7"));
assertThat(ApiRoutes.matchV2Write("POST", "/api/v2/offers/7/decline").orElseThrow().op()).isEqualTo(ApiRoutes.V2Op.OFFER);
assertThat(ApiRoutes.matchV2Write("POST", "/api/v2/Offers/7/Accept/").orElseThrow().id()).isEqualTo("7");
assertThat(ApiRoutes.matchV2Write("GET", "/api/v2/offers/7")).isEmpty();
}
}
Loading
Loading