aorecomp

Anarchy Online classic in the browser

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


commit 34487fcc561eeca8d04ffada4dd55890c7d0e193
parent 6f909a18b104936eccc986b22175e48070502e83
Author: anon <anon@example.com>
Date:   Thu,  5 Nov 2026 07:50:13 +0000

Reduce NPC activity range and batch periodic checkpoints

Diffstat:
Mdocs/npc-pursuit.md | 2+-
Mdocs/npc-regeneration.md | 2+-
Mdocs/world-state.md | 13++++++++-----
Mserver/corpse_credit_write_test.go | 4++++
Mserver/interest.go | 9++++-----
Mserver/interest_test.go | 22+++++++++++-----------
Mserver/npc_activity_test.go | 6+++---
Aserver/npc_checkpoint_batch_test.go | 140+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/world_store.go | 109+++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------
9 files changed, 251 insertions(+), 56 deletions(-)

diff --git a/docs/npc-pursuit.md b/docs/npc-pursuit.md @@ -44,7 +44,7 @@ original-server scheduling frequency. Return to the retained spawn is an explicit reconstruction policy. A bounded source search found no period Leet rule proving that exact destination or its -timing. Motion, including returns, runs within 600 metres horizontally of a +timing. Motion, including returns, runs within 200 metres horizontally of a ready player in the same playfield, and for fifteen minutes after the last nearby player leaves. Loading players do not activate NPCs. Health uses the separate [recovery rule](npc-regeneration.md), including while returning. Unprofiled diff --git a/docs/npc-regeneration.md b/docs/npc-regeneration.md @@ -64,7 +64,7 @@ balance. NPC nano recovery and changed recovery stats remain outside the implementation. The server keeps one two-second phase and counter per living NPC. Recovery runs -within 600 metres horizontally of a ready, non-loading player in the same +within 200 metres horizontally of a ready, non-loading player in the same playfield and for fifteen minutes after the last nearby player leaves. After that, dormant NPCs retain their health and clock until a player returns. Starting or stopping an attack changes the applicable branch diff --git a/docs/world-state.md b/docs/world-state.md @@ -60,16 +60,19 @@ replacements settle the reservation in their own transaction. See The world header is updated only when its counters, clock or population-initialization state change. NPC state is checked -on the one-second world tick, but routine writes occur at least 20 seconds -apart, with random starting phases, only for NPCs within 600 metres horizontally +on the one-second world tick, but routine writes occur 20-30 seconds +apart, with fresh jitter after each checkpoint, only for NPCs within 200 metres +horizontally of a ready, non-loading player in the same playfield, or within a fifteen-minute grace period after the last nearby player leaves. Roaming, pursuit, returns, recovery and periodic effects use the same activity gate. Grace expiry triggers one final snapshot; an occupied zone does not activate its entire population. The activity deadline lives in memory; after a restart, NPCs wait for a nearby -player before resuming. Unchanged rows -are skipped. Corpse ownership and cash changes save immediately with their -loot transaction. A new database takes one initial population snapshot. +player before resuming. Changed character and NPC metadata rows are batched +in groups of up to 100 per statement in one transaction. Unchanged tables and +contribution records are skipped; snapshots and deadlines publish only after +commit. Corpse ownership and cash changes save immediately with their loot +transaction. A new database takes one initial population snapshot. SIGINT/SIGTERM flush pending state before closing the database. A crash can lose simulation changes since the relevant checkpoint. Network sessions and in-progress client requests are recreated on connection. diff --git a/server/corpse_credit_write_test.go b/server/corpse_credit_write_test.go @@ -17,6 +17,10 @@ func TestCorpseCreditIgnoredNPCCheckpointRollsBackAndRetries(t *testing.T) { if err := world.saveInventory_locked(player, player.inventory); err != nil { t.Fatal(err) } + // Character checkpoints only write when their fields have changed. + if table == "characters" { + corpse.position[0]++ + } previous := world.savedNPCs[corpse.id] persisted, err := readTestItemStore(world) if err != nil { diff --git a/server/interest.go b/server/interest.go @@ -13,7 +13,7 @@ func (server *server) npcActive_locked(npc *character, now time.Time) bool { continue } x, z := player.position[0]-npc.position[0], player.position[2]-npc.position[2] - if x*x+z*z <= 600*600 { + if x*x+z*z <= 200*200 { npc.npcActiveUntil = now.Add(15 * time.Minute) return true } @@ -26,13 +26,12 @@ func (server *server) updateNPCInterest_locked(client *worldClient, now time.Tim position := predictedPosition_locked(player, now) var updates [][]byte - // Retain a margin beyond the 500-metre minimap query and avoid boundary churn. - // Original ddr.dll N3Msg_GetMapCharacters call: 0x2B05634A. + // Add NPCs within 180 metres and retain them to 200 to avoid boundary churn. for id := range client.npcs { other := server.characters[id] if other != nil && other.playfield == player.playfield { x, z := other.position[0]-position[0], other.position[2]-position[2] - if x*x+z*z <= 600*600 { + if x*x+z*z <= 200*200 { continue } } @@ -53,7 +52,7 @@ func (server *server) updateNPCInterest_locked(client *worldClient, now time.Tim continue } x, z := other.position[0]-position[0], other.position[2]-position[2] - if x*x+z*z > 550*550 { + if x*x+z*z > 180*180 { continue } client.npcs[id] = true diff --git a/server/interest_test.go b/server/interest_test.go @@ -8,11 +8,11 @@ import ( "time" ) -func TestLoginIncludesMinimapNPCsButNotDistantPopulation(t *testing.T) { +func TestLoginIncludesNearbyNPCsButNotDistantPopulation(t *testing.T) { for _, target := range []bool{false, true} { t.Run(map[bool]string{false: "original", true: "1491"}[target], func(t *testing.T) { data := testNPCData() - data.Playfields[0].Districts[0].Groups[0].Positions = [][3]float32{{1500, 1000, 1000}, {1550, 0, 1000}, {1551, 0, 1000}} + data.Playfields[0].Districts[0].Groups[0].Positions = [][3]float32{{1170, 1000, 1000}, {1180, 0, 1000}, {1181, 0, 1000}} useNPCData(t, data) world := newTestServer(t) player := world.newCharacter() @@ -53,9 +53,9 @@ func TestLoginIncludesMinimapNPCsButNotDistantPopulation(t *testing.T) { } } -func TestHeldMovementStreamsNPCBeforeMinimapRange(t *testing.T) { +func TestHeldMovementStreamsNPCWithinInterestRange(t *testing.T) { data := testNPCData() - data.Playfields[0].Districts[0].Groups[0].Positions = [][3]float32{{1000, 0, 1551}} + data.Playfields[0].Districts[0].Groups[0].Positions = [][3]float32{{1000, 0, 1181}} useNPCData(t, data) world := newTestServer(t) player := world.newCharacter() @@ -91,7 +91,7 @@ func TestHeldMovementStreamsNPCBeforeMinimapRange(t *testing.T) { func TestNPCInterestRetainsBoundaryMarginAndRespawns(t *testing.T) { data := testNPCData() - data.Playfields[0].Districts[0].Groups[0].Positions = [][3]float32{{1500, 0, 1000}} + data.Playfields[0].Districts[0].Groups[0].Positions = [][3]float32{{1180, 0, 1000}} useNPCData(t, data) world := newTestServer(t) player := world.newCharacter() @@ -99,9 +99,9 @@ func TestNPCInterestRetainsBoundaryMarginAndRespawns(t *testing.T) { client := connectZoningClient(t, world, false) now := time.Now() - player.position[0] = 900 + player.position[0] = 980 world.advanceNPCs(now) - player.position[0] = 899 + player.position[0] = 979 done := make(chan struct{}) go func() { world.advanceNPCs(now); close(done) }() removed, err := readPacket(client) @@ -109,9 +109,9 @@ func TestNPCInterestRetainsBoundaryMarginAndRespawns(t *testing.T) { t.Fatal(err) } <-done - player.position[0] = 949 + player.position[0] = 999 world.advanceNPCs(now) - player.position[0] = 950 + player.position[0] = 1000 done = make(chan struct{}) go func() { world.advanceNPCs(now); close(done) }() spawn, err := readPacket(client) @@ -131,7 +131,7 @@ func TestNPCInterestRetainsBoundaryMarginAndRespawns(t *testing.T) { func TestRoamingNPCStreamsSpawnBeforeCurrentMotion(t *testing.T) { data := testNPCData() data.Playfields[0].Districts[0].Groups[0].PlacementStatus = "authored_point" - data.Playfields[0].Districts[0].Groups[0].Positions = [][3]float32{{1550.25, 0, 1000}, {2000, 0, 1000}} + data.Playfields[0].Districts[0].Groups[0].Positions = [][3]float32{{1180.25, 0, 1000}, {2000, 0, 1000}} useNPCData(t, data) world := newTestServer(t) player := world.newCharacter() @@ -166,7 +166,7 @@ func TestRoamingNPCStreamsSpawnBeforeCurrentMotion(t *testing.T) { if binary.BigEndian.Uint32(spawn[20:]) != 0x271b3a6b || binary.BigEndian.Uint32(spawn[28:]) != 1000000 { t.Fatalf("entering NPC spawn: %x", spawn) } - if binary.BigEndian.Uint32(motion[20:]) != 0x260f3671 || binary.BigEndian.Uint32(motion[28:]) != 1000000 || motion[48] != 22 || math.Abs(float64(math.Float32frombits(binary.BigEndian.Uint32(motion[49:]))-1549.887)) > .001 { + if binary.BigEndian.Uint32(motion[20:]) != 0x260f3671 || binary.BigEndian.Uint32(motion[28:]) != 1000000 || motion[48] != 22 || math.Abs(float64(math.Float32frombits(binary.BigEndian.Uint32(motion[49:]))-1179.887)) > .001 { t.Fatalf("entering NPC motion: %x", motion) } if world.characters[1000001].position != [3]float32{2000, 0, 1000} { diff --git a/server/npc_activity_test.go b/server/npc_activity_test.go @@ -15,9 +15,9 @@ func TestNPCActivitySkipsDistantAndUnavailablePlayers(t *testing.T) { npc.health = 50 switch scenario { case "distant": - world.characters[1].position = [3]float32{602, 0, 0} + world.characters[1].position = [3]float32{202, 0, 0} case "diagonal": - world.characters[1].position = [3]float32{500, 0, 500} + world.characters[1].position = [3]float32{150, 0, 150} case "other zone": world.characters[1].playfield = 635 case "offline": @@ -54,7 +54,7 @@ func TestNPCActivityResumesNearAnyPlayerWithoutMovementCatchup(t *testing.T) { world.characters[1].position = [3]float32{2000, 0, 0} world.advanceNPCs(start.Add(time.Hour)) before := npc.position - world.characters[2] = &character{id: 2, playfield: 950, position: [3]float32{600, 0, 0}} + world.characters[2] = &character{id: 2, playfield: 950, position: [3]float32{201, 0, 0}} world.clients[2] = &worldClient{id: 2, ready: true, conn: &combatTestConn{}, npcs: make(map[uint32]bool)} world.advanceNPCs(start.Add(time.Hour + 250*time.Millisecond)) diff --git a/server/npc_checkpoint_batch_test.go b/server/npc_checkpoint_batch_test.go @@ -0,0 +1,140 @@ +package main + +import ( + "maps" + "reflect" + "testing" + "time" +) + +func newNPCCheckpointPopulation(t *testing.T, count int) (*server, time.Time) { + t.Helper() + data := testNPCData() + group := &data.Playfields[0].Districts[0].Groups[0] + group.PlacementStatus = "authored_point" + group.Positions = make([][3]float32, count) + for index := range group.Positions { + group.Positions[index] = [3]float32{52, 14, 56} + } + useNPCData(t, data) + world := newTestServer(t) + player := world.newCharacter() + player.position = [3]float32{52, 14, 56} + world.clients[player.id] = &worldClient{id: player.id, ready: true} + start := time.Now() + if err := world.checkpointWorld(start); err != nil { + t.Fatal(err) + } + return world, start +} + +func TestNPCCheckpointBatchesOnlyChangedTables(t *testing.T) { + for _, change := range []string{"position", "route", "both"} { + t.Run(change, func(t *testing.T) { + world, start := newNPCCheckpointPopulation(t, 1000) + for _, npc := range world.characters { + if !npc.npc { + continue + } + if change != "route" { + npc.position[0] = 53 + } + if change != "position" { + npc.motion.destination[0] = 53 + } + } + queries := world.databaseQueries.Load() + now := start.Add(41 * time.Second) + + if err := world.checkpointWorld(now); err != nil { + t.Fatal(err) + } + + want := uint64(12) + if change == "both" { + want = 22 + } + if got := world.databaseQueries.Load() - queries; got != want { + t.Fatalf("1000 NPC checkpoints: got %d queries, want %d", got, want) + } + var positions, routes int + if err := world.db.QueryRow(`SELECT sum(position_x=53), sum(destination_x=53) + FROM characters JOIN npcs USING(id)`).Scan(&positions, &routes); err != nil { + t.Fatal(err) + } + if change != "route" && positions != 1000 || change != "position" && routes != 1000 { + t.Fatal("batch lost NPC state", positions, routes) + } + deadlines := make(map[time.Time]bool) + for _, saved := range world.savedNPCs { + if saved.NextSave.Before(now.Add(20*time.Second)) || !saved.NextSave.Before(now.Add(30*time.Second)) { + t.Fatal("checkpoint did not schedule 20-30 second jitter", saved.NextSave.Sub(now)) + } + deadlines[saved.NextSave] = true + } + if len(deadlines) < 2 { + t.Fatal("checkpoint deadlines were synchronized") + } + + // Further movement remains in memory until the next checkpoint is due. + world.characters[1000000].position[0] = 54 + queries = world.databaseQueries.Load() + if err := world.checkpointWorld(now.Add(19 * time.Second)); err != nil { + t.Fatal(err) + } + if world.databaseQueries.Load()-queries != 2 || world.savedNPCs[1000000].State.Character.Position.Position[0] == 54 { + t.Fatal("routine movement persisted before 20 seconds") + } + }) + } +} + +func TestNPCCheckpointBatchFailureRollsBackAndRetries(t *testing.T) { + for _, table := range []string{"characters", "npcs"} { + for _, failure := range []string{"IGNORE", "ABORT, 'checkpoint failure'"} { + t.Run(table+"/"+failure, func(t *testing.T) { + world, start := newNPCCheckpointPopulation(t, 250) + before := maps.Clone(world.savedNPCs) + for _, npc := range world.characters { + if npc.npc { + npc.position[0], npc.motion.destination[0] = 53, 53 + } + } + column := "position_x" + if table == "npcs" { + column = "destination_x" + } + // Fail after two full batches have already written inside the transaction. + if _, err := world.db.Exec("CREATE TRIGGER reject_checkpoint BEFORE UPDATE ON " + table + + " WHEN (SELECT count(*) FROM " + table + " WHERE id>=1000000 AND " + column + "=53)>=200" + + " BEGIN SELECT RAISE(" + failure + "); END"); err != nil { + t.Fatal(err) + } + now := start.Add(41 * time.Second) + + if err := world.checkpointWorld(now); err == nil { + t.Fatal("incomplete batch succeeded") + } + + var changed int + if err := world.db.QueryRow(`SELECT count(*) FROM characters JOIN npcs USING(id) + WHERE position_x=53 OR destination_x=53`).Scan(&changed); err != nil { + t.Fatal(err) + } + if changed != 0 || !reflect.DeepEqual(before, world.savedNPCs) { + t.Fatal("failed checkpoint published partial database or cache state", changed) + } + if _, err := world.db.Exec("DROP TRIGGER reject_checkpoint"); err != nil { + t.Fatal(err) + } + if err := world.checkpointWorld(now); err != nil { + t.Fatal(err) + } + if err := world.db.QueryRow(`SELECT count(*) FROM characters JOIN npcs USING(id) + WHERE position_x=53 AND destination_x=53`).Scan(&changed); err != nil || changed != 250 { + t.Fatal("checkpoint retry lost rows", changed, err) + } + }) + } + } +} diff --git a/server/world_store.go b/server/world_store.go @@ -5,6 +5,7 @@ import ( "fmt" "maps" "math/rand/v2" + "strings" "time" ) @@ -65,6 +66,37 @@ func (npc *character) worldState(present bool, respawnAt time.Time) npcState { return state } +func writeNPCBatch(tx *sql.Tx, table, columns string, records [][]any) error { + if len(records) == 0 { + return nil + } + names := strings.Split(columns, ", ") + assignments := make([]string, len(names)) + for index, name := range names { + assignments[index] = name + " = excluded." + name + } + values := "(?" + strings.Repeat(", ?", len(names)) + ")" + query := "INSERT INTO " + table + " (id, " + columns + ") VALUES " + + strings.TrimSuffix(strings.Repeat(values+", ", len(records)), ", ") + + " ON CONFLICT(id) DO UPDATE SET " + strings.Join(assignments, ", ") + var fields []any + for _, record := range records { + fields = append(fields, record...) + } + result, err := tx.Exec(query, fields...) + if err != nil { + return err + } + changed, err := result.RowsAffected() + if err != nil { + return err + } + if changed != int64(len(records)) { + return fmt.Errorf("checkpoint %s: saved %d of %d rows", table, changed, len(records)) + } + return nil +} + func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, active map[uint32]bool) (map[uint32]savedNPC, error) { characters := maps.Clone(server.characters) deadlines := make(map[uint32]time.Time) @@ -80,17 +112,19 @@ func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, active map[u } } - // Prepare the bulk writes once for the initial population checkpoint. - characterWrite, err := tx.Prepare(upsertRecordSQL("characters", characterColumns) + " RETURNING id") - if err != nil { - return nil, err - } - defer characterWrite.Close() - npcWrite, err := tx.Prepare(upsertRecordSQL("npcs", npcColumns) + " RETURNING id") - if err != nil { - return nil, err + // Bound each statement below SQLite's parameter limit, including full character rows. + var characterRows, npcRows [][]any + var contributors, effects []*character + flush := func() error { + if err := writeNPCBatch(tx, "characters", characterColumns, characterRows); err != nil { + return err + } + if err := writeNPCBatch(tx, "npcs", npcColumns, npcRows); err != nil { + return err + } + characterRows, npcRows = characterRows[:0], npcRows[:0] + return nil } - defer npcWrite.Close() // Routine checkpoints are staggered; dormant NPCs retain their last snapshot. now := store.checkpointAt @@ -118,36 +152,51 @@ func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, active map[u } state := npc.worldState(server.characters[id] != nil, deadlines[id]) nextSave := previous.NextSave - if nextSave.IsZero() || !server.activeNPCs[id] && active[id] { - nextSave = now.Add(20*time.Second + time.Duration(rand.Int64N(int64(20*time.Second)))) - } else if !now.Before(nextSave) { - nextSave = now.Add(20 * time.Second) + if nextSave.IsZero() || !server.activeNPCs[id] && active[id] || !now.Before(nextSave) { + nextSave = now.Add(20*time.Second + time.Duration(rand.Int64N(int64(10*time.Second)))) } saved[id] = savedNPC{state, maps.Clone(npc.damageContributors), nextSave} - if !exists || previous.State != state || !maps.Equal(previous.Contributors, npc.damageContributors) { - var savedID uint32 - if err := characterWrite.QueryRow(append([]any{id}, state.Character.fields()...)...).Scan(&savedID); err != nil { - return nil, fmt.Errorf("checkpoint NPC %d character: %w", id, err) - } - if err := npcWrite.QueryRow(append([]any{id}, state.fields()...)...).Scan(&savedID); err != nil { - return nil, fmt.Errorf("checkpoint NPC %d state: %w", id, err) - } - if _, err := tx.Exec("DELETE FROM npc_damage_contributors WHERE npc_id=?", id); err != nil { + if !exists || previous.State.Character != state.Character { + characterRows = append(characterRows, append([]any{id}, state.Character.fields()...)) + } + // Character fields live in their own table; compare only NPC metadata here. + previous.State.Character = state.Character + if !exists || previous.State != state { + npcRows = append(npcRows, append([]any{id}, state.fields()...)) + } + if !maps.Equal(previous.Contributors, npc.damageContributors) { + contributors = append(contributors, npc) + } + if len(characterRows) == 100 || len(npcRows) == 100 { + if err := flush(); err != nil { return nil, err } - for contributor, damage := range npc.damageContributors { - if _, err := tx.Exec("INSERT INTO npc_damage_contributors (npc_id, player_id, team_id, damage) VALUES (?, ?, ?, ?)", id, contributor.player, contributor.team, damage); err != nil { - return nil, err - } - } } // Effect time follows the same periodic checkpoint even when the NPC is still. if len(npc.activeNanos) != 0 { - if err := writeActiveNanos(tx, npc, now); err != nil { + effects = append(effects, npc) + } + } + if err := flush(); err != nil { + return nil, err + } + + // Referencing rows follow the actor batches in the same transaction. + for _, npc := range contributors { + if _, err := tx.Exec("DELETE FROM npc_damage_contributors WHERE npc_id=?", npc.id); err != nil { + return nil, err + } + for contributor, damage := range npc.damageContributors { + if _, err := tx.Exec("INSERT INTO npc_damage_contributors (npc_id, player_id, team_id, damage) VALUES (?, ?, ?, ?)", npc.id, contributor.player, contributor.team, damage); err != nil { return nil, err } } } + for _, npc := range effects { + if err := writeActiveNanos(tx, npc, now); err != nil { + return nil, err + } + } for id, previous := range server.savedNPCs { if characters[id] != nil { continue @@ -224,7 +273,7 @@ func (server *server) loadNPCs() (bool, error) { server.npcRespawns = append(server.npcRespawns, npcRespawn{npc, state.RespawnAt}) } characters[npc.id] = npc - server.savedNPCs[npc.id] = savedNPC{State: state, NextSave: time.Now().Add(time.Duration(rand.Int64N(int64(20 * time.Second))))} + server.savedNPCs[npc.id] = savedNPC{State: state, NextSave: time.Now().Add(20*time.Second + time.Duration(rand.Int64N(int64(10*time.Second))))} } if err := rows.Err(); err != nil { rows.Close()