commit 6e36cdc7cc18853e54f9af57e498809be6cbc23c
parent 2d0085775b627755df1d06cc129cbeb5930bee64
Author: anon <anon@example.com>
Date: Sat, 7 Nov 2026 06:06:12 +0000
Run production simulation on independent zone owners
Diffstat:
16 files changed, 478 insertions(+), 139 deletions(-)
diff --git a/DEVELOPERS.md b/DEVELOPERS.md
@@ -73,21 +73,29 @@ replacement.
| Rules and content | Action implementations such as `inventory.go`, combat and nano handlers decide admission and outcomes using `gamedata`. UI and transport code report those outcomes rather than reproducing the rules. |
| Durable transactions | `database.go`, `item_store.go` and `world_store.go` own database records, item ownership and checkpoints. Significant actions commit their related changes before updating shared ownership or publishing success. Keep frequent movement in memory until its checkpoint. |
-`server.mutex` protects shared world state. Helpers suffixed `_locked` require
-that lock. Operations needing ordered simulation/session changes acquire
-`updateMutex` before `mutex`; retain that order in new code. Build outbound
-updates under the world lock and use the existing output queues after releasing
-it. Do not hold the world lock across a blocking network write.
+Production startup checkpoints the initial population, partitions mutable state
+by playfield, and starts one `zone_runtime.go` goroutine per zone. The root server
+relinquishes its character, client, item and lifecycle maps. External requests
+reach owners through channels; there is no shared simulation lock across zones.
+Bank, reclaim and bag contents follow their player; corpses, pets, resource state
+and mission floor items belong to their physical zone. Unassigned items remain
+in SQLite and are imported only through a transaction that claims ownership.
+
+Existing mutation helpers retain zone-local `mutex` and `updateMutex` wrappers,
+also used by standalone test fixtures. Helpers suffixed `_locked` require the
+corresponding local lock; acquire `updateMutex` before `mutex`. These wrappers do
+not grant access to another zone. Use owner commands for external access and the
+existing output queues for network delivery. Transport buffers and geometry
+caches retain their own small locks.
Unworn item moves between carried slots, backpacks and the bank use
`moveStoredItem`: SQLite checks the expected source and backpack ownership,
enforces destination slot uniqueness and commits the placement atomically.
The transaction takes values and has no access to live server state. Its caller
publishes only the affected inventory, placement and backpack references after
-commit; it does not reconstruct world inventory or checkpoint NPCs. The caller
-still holds the simulation locks while waiting. Releasing them requires ordered
-completion with the remaining snapshot-based inventory writers, not just a
-goroutine around the SQL call.
+commit; it does not reconstruct world inventory or checkpoint NPCs. The affected zone waits for the transaction before processing another command.
+Other zones continue advancing. This preserves immediate atomic item/credit
+changes without speculative live-state publication.
`database_writer.go` executes detached write requests on one goroutine. Inventory,
NPC/player checkpoints, combat outcomes, teams, lifecycle transitions and creation
@@ -102,8 +110,8 @@ ownership, then wait for SQLite outside it. The bounded writer queue preserves
submission order; a full queue defers a checkpoint to the next visit. Each completion compares
the captured saved basis per actor, preserving newer durable outcomes without
forcing unrelated players or NPCs to retry.
-Significant mutations still wait while holding simulation locks, so this does
-not yet establish independent zone ownership.
+Significant mutations wait on their affected owners. Periodic writes leave the
+zone event loop available for commands and ticks.
`world_session.go` contains world-session admission and departure, separate from
socket decoding. `zone_runtime.go` runs movement, actions and commands for a
@@ -112,8 +120,9 @@ move and checks that a second owned state accepts movement and advances position
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: startup and external entry
-points still require migration before replacing the global loops.
+Production startup uses these same owners. A startup regression holds both old
+root locks and blocks SQLite in one zone while another zone accepts movement and
+advances its position; shutdown persists both zones' final changes.
`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
@@ -126,8 +135,6 @@ 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 and external entry points
-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
@@ -148,8 +155,7 @@ It drains accepted lifecycle operations, creation and evacuation on shutdown.
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 and
-external entry points still need to use the zone owners.
+handoffs. Production startup and external entry points use these ownership boundaries.
`service_tasks.go` owns admission and lifetimes for listeners, HTTP requests,
native sessions, WebSockets and detached browser streams through channels.
@@ -182,22 +188,22 @@ Pending native creation attempts belong to the coordinator; password derivation
runs outside it and then rechecks both the credential and attempt identity.
Native creation retains its browser cookie, so replacement revokes only the old
player's streams and preserves a new connection already awaiting publication.
-Production state partitioning and administrative/test entry points still need
-migration before the global simulation loops can be removed.
Per-player admin inspection, editing and teleport requests run as commands on
the current zone owner. Request bodies are read before admission, and responses
are buffered until the command returns, so network I/O cannot hold an owner.
Only a pre-execution ownership change retries a request. The test setup API uses
the same boundary, rechecks its cookie against the selected player and transfers
-the actor and inventory after a committed position change. Global admin views,
-environment controls and item administration still need routed ownership.
+the actor and inventory after a committed position change. Global admin views sample detached zone snapshots. Environment controls update
+directory defaults and notify existing zones; future zones inherit those defaults.
+Item administration reads committed SQLite snapshots, routes owned edits to the
+current zone and uses private coordinator drafts for unassigned edits. Claims
+revalidate item records and bag contents in the ownership transaction.
World and chat transport entry points use the routing directory and chat owner
-when a world runtime is installed. An integration regression empties the root
+in production. An integration regression empties the root
character map and holds both root simulation locks while exercising native login,
-browser world admission, chat replay, cleanup and missing-stream refusal. This
-proves the transport boundary; production startup still runs the global loops.
+browser world admission, chat replay, cleanup and missing-stream refusal. Production startup, shutdown and ownership partitioning have separate regressions.
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
@@ -211,7 +217,7 @@ allow the owner and pet to occupy different zones.
Item and NPC reservations use shared atomic counters, independent of SQLite and
zone simulation. Failed operations may leave unused identities; they do not
publish objects or advance durable watermarks. A retry gets a new reservation.
-Character creation still uses the root server's counter. Players retain pet IDs,
+Character creation allocates its durable identity inside SQLite. Players retain pet IDs,
not pointers to NPCs that can remain in another playfield. Resource collection
checks its own changed depletion rows and item ownership inside the transaction.
diff --git a/docs/team-chat.md b/docs/team-chat.md
@@ -91,8 +91,8 @@ Additional eligibility tests cover dead, distant, loading and offline members.
Ownership regressions hold both zone owners and the root simulation mutex while
cross-zone team chat and buddy updates complete. Other checks hold SQLite while
movement and metadata publication continue, including movement in the same zone
-as a pending vicinity message. These component checks do not establish that all
-production entrypoints have migrated to independent zone ownership.
+as a pending vicinity message. Production startup and entrypoints now use these owners; startup partitioning
+and shutdown have separate regression coverage.
The retained protocol and browser evidence below predates the ownership
refactor; its full Go suite passed in 299 seconds. All chat/team tests passed twice under
diff --git a/docs/team-ownership.md b/docs/team-ownership.md
@@ -35,7 +35,7 @@ processing commands and simulation ticks. Team owners do not wait for recipient
zones. World shutdown drains their accepted messages before joining zone owners;
database shutdown joins team owners before stopping the SQLite writer.
-## Verification and remaining integration
+## Verification
The focused tests cover native team behavior, transaction rollback and retry,
remote roster replay and affiliation, remote combat checks, stale updates after
@@ -44,9 +44,8 @@ and shutdown delivery that revokes remote loot access. Owner tests also cover
authority checks while another team is blocked, composition of queued actions,
unique membership across team owners, and draining accepted writes on shutdown.
-The production team mutation path uses the team service. Production startup
-still needs to partition world state and route all entrypoints to zone owners.
-Chat sessions and buddy presence have a separate channel owner; committed team
-changes publish revisioned membership to it. Mission lifecycle coordination and
-production routing remain unfinished. The global simulation lock remains until
-that migration is complete.
+Production startup partitions mutable world state by zone and uses owner commands
+for external access. Teams remain independent of that partition: a per-team
+owner coordinates members across zones. Chat sessions and buddy presence have a
+separate channel owner; committed team changes publish revisioned membership to
+it. Mission lifecycle operations coordinate only their participating owners.
diff --git a/server/player_movement.go b/server/player_movement.go
@@ -590,21 +590,6 @@ func (player *character) vehicleState() []byte {
return vehicle
}
-func (server *server) movePlayers(stop <-chan struct{}) {
- ticker := time.NewTicker(time.Second / 60)
- defer ticker.Stop()
- for {
- select {
- case <-stop:
- return
- case now := <-ticker.C:
- started := time.Now()
- server.advancePlayerMovement(now)
- reportSimulationTick("player movement", now, started)
- }
- }
-}
-
func (server *server) advancePlayerMovement(now time.Time) {
server.updateMutex.Lock()
defer server.updateMutex.Unlock()
diff --git a/server/roaming.go b/server/roaming.go
@@ -20,21 +20,6 @@ type npcMotion struct {
navigation *navigationJob
}
-func (server *server) roamNPCs(stop <-chan struct{}) {
- ticker := time.NewTicker(250 * time.Millisecond)
- defer ticker.Stop()
- for {
- select {
- case <-stop:
- return
- case now := <-ticker.C:
- started := time.Now()
- server.advanceActions(now)
- reportSimulationTick("NPC and actions", now, started)
- }
- }
-}
-
func (server *server) advanceActions(now time.Time) {
server.advanceMissions(now)
server.advanceCorpseExpiry(now)
diff --git a/server/service_shutdown_test.go b/server/service_shutdown_test.go
@@ -41,7 +41,11 @@ func TestServiceShutdownDrainsAcceptedHTTPMutationBeforeClosingDatabase(t *testi
<-r.Context().Done()
close(cancelled)
<-release
- mutation <- fixture.updateUser(destination)
+ owner, err := fixture.world.owner(1)
+ if err == nil {
+ err = owner.call(zoneShutdownUpdate{destination})
+ }
+ mutation <- err
})
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
@@ -157,7 +161,7 @@ func TestServiceShutdownJoinsNativeSessionsAndReleasesSimulationLocks(t *testing
t.Fatal("session cleanup did not retire the world client")
}
select {
- case <-fixture.simulationDone:
+ case <-fixture.world.done:
default:
t.Fatal("simulation workers outlived shutdown")
}
@@ -247,18 +251,22 @@ func TestServiceShutdownReportsFailedFinalWriteAndClosesWorkers(t *testing.T) {
fixture := newCheckpointWorld(t)
fixture.characters[1].nextPositionSave = time.Now().Add(time.Hour)
shutdown := startTestService(t, fixture)
- fixture.mutex.Lock()
- fixture.characters[1].position[0] = 53
- fixture.mutex.Unlock()
+ owner, err := fixture.world.owner(1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := owner.call(zoneCheckpointPosition(53)); err != nil {
+ t.Fatal(err)
+ }
if _, err := fixture.db.Exec("CREATE TRIGGER fail_service_final BEFORE UPDATE ON characters WHEN OLD.id=1 BEGIN SELECT RAISE(ABORT,'service final rejected'); END"); err != nil {
t.Fatal(err)
}
- err := shutdown()
+ err = shutdown()
if err == nil || !strings.Contains(err.Error(), "service final rejected") {
t.Fatal("shutdown hid its final write failure", err)
}
select {
- case <-fixture.simulationDone:
+ case <-fixture.world.done:
default:
t.Fatal("failed shutdown retained simulation workers")
}
@@ -275,3 +283,9 @@ func TestServiceShutdownReportsFailedFinalWriteAndClosesWorkers(t *testing.T) {
t.Fatal("failed final save committed partial state")
}
}
+
+type zoneShutdownUpdate struct{ destination userData }
+
+func (command zoneShutdownUpdate) execute(state *server) error {
+ return state.updateUser(command.destination)
+}
diff --git a/server/simulation.go b/server/simulation.go
@@ -2,45 +2,32 @@ package main
import (
"errors"
- "sync"
"time"
)
func (server *server) startSimulation() error {
- // Persist initial population before any listener admits game traffic.
+ // Persist and partition startup state before any listener admits traffic.
if err := server.checkpointWorld(time.Now()); err != nil {
return err
}
+ states, err := server.partitionWorld()
+ if err != nil {
+ return err
+ }
+ world, err := newWorldRuntime(server, states)
+ if err != nil {
+ return err
+ }
+ server.relinquishWorld()
+ server.world = world
server.tasks = newServiceTasks()
- server.simulationStop, server.simulationDone = make(chan struct{}), make(chan struct{})
- go func() {
- defer close(server.simulationDone)
- var workers sync.WaitGroup
- for _, run := range []func(<-chan struct{}){server.roamNPCs, server.movePlayers, server.saveWorld, server.checkZoneCrossings} {
- workers.Add(1)
- go func() { defer workers.Done(); run(server.simulationStop) }()
- }
- workers.Wait()
- }()
return nil
}
func (server *server) shutdown() error {
- // Stop inputs while their session owners can still process departures.
+ // Stop inputs while owners can still process their accepted work. The
+ // directory drains handoffs and each zone's final checkpoint before SQL stops.
server.tasks.stop()
- close(server.simulationStop)
- <-server.simulationDone
- server.stopNavigation()
-
- // All mutation producers have joined. Final persistence needs no state lock
- // and must report failure without leaving the database worker running.
- checkpoint := server.prepareFinalCheckpoint_locked(time.Now())
- var err error
- if checkpoint.changed() {
- err = server.commitWrite(checkpoint)
- }
- if err == nil {
- server.applySimulationCheckpoint_locked(checkpoint)
- }
+ err := server.world.stop()
return errors.Join(err, server.closeDatabase())
}
diff --git a/server/simulation_timing.go b/server/simulation_timing.go
@@ -30,9 +30,9 @@ func (mutex *simulationMutex) Unlock() {
}
}
-func reportSimulationTick(name string, scheduled, started time.Time) {
+func reportSimulationTick(playfield uint32, name string, scheduled, started time.Time) {
delay, elapsed := started.Sub(scheduled), time.Since(started)
if delay >= 100*time.Millisecond || elapsed >= 100*time.Millisecond {
- log.Printf("Slow simulation tick: phase=%s delay=%s elapsed=%s", name, max(0, delay), elapsed)
+ log.Printf("Slow simulation tick: playfield=%d phase=%s delay=%s elapsed=%s", playfield, name, max(0, delay), elapsed)
}
}
diff --git a/server/state.go b/server/state.go
@@ -125,8 +125,6 @@ type server struct {
browserStreamService *browserStreamRegistry
tasks *serviceTasks
- simulationStop chan struct{}
- simulationDone chan struct{}
world *worldRuntime
zone *zoneRuntime
playfield uint32
diff --git a/server/users.go b/server/users.go
@@ -4,7 +4,6 @@ import (
"ao/server/gamedata"
"fmt"
"io"
- "log"
"math"
"math/rand/v2"
"slices"
@@ -247,20 +246,3 @@ func (server *server) flushPositions(now time.Time) error {
server.applyPlayerCheckpoint_locked(checkpoint, now)
return nil
}
-
-func (server *server) saveWorld(stop <-chan struct{}) {
- ticker := time.NewTicker(time.Second)
- defer ticker.Stop()
- for {
- select {
- case <-stop:
- return
- case now := <-ticker.C:
- started := time.Now()
- if err := server.checkpointSimulation(now); err != nil {
- log.Printf("Saving simulation: %v", err)
- }
- reportSimulationTick("checkpoint", now, started)
- }
- }
-}
diff --git a/server/world_partition.go b/server/world_partition.go
@@ -0,0 +1,145 @@
+package main
+
+import "fmt"
+
+// Startup has no input producers or simulation workers. Build distinct mutable
+// maps first; the caller relinquishes the root maps only after owners start.
+func (source *server) partitionWorld() (map[uint32]*server, error) {
+ states := make(map[uint32]*server)
+ zone := func(playfield uint32) *server {
+ if states[playfield] == nil {
+ state := source.emptyZone()
+ state.savedNPCs = make(map[uint32]savedNPC)
+ state.activeNPCs = make(map[uint32]bool)
+ state.simulatedNPCs = make(map[uint32]*character)
+ state.lastNPCUpdate = source.lastNPCUpdate
+ states[playfield] = state
+ }
+ return states[playfield]
+ }
+ for id, actor := range source.characters {
+ zone(actor.playfield).characters[id] = actor
+ }
+ for id, client := range source.clients {
+ actor := source.characters[id]
+ if actor == nil {
+ return nil, fmt.Errorf("client %d has no character owner", id)
+ }
+ zone(actor.playfield).clients[id] = client
+ }
+ for id, actor := range source.fighting {
+ zone(actor.playfield).fighting[id] = actor
+ }
+ for playfield, actors := range source.mobileNPCs {
+ zone(playfield).mobileNPCs[playfield] = actors
+ }
+ for id, saved := range source.savedNPCs {
+ zone(saved.State.Character.Position.Playfield).savedNPCs[id] = saved
+ }
+ for id := range source.activeNPCs {
+ if actor := source.characters[id]; actor != nil {
+ zone(actor.playfield).activeNPCs[id] = true
+ } else if saved, exists := source.savedNPCs[id]; exists {
+ zone(saved.State.Character.Position.Playfield).activeNPCs[id] = true
+ } else {
+ return nil, fmt.Errorf("active NPC %d has no live or saved owner", id)
+ }
+ }
+ for id, actor := range source.simulatedNPCs {
+ if source.characters[id] == actor {
+ zone(actor.playfield).simulatedNPCs[id] = actor
+ }
+ }
+ // Keep expiry and respawn ordering within each destination zone.
+ for _, respawn := range source.npcRespawns {
+ state := zone(respawn.npc.playfield)
+ state.npcRespawns = append(state.npcRespawns, respawn)
+ }
+ for _, pet := range source.petExpiry {
+ state := zone(pet.playfield)
+ state.petExpiry = append(state.petExpiry, pet)
+ }
+ for _, corpse := range source.corpseExpiry {
+ state := zone(corpse.playfield)
+ state.corpseExpiry = append(state.corpseExpiry, corpse)
+ }
+ missions := make(map[uint32]uint32)
+ for _, mission := range source.missionExpiry {
+ missions[mission.id] = mission.world
+ zone(mission.world)
+ }
+ for id := range source.depletedResources {
+ resource, exists := source.worldResources[id]
+ if !exists {
+ return nil, fmt.Errorf("depleted resource %d has no playfield", id)
+ }
+ zone(resource.playfield).depletedResources[id] = true
+ }
+
+ // Bags and children share the root item's owner. Unassigned roots and their
+ // children remain SQLite-only and never enter a simulation cache.
+ for id, placement := range source.itemPlacements {
+ root := placement
+ if placement.Backpack != 0 {
+ if _, exists := source.items[placement.Backpack]; !exists {
+ return nil, fmt.Errorf("item %d has no parent bag %d", id, placement.Backpack)
+ }
+ var assigned bool
+ root, assigned = source.itemPlacements[placement.Backpack]
+ if !assigned {
+ continue
+ }
+ if root.Backpack != 0 {
+ return nil, fmt.Errorf("item %d has a nested bag", id)
+ }
+ }
+ owner := root.Player
+ if owner == 0 {
+ owner = root.Bank
+ }
+ if owner == 0 {
+ owner = root.Corpse
+ }
+ var playfield uint32
+ switch {
+ case owner != 0:
+ actor := source.characters[owner]
+ if actor == nil {
+ return nil, fmt.Errorf("item %d has no character owner %d", id, owner)
+ }
+ playfield = actor.playfield
+ case root.Mission != 0:
+ var exists bool
+ playfield, exists = missions[root.Mission]
+ if !exists {
+ return nil, fmt.Errorf("item %d has no mission owner %d", id, root.Mission)
+ }
+ case root.Resource != 0:
+ resource, exists := source.worldResources[root.Resource]
+ if !exists {
+ return nil, fmt.Errorf("item %d has no resource owner %d", id, root.Resource)
+ }
+ playfield = resource.playfield
+ default:
+ return nil, fmt.Errorf("item %d has an empty placement", id)
+ }
+ record, exists := source.items[id]
+ if !exists {
+ return nil, fmt.Errorf("placed item %d has no record", id)
+ }
+ state := zone(playfield)
+ state.items[id], state.itemPlacements[id] = record, placement
+ if item, exists := source.worldItems[id]; exists {
+ state.worldItems[id] = item
+ }
+ }
+ return states, nil
+}
+
+func (source *server) relinquishWorld() {
+ source.characters, source.clients, source.fighting = nil, nil, nil
+ source.items, source.itemPlacements, source.worldItems = nil, nil, nil
+ source.savedNPCs, source.activeNPCs, source.depletedResources = nil, nil, nil
+ source.mobileNPCs, source.simulatedNPCs, source.npcCells, source.npcLocations = nil, nil, nil, nil
+ source.npcRespawns, source.petExpiry, source.corpseExpiry, source.missionExpiry = nil, nil, nil, nil
+}
diff --git a/server/world_partition_test.go b/server/world_partition_test.go
@@ -0,0 +1,243 @@
+package main
+
+import (
+ "maps"
+ "net/http"
+ "slices"
+ "testing"
+ "time"
+)
+
+type zoneStartupQuery struct {
+ items, worldItems, corpses, respawns, pets, depleted []uint32
+}
+
+func (query *zoneStartupQuery) execute(state *server) error {
+ query.items = slices.Sorted(maps.Keys(state.items))
+ query.worldItems = slices.Sorted(maps.Keys(state.worldItems))
+ query.depleted = slices.Sorted(maps.Keys(state.depletedResources))
+ for _, corpse := range state.corpseExpiry {
+ query.corpses = append(query.corpses, corpse.id)
+ }
+ for _, respawn := range state.npcRespawns {
+ query.respawns = append(query.respawns, respawn.npc.id)
+ }
+ for _, pet := range state.petExpiry {
+ query.pets = append(query.pets, pet.id)
+ }
+ return nil
+}
+
+func startupQuery(t *testing.T, fixture *server, actor uint32) *zoneStartupQuery {
+ t.Helper()
+ owner, err := fixture.world.owner(actor)
+ if err != nil {
+ t.Fatal(err)
+ }
+ query := &zoneStartupQuery{}
+ if err := owner.call(query); err != nil {
+ t.Fatal(err)
+ }
+ return query
+}
+
+func TestProductionStartupPartitionsOwnedBagsAndLeavesUnassignedItemsInSQLite(t *testing.T) {
+ fixture := newControlInventoryWorld(t)
+ player := fixture.characters[1]
+ inventory := player.inventory
+ inventory.Reclaim = []reclaimItem{{Item: inventory.Items[0], AvailableAt: time.Now().Add(time.Hour)}}
+ inventory.Bank = []ownedItem{inventory.Items[2]}
+ inventory.Bank[0].Slot = 2
+ inventory.Items = inventory.Items[1:2]
+ if err := fixture.saveInventory_locked(player, inventory); err != nil {
+ t.Fatal(err)
+ }
+ second := fixture.newCharacter()
+ second.playfield = 800
+ if err := fixture.saveUser_locked(second); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fixture.grantItem_locked(second, 116628); err != nil {
+ t.Fatal(err)
+ }
+ created := adminRequest(adminTestHandler(fixture), "POST", "/admin/items", "template=121567", nil)
+ if created.Code != http.StatusSeeOther {
+ t.Fatal(created.Code, created.Body.String())
+ }
+
+ shutdown := startTestService(t, fixture)
+ one, two := startupQuery(t, fixture, 1), startupQuery(t, fixture, 2)
+ if !slices.Equal(one.items, []uint32{1, 2, 3, 4}) || !slices.Equal(two.items, []uint32{5}) {
+ t.Fatal("startup mixed inventory ownership", one, two)
+ }
+ if fixture.characters != nil || fixture.items != nil || fixture.clients != nil || fixture.itemPlacements != nil {
+ t.Fatal("root retained mutable simulation state")
+ }
+ if err := shutdown(); err != nil {
+ t.Fatal(err)
+ }
+ restored := newTestInventoryServer(t)
+ if len(restored.items) != 6 || restored.itemPlacements[3].Bank != 1 || restored.itemPlacements[4].Backpack != 3 || len(restored.characters[1].inventory.Reclaim) != 1 {
+ t.Fatal("startup or final checkpoint lost bank, reclaim, bag contents or unassigned items")
+ }
+}
+
+func TestProductionStartupPreservesCorpseAndRespawnOwnership(t *testing.T) {
+ fixture, now := newRespawnWithFilledCorpse(t)
+ fixture.characters[1000000].corpse.expiresAt = now.Add(time.Hour)
+ fixture.npcRespawns[0].at = now.Add(2 * time.Hour)
+ fixture.characters[1].playfield = 800
+ shutdown := startTestService(t, fixture)
+ corpse, player := startupQuery(t, fixture, 1000000), startupQuery(t, fixture, 1)
+ if !slices.Equal(corpse.items, []uint32{17, 18}) || !slices.Equal(corpse.corpses, []uint32{1000000}) || !slices.Equal(corpse.respawns, []uint32{1000000}) || !slices.Equal(player.items, []uint32{19}) {
+ t.Fatal("startup separated corpse contents or lifecycle queues from their owner", corpse, player)
+ }
+ if err := shutdown(); err != nil {
+ t.Fatal(err)
+ }
+ restored := newTestInventoryServer(t)
+ if len(restored.npcRespawns) != 1 || len(restored.corpseExpiry) != 1 || restored.itemPlacements[18].Backpack != 17 {
+ t.Fatal("final checkpoint lost corpse lifecycle")
+ }
+}
+
+func TestProductionStartupPreservesMissionFloorItems(t *testing.T) {
+ fixture, _, _ := enteredObjectiveWorld(t)
+ shutdown := startTestService(t, fixture)
+ query := startupQuery(t, fixture, 1)
+ if !slices.Equal(query.worldItems, []uint32{3}) {
+ t.Fatal("startup lost mission floor item", query)
+ }
+ if err := shutdown(); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestProductionStartupPreservesResourceDepletion(t *testing.T) {
+ fixture, _, _ := newResourcePickupWorld(t)
+ if err := fixture.handleInventory(fixture.clients[1], worldPickupRequest(1, 1)); err != nil {
+ t.Fatal(err)
+ }
+ fixture.characters[1].playfield = 800
+ shutdown := startTestService(t, fixture)
+ player, resource := startupQuery(t, fixture, 1), startupQuery(t, fixture, 2)
+ if !slices.Equal(player.items, []uint32{1}) || !slices.Equal(resource.depleted, []uint32{1000001}) || len(resource.worldItems) != 0 {
+ t.Fatal("startup lost resource ownership or depletion", player, resource)
+ }
+ if err := shutdown(); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestProductionZonesAdvanceIndependentlyOfRootLocksAndBlockedSQLite(t *testing.T) {
+ fixture, _ := newTeamWorld(t)
+ player := fixture.characters[2]
+ player.playfield, player.position, player.rotation = 800, [3]float32{52, 14, 56}, [4]float32{0, 0, 0, 1}
+ move := playerMovementRequest(player, 5)
+ shutdown := startTestService(t, fixture)
+ fixture.updateMutex.Lock()
+ defer fixture.updateMutex.Unlock()
+ fixture.mutex.Lock()
+ defer fixture.mutex.Unlock()
+ first, err := fixture.world.owner(1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ second, err := fixture.world.owner(2)
+ if err != nil || first == second {
+ t.Fatal("production did not start independent owners", err)
+ }
+ blocker, err := fixture.db.Begin()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer blocker.Rollback()
+ waits := fixture.db.Stats().WaitCount
+ granted := make(chan error, 1)
+ go func() { granted <- first.call(&zoneItemGrant{player: 1}) }()
+ deadline := time.NewTimer(3 * time.Second)
+ defer deadline.Stop()
+ poll := time.NewTicker(time.Millisecond)
+ defer poll.Stop()
+ for fixture.db.Stats().WaitCount == waits {
+ select {
+ case <-poll.C:
+ case err := <-granted:
+ t.Fatal("grant did not wait for SQLite", err)
+ case <-deadline.C:
+ t.Fatal("grant never reached SQLite")
+ }
+ }
+ responsive := make(chan error, 1)
+ go func() { responsive <- second.call(zoneTeamAction{2, move}) }()
+ select {
+ case err := <-responsive:
+ if err != nil {
+ t.Fatal(err)
+ }
+ case <-deadline.C:
+ t.Fatal("root locks or other zone's write blocked movement")
+ }
+ for {
+ query := &zonePositionQuery{player: 2}
+ if err := second.call(query); err != nil {
+ t.Fatal(err)
+ }
+ if query.position[0] > 52 {
+ break
+ }
+ select {
+ case <-poll.C:
+ case <-deadline.C:
+ t.Fatal("other zone's write blocked simulation ticks")
+ }
+ }
+ if err := blocker.Rollback(); err != nil {
+ t.Fatal(err)
+ }
+ if err := <-granted; err != nil {
+ t.Fatal(err)
+ }
+ if err := shutdown(); err != nil {
+ t.Fatal(err)
+ }
+ restored := newTestInventoryServer(t)
+ if restored.characters[2].position[0] <= 52 || len(restored.characters[1].inventory.Items) != 1 {
+ t.Fatal("shutdown lost independent movement or committed item")
+ }
+}
+
+func TestProductionStartupPreservesPetInDifferentZoneFromOwner(t *testing.T) {
+ fixture, _ := newPetSummonWorld(t)
+ if err := (zoneSummonPet{}).execute(fixture); err != nil {
+ t.Fatal(err)
+ }
+ fixture.characters[1].playfield = 800
+ if err := fixture.savePosition_locked(fixture.characters[1]); err != nil {
+ t.Fatal(err)
+ }
+ if err := fixture.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ fixture = newServerForTest(t)
+ shutdown := startTestService(t, fixture)
+ pet, player := startupQuery(t, fixture, 1000001), startupQuery(t, fixture, 1)
+ if !slices.Equal(pet.pets, []uint32{1000001}) || len(player.pets) != 0 {
+ t.Fatal("startup assigned pet lifetime to the owner's remote zone", pet, player)
+ }
+ if err := shutdown(); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestProductionStartupPreservesUnclaimedResourceInstance(t *testing.T) {
+ fixture, _, _ := newResourcePickupWorld(t)
+ shutdown := startTestService(t, fixture)
+ resource := startupQuery(t, fixture, 1)
+ if !slices.Equal(resource.worldItems, []uint32{1}) || !slices.Equal(resource.items, []uint32{1}) || len(resource.depleted) != 0 {
+ t.Fatal("startup lost unclaimed resource instance", resource)
+ }
+ if err := shutdown(); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/server/zone_runtime.go b/server/zone_runtime.go
@@ -99,15 +99,23 @@ func (zone *zoneRuntime) run(state *server) {
zone.publishPresence(state)
request.done <- err
case now := <-movementTicks:
+ started := time.Now()
state.advancePlayerMovement(now)
+ reportSimulationTick(state.playfield, "player movement", now, started)
case now := <-actionTicks:
+ started := time.Now()
state.advanceActions(now)
+ reportSimulationTick(state.playfield, "NPC and actions", now, started)
zone.publishPresence(state)
case now := <-crossingTicks:
+ started := time.Now()
state.advanceZoneCrossings(now)
+ reportSimulationTick(state.playfield, "zone crossings", now, started)
zone.publishPresence(state)
case now := <-checkpointTicks:
+ started := time.Now()
zone.startCheckpoint(state, now)
+ reportSimulationTick(state.playfield, "checkpoint", now, started)
case err := <-zone.checkpointDone:
zone.finishCheckpoint(state, err)
case <-quiescing:
diff --git a/server/zone_transfer.go b/server/zone_transfer.go
@@ -10,7 +10,8 @@ import (
func (source *server) emptyZone() *server {
return &server{
db: source.db, databaseWriter: source.databaseWriter, teamService: source.teamService, chatService: source.chatService, identities: source.identities_locked(),
- loginPort: source.loginPort, worldPort: source.worldPort, httpPort: source.httpPort, baseURL: source.baseURL,
+ combatRoll: source.combatRoll,
+ loginPort: source.loginPort, worldPort: source.worldPort, httpPort: source.httpPort, baseURL: source.baseURL,
terrain: source.terrain, geometry: source.geometry, zoneLinks: source.zoneLinks, cityDoors: maps.Clone(source.cityDoors),
weather: source.weather, weatherUntil: source.weatherUntil,
worldResources: source.worldResources, gameSeconds: source.gameSeconds, clockStarted: source.clockStarted,
diff --git a/server/zoning.go b/server/zoning.go
@@ -212,21 +212,6 @@ func (server *server) zoneDestination_locked(character *character, client *world
return nil, nil
}
-func (server *server) checkZoneCrossings(stop <-chan struct{}) {
- ticker := time.NewTicker(100 * time.Millisecond)
- defer ticker.Stop()
- for {
- select {
- case <-stop:
- return
- case now := <-ticker.C:
- started := time.Now()
- server.advanceZoneCrossings(now)
- reportSimulationTick("zone crossings", now, started)
- }
- }
-}
-
func (server *server) advanceZoneCrossings(now time.Time) {
server.updateMutex.Lock()
defer server.updateMutex.Unlock()
diff --git a/tools/stress/README.md b/tools/stress/README.md
@@ -50,10 +50,11 @@ benchmarks alongside a measured run. SIGINT cancels connections and joins reader
it does not stop the external server or delete its database.
Compare `96de3545` (before the lock initiative), `9cd2d916` (spatial/navigation work
-before ownership), the current revision, and the eventual production zone runtime.
+before ownership), the current production zone runtime.
Build each revision separately with `-tags=e2e`; use this same client against each.
Keep assets, scenario, hardware, durations and persistence settings fixed. Repeat
runs, compare admission separately from steady load, and retain failures and missed
-actions. Current production still uses shared simulation locks, so a speedup at
-this point cannot be attributed to a completed zone-owner migration.
+actions. Production now runs independent zone owners. A comparison with the original
+baseline measures the entire initiative, including spatial queries, navigation
+and persistence changes; it does not isolate the cost of channels versus locks.