Files
aeternalis/planning/RELIABILITY-AND-PERSISTENCE.md

376 lines
24 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Reliability issues and persistence plan
Reviewed 2026-09-11 against repository revision `ca57157`. This records findings
and proposed resolutions; it does not implement fixes. Issue numbers below match
the user's report and are separate from milestone numbers. All issues remain open.
The persistence problem is a prerequisite for the expanding-world redesign, not
a cleanup task after it. Keep the existing single world owner, database-time lease,
revision fencing, and atomic character/transfer/death/housing claims. Replace the
whole-world storage and scheduling beneath those boundaries.
## Evidence and qualifications
The code confirms duplicate whole-world serialization and payload updates inside
the simulation lock, plus a periodic save even without a dirty world. It does not
establish production throughput or capacity. The reported 1,084-byte snapshot,
revision 230,254, 76 dirty sites, and 50 databases/150 files are user observations,
not measurements reproduced in this review. A revision is not a count of payload
updates: the second payload update does not increment it.
Three details change the proposed remedies:
- Saves also renew the owner lease. Skipping idle saves requires an independent,
fenced heartbeat; otherwise an apparently idle owner loses its lease.
- Pending travel already supports another eligible destination and, for a journey
from a hub, return to its viable source hub. Strict destination equality would
remove an existing recovery mechanism. Explicit cancellation and recovery when
all destinations are unavailable are still missing.
- `Snapshot` dereferences a missing character, but the proposed `Arrive` race is
not reproduced. Acceptance deletes/replaces the legacy copy in a cloned map,
then publishes that map only after successful commit under the service lock.
Guarding stale peers remains necessary without claiming that exact race exists.
## Issue register
### 1. Whole-world persistence dominates simulation work — prerequisite
**Verified:** [Lease.save](../server/internal/store/store.go) marshals the staged
world, writes it, synchronizes passages/characters, resolves further mutations and
title claims, then marshals/writes and synchronizes those projections again.
[Service.Run](../server/internal/transport/service.go) holds `s.mu` throughout and
saves on `Dirty() || elapsed >= one second`. Nominally the periodic branch alone
can cause about 86,400 save transactions per day, each with two payload updates;
actual timing depends on tick and database delays. Combat can trigger more saves.
[World.chunk](../server/internal/game/world.go) retains explored `ResourceLayouts`
even when meshes are evicted. This makes each full save depend on historical
exploration. Corpse retention is intentional: current
[lootCorpse](../server/internal/game/equipment.go) keeps even fully looted player
corpses for resurrection; it removes other corpses after looting. Do not prune
player corpses to solve storage cost.
**Near-term plan:**
- Measure save causes, serialized bytes, transaction time, and time holding the
simulation lock before changing scheduling.
- Split a lightweight database-time lease heartbeat from gameplay persistence.
Coordinate heartbeat and commits through the same owner/revision discipline;
lease loss or an ambiguous write still freezes the world. Schedule renewal with
margin inside the current 30-second lease, including during slow storage.
- Save only when durable state changes or bounded position/play-time accounting
needs flushing. No connected players is not an idle test: world deadlines,
depletion, effects, control commands, and housing recovery may still be due.
Volatile tick counters and projectile presentation must not alone force saves.
- Acquire the metadata fence and required row locks first, resolve claims and
mutations, and serialize the final world once. Preserve the existing global
lock order and atomic projections; remove duplicate projection work only after
separating required claim/locking operations from final payload writes.
**Exit checks:** unchanged worlds renew leases without full payload writes; due
offline lifecycle work still commits; one final serialization per save; competing
first-title claims, revival, housing, and transfers remain atomic. These wins do
not make whole-world checkpoints suitable for infinite exploration. The durable
foundation below is still required before milestone 5.
### 2. Missing-character snapshot can panic a world — high priority
**Verified:** [World.Snapshot](../server/internal/game/world.go) dereferences
`w.Characters[id]` without checking it; the tick loop calls it for every peer.
The reported trigger through [Arrive](../server/internal/game/travel.go) is not
established by [staged acceptance](../server/internal/store/travel.go).
**Plan:** define an explicit absent-character result and make the service close
and remove that stale peer. Audit removal/replacement paths against peer lifetime.
Do not send an empty snapshot that looks like a valid playable character.
**Exit checks:** an injected stale peer cannot panic or interrupt other players;
daily-cap closure, disconnect, travel retries, and legacy-copy replacement keep
peer and character ownership consistent, including failed acceptance.
### 3. Incomplete travel recovery lifecycle — high priority
**Verified:** [travel storage](../server/internal/store/travel.go) reserves the
life in `transit` until acceptance. There is no explicit cancel/expiry/operator
recovery path in [travel routes](../server/internal/transport/travel.go).
However, [the client](../client/src/travel.ts) and
[existing travel contract](../docs/MILESTONE-5.md) already allow alternate eligible
destinations. Failure of one destination alone is not permanent stranding.
**Proposed resolution:** retain durable escrow and alternate-hub selection; expose
pending age, last failure, and available recovery actions. Add an audited operator
action to retry/route the same transfer through ordinary destination acceptance,
not to create or copy a character. Alert on aged transfers. If every hub is down,
retain the reservation until an eligible hub is available; provisioning/bringing
a hub back is an operational prerequisite, not a reason to discard the life.
Treat cancellation as a validated return, not deletion of escrow. A hub-origin
journey can already return to its source if viable. Returning to a survival world,
escape-stone refunds, and survivor-credit behavior need an explicit policy before
adding such a route. Recommendation: no automatic survival return or refund in the
first repair. Expiry should escalate to recovery, never expire the character.
**Exit checks:** full/down/ended destinations, lost responses, restart, source
destruction, concurrent accept/return/operator requests, and no hubs available.
Exactly one place owns the same life and items; replacement stays blocked in
transit; daily usage and progression persist; costs/credit are never applied twice.
### 4. Destination field does not express the actual travel contract — high priority
**Verified:** preparation validates `Destination`; acceptance checks actual local
eligibility/capacity and route kind but not equality with that field. The single
prepared-to-accepted claim still prevents duplicate redemption. Retargeting is
already documented behavior, so a strict comparison is not a drop-in bug fix.
**Proposed resolution:** define the field as the requested/preferred destination,
with `acceptedWorld` the actual destination. Preserve explicit player selection
of an alternate eligible destination and record original selection, actual choice,
actor, and result in travel audit history. Preparation is not a capacity reservation;
acceptance must always revalidate the actual destination. If a future route requires
a bound destination, encode that policy explicitly and provide an atomic retarget
operation rather than silently changing the current recovery contract.
**Exit checks:** eligible retarget and hub return work; survival-origin travel
cannot enter another survival world; actual capacity/phase checks cannot be
bypassed; simultaneous destinations yield one accepted owner and consistent retry
responses. Update protocol/client/docs together if the field is renamed.
### 5. Unreachable legacy passage join code — small reliability cleanup
**Verified:** [Service.join](../server/internal/transport/service.go) rejects a
nonempty claim before its later passage/import branches can run.
**Plan:** remove unreachable branching and retire the obsolete join request field
with an explicit compatibility error for old callers. Keep ledger/history and
migration functions that still have callers. Update generated protocol through
`schemas/protocol.json` and `npm run generate` if its contract changes.
**Exit checks:** ordinary new/resumed joins still work; direct passage requests
cannot bypass travel; legacy survivor reconnect and portal travel still work.
### 6. Ingress rejects valid-sized catalog requests — small operational fix
**Verified:** [world ingress](../deploy/chart/templates/worlds.yaml) limits bodies
to `8k`; [catalog publication/preview](../server/internal/transport/catalog.go)
allows 32,768 bytes. A single catalog change with large pools/effects/recipes can
cross the edge limit; it need not be a publication of the entire catalog.
**Plan:** align all ingress/proxy paths with the largest supported app request,
keeping the app's endpoint-specific bounds. Make the editor explain an oversized
request, including a non-JSON 413 returned by the edge.
**Exit checks:** valid catalog changes above 8 KiB through 32 KiB reach validation;
oversized requests remain rejected. Check rendered chart routes and an ingress
request, not just direct app calls. Other endpoint limits remain bounded.
### 7. Public configuration/preview compete with simulation — priority repair
**Verified:** [HTTP routes](../server/internal/transport/http.go) take `s.mu`;
preview generates nine chunks and serializes the response while holding it.
[PreviewChunk](../server/internal/game/biomes.go) is read-only, but uses the world's
generator and existing resource layouts. The limiter refills at five requests per
second with a burst of 60; an ingress may aggregate clients under one remote IP.
**Plan:** publish immutable, pre-encoded config/preview responses. Build the initial
preview at startup and refresh from copied inputs on relevant generator/catalog,
config, or preview-layout changes. Never generate terrain in a public request or
marshal mutable live state on a background goroutine. Keep pre-login preview public.
Review trusted-proxy/rate-limit deployment separately without trusting arbitrary
forwarded IP headers.
**Exit checks:** repeated requests perform no terrain work or simulation-lock
acquisition; catalog changes cannot leave a permanently stale preview; cached
responses contain no private state and match the intended generator/layout version.
### 8. Pending OIDC flows are process-local and globally capacity-limited
**Verified:** [Auth](../server/internal/transport/auth.go) stores pending flows in
a map, expires them after ten minutes, and rejects new login attempts at 4,096.
Restart loses pending flows. The cap bounds memory; failing closed is correct,
but unauthenticated flow creation can exhaust shared login capacity.
**Plan:** add bounded initiation throttles and saturation metrics; move pending
flows to a shared short-TTL store with atomic single-use consumption. Prefer the
existing PostgreSQL dependency in production, with SQLite development coverage,
unless measurement justifies another service. Protect PKCE verifier data and keep
state-cookie matching, nonce, redirect validation, and expiry checks. Multi-replica
authentication must not introduce multiple simulation owners for a world.
**Exit checks:** callback survives restart/another auth replica; replay/expired or
mismatched state is rejected; one abusive source cannot easily monopolize the
global pool; overload stays bounded and safe. Verify real ingress client identity
and normal login bursts. Do not evict arbitrary valid flows to appear available.
### 9. Snapshot writer parses its own payload — small performance fix
**Verified:** [WebSocket writer](../server/internal/transport/http.go) unmarshals
each outgoing snapshot solely to recover `Self.RemainingSeconds`.
**Plan:** queue an envelope containing encoded bytes and a close-after-write flag
derived from the same snapshot. Keep the bounded queue and slow-client handling.
**Exit checks:** no writer-side JSON parse; daily-limit closure happens after the
final snapshot is written; queued metadata cannot refer to a different snapshot;
disconnect and backpressure still release the peer correctly.
### 10. Dense client formatting obscures control flow — isolated maintenance
**Verified:** [main.ts](../client/src/main.ts), notably selection and boot wiring,
contains densely packed action branches. The repository has no pinned formatter.
**Plan:** pin a formatter and configuration, then format hand-authored client code
in a dedicated commit. Keep generated bindings under their generator's control.
Preserve useful comments. Separate behavior-changing module extraction from the
formatting pass, prioritizing targeting, input, and startup when next touched.
**Exit checks:** typecheck/build and generated-contract consistency; review shows
formatting-only source changes. Do not mix a broad reformat into persistence fixes.
### 11. E2E temporary databases are never cleaned up — isolated tooling
**Verified:** [dev server](../tools/dev-server.mjs) creates timestamped E2E databases;
[Playwright configuration](../playwright.config.ts) has no corresponding cleanup.
The reported local file count is not independently verified here.
**Plan:** allocate a unique run-owned temporary directory and record its exact path.
Use server-exit cleanup or a coordinated teardown that first stops and waits for
the server, then removes that run's database/WAL/SHM files. Preserve failure traces
and screenshots separately. An interrupted-run sweeper must be scoped, age-aware,
and avoid active runs. Never delete user-supplied `DATABASE_URL` databases or use
a broad `.local` wildcard cleanup.
**Exit checks:** successful/failed runs clean only their own closed files; concurrent
runs and developer data are untouched; interrupted runs have a safe cleanup path.
This does not resume deferred Playwright authoring or routine full-suite runs.
## Revised milestone 4: gates before expanding worlds
Keep the user-facing milestone numbers. Break #4 into reviewable handoffs, with
commit/push after each implemented slice and a short manual checklist where useful.
The list below is the proposed execution plan; this document completes its planning
inventory, not its implementation gates.
| Gate | Scope | Required outcome |
| --- | --- | --- |
| 4A — contract and measurements | This issue register; persistence baseline; world and transfer lifecycle decisions | Define durable versus transient state, migration contract, and unresolved world rules before changing storage |
| 4B — bounded repairs | Issues 2, 5, 6, 7, 9; issue 1 heartbeat/idle/one-payload improvements; travel recovery/contract work in 3–4; authentication in 8 | Remove immediate failure paths while preserving existing ownership and acknowledgements; give travel/auth their own scoped handoffs |
| 4C — durable storage foundation | Versioned journal, partitioned state, committed views, bounded working set, async checkpoints, migration | Historical exploration no longer determines every save or startup's resident chunk set |
| 4D — recovery and performance qualification | Crash/retry/fencing tests, PostgreSQL measurements, migration rehearsal | Demonstrate correctness and measured cost before milestone 5 builds against the new storage |
Issues 10 and 11 are separate small maintenance commits around 4B; they do not
need to wait for the Control revamp. Implement the foundation incrementally with
the finite generator first. Milestone 5 then adds expansion, external generation,
and roaming/depletion against the established persistence API.
### Storage and commit model to design in 4A and implement in 4C
1. **Partition durable state.** Keep bounded world metadata (seed, versions, phase,
origin/frontier policy, committed sequence, owner/revision). Store explored chunk
records keyed by world/coordinates with generator/catalog provenance, stable
resource identities, depletion and mutation state. Store characters, corpses,
structures, and movable entities by stable ID with spatial indexes. Preserve
existing account-life, transfer, title-claim, housing/key and audit ledgers; do
not create competing authoritative copies. Partitioning may use versioned JSON
per bounded record; it must not hide another entire world in a single value.
2. **Append committed outcomes.** Assign ordered world event/batch sequences under
the existing lease/revision fence. Persist authoritative outcomes and affected
records/claims atomically. Include event/schema versions, command idempotency,
resolved random outcomes, and relevant catalog versions. Replaying raw player
inputs against today's clock, RNG, or catalog must not reroll rewards or deaths.
3. **Separate commit from publication.** Stage bounded mutation batches. A bounded
persistence queue can commit outside the global simulation lock; only committed
results become externally visible/acknowledged. Publish under the owner after
checking ordering and ownership. Do not simulate irreversible dependent actions
against uncommitted state without an explicit staged-state design. Backpressure
pauses admission of more work; ambiguous commits or lease loss freeze service.
Async checkpoints alone do not solve blocking durable event appends.
4. **Checkpoint immutable committed state.** Build incremental/versioned checkpoints
at a known committed sequence from immutable records or a consistent database
view. Never marshal the live mutable world concurrently. Publish a complete
checkpoint manifest atomically; crash during construction leaves the prior one
usable. Replay only the committed tail, with partition watermarks that prevent
applying an event twice. Compact journals only once recovery no longer needs
them; retain separate audit and lifecycle history according to explicit policy.
5. **Bound active memory and recovery work.** Load metadata and relevant partitions,
not every visited chunk. Evict inactive loaded state only after its mutations
are durable. Schedule offscreen deadlines/depletion from indexed metadata rather
than keeping all entities active. Retained corpses are durable cold records, not
garbage to prune. Restore stable loot and resource state on revisits.
The authoritative write unit and lock order must cover cross-record changes such
as corpse loot into an inventory, housing storage, revival consumption, first-title
claims, and travel reservation. Journal entries do not replace their unique claims
or justify eventual consistency for item ownership.
### Durability classes
| State | Required boundary |
| --- | --- |
| Death/revival/replacement, item ownership and costs, progression/rewards, title claims, housing/key changes, travel, world ending | Commit effects and claims atomically before publishing success; retry cannot duplicate or reverse them |
| Combat outcomes and persistent resource changes | Ordered committed batches; visible effects cannot contradict the restored authoritative outcome |
| Position and daily play usage | Explicit bounded flush policy no weaker than today's documented one-second rollback; save exact relevant state at lifecycle transitions; daily cap is enforced by Go |
| Projectile trails, particles, client interpolation and other presentation | Reconstruct or expire; do not force durable saves merely to display them |
| World schedules, depletion/frontier decisions, retained corpse eligibility | Persist deadlines/decisions; progress correctly offline and after restart, without regenerating deleted resources |
Before coding, inventory current dirty sites into these classes. A projectile's
visual trail is transient; its eventual damage, costs, and rewards are not. Decide
and document active projectile/cast restart behavior without granting replay damage
or charging resources twice. Do not silently change current lifecycle rules.
### Generator and world lifecycle integration
- Generation workers receive seed, coordinates, generator/content version and
policy revision. They return deterministic candidate data; only the leased world
owner decides spawn/admission, applies depletion, and commits accepted results.
Reject duplicate, stale, or now-outside-frontier work. A worker never owns players.
- Chunk state and entity indexes must support moves across chunk boundaries without
duplicate mobs/items, including movement between loaded and unloaded regions.
- Preserve all confirmed rules in [Changes-Needed](Changes-Needed.md): no fixed
outer boundary before awakening; fixed origin and distance difficulty; constrained
outward generation afterward; traversable depleted chunks; retained player corpses.
- Finalize the proposed finite-frontier/loss condition and offscreen Harbinger
advancement before implementing them. Also settle disconnected-after-victory
fallback, invalid high-level arrivals, existing mobs/structures and contents,
later drops, and key-ledger effects of ordinary-loot deletion. These remain
gameplay decisions, not assumptions made by the storage migration.
- Victory evacuation must reserve every remaining living character durably before
cleanup, resumably in bounded batches. A terminal transition closes admissions
and conflicting actions before sweeping characters. Full hubs leave recoverable
escrow; they cannot erase survivors. Corpses and house-recovery retention follow
the authoritative terminal world record. Never resurrect dead characters during
evacuation or preserve corpse revival after world destruction.
### Migration, rollback, and qualification
Migration must run under exclusive fenced ownership with old writers blocked.
Version the storage format and make conversion resumable: read the legacy snapshot,
export stable IDs/coordinates and records, reconcile existing external ledgers,
validate ownership/counts/checksums, then atomically mark the new format usable.
Cover legacy generator layouts, offline characters, corpses (including empty
revivable ones), pending transfer escrow, house keys/recovery, title claims, and
daily usage. Do not fold the still-open inherited-title policy into this migration.
Rehearse on disposable copies. Compare old and converted state before cutover and
canary one world first. Rollback before new-format writes can use the verified old
state. After new writes, restoring an old snapshot or binary can reverse deaths and
transfers: require a tested reverse migration or forward repair instead. Keep backups
and incomplete conversion artifacts until validation; backups are not permission to
rewind a live world.
Measure idle, active combat/boss, and exploration-heavy worlds with increasing
historical chunk counts. Record tick p50/p95/p99, simulation-lock duration, bytes
serialized, payload writes, transaction latency, PostgreSQL WAL volume, loaded
state size, commit queue depth/age, checkpoint lag and recovery time. Set acceptance
budgets from a recorded baseline and the 20 Hz tick target, not invented capacity.
At a fixed active set, ordinary commit cost and resident memory must not grow with
every historically explored chunk; scheduled work must remain bounded as well.
Fault tests must include commit-success/response-loss, crashes around journal and
checkpoint publication, lease expiry and competing takeover, stale queued writes,
database delay/outage, duplicate generation results, and mid-migration restart.
Run SQLite and production PostgreSQL transaction coverage, with focused lifecycle
tests proving one life/one item owner and preserved daily limits after recovery.
Use required repository checks for implementation slices. Routine Playwright work
remains deferred; manual testing does not replace storage fault tests or a
representative load test before any increase in documented tested capacity.