aorecomp

Anarchy Online classic in the browser

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


commit 09c7b8b0db706c525d889b18941b88c914f3ee8d
parent e08b4325077be8f5826cd7856119f5b6d0e1a0c2
Author: anon <anon@example.com>
Date:   Sat, 24 Oct 2026 04:55:32 +0000

Verify Fling Shot recovery across forced process termination

Diffstat:
MTODO.md | 17+++++++++++++----
Mdocs/fling-shot.md | 31++++++++++++++++++++++++++++++-
Aserver/fling_crash_test.go | 205+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 248 insertions(+), 5 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -209,11 +209,17 @@ Normal-hit additions and weapon-range modifiers are described in combat-start behavior. Check: period evidence and native tests distinguish independent special use from normal attacks; invalid uses neither damage a target nor create a lock. Do not import the 15.5.5 ammo/evade changes. -- [ ] Stress special outcomes with forced process termination. Check: interrupt +- [x] Crash-test Fling's current damage/cooldown/corpse transaction. Check: interrupt a shot before and after database commit, including a killing hit, and recover - exactly one outcome with matching cooldown and corpse/reward state. Fling's - lock, NPC HP, contributions and corpse/respawn state now commit together; - SQL failure and database reopen tests cover rollback and restoration. + exactly one outcome with matching cooldown and corpse state. + Fling's lock, NPC HP, contributions and corpse/respawn state commit together. + Real subprocess kills at SQLite's commit hook and the first native-result + write cover living/killing hits and repeated requests after recovery. A WASM + killing shot followed by SIGKILL and restart retained the native corpse and + ownership. See `server/fling_crash_test.go` and [Fling Shot](docs/fling-shot.md). +- [ ] Extend forced-termination coverage to complete special reward outcomes. + Check: once kill XP/rewards exist, the killing hit, cooldown, corpse and rewards + recover together exactly once; failure or replay cannot lose or repeat any part. - [ ] Dual wield one verified weapon pair. Check: the actor's shared scheduling matches expected attack/recharge ordering without independent timer exploits. - [ ] Swap a weapon during combat. Check: swapping cannot bypass an existing @@ -655,6 +661,9 @@ and unresolved indoor lifecycle are explicit in [flight](docs/vehicles.md#yalmah ## Complete coverage beyond first examples +- [ ] Refresh the control editor's skill guidance. Check: it accurately explains + current native IP spending and administrative stat edits; `server/control.go` + still says native IP spending is not implemented. - [x] Show readable item tables below the control panel's character YAML editor. Check: inventory and equipment rows show slot, item name and a link to the exact item instance; empty slots are clear, and the YAML remains editable. diff --git a/docs/fling-shot.md b/docs/fling-shot.md @@ -100,10 +100,39 @@ The handler prepares damage on a detached NPC copy, then commits the lock, NPC HP, contributions and corpse/respawn state in one SQLite transaction before publishing live state or success feedback. Failure leaves both actors and feedback unchanged. Database reopen tests restore living and killing outcomes; -forced process termination immediately around commit remains a stress-test TODO. +forced process termination immediately around commit is covered below. ## Verification +`server/fling_crash_test.go` starts real child processes with disposable SQLite +databases. For both a living and a killing hit, the parent sends a forced kill +at either SQLite's commit hook or the first native special-result write. The +commit-hook stop occurs after the transaction's writes and before commit; +the output stop occurs after commit and before any result bytes are published. +The test does not add production fault switches or change transaction code. + +Recovery before commit retains the original HP, ammunition and empty cooldown, +contribution and corpse state. Recovery after commit retains the shot's HP and +cooldown, living damage contribution or dead corpse rights, expiry and pending +respawn. Killing hits retire the contribution map after assigning the corpse's +owner. A replacement session replays the request twice: an uncommitted shot can +succeed once; a committed shot emits no new result. A second database reopen +checks the recovered/retried outcome. These checks cover implemented outcomes; +future kill XP and other rewards must join the same atomic transition. + +The published WASM client separately performed a controlled killing Fling +against an isolated test Leet. Both clients received the same 95-point result; +the preview process was killed on receipt of that result, without graceful +shutdown. SQLite retained HP zero, killer ownership and corpse/respawn deadlines. +After restart, the killer loaded the native corpse and received the native +loot-rights message; both clients reconnected without another Fling result. +Loaded/loose ammunition stayed 20/100 and there were no page errors or +unimplemented-adapter messages. The 19-second lock +expires during this cold start; the automated cases verify active-lock recovery +before expiry. Raw captures and cleanup records are under +`local/fling-crash-research/`. Only owned actors/items were removed afterward; +the single shared preview and existing item records were preserved. + `client/tests/fling_result.c` executes unchanged `sub_360B2CB0` from `client/game/kkr.dll/lifted-0053.c`. Eight Linux and WASM cases verify target-only HP subtraction once, attacker/defender/observer feedback categories, ammo values diff --git a/server/fling_crash_test.go b/server/fling_crash_test.go @@ -0,0 +1,205 @@ +package main + +import ( + "ao/server/gamedata" + "bytes" + "context" + "encoding/binary" + "encoding/json" + "os" + "os/exec" + "strings" + "testing" + "time" + + "github.com/mattn/go-sqlite3" +) + +type flingCrashCheckpoint struct { + Directory string + Packet []byte + Published int +} + +type flingCrashConn struct { + combatTestConn + checkpoint func([]byte) +} + +func (conn *flingCrashConn) Write(packet []byte) (int, error) { + conn.checkpoint(packet) + return conn.combatTestConn.Write(packet) +} + +func runFlingCrashChild(t *testing.T, mode string) { + t.Helper() + world, output := newRangedWorld(t) + target := world.characters[1000000] + target.health, target.monsterData, target.level = 100, 17655, 1 + target.combatProfile = gamedata.NPCCombatProfiles[17655][1] + if strings.HasSuffix(mode, "/kill") { + target.health = 1 + } + if err := world.saveNPCDeath_locked(target, time.Now()); err != nil { + t.Fatal(err) + } + + // Notify the parent at the transaction boundary, then await its forced kill. + directory, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + pipe := os.NewFile(3, "crash-checkpoint") + defer pipe.Close() + checkpoint := func(packet []byte) { + if err := json.NewEncoder(pipe).Encode(flingCrashCheckpoint{directory, packet, len(output.packets)}); err != nil { + panic(err) + } + time.Sleep(time.Minute) + panic("parent did not terminate the crash fixture") + } + if strings.HasPrefix(mode, "before/") { + connection, err := world.db.Conn(context.Background()) + if err != nil { + t.Fatal(err) + } + err = connection.Raw(func(driver any) error { + driver.(*sqlite3.SQLiteConn).RegisterCommitHook(func() int { checkpoint(nil); return 0 }) + return nil + }) + connection.Close() + if err != nil { + t.Fatal(err) + } + } else { + world.clients[1].conn = &flingCrashConn{checkpoint: checkpoint} + } + if err := world.handleFlingShot(world.clients[1], flingShotRequest(1, 1000000)[20:]); err != nil { + t.Fatal(err) + } + t.Fatal("shot completed without reaching its crash boundary") +} + +func TestFlingShotProcessCrashRecovery(t *testing.T) { + if mode := os.Getenv("AO_TEST_FLING_CRASH"); mode != "" { + runFlingCrashChild(t, mode) + return + } + for _, mode := range []string{"before/living", "after/living", "before/kill", "after/kill"} { + t.Run(mode, func(t *testing.T) { + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + reader, writer, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer reader.Close() + defer writer.Close() + // Instrumented children initialize the full item and monster catalogs. + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + command := exec.CommandContext(ctx, executable, "-test.run=^TestFlingShotProcessCrashRecovery$") + command.Env = append(os.Environ(), "AO_TEST_FLING_CRASH="+mode, "TMPDIR="+t.TempDir()) + command.ExtraFiles = []*os.File{writer} + var processOutput bytes.Buffer + command.Stdout, command.Stderr = &processOutput, &processOutput + if err := command.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if command.ProcessState == nil { + command.Process.Kill() + command.Wait() + } + }) + writer.Close() + var checkpoint flingCrashCheckpoint + ready := make(chan error, 1) + go func() { ready <- json.NewDecoder(reader).Decode(&checkpoint) }() + + select { + case err := <-ready: + if err != nil { + command.Wait() + t.Fatalf("crash checkpoint: %v\n%s", err, processOutput.String()) + } + case <-ctx.Done(): + t.Fatal("child did not reach the crash checkpoint") + } + if err := command.Process.Kill(); err != nil { + t.Fatal(err) + } + if _, killed := command.Wait().(*exec.ExitError); !killed { + t.Fatalf("child was not forcibly terminated: %s", processOutput.String()) + } + if bytes.Contains(processOutput.Bytes(), []byte("WARNING: DATA RACE")) { + t.Fatalf("child reported a race before termination: %s", processOutput.String()) + } + t.Chdir(checkpoint.Directory) + restored := newTestInventoryServer(t) + player, target := restored.characters[1], restored.characters[1000000] + initialHealth := uint32(100) + if strings.HasSuffix(mode, "/kill") { + initialHealth = 1 + } + + if checkpoint.Published != 0 { + t.Fatal("shot published feedback before its commit boundary") + } + if player.inventory.Items[0].Ammo != 3 || player.inventory.Items[1].Count != 100 { + t.Fatal("crash changed pre-15.5 ammunition") + } + if strings.HasPrefix(mode, "before/") { + if target.health != initialHealth || len(player.specialAttackLocks) != 0 || len(target.damageContributors) != 0 || + target.corpse != nil || len(restored.npcRespawns) != 0 { + t.Fatalf("uncommitted shot survived the process kill: %+v", target) + } + } else { + if len(checkpoint.Packet) < 57 || binary.BigEndian.Uint32(checkpoint.Packet[16:20]) != 0x754f1115 { + t.Fatalf("first post-commit output was not the native special result: %x", checkpoint.Packet) + } + damage := binary.BigEndian.Uint32(checkpoint.Packet[33:37]) + if damage == 0 || damage > initialHealth || target.health != initialHealth-damage || !player.specialAttackLocks[150].After(time.Now()) || + initialHealth != 1 && target.damageContributors[damageContributor{player: 1}] != damage { + t.Fatalf("committed shot was lost or partially recovered: HP=%d damage=%d lock=%v", target.health, damage, player.specialAttackLocks) + } + if initialHealth == 1 && (target.corpse == nil || target.corpse.looter != 1 || target.corpse.expiresAt.IsZero() || len(restored.npcRespawns) != 1) { + t.Fatal("committed death lost corpse rights, expiry or pending respawn") + } + if initialHealth != 1 && (target.corpse != nil || len(restored.npcRespawns) != 0) { + t.Fatal("living shot created death state") + } + } + + // Retry the original request twice through a newly authenticated session. + output := &combatTestConn{} + restored.clients[1] = &worldClient{id: 1, ready: true, target: true, conn: output, npcs: map[uint32]bool{1000000: true}} + for range 2 { + if err := restored.handleFlingShot(restored.clients[1], flingShotRequest(1, 1000000)[20:]); err != nil { + t.Fatal(err) + } + } + results := 0 + for _, packet := range output.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x754f1115 { + results++ + } + } + if strings.HasPrefix(mode, "before/") && results != 1 || strings.HasPrefix(mode, "after/") && results != 0 { + t.Fatalf("retry published %d special results", results) + } + again := newTestInventoryServer(t) + if target.health >= initialHealth || initialHealth != 1 && target.damageContributors[damageContributor{player: 1}] != initialHealth-target.health || + again.characters[1000000].health != target.health || !again.characters[1].specialAttackLocks[150].Equal(player.specialAttackLocks[150]) || + again.characters[1].inventory.Items[0].Ammo != 3 || again.characters[1].inventory.Items[1].Count != 100 { + t.Fatal("retry lost or duplicated a durable damage, cooldown or ammunition outcome") + } + if initialHealth == 1 && (again.characters[1000000].corpse == nil || again.characters[1000000].corpse.looter != 1 || len(again.npcRespawns) != 1 || + len(again.characters[1000000].damageContributors) != 0 || again.characters[1000000].leadingContributor != (damageContributor{player: 1})) { + t.Fatal("retried kill lost its single corpse or pending respawn") + } + }) + } +}