Commit b8ee3498 authored by Christos Tranoris's avatar Christos Tranoris
Browse files

fix reservation lifecycle

parent 0e4bd52e
Loading
Loading
Loading
Loading
+3
Changes for .gitignore: 3 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -7,6 +7,9 @@ dist
# TypeScript build info
*.tsbuildinfo

# Test coverage output
coverage

# Local env
.env.local
.env.*.local
+1 −1
Changes for CLAUDE.md: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -66,7 +66,7 @@ Always import via these aliases, not deep relative paths.
### Directory map (actual)
```
src/
  domain/          # Pure TS: entities, primitives, FeasibilityResult union, ports.ts (gateway interfaces), validation
  domain/          # Pure TS: entities, primitives, FeasibilityResult union, gateways.ts (gateway interfaces), ports.ts (AuthPort/TimePort), validation
  app/             # One file per aggregate (pools.ts, reservations.ts, …) = TanStack Query hooks. queryKeys.ts is the single key registry. (mutations/ and queries/ dirs exist but are empty.)
  adapters/
    api/
+1 −1

File changed.

Preview size limit exceeded, changes collapsed.

+206
Changes for docs/20260807_0145_reservation_lifecycle_signals_reconcile.md: 206 added lines, 0 removed lines.
Original line number Diff line number Diff line
# Reservation lifecycle signals + break-glass reconcile (admin)

**Date:** 2026-08-07 01:45

## What & why

The Chronos backend grew two admin-only reservation endpoints that the UI did not expose:

| | |
|---|---|
| `POST /api/v1/reservations/{id}/signals` | Report an orchestrator lifecycle signal → `ReservationView` |
| `POST /api/v1/reservations/{id}/reconcile` | Break-glass recovery from `RELEASE_FAILED` (no body) → `ReservationView` |

`lifecycleState` is deliberately not settable directly — Chronos *derives* it from a
reported signal so the OpenSlice status write, attempt accounting and outbound event always
travel with the transition. Before this change an operator running Chronos in **EXTERNAL**
timing mode had no UI at all to drive a reservation through
`CREATED → PROVISIONING → ACTIVE → RELEASING → RELEASED`, and a reservation stuck in
`RELEASE_FAILED` held its capacity forever with no way to free it from the UI.

### Contract delta

The committed `api-docs.json` was regenerated from the live document at
`http://localhost:8888/v3/api-docs`. Verified non-destructive against
`git show HEAD:api-docs.json`: **no schema property was removed** — the live contract is a
strict superset. Beyond the two paths above it adds:

- new schema `LifecycleSignalRequest { signal (required), attemptSequence?, failureKind? }`
- `LIFECYCLE_SIGNAL_REJECTED` in the `ChronosProblemDetail.code` enum
- `RESERVATION_RECONCILE` in `InconsistencyFlagEntity.operationType`
- `ReservationView.updatedAt`

Everything else in the live contract is description-only churn.

### Semantics confirmed from backend source, not just the OpenAPI text

Read from `app/ReservationSignalDispatcher.java`, `app/SignalOutcome.java`,
`edge/rest/ProblemDetailExceptionHandler.java:162` and `e2e/LifecycleSignalRestIT.java`:

- **State preconditions are hard.** `EXTERNAL_START` ← `CREATED`;
  `PROVISIONING_CONFIRMED`/`PROVISIONING_FAILED` ← `PROVISIONING`; `EXTERNAL_END` ← `ACTIVE`;
  `RELEASE_CONFIRMED`/`RELEASE_FAILED` ← `RELEASING`. Any terminal state →
  `IGNORED_TERMINAL`.
- **`attemptSequence`** is required for the four CONFIRMED/FAILED signals and ignored for
  the two timing signals. `null` counts as a mismatch → `IGNORED_STALE`. The counter it must
  match (`provisioningAttempts`/`releaseAttempts`) **is exposed by no read endpoint** —
  `ReservationView` does not carry it. Per the backend IT, `EXTERNAL_START` raises
  `provisioningAttempts` to 1, so the normal single-attempt flow uses `1`. The UI therefore
  prefills `1`, leaves it editable, and explains how the counter moves when the server
  answers `IGNORED_STALE`.
- **`failureKind`** (`CLEAN`|`DIRTY`) is read only for the two FAILED signals; absent
  defaults to `DIRTY`.
- **The 409 body carries an extra `signalOutcome` property** (`IGNORED_TERMINAL` |
  `IGNORED_WRONG_STATE` | `IGNORED_STALE` | `IGNORED_TIMING_MODE` | `CSU_FAILED`) that is
  *not* declared in the `ChronosProblemDetail` schema, so the codec has to read it off the
  raw body.
- **`reconcile`** is valid only from `RELEASE_FAILED`; on `CSU_FAILED` it leaves an
  `InconsistencyFlag` the background reconciliation job retries, so that 409 is genuinely
  retriable.

## Changes

### Contract & generated types
- `api-docs.json` overwritten from the live document; `src/adapters/api/generated/schema.d.ts`
  regenerated via `npm run gen:types`.

### Domain (pure)
- `domain/reservation.ts` — `LIFECYCLE_SIGNALS` / `LifecycleSignal`, `FAILURE_KINDS` /
  `FailureKind`, `SIGNAL_OUTCOMES` / `SignalOutcome` with `isLifecycleSignal` and
  `isSignalOutcome` guards, plus the state machine as pure functions:
  `signalsValidFrom(state)`, `requiresAttemptSequence(signal)`, `isFailureSignal(signal)`.
  These are business rules, so they live in `domain/`, not in a component.
- `domain/feasibility.ts` — `'LIFECYCLE_SIGNAL_REJECTED'` added to `PROBLEM_CODES`;
  `ProblemDetail` gained an optional `signalOutcome?: SignalOutcome`.
- `domain/gateways.ts` — new `LifecycleSignalDraft`, and `ReservationGateway` gained
  `sendSignal(id, draft)` and `reconcile(id)`.

### Codec (`adapters/api/`)
- `mappers/entities.ts` — `encodeLifecycleSignal`, which omits `attemptSequence` for the two
  timing signals and `failureKind` for non-failure signals. The server ignores them either
  way, but the wire body should say what it means.
- `mappers/problems.ts` — `decodeProblemDetail` now recovers `signalOutcome` from the raw
  body through `(body as Record<string, unknown>).signalOutcome`, validated with
  `isSignalOutcome`; an unrecognised or non-string value is dropped rather than passed on.
- `gateways/reservationGateway.ts` — the two new methods. Deliberately **not** wrapped in the
  existing `isConflictProblem`/`buildConflictResult` try/catch used by `createFirm`: that
  turns a 409 into a `FeasibilityResult` `CONFLICT`, which would swallow the `signalOutcome`
  the operator needs. A rejected signal throws.
- `feedback/treatmentMap.ts` — `LIFECYCLE_SIGNAL_REJECTED` treated as
  `{ severity: 'warning', recoverable: true, showRequestId: true }`: nothing moved and
  nothing broke, so the operator can correct the signal and send it again.

### Hooks & capability
- `app/reservations.ts` — `useSendLifecycleSignal()` and `useReconcileReservation()`,
  re-exported from `app/index.ts`. Both invalidate `activity.all()`,
  **`activity.detail(id)`**, `reservations.all()`, `inventory.all()` and `statistics.all()`;
  reconcile also invalidates `flags.all()`. `activity.detail(id)` matters specifically —
  `queryKeys.reservations.*` is backed by no live query today, so invalidating only that
  would leave the detail page showing the pre-signal state.
- `features/shell/capabilities.ts` — new `canDriveLifecycle: isAdmin`. Both endpoints are
  admin-only server-side (`gate.requireLifecycleSignal()`); reusing `canCreateReservations`
  would be wrong (admin **or** requester) and `canManagePools` is unrelated. No new route, so
  no `RoleGuard` change.

### UI (`features/activity/`)
- **New `LifecycleSignalPanel.tsx`** — guided panel plus an advanced escape hatch. Buttons
  come from `signalsValidFrom(reservation.lifecycleState)`; in a terminal state it says
  "No lifecycle signal applies in state X" instead. The attempt field appears only when an
  attempt-bearing signal is offered (default `1`, with helper text explaining Chronos does
  not report the counter), and the failure-kind radio only when a failure signal is offered
  (default `DIRTY`). The collapsible **Advanced — send any signal** section exposes all six
  signals, because the state rendered here is a cached read and can be behind the server. One
  shared set of fields serves both paths. Every send goes through a `ConfirmDialog` naming the
  resulting state.
- **New `ReconcileReservationButton.tsx`** — modelled on `CancelReservationButton`
  (`variant: 'icon' | 'button'`, capability gate, `ConfirmDialog`, `stopPropagation` on the
  icon so the row's navigation does not fire). Renders **nothing** outside `RELEASE_FAILED`
  rather than a permanently disabled control, so the activity table stays clean. The confirm
  copy states what the admin is asserting: that they have inspected the infrastructure and
  the resource really is clean.
- **New `signalOutcomeHints.ts`** — plain-language explanation per `SignalOutcome`, shown
  beside the `ProblemDetailAlert`. This carries the most weight for `IGNORED_STALE`, where
  the attempt counter is unreadable from any endpoint and the operator has no way to work out
  the right number without being told how it moves.
- Mounted in `ReservationDetailPage.tsx` (Actions block) and, as an icon, in the
  `ActivityPage.tsx` Actions cell; both exported from `features/activity/index.ts`.

### Tests
- `domain/reservation.test.ts` — `signalsValidFrom` for all 8 lifecycle states, the two
  predicates, both type guards (including that `APPLIED`/`RETRY_PENDING`/`NOT_FOUND` are
  rejected — they never reach a problem detail), and that the returned array cannot be used
  to mutate the table.
- `mappers/entities.test.ts` — `encodeLifecycleSignal` field omission per signal.
- `mappers/problems.test.ts` — all five outcomes recovered; unknown and non-string dropped;
  absent on an ordinary problem.
- `gateways/gateways.test.ts` — request body, decoded response, id percent-encoding, and that
  a 409 **rejects** with `signalOutcome` rather than becoming a `CONFLICT` result.
- `app/reservations.test.ts` — both mutations, including the `activity.detail(id)`,
  `inventory` and `flags` invalidations.
- New `LifecycleSignalPanel.test.tsx` (25 cases) and `ReconcileReservationButton.test.tsx`
  (19 cases), the latter covering that the icon variant's click does not bubble up to the
  navigating row and that `onReconciled` fires only on success.
- `shell/Shell.test.tsx` — `canDriveLifecycle` true for admin, false for requester/auditor.
- `feedback/feedback.test.tsx` — the hardcoded "covers all 15 ProblemCodes" assertion now
  compares against `PROBLEM_CODES` itself, so it no longer needs editing when a code is added.
- `test/handlers.ts` — MSW handlers for both endpoints.
- `e2e/journeys.spec.ts` — three `test.fixme` stubs under *Admin journeys* (full signal drive
  to RELEASED, the `IGNORED_STALE` explanation, and the reconcile recovery).

## Verification

```
npx vitest run --testTimeout=30000 → 847 passed (61 files), 0 failed   [was 729]
npx eslint <changed files>         → clean; no boundary violations
npx vite build                     → built in 11.35s
openapi-typescript diff            → schema.d.ts byte-identical to a fresh generation
```

The longer timeout is needed because a **rotating** handful of pre-existing tests
(`Shell`, `FirmReservationForm`, `AvailabilitySearchPage`, `MembershipsListPage`, …) trip
Vitest's 5s default under load on this machine — a different set each run, never one of the
tests added here. A plain `npm test` also reached 845/845 clean on one run.

Per-file coverage for everything this change touched:

| File | Stmts | Branch | Funcs | Lines |
|---|---|---|---|---|
| `domain/reservation.ts` | 100 | 100 | 100 | 100 |
| `domain/gateways.ts` | 100 | 100 | 100 | 100 |
| `mappers/entities.ts` | 100 | 72.4 | 100 | 100 |
| `mappers/problems.ts` | 100 | 96.7 | 100 | 100 |
| `app/reservations.ts` | 100 | 100 | 100 | 100 |
| `shell/capabilities.ts` | 100 | 100 | 100 | 100 |
| `feedback/treatmentMap.ts` | 100 | 100 | 100 | 100 |
| `activity/signalOutcomeHints.ts` | 100 | 100 | 100 | 100 |
| `activity/LifecycleSignalPanel.tsx` | 97.4 | 96.6 | 100 | 100 |
| `activity/ReconcileReservationButton.tsx` | 95.2 | 94.7 | 83.3 | 94.7 |

The codec mappers clear the ≥90% bar. Note two things about the gates:

- **`npm run check:types-drift` reports a diff** only because the regenerated `schema.d.ts`
  is not committed yet — the script is `gen:types && git diff --exit-code`, so it compares
  against HEAD, not against a fresh generation. Verified separately that generating into a
  temp file produces a byte-identical result. It will pass once committed.
- **`npm run test:coverage` fails its 80% global thresholds** (76.25% stmts / 77.78% lines).
  This is pre-existing and not caused by this change: every file touched here sits at 85–100%,
  so removing them would lower the average, not raise it. The shortfall is in untouched
  feature pages (e.g. `ActivityPage.tsx` at 50%). Under coverage instrumentation a handful of
  unrelated tests also trip the 5s default timeout; `--testTimeout=30000` makes all 845 pass.
- `npm run build` remains broken for the pre-existing reason recorded in CLAUDE.md, plus a
  second one worth noting: `tsconfig.app.json` declares only `@domain/*`, not the bare
  `@domain` specifier that most files import, so `tsc` cannot resolve it repo-wide. Vite
  resolves it via `vite.config.ts`, which is why `npx vite build` succeeds.

### Manual check against the live backend

Not yet run. The backend is up at `localhost:8888`, so the intended sequence is:
`npm run dev`, sign in as `chronos.admin`, create a FIRM reservation in EXTERNAL timing mode,
open it from `/activity`, then drive it with the panel — `EXTERNAL_START` → PROVISIONING,
`PROVISIONING_CONFIRMED` (attempt 1) → ACTIVE, `EXTERNAL_END` → RELEASING,
`RELEASE_CONFIRMED` (attempt 1) → RELEASED — confirming each transition renders from the
returned view without a manual refresh. Then the rejection paths (attempt `0` →
`IGNORED_STALE` hint; any signal on the RELEASED reservation → `IGNORED_TERMINAL`), and
finally reconcile: drive one to `RELEASE_FAILED`, confirm the action appears both on the
detail page and as a row icon, run it, and confirm the reservation lands in `RELEASED` with
its capacity bookable again in the inventory view.
+88
Changes for docs/20260807_1255_activity_page_staleness_fixes.md: 88 added lines, 0 removed lines.
Original line number Diff line number Diff line
# Activity page — stale and misleading reads

## What & why

Reported symptom: `/activity` "seems cached and sometimes displays wrong information."

It was four independent defects stacked, not one cache bug. Reservations advance
`CREATED → PROVISIONING → ACTIVE → RELEASING → RELEASED` on the **server** — by scheduler, by
an external orchestrator, or by another operator's lifecycle signal — with nothing happening in
the operator's tab to trigger a refetch. Every layer of this page assumed the opposite.

| # | Defect | Where | Effect |
|---|---|---|---|
| 1 | No refresh mechanism at all | `app/queryClient.ts:28-30` — `staleTime: 30_000`, `refetchInterval: false`, `refetchOnWindowFocus: false` | Rows were only ever as fresh as the moment they were first fetched. No poll, no focus refetch, no Refresh button. |
| 2 | Background refetches were invisible | `ActivityPage.tsx` read `isPending` | In Query v5 `isPending` is only true with **no** cached data. A background refetch is `isFetching`, so the table kept rendering old rows, with no indication, until new data landed. Re-entering within `staleTime` refetched nothing at all. |
| 3 | A failed fetch rendered as an empty result | `ActivityPage.tsx` passed `loading`/`empty` to `StateView` but not `error` | Failure → `data` undefined → `empty` true → *"No reservations match the current filters."* Above it, `{String(error)}` on a `ProblemDetail` object rendered the literal text `[object Object]`. |
| 4 | Every mount fired a request the server cannot answer | the off-screen view was parked on `{ page: 0, size: 0, to: DateTime.fromMillis(0) }` with no `enabled` flag | `size=0` is what Spring's `PageRequest.of(0, 0)` rejects. |

Defect 3 is the one that most literally matches "displays wrong information": a broken backend
read as "nothing is booked".

**Refresh policy chosen (by the user): poll while visible.** 15s on the activity list, plus
`refetchOnWindowFocus`, both scoped to these queries rather than changing the global defaults.
Polling pauses while the tab is in the background (`refetchIntervalInBackground: false`).

### Two things that looked like causes and were not

- **Mutation invalidation is correct.** `queryKeys.activity.all()` is `['activity']`, a prefix of
  both `activity.list(params)` and `activity.detail(id)`, so the existing `invalidateQueries`
  calls do cover the list and the detail page.
- **`buildActivityParams` silently drops `membershipId` and `correlationId`** (`ActivityListInput`
  in `mappers/pagination.ts` never declared them) — but it is **dead code**. Only its own test
  imports it; `activityGateway.ts:23-38` builds its own params and forwards both correctly. Left
  alone here; worth deleting or reconciling separately.

## Changes

**`src/app/activity.ts`**

- `useReservations(q, options?)` gains a `ReservationListOptions` bag — `refetchInterval`
  (default `false`) and `enabled` (default `true`). Callers opt in; the global defaults are
  untouched for every other query in the app.
- On that query: `refetchIntervalInBackground: false`, and `refetchOnWindowFocus: true` +
  `staleTime: 0` overriding the global `false`/`30_000`.
- `useReservation(id)` gets the same `refetchOnWindowFocus` + `staleTime: 0`. The detail page
  picks which lifecycle signals to offer from `lifecycleState`, so a cached read there does not
  just look wrong — it offers the wrong actions.

**`src/features/activity/ActivityPage.tsx`**

- `ACTIVITY_POLL_MS = 15_000`; the displayed view polls, the off-screen one is `enabled: false`
  against an inert placeholder key (`INERT_QUERY`) instead of throwaway params. Both hooks stay
  mounted so hook order is stable.
- Destructures `isFetching` and `dataUpdatedAt`; `refreshing = isFetching && !isPending` drives a
  16px spinner, and an "Updated HH:mm:ss" caption sits beside the view toggle. The caption is
  suppressed until the first response (`dataUpdatedAt > 0`) so the page never claims a freshness
  it does not have.
- `error` now flows into `StateView` (which already renders `ProblemDetailAlert` — the `FlagsTab`
  in the same file was already doing this); the calendar branch renders `ProblemDetailAlert`
  directly. The `{String(error)}` alert is gone, as is the now-unused `Alert` import.

## Verification

```
npx vitest run --testTimeout=30000   → 858 passed (61 files), 0 failed   [was 847]
npx eslint <4 changed files>         → 8 errors, all pre-existing no-explicit-any in the
                                        test mock harnesses (HEAD has the same 8); no
                                        boundary violations
npx vite build                       → built in 9.19s
```

11 tests added:

- `src/app/activity.test.ts` — `enabled: false` never calls the gateway; remounting re-reads
  (pins `staleTime: 0`); polls twice over two 15s fake-timer advances; does **not** poll when not
  asked, even after 120s; `useReservation` re-reads on remount and stays idle without an id.
- `src/features/activity/ActivityPage.test.tsx` — the displayed view polls at 15s while the
  off-screen one is disabled; the "Updated 14:30:05" caption; the refreshing spinner appears over
  rows that are still on screen; no freshness claim before the first response; a failed fetch
  shows the problem instead of the empty-state text, and never `[object Object]`.

Three existing assertions on `useReservations` call args gained a second `expect.anything()` for
the new options argument.

**Not yet run:** the live check against `localhost:8888` — open `/activity`, confirm the Updated
caption advances every 15s without interaction, drive a reservation's lifecycle from another tab
and confirm the row's State column follows within one poll, and stop the backend to confirm the
table shows a Problem Detail rather than "No reservations match the current filters."
Loading