aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit a20b560fdaa7b3f12b468ccafc71c683383d05e3
parent 9ee5ad0b922ce9454d802b3560dd39ed30444095
Author: anon <anon@example.com>
Date:   Sat,  7 Nov 2026 04:10:53 +0000

Keep periodic and final checkpoints on their zone owners

Diffstat:
MDEVELOPERS.md | 20+++++++++++++-------
Mserver/simulation_checkpoint.go | 83+++++++++++++++++++++++++++++++++++++++++++++++++------------------------------
Mserver/world_runtime.go | 9+++++++--
Aserver/zone_checkpoint.go | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/zone_checkpoint_test.go | 308+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/zone_runtime.go | 42+++++++++++++++++++++++++-----------------
6 files changed, 461 insertions(+), 57 deletions(-)

diff --git a/DEVELOPERS.md b/DEVELOPERS.md @@ -109,9 +109,11 @@ not yet establish independent zone ownership. socket decoding. `zone_runtime.go` runs movement, actions and commands for a transferred state on one goroutine. A regression holds SQLite during an inventory move and checks that a second owned state accepts movement and advances position. -The component is not yet wired into production: external entry points and final -checkpoint coordination still require ownership migration before replacing the -global loops. +Each zone submits at most one periodic checkpoint at a time and receives its +completion directly in the event loop. A blocked writer leaves commands and +ticks running; a full writer queue defers the checkpoint to the next visit. +The component is not yet wired into production: external entry points and +transport shutdown still require migration before replacing the global loops. `world_runtime.go` owns the zone directory on a separate goroutine. Committed teleports transfer a player's entity and item records to the destination through @@ -119,9 +121,13 @@ its command channel. Reconnects wait for arrival; old connections remain bound to their source zone. A departure never waits for the destination to execute, so simultaneous opposite transfers cannot deadlock. Shutdown quiesces ticks, drains accepted handoffs (including newly created destinations), then joins the -zone workers. External producers must stop before that shutdown. These are -component boundaries: production startup, external entry points and final -checkpoint coordination remain to be connected. +zone workers. Each zone drains its pending periodic write and saves all remaining +player and NPC simulation state in one final transaction, regardless of periodic +deadlines. Final saves use the current effect time and do not rewrite inventory +or rewards. A failed final write is returned to the caller without preventing +other zones from stopping. External producers must stop before this shutdown. +These are component boundaries: production startup, external entry points and +transport shutdown remain to be connected. The directory also owns the committed mission catalog, with detached lookups by contract, private world and exterior playfield. Routed acceptance commits the @@ -143,7 +149,7 @@ A retired mission zone returns late arrivals to the exterior through a durable handoff, so an earlier committed departure cannot strand a player there. Retired zones stop their simulation timers and retain only command handling for late handoffs. These boundaries have component coverage; production startup, external entry points -and final checkpoints still need to use the zone owners. +and transport shutdown still need to use the zone owners. NPC lifetimes register and retire their directory entries from the owning zone. Cross-zone messages retain acceptance order for each entity and follow it through diff --git a/server/simulation_checkpoint.go b/server/simulation_checkpoint.go @@ -28,20 +28,24 @@ func (checkpoint playerCheckpoint) persist(tx *sql.Tx) error { return nil } +func (checkpoint *playerCheckpoint) include(player *character, now time.Time) { + position := playerPosition{player.playfield, player.position, player.rotation, player.returnDoor} + changed := position != player.savedPosition || player.vitals() != player.savedVitals + basis := playerCheckpointBasis{player.id, player.savedPosition, player.savedVitals, player.nextPositionSave, -1} + if changed || len(player.activeNanos) != 0 { + basis.write = len(checkpoint.writes) + checkpoint.writes = append(checkpoint.writes, playerPositionWrite{record: player.record(), effects: slices.Clone(player.activeNanos), now: now, updatePosition: changed}) + } + checkpoint.due = append(checkpoint.due, basis) +} + func (server *server) preparePlayerCheckpoint_locked(now time.Time) playerCheckpoint { var checkpoint playerCheckpoint visit := func(player *character) { if player == nil || player.savedProfile.ID == 0 || now.Before(player.nextPositionSave) { return } - position := playerPosition{player.playfield, player.position, player.rotation, player.returnDoor} - changed := position != player.savedPosition || player.vitals() != player.savedVitals - basis := playerCheckpointBasis{player.id, player.savedPosition, player.savedVitals, player.nextPositionSave, -1} - if changed || len(player.activeNanos) != 0 { - basis.write = len(checkpoint.writes) - checkpoint.writes = append(checkpoint.writes, playerPositionWrite{record: player.record(), effects: slices.Clone(player.activeNanos), now: now, updatePosition: changed}) - } - checkpoint.due = append(checkpoint.due, basis) + checkpoint.include(player, now) } // Zone membership includes arrivals whose IDs exceed the zone's startup // watermark. The shared simulation still uses the player ID range. @@ -79,31 +83,52 @@ func (write npcWrite) changed() bool { return len(write.characterRows)+len(write.npcRows)+len(write.contributors)+len(write.effects)+len(write.checkpoint.removed) != 0 } +// A checkpoint owns detached writes and their publication bases. Only its owner +// applies the completion; the writer goroutine never reads live simulation state. +type simulationCheckpoint struct { + players playerCheckpoint + npcs npcWrite + active map[uint32]bool + now time.Time +} + +func (checkpoint simulationCheckpoint) changed() bool { + return len(checkpoint.players.writes) != 0 || checkpoint.npcs.changed() +} + +func (checkpoint simulationCheckpoint) persist(tx *sql.Tx) error { + if err := checkpoint.players.persist(tx); err != nil { + return err + } + return checkpoint.npcs.persist(tx) +} + +func (server *server) prepareSimulationCheckpoint_locked(now time.Time) simulationCheckpoint { + checkpoint := simulationCheckpoint{players: server.preparePlayerCheckpoint_locked(now), active: make(map[uint32]bool), now: now} + for id := range server.simulationNPCs_locked(now) { + checkpoint.active[id] = true + } + checkpoint.npcs = server.prepareNPCWrite_locked(itemStore{checkpointAt: now}, checkpoint.active) + return checkpoint +} + +func (server *server) applySimulationCheckpoint_locked(checkpoint simulationCheckpoint) { + server.applyPlayerCheckpoint_locked(checkpoint.players, checkpoint.now) + server.applyNPCCheckpoint_locked(checkpoint.npcs.checkpoint) + server.activeNPCs = checkpoint.active +} + // The periodic checkpoint visitor waits outside simulation ownership. Its // detached batch enters the writer queue before any later mutation can commit. func (server *server) checkpointSimulation(now time.Time) error { server.mutex.Lock() - players := server.preparePlayerCheckpoint_locked(now) - active := make(map[uint32]bool) - for id := range server.simulationNPCs_locked(now) { - active[id] = true - } - npcs := server.prepareNPCWrite_locked(itemStore{checkpointAt: now}, active) - var batch databaseBatch - if len(players.writes) != 0 { - batch = append(batch, players) - } - if npcs.changed() { - batch = append(batch, npcs) - } - if len(batch) == 0 { - server.applyPlayerCheckpoint_locked(players, now) - server.applyNPCCheckpoint_locked(npcs.checkpoint) - server.activeNPCs = active + checkpoint := server.prepareSimulationCheckpoint_locked(now) + if !checkpoint.changed() { + server.applySimulationCheckpoint_locked(checkpoint) server.mutex.Unlock() return nil } - done := server.databaseWriter.trySubmit(batch) + done := server.databaseWriter.trySubmit(checkpoint) server.mutex.Unlock() if done == nil { return nil @@ -114,10 +139,6 @@ func (server *server) checkpointSimulation(now time.Time) error { server.mutex.Lock() defer server.mutex.Unlock() - // Publish only actors whose saved basis still matches the captured one. - // Unrelated durable writes must not force otherwise successful retries. - server.applyPlayerCheckpoint_locked(players, now) - server.applyNPCCheckpoint_locked(npcs.checkpoint) - server.activeNPCs = active + server.applySimulationCheckpoint_locked(checkpoint) return nil } diff --git a/server/world_runtime.go b/server/world_runtime.go @@ -1,6 +1,7 @@ package main import ( + "errors" "fmt" "log" "net" @@ -24,6 +25,7 @@ type worldRuntime struct { missionParticipants chan missionParticipantsQuery stopping chan struct{} done chan struct{} + stopError error } type worldRoute struct { @@ -125,7 +127,9 @@ func (world *worldRuntime) run(configuration *server, zones map[uint32]*zoneRunt for { if stopping == nil && arrivals == 0 && quiescing == 0 && messages == 0 && len(lifecycle) == 0 { for _, zone := range zones { - zone.stop() + if err := zone.stop(); err != nil { + world.stopError = errors.Join(world.stopError, err) + } } return } @@ -342,9 +346,10 @@ func (world *worldRuntime) transfer(source *zoneRuntime, arrival playerTransfer) } } -func (world *worldRuntime) stop() { +func (world *worldRuntime) stop() error { close(world.stopping) <-world.done + return world.stopError } // Each connection keeps its admitted owner, even after the directory changes. diff --git a/server/zone_checkpoint.go b/server/zone_checkpoint.go @@ -0,0 +1,56 @@ +package main + +import ( + "fmt" + "log" + "time" +) + +// One in-flight batch per zone bounds memory and keeps periodic submissions +// from queuing repeatedly behind a slow disk. Full writer queues retry next tick. +func (zone *zoneRuntime) startCheckpoint(state *server, now time.Time) { + if zone.checkpoint != nil { + return + } + checkpoint := state.prepareSimulationCheckpoint_locked(now) + if !checkpoint.changed() { + state.applySimulationCheckpoint_locked(checkpoint) + return + } + done := state.databaseWriter.trySubmit(checkpoint) + if done != nil { + zone.checkpoint, zone.checkpointDone = &checkpoint, done + } +} + +func (zone *zoneRuntime) finishCheckpoint(state *server, err error) { + if err != nil { + log.Printf("Zone %d checkpoint: %v", state.playfield, err) + } else { + state.applySimulationCheckpoint_locked(*zone.checkpoint) + } + zone.checkpoint, zone.checkpointDone = nil, nil +} + +// Shutdown has drained departures, arrivals and cross-zone operations. Capture +// every remaining actor at the current time, regardless of its periodic deadline. +// Inventory and rewards are already durable; do not rewrite them on shutdown. +func (zone *zoneRuntime) finalCheckpoint(state *server, now time.Time) error { + checkpoint := simulationCheckpoint{active: make(map[uint32]bool), now: now} + for _, player := range zone.players { + if player.savedProfile.ID != 0 { + checkpoint.players.include(player, now) + } + } + for id := range state.simulationNPCs_locked(now) { + checkpoint.active[id] = true + } + checkpoint.npcs = state.prepareNPCWrite_locked(itemStore{flush: true}, checkpoint.active) + if checkpoint.changed() { + if err := state.databaseWriter.commit(checkpoint); err != nil { + return fmt.Errorf("zone %d final checkpoint: %w", state.playfield, err) + } + } + state.applySimulationCheckpoint_locked(checkpoint) + return nil +} diff --git a/server/zone_checkpoint_test.go b/server/zone_checkpoint_test.go @@ -0,0 +1,308 @@ +package main + +import ( + "strings" + "testing" + "time" +) + +type zoneCheckpoint time.Time + +func (checkpoint zoneCheckpoint) execute(state *server) error { + state.zone.startCheckpoint(state, time.Time(checkpoint)) + return nil +} + +type zoneCheckpointPosition float32 + +func (position zoneCheckpointPosition) execute(state *server) error { + state.characters[1].position[0] = float32(position) + return nil +} + +type zoneCheckpointObservation struct { + position, saved float32 + pending bool +} + +func (query *zoneCheckpointObservation) execute(state *server) error { + query.position = state.characters[1].position[0] + query.saved = state.characters[1].savedPosition.Position[0] + query.pending = state.zone.checkpoint != nil + return nil +} + +func TestZoneCheckpointKeepsItsOwnerResponsiveWhileSQLiteWaits(t *testing.T) { + fixture := newCheckpointWorld(t) + now := time.Now() + fixture.characters[1].nextPositionSave = now + fixture.characters[1].position[0] = 53 + zone := newZoneRuntime(fixture) + defer func() { + if err := zone.stop(); err != nil { + t.Error(err) + } + }() + blocker, err := fixture.db.Begin() + if err != nil { + t.Fatal(err) + } + defer blocker.Rollback() + waits := fixture.db.Stats().WaitCount + if err := zone.call(zoneCheckpoint(now)); err != nil { + t.Fatal(err) + } + deadline := time.After(3 * time.Second) + poll := time.NewTicker(time.Millisecond) + defer poll.Stop() + for fixture.db.Stats().WaitCount == waits { + select { + case <-poll.C: + case <-deadline: + t.Fatal("checkpoint did not reach SQLite") + } + } + + responsive := make(chan error, 1) + go func() { responsive <- zone.call(zoneCheckpointPosition(54)) }() + select { + case err := <-responsive: + if err != nil { + t.Fatal(err) + } + case <-deadline: + t.Fatal("checkpoint blocked commands in its own zone") + } + // Repeated visits cannot create an unbounded backlog behind the pending write. + for range 3 { + if err := zone.call(zoneCheckpoint(now.Add(time.Second))); err != nil { + t.Fatal(err) + } + } + if len(fixture.databaseWriter.requests) != 0 { + t.Fatal("zone queued duplicate periodic checkpoints") + } + if err := blocker.Rollback(); err != nil { + t.Fatal(err) + } + query := &zoneCheckpointObservation{} + for { + if err := zone.call(query); err != nil { + t.Fatal(err) + } + if !query.pending { + break + } + select { + case <-poll.C: + case <-deadline: + t.Fatal("checkpoint completion did not return to its owner") + } + } + var position float32 + if err := fixture.db.QueryRow("SELECT position_x FROM characters WHERE id=1").Scan(&position); err != nil { + t.Fatal(err) + } + if position != 53 || query.saved != 53 || query.position != 54 { + t.Fatal("checkpoint consumed later live state or lost its completion", position, query) + } +} + +func TestWorldShutdownDrainsPendingCheckpointThenSavesLatestPosition(t *testing.T) { + fixture := newCheckpointWorld(t) + now := time.Now() + fixture.characters[1].nextPositionSave = now + fixture.characters[1].position[0] = 53 + world := newRoutedTestWorld(t, fixture) + finished := make(chan struct{}) + var shutdownError error + started := false + t.Cleanup(func() { + if started { + <-finished + } else if err := world.stop(); err != nil { + t.Error(err) + } + }) + source, _ := world.owner(1) + blocker, err := fixture.db.Begin() + if err != nil { + t.Fatal(err) + } + defer blocker.Rollback() + if err := source.call(zoneCheckpoint(now)); err != nil { + t.Fatal(err) + } + if err := source.call(zoneCheckpointPosition(54)); err != nil { + t.Fatal(err) + } + started = true + go func() { shutdownError = world.stop(); close(finished) }() + select { + case <-source.quiesced: + case <-time.After(3 * time.Second): + t.Fatal("pending checkpoint prevented quiescing") + } + select { + case <-finished: + t.Fatal("shutdown returned while SQLite was blocked", shutdownError) + default: + } + if err := blocker.Rollback(); err != nil { + t.Fatal(err) + } + select { + case <-finished: + if shutdownError != nil { + t.Fatal(shutdownError) + } + case <-time.After(3 * time.Second): + t.Fatal("shutdown did not drain its pending checkpoint") + } + var position float32 + if err := fixture.db.QueryRow("SELECT position_x FROM characters WHERE id=1").Scan(&position); err != nil || position != 54 { + t.Fatal("final checkpoint lost movement after its periodic snapshot", position, err) + } +} + +func TestWorldShutdownSavesDormantActorsWithoutRewritingInventory(t *testing.T) { + fixture := newCheckpointWorld(t) + auditCheckpointWrites(t, fixture) + now := time.Now() + fixture.characters[1].nextPositionSave = now.Add(time.Hour) + fixture.characters[1].position[0], fixture.characters[1].health, fixture.characters[1].nano = 53, 17, 11 + fixture.characters[1].activeNanos = []activeNano{{program: 27169, caster: 1, expiresAt: now.Add(time.Minute)}} + fixture.characters[1000000].health = 23 + world := newRoutedTestWorld(t, fixture) + if err := world.stop(); err != nil { + t.Fatal(err) + } + var position float32 + var health, nano, npcHealth uint32 + var remaining time.Duration + if err := fixture.db.QueryRow(`SELECT position_x,health,nano,(SELECT health FROM characters WHERE id=1000000), + (SELECT remaining_ns FROM active_nanos WHERE character_id=1) FROM characters WHERE id=1`).Scan(&position, &health, &nano, &npcHealth, &remaining); err != nil { + t.Fatal(err) + } + if position != 53 || health != 17 || nano != 11 || npcHealth != 23 { + t.Fatal("shutdown skipped actors outside their periodic deadline", position, health, nano, npcHealth) + } + if remaining < 55*time.Second || remaining > time.Minute { + t.Fatal("shutdown advanced effect time to force a checkpoint", remaining) + } + for table, count := range checkpointWrites(t, fixture) { + if !strings.HasPrefix(table, "characters/") && count != 0 { + t.Fatal("shutdown rewrote significant state already committed by its action", table, count) + } + } +} + +func TestWorldShutdownReportsCheckpointFailureAndStillStopsOtherZones(t *testing.T) { + fixture := newCheckpointWorld(t) + other := fixture.newCharacter() + other.playfield, other.position = 540, [3]float32{40, 14, 50} + if err := fixture.saveUser_locked(other); err != nil { + t.Fatal(err) + } + fixture.characters[1].position[0] = 53 + fixture.characters[1000000].health = 23 + other.position[0] = 41 + fixture.characters[1].nextPositionSave, other.nextPositionSave = time.Now().Add(time.Hour), time.Now().Add(time.Hour) + if _, err := fixture.db.Exec("CREATE TRIGGER fail_final BEFORE UPDATE ON characters WHEN OLD.id=1000000 BEGIN SELECT RAISE(ABORT,'final checkpoint rejected'); END"); err != nil { + t.Fatal(err) + } + world := newRoutedTestWorld(t, fixture) + first, _ := world.owner(1) + second, _ := world.owner(other.id) + err := world.stop() + if err == nil || !strings.Contains(err.Error(), "final checkpoint rejected") { + t.Fatal("shutdown hid its checkpoint failure", err) + } + for _, zone := range []*zoneRuntime{first, second} { + select { + case <-zone.done: + default: + t.Fatal("failed checkpoint prevented another zone from stopping") + } + } + var firstPosition, secondPosition float32 + if err := fixture.db.QueryRow("SELECT (SELECT position_x FROM characters WHERE id=1),(SELECT position_x FROM characters WHERE id=2)").Scan(&firstPosition, &secondPosition); err != nil || firstPosition != 52 || secondPosition != 41 { + t.Fatal("shutdown partially published its failed write or skipped the other zone", firstPosition, secondPosition, err) + } +} + +func TestZoneCheckpointTimerPersistsDueMovement(t *testing.T) { + fixture := newCheckpointWorld(t) + fixture.characters[1].position[0] = 53 + fixture.characters[1].nextPositionSave = time.Now() + zone := newZoneRuntime(fixture) + defer func() { + if err := zone.stop(); err != nil { + t.Error(err) + } + }() + deadline := time.After(3 * time.Second) + poll := time.NewTicker(10 * time.Millisecond) + defer poll.Stop() + for { + var position float32 + if err := fixture.db.QueryRow("SELECT position_x FROM characters WHERE id=1").Scan(&position); err != nil { + t.Fatal(err) + } + if position == 53 { + break + } + select { + case <-poll.C: + case <-deadline: + t.Fatal("zone loop did not checkpoint due movement") + } + } +} + +func TestZoneCheckpointFailureRetainsItsBasisAndRetries(t *testing.T) { + fixture := newCheckpointWorld(t) + now := time.Now() + fixture.characters[1].position[0], fixture.characters[1].nextPositionSave = 53, now + if _, err := fixture.db.Exec("CREATE TRIGGER fail_periodic BEFORE UPDATE ON characters WHEN OLD.id=1 BEGIN SELECT RAISE(ABORT,'periodic checkpoint rejected'); END"); err != nil { + t.Fatal(err) + } + zone := newZoneRuntime(fixture) + defer func() { + if err := zone.stop(); err != nil { + t.Error(err) + } + }() + deadline := time.After(3 * time.Second) + poll := time.NewTicker(time.Millisecond) + defer poll.Stop() + query := &zoneCheckpointObservation{} + for attempt := range 2 { + if err := zone.call(zoneCheckpoint(now)); err != nil { + t.Fatal(err) + } + for { + if err := zone.call(query); err != nil { + t.Fatal(err) + } + if !query.pending { + break + } + select { + case <-poll.C: + case <-deadline: + t.Fatal("failed checkpoint did not return to its owner") + } + } + if attempt == 0 { + if query.saved != 52 || query.position != 53 { + t.Fatal("failed checkpoint published a saved basis", query) + } + if _, err := fixture.db.Exec("DROP TRIGGER fail_periodic"); err != nil { + t.Fatal(err) + } + } else if query.saved != 53 || query.position != 53 { + t.Fatal("checkpoint did not retry after the failure", query) + } + } +} diff --git a/server/zone_runtime.go b/server/zone_runtime.go @@ -10,13 +10,16 @@ import ( // A zone receives commands and advances its own state on one goroutine. The // caller transfers the state at construction and must subsequently use commands. type zoneRuntime struct { - commands chan zoneRequest - quiescing chan struct{} - quiesced chan struct{} - stopping chan struct{} - done chan struct{} - players map[uint32]*character - presence map[uint32]playerPresence + commands chan zoneRequest + quiescing chan struct{} + quiesced chan struct{} + stopping chan struct{} + done chan struct{} + players map[uint32]*character + presence map[uint32]playerPresence + checkpoint *simulationCheckpoint + checkpointDone <-chan error + stopError error } type zoneCommand interface { @@ -37,13 +40,6 @@ func (packet zonePacket) execute(state *server) error { return state.handleWorldMessage(packet.client, packet.body) } -type zoneCheckpoint time.Time - -func (checkpoint zoneCheckpoint) execute(state *server) error { - now := time.Time(checkpoint) - return errors.Join(state.checkpointWorld(now), state.flushPositions(now)) -} - func newZoneRuntime(state *server) *zoneRuntime { zone := &zoneRuntime{commands: make(chan zoneRequest), quiescing: make(chan struct{}), quiesced: make(chan struct{}), stopping: make(chan struct{}), done: make(chan struct{})} zone.players = make(map[uint32]*character) @@ -63,16 +59,19 @@ func (zone *zoneRuntime) run(state *server) { movement := time.NewTicker(time.Second / 60) actions := time.NewTicker(250 * time.Millisecond) crossings := time.NewTicker(100 * time.Millisecond) + checkpoints := time.NewTicker(time.Second) defer movement.Stop() defer actions.Stop() defer crossings.Stop() - movementTicks, actionTicks, crossingTicks := movement.C, actions.C, crossings.C + defer checkpoints.Stop() + movementTicks, actionTicks, crossingTicks, checkpointTicks := movement.C, actions.C, crossings.C, checkpoints.C quiescing := zone.quiescing stopTicks := func() { movement.Stop() actions.Stop() crossings.Stop() - movementTicks, actionTicks, crossingTicks = nil, nil, nil + checkpoints.Stop() + movementTicks, actionTicks, crossingTicks, checkpointTicks = nil, nil, nil, nil quiescing = nil close(zone.quiesced) } @@ -98,9 +97,17 @@ func (zone *zoneRuntime) run(state *server) { case now := <-crossingTicks: state.advanceZoneCrossings(now) zone.publishPresence(state) + case now := <-checkpointTicks: + zone.startCheckpoint(state, now) + case err := <-zone.checkpointDone: + zone.finishCheckpoint(state, err) case <-quiescing: stopTicks() case <-zone.stopping: + if zone.checkpointDone != nil { + zone.finishCheckpoint(state, <-zone.checkpointDone) + } + zone.stopError = zone.finalCheckpoint(state, time.Now()) state.stopNavigation() return } @@ -124,9 +131,10 @@ func (zone *zoneRuntime) call(command zoneCommand) error { } } -func (zone *zoneRuntime) stop() { +func (zone *zoneRuntime) stop() error { close(zone.stopping) <-zone.done + return zone.stopError } // A connection stays with its source zone until the protocol redirects it. Its