aorecomp

Anarchy Online classic in the browser

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


commit b4b55fa5548f3936bb230cb53787350f728725ae
parent b48e6099c4bce66a835f508dfc99c25ee9549501
Author: anon <anon@example.com>
Date:   Sat, 24 Oct 2026 02:04:51 +0000

Commit NPC respawn lifecycle before publishing replacements

Diffstat:
MTODO.md | 20+++++++++++---------
Mdocs/npc-respawn.md | 42+++++++++++++++++++++++++++++++++++-------
Mserver/npc_outcome.go | 16++++++++++------
Mserver/respawn.go | 84++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Aserver/respawn_durability_test.go | 208+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/respawn_test.go | 14+++++++++++---
6 files changed, 358 insertions(+), 26 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -273,6 +273,8 @@ Historical outdoor give-up timing and obstacle navigation remain open. - [x] Respawn one creature. Check: after the profile's respawn interval, exactly one living replacement appears with fresh resources and no old fight state. + Creation, consumption of the pending deadline and identity reservation commit + before clients see the replacement; failed saves retry without duplication. - [x] Resurrect a player through the native flow. Check: death leads to a valid resurrection location and usable character without reloading the browser. - [x] Save a resurrection location. Check: using one save terminal persists the @@ -795,15 +797,15 @@ and server restarts. Turn every reproduced bug into a focused regression test. - [ ] Audit NPC pursuit, recovery and lifecycle. Cover multiple observers, target loss, re-engagement, terrain boundaries, death during movement, no-observer periods and restart during pursuit, return, corpse and respawn. - Respawn creation currently reaches clients before its creation and retirement - of the source's pending respawn are checkpointed. Commit both transitions and - the identity reservation atomically before publication; a crash in that gap - must not replay the source respawn. Combat outcome saves now reserve freshly - persisted NPC IDs, including a newly respawned NPC killed before a checkpoint. - An isolated public-combat reproduction publishes the new actor, then reopening - the DB finds no new NPC and one stale pending source respawn. Evidence and the - temporary regression are retained in `local/ranged-outcome-research/` as - `respawn-birth-audit-red.log` and `respawn-birth-audit-test.go.txt`. + Respawn creation, retirement of the source's pending deadline and reservation + of the new identity now commit atomically before publication. Failure leaves + the original pending life intact for retry. Expired-source cleanup removes + only unlooted items and filled-container contents, preserving transferred + backpacks. `server/respawn_durability_test.go` covers first-packet durability, + write/commit failures, repeated retries, expiry on either side of a checkpoint, + and ownership rollback. Combat outcome saves also reserve freshly persisted + NPC IDs, including a new replacement killed before a checkpoint. The broader + pursuit/recovery audit remains open. - [ ] Audit idle checkpoint database churn. Count item, player, vital, learned nano and lock writes as well as NPC writes. `checkpointWorld` still routes through the full inventory store every second; unchanged unrelated state diff --git a/docs/npc-respawn.md b/docs/npc-respawn.md @@ -47,10 +47,19 @@ transfer, and repeating that request cannot manufacture a new drop. Corpse expiration uses the profile's independent provisional 180-second lifetime; see [corpse expiry](corpse-loot.md#corpse-expiry). -NPC lives, corpses and pending timers remain runtime state. Restart reconstructs -exactly the authored living population with full resources; it does not persist -elapsed NPC timers or resurrect additional copies from the old queue. Player -inventory obtained before restart remains durable. +NPC lives, corpses and pending timers are stored in SQLite. A replacement's +creation, retirement of its source's pending deadline and reservation of its +fresh identity commit together before the new actor reaches clients. A failed +transaction retains the pending deadline for retry and publishes nothing. +Restart loads the committed replacement and cannot replay the consumed timer. +This significant transition saves immediately; routine movement still uses +periodic checkpoints. + +If the source corpse is still present, its identity, contents and loot rights +remain intact. If it has expired, the transaction removes its remaining item +ownership and contents along with the source. A backpack already transferred +to a player retains its contents. The cleanup also works when a checkpoint +has already removed the expired loot. ## Verification @@ -59,14 +68,33 @@ ticks, two successive kills, old loot after replacement, fresh home/resources and combat state, identical owner/observer spawn packets, observer-free respawning, interest reentry, restart and exclusion of unprofiled creatures. +`server/respawn_durability_test.go` reads SQLite during the first outgoing actor +packet to verify that the replacement, consumed timer and identity reservation +are already committed. It covers failures in the source update, replacement +character/NPC writes, identity reservation and commit; repeated failure and +retry; expiry before and after a checkpoint; filled-container cleanup; preserved +transferred backpacks; and rollback of failed item/source deletion. + +Two published WASM clients also exercised the SQLite failure/retry path on the +normal HTTPS preview. A trigger rejected only the fixture's replacement for +multiple ticks after its normal 100-second deadline; no actor was published. +Removing the trigger produced one replacement, ID 1068610, at 100 HP. A SQLite +read during the first received actor frame found that life committed, the old +deadline cleared and the allocator at 1068611. Both clients saw that same idle +life; repeating the attack key after death left it unharmed and ammunition at +17. An ungraceful server stop followed by reconnect retained the same identity +and full health without another replacement. Both runs had no page errors. +The original fixture profiles, NPC, items and placements were restored. +Evidence is in `local/respawn-durability-research/`. + Two published WASM clients exercised two full-health kills with the existing QL 1 Kinetic Axe and two timed replacements. The live identities progressed from 1000000 to 1068609 to 1068610; each replacement started at 100 HP without attacking until a new request. Both observers saw the new living creature and the old remains. The first corpse's window stayed open across respawn, and its fixture item transferred once afterward. That item remained in the native -inventory after page reconnect and server restart. Restart produced one living -authored creature with no old corpses or pending timers. There were no page -errors; connection-refused logs occurred during the intentional restart. +inventory after page reconnect and server restart. That earlier run exercised +the runtime lifecycle before SQLite NPC persistence. There were no page errors; +connection-refused logs occurred during the intentional restart. Screenshots, per-step states and the isolated fixture are retained in `local/respawn-smoke/`. diff --git a/server/npc_outcome.go b/server/npc_outcome.go @@ -15,25 +15,29 @@ func writeNPCOutcome_locked(tx *sql.Tx, target *character, now time.Time) (npcSt state.RespawnAt = now.Add(time.Duration(target.combatProfile.RespawnSeconds) * time.Second) } } + return state, writeNPCState_locked(tx, target, &state) +} + +func writeNPCState_locked(tx *sql.Tx, target *character, state *npcState) error { if _, err := tx.Exec(upsertRecordSQL("characters", characterColumns), append([]any{target.id}, state.Character.fields()...)...); err != nil { - return state, err + return err } if _, err := tx.Exec(upsertRecordSQL("npcs", npcColumns), append([]any{target.id}, state.fields()...)...); err != nil { - return state, err + return err } if _, err := tx.Exec("DELETE FROM npc_damage_contributors WHERE npc_id=?", target.id); err != nil { - return state, err + return err } for contributor, damage := range target.damageContributors { if _, err := tx.Exec("INSERT INTO npc_damage_contributors (npc_id, player_id, team_id, damage) VALUES (?, ?, ?, ?)", target.id, contributor.player, contributor.team, damage); err != nil { - return state, err + return err } } // A newly persisted respawn must not have its identity reused after restart. if _, err := tx.Exec("UPDATE world SET last_npc_id=? WHERE id=1 AND last_npc_id<?", target.id+1, target.id+1); err != nil { - return state, err + return err } - return state, nil + return nil } func (server *server) rememberNPCOutcome_locked(target *character, state npcState, now time.Time) { diff --git a/server/respawn.go b/server/respawn.go @@ -1,6 +1,7 @@ package main import ( + "log" "slices" "time" ) @@ -31,11 +32,20 @@ func (server *server) advanceNPCRespawns(now time.Time) { monsterData: respawn.npc.monsterData, level: respawn.npc.level, npc: true, combatProfile: respawn.npc.combatProfile, npcDefinitionID: respawn.npc.npcDefinitionID, } - server.nextNPC++ npc.health = npc.maximumHealth() if respawn.npc.roaming != nil { npc.position = respawn.npc.roaming.home npc.roaming = &npcRoaming{home: npc.position} + } + if err := server.saveNPCRespawn_locked(respawn.npc, npc, now); err != nil { + log.Printf("Respawn: %v", err) + server.npcRespawns = append(server.npcRespawns, respawn) + continue + } + + // Publish the committed life and update its roaming worker only once. + server.nextNPC++ + if npc.roaming != nil { index := slices.Index(server.roamingNPCs[npc.playfield], respawn.npc) if index < 0 { server.roamingNPCs[npc.playfield] = append(server.roamingNPCs[npc.playfield], npc) @@ -59,3 +69,75 @@ func (server *server) advanceNPCRespawns(now time.Time) { server.mutex.Unlock() server.sendCombatUpdates(updates) } + +func (server *server) saveNPCRespawn_locked(source, npc *character, now time.Time) error { + db, err := server.database() + if err != nil { + return err + } + tx, err := db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + sourceState := source.worldState(server.characters[source.id] != nil, time.Time{}) + state := npc.worldState(true, time.Time{}) + var expiredItems []uint32 + if sourceState.Present { + // Retire the pending deadline while preserving still-visible loot rights. + if err := writeNPCState_locked(tx, source, &sourceState); err != nil { + return err + } + } else { + // An expired source may still own a filled container until its checkpoint. + rows, err := tx.Query("SELECT item_id FROM item_locations WHERE corpse_id=? OR backpack_id IN (SELECT item_id FROM item_locations WHERE corpse_id=?)", source.id, source.id) + if err != nil { + return err + } + for rows.Next() { + var id uint32 + if err := rows.Scan(&id); err != nil { + rows.Close() + return err + } + expiredItems = append(expiredItems, id) + } + if err := rows.Err(); err != nil { + rows.Close() + return err + } + rows.Close() + for _, id := range expiredItems { + if _, err := tx.Exec("DELETE FROM item_locations WHERE item_id=?", id); err != nil { + return err + } + } + for _, id := range expiredItems { + if _, err := tx.Exec("DELETE FROM items WHERE id=?", id); err != nil { + return err + } + } + if _, err := tx.Exec("DELETE FROM characters WHERE id=?", source.id); err != nil { + return err + } + } + if err := writeNPCState_locked(tx, npc, &state); err != nil { + return err + } + if err := tx.Commit(); err != nil { + return err + } + + // Change caches only after both sides of the lifecycle transition are durable. + if sourceState.Present { + server.rememberNPCOutcome_locked(source, sourceState, now) + } else { + delete(server.savedNPCs, source.id) + for _, id := range expiredItems { + delete(server.items, id) + delete(server.itemPlacements, id) + } + } + server.rememberNPCOutcome_locked(npc, state, now) + return nil +} diff --git a/server/respawn_durability_test.go b/server/respawn_durability_test.go @@ -0,0 +1,208 @@ +package main + +import ( + "ao/server/gamedata" + "database/sql" + "encoding/binary" + "reflect" + "testing" + "time" +) + +type respawnCommitConn struct { + combatTestConn + db *sql.DB + health uint32 + deadline time.Time + nextID uint32 + err error +} + +func (conn *respawnCommitConn) Write(packet []byte) (int, error) { + if binary.BigEndian.Uint32(packet[16:20]) == 0x271b3a6b && binary.BigEndian.Uint32(packet[24:28]) == 1000001 { + conn.err = conn.db.QueryRow("SELECT replacement.health, source.respawn_at, world.last_npc_id FROM characters replacement JOIN npcs source ON source.id=1000000 JOIN world ON world.id=1 WHERE replacement.id=1000001").Scan(&conn.health, &conn.deadline, &conn.nextID) + } + return conn.combatTestConn.Write(packet) +} + +func TestNPCRespawnBirthIsDurableBeforePublication(t *testing.T) { + world, _ := newRangedWorld(t) + target := world.characters[1000000] + target.health, target.monsterData, target.level = 1, 17655, 1 + target.combatProfile = gamedata.NPCCombatProfiles[17655][1] + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:]) + world.advanceCombat(world.characters[1].nextAttack) + conn := &respawnCommitConn{db: world.db} + world.clients[1].conn = conn + + world.advanceNPCRespawns(world.npcRespawns[0].at) + restored := newTestInventoryServer(t) + published := false + for _, packet := range conn.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x271b3a6b && binary.BigEndian.Uint32(packet[24:28]) == 1000001 { + published = true + } + } + + if !published { + t.Fatal("fixture did not publish its new actor") + } + if conn.err != nil || conn.health != 100 || !conn.deadline.IsZero() || conn.nextID != 1000002 { + t.Fatalf("first native actor packet preceded the committed lifecycle: health=%d deadline=%v nextID=%d, %v", conn.health, conn.deadline, conn.nextID, conn.err) + } + if restored.characters[1000001] == nil || len(restored.npcRespawns) != 0 { + t.Fatalf("published respawn not committed: new NPC exists=%t; old pending respawns=%d", restored.characters[1000001] != nil, len(restored.npcRespawns)) + } +} + +func TestNPCRespawnFailureKeepsPendingLifeAndRetriesOnce(t *testing.T) { + for _, failure := range []struct{ name, statement string }{ + {"source", "CREATE TRIGGER fail_respawn BEFORE UPDATE ON npcs WHEN NEW.id=1000000 BEGIN SELECT RAISE(FAIL, 'test source failure'); END"}, + {"new character", "CREATE TRIGGER fail_respawn BEFORE INSERT ON characters WHEN NEW.id=1000001 BEGIN SELECT RAISE(FAIL, 'test actor failure'); END"}, + {"new NPC", "CREATE TRIGGER fail_respawn BEFORE INSERT ON npcs WHEN NEW.id=1000001 BEGIN SELECT RAISE(FAIL, 'test NPC failure'); END"}, + {"identity", "CREATE TRIGGER fail_respawn BEFORE UPDATE ON world WHEN NEW.last_npc_id=1000002 BEGIN SELECT RAISE(FAIL, 'test identity failure'); END"}, + {"commit", "CREATE TABLE pending_spawn (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_respawn AFTER INSERT ON npcs WHEN NEW.id=1000001 BEGIN INSERT INTO pending_spawn VALUES (999999); END"}, + } { + t.Run(failure.name, func(t *testing.T) { + world, conn := newRespawnWorld(t) + world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]) + world.advanceCombat(world.characters[1].nextAttack) + due := world.npcRespawns[0].at + before := world.savedNPCs[1000000] + source := world.characters[1000000] + if _, err := world.db.Exec(failure.statement); err != nil { + t.Fatal(err) + } + conn.packets = nil + + world.advanceNPCRespawns(due) + world.advanceNPCRespawns(due.Add(time.Second)) + restored := newTestInventoryServer(t) + if world.characters[1000001] != nil || world.nextNPC != 1000001 || len(world.npcRespawns) != 1 || + !world.npcRespawns[0].at.Equal(due) || !reflect.DeepEqual(world.savedNPCs[1000000], before) || + len(world.roamingNPCs[950]) != 1 || world.roamingNPCs[950][0] != source || len(conn.packets) != 0 || + restored.characters[1000001] != nil || restored.nextNPC != 1000001 || len(restored.npcRespawns) != 1 || + !restored.npcRespawns[0].at.Equal(due) { + t.Fatal("failed transaction changed live or durable respawn state, or published an actor") + } + if _, err := world.db.Exec("DROP TRIGGER fail_respawn"); err != nil { + t.Fatal(err) + } + world.advanceNPCRespawns(due.Add(2 * time.Second)) + world.advanceNPCRespawns(due.Add(3 * time.Second)) + afterRetry := newTestInventoryServer(t) + + if world.characters[1000001] == nil || world.characters[1000001].health != 100 || len(world.npcRespawns) != 0 || + world.nextNPC != 1000002 || world.roamingNPCs[950][0].id != 1000001 || len(conn.packets) != 2 || + afterRetry.characters[1000001] == nil || len(afterRetry.npcRespawns) != 0 || afterRetry.nextNPC != 1000002 { + t.Fatal("retry did not create and commit exactly one fresh life") + } + }) + } +} + +func newRespawnWithFilledCorpse(t *testing.T) (*server, time.Time) { + t.Helper() + useNPCData(t, testNPCData()) + world := newFilledLootContainerWorld(t, 143832) + source := world.characters[1000000] + source.level = 1 + source.combatProfile = gamedata.NPCCombatProfiles[17655][1] + now := time.Now().UTC() + source.corpse.expiresAt = now.Add(time.Second) + world.corpseExpiry = []*character{source} + world.npcRespawns = []npcRespawn{{source, now.Add(3 * time.Second)}} + if granted, err := world.grantItem_locked(world.characters[1], 121567); !granted || err != nil { + t.Fatalf("fixture inventory item: %t %v", granted, err) + } + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + return world, now +} + +func TestNPCRespawnAfterExpiryCleansOnlyUnlootedContents(t *testing.T) { + for _, checkpoint := range []bool{false, true} { + t.Run(map[bool]string{false: "before checkpoint", true: "after checkpoint"}[checkpoint], func(t *testing.T) { + world, now := newRespawnWithFilledCorpse(t) + world.advanceCorpseExpiry(now.Add(time.Second)) + if checkpoint { + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + } + + world.advanceNPCRespawns(now.Add(3 * time.Second)) + restored := newTestInventoryServer(t) + + if world.characters[1000000] != nil || restored.characters[1000000] != nil || restored.characters[1000001] == nil || + len(world.items) != 1 || len(restored.items) != 1 || len(restored.npcRespawns) != 0 || len(restored.corpseExpiry) != 0 || + restored.nextNPC != 1000002 || restored.nextItem != 19 || len(restored.characters[1].inventory.Items) != 1 || + restored.characters[1].inventory.Items[0].ID != 19 || restored.items[19].Template != 121567 || + len(world.itemPlacements) != 1 || world.itemPlacements[19].Player != 1 { + t.Fatal("expired filled corpse cleanup lost unrelated inventory, retained orphan items or replayed its respawn") + } + }) + } +} + +func TestNPCRespawnAfterExpiryPreservesTransferredBackpack(t *testing.T) { + world, now := newRespawnWithFilledCorpse(t) + if err := world.handleLootUse(world.clients[1], lootUseRequest(1)); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(world.clients[1], lootTakeRequest()); err != nil { + t.Fatal(err) + } + world.advanceCorpseExpiry(now.Add(time.Second)) + + world.advanceNPCRespawns(now.Add(3 * time.Second)) + restored := newTestInventoryServer(t) + + if restored.characters[1000000] != nil || restored.characters[1000001] == nil || len(restored.items) != 3 || restored.nextItem != 19 || + len(restored.characters[1].inventory.Items) != 2 || len(restored.characters[1].inventory.Containers[17]) != 1 || + restored.characters[1].inventory.Containers[17][0] != (ownedItem{ID: 18, Type: 51005, Template: 152030, Quality: 42, Count: 3}) || + world.itemPlacements[17].Player != 1 || world.itemPlacements[18].Backpack != 17 { + t.Fatal("retiring an expired source removed or changed a backpack already transferred to a player") + } +} + +func TestNPCRespawnExpiredCleanupFailureRestoresOwnershipAndRetries(t *testing.T) { + for _, statement := range []string{ + "CREATE TRIGGER fail_cleanup BEFORE DELETE ON items WHEN OLD.id=18 BEGIN SELECT RAISE(FAIL, 'test contents failure'); END", + "CREATE TRIGGER fail_cleanup BEFORE DELETE ON characters WHEN OLD.id=1000000 BEGIN SELECT RAISE(FAIL, 'test source removal failure'); END", + } { + t.Run(statement, func(t *testing.T) { + world, now := newRespawnWithFilledCorpse(t) + world.advanceCorpseExpiry(now.Add(time.Second)) + if _, err := world.db.Exec(statement); err != nil { + t.Fatal(err) + } + conn := world.clients[1].conn.(*combatTestConn) + conn.packets = nil + + world.advanceNPCRespawns(now.Add(3 * time.Second)) + var locations uint32 + if err := world.db.QueryRow("SELECT count(*) FROM item_locations WHERE item_id IN (17,18)").Scan(&locations); err != nil { + t.Fatal(err) + } + if locations != 2 || len(world.items) != 3 || len(world.itemPlacements) != 3 || len(world.npcRespawns) != 1 || + world.characters[1000001] != nil || world.nextNPC != 1000001 || len(conn.packets) != 0 { + t.Fatal("failed cleanup destroyed contents, lost the pending life or published a replacement") + } + if _, err := world.db.Exec("DROP TRIGGER fail_cleanup"); err != nil { + t.Fatal(err) + } + world.advanceNPCRespawns(now.Add(4 * time.Second)) + restored := newTestInventoryServer(t) + + if restored.characters[1000001] == nil || restored.characters[1000000] != nil || len(restored.items) != 1 || + restored.items[19].Template != 121567 || len(restored.npcRespawns) != 0 || restored.nextNPC != 1000002 { + t.Fatal("retry failed to commit cleanup and one replacement") + } + }) + } +} diff --git a/server/respawn_test.go b/server/respawn_test.go @@ -20,6 +20,12 @@ func newRespawnWorld(t *testing.T) (*server, *combatTestConn) { conn := &combatTestConn{} world.clients[player.id] = &worldClient{id: player.id, conn: conn, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} world.characters[1000000].health = 1 + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } return world, conn } @@ -89,6 +95,7 @@ func TestNPCRespawnWithoutObserversThenReentryAndRestart(t *testing.T) { world.clients[1].npcs = make(map[uint32]bool) world.advanceNPCs(killed.Add(101 * time.Second)) restarted := newServer() + t.Cleanup(func() { restarted.db.Close() }) spawns, corpses, profiles := 0, 0, 0 for _, packet := range conn.packets { @@ -104,9 +111,10 @@ func TestNPCRespawnWithoutObserversThenReentryAndRestart(t *testing.T) { if spawns != 1 || corpses != 1 || profiles != 1 { t.Fatalf("reentry lost the living replacement or old corpse: %d/%d/%d", spawns, corpses, profiles) } - if len(restarted.characters) != 1 || restarted.characters[1000000].health != 100 || - restarted.characters[1000000].corpse != nil || len(restarted.npcRespawns) != 0 || len(restarted.roamingNPCs[950]) != 1 { - t.Fatal("restart duplicated the authored population or retained a dead life") + if len(restarted.characters) != 3 || restarted.characters[1000001].health != 100 || + restarted.characters[1000000].corpse == nil || len(restarted.npcRespawns) != 0 || len(restarted.roamingNPCs[950]) != 1 || + restarted.roamingNPCs[950][0].id != 1000001 { + t.Fatal("restart lost the living replacement, old remains or consumed respawn deadline") } }