aorecomp

Anarchy Online classic in the browser

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


commit 37decc5d6fabe3175b4c40219bbbf3022b0be4ef
parent 35fe5017198af83d82bb659b834a1ccfce79b160
Author: anon <anon@example.com>
Date:   Wed,  4 Nov 2026 16:56:32 +0000

Cancel owned pet combat after committed retirement

Diffstat:
MTODO.md | 9+++++++--
Mdocs/pet-dismissal.md | 34++++++++++++++++++++++++++++++++++
Mserver/browser_pet_dismiss_test.go | 30++++++++++++++++++++++++++++--
Aserver/pet_retirement_combat_test.go | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/pets.go | 1+
Mtools/client/test_pet_dismiss.mjs | 22++++++++++++++++++++++
6 files changed, 190 insertions(+), 4 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -3241,12 +3241,17 @@ and unresolved indoor lifecycle are explicit in [flight](docs/vehicles.md#yalmah owners in another playfield receive retirement. Native follow/terminate, real replacement casting, both page reloads and cold recovery retain the other owner's pet and exact costs. See [pet dismissal](docs/pet-dismissal.md). + Retirement now also cancels outgoing/incoming combat after its database + commit, before native destruction. A held-swing WASM reproduction retained + the deleted pet's schedule; cancellation, failure/retry, old-deadline advance + and unaffected replacement now have focused checks. - [ ] [P1] Expire a timed pet. Check: its lifetime ends at the expected point without removing a newer pet or allowing another queued attack. The admitted summon now interprets TimeExist600 as seconds. Ignored retirement writes retry without dropping ownership; cold startup removes expired rows, - and native removal/new-identity replacement pass. Original14.9.1 timer units, - the complete combat lifecycle and queued-attack behavior remain unverified. + and native removal/new-identity replacement pass. Original14.9.1 timer units + and the complete combat lifecycle remain unverified. Committed expiry now + clears both sides' queued combat through the shared retirement path above. - [ ] [P1] Handle the pet owner's disconnect. Check: the documented pet lifecycle policy runs without leaving an active attack on an unavailable owner/target. - [ ] [P1] Give one healing pet a heal command. Check: it heals an eligible target diff --git a/docs/pet-dismissal.md b/docs/pet-dismissal.md @@ -27,6 +27,13 @@ Required deletion uses RETURNING and completes its commit before in-memory ownership, the world entry, saved NPC cache and active expiry list are removed. Failed or ignored writes preserve the complete entity and permit retry. +Committed retirement also uses the shared encounter-cancellation path before +removing the world entry. It clears the pet's outgoing target, swing deadline +and scheduler entry, removes encounter threat against it, and stops opponents +still targeting it. StopFight reaches interested clients before typed Destroy. +Deletion failures leave these transient encounters untouched for retry; no +stop is published before the ownership transaction commits. + After commit, original RemovePet updates native membership, stat251 publishes the remaining packed limit, and a typed Destroy removes the interested actor. Ready observers whose snapshots are still loading receive the queued removal. @@ -64,3 +71,30 @@ results, including concurrent expiry/dismissal and the replacement deadline. All six native traces have no client errors or dropped events. Vet, driver syntax and the packet/ownership checks retained in `local/pet-dismiss/validation.json` pass. + +## Combat during retirement + +A controlled held-swing fixture reproduces a second defect: native terminate +removes the actor and ownership row while its target/deadline and scheduler +entry remain live. The baseline two-client check fails in 17.21 seconds with +`scheduled=true`, target 1 and the original deadline after dismissal. This does +not establish a PT50 weapon binding or historical attack/expiry timing. + +`TestPetRetirementCancelsCombatOnlyAfterCommit` covers dismissal and timed +expiry, mutual queued combat, ignored deletion, cascade failure and deferred +COMMIT failure. Failed attempts preserve database contents, both encounters, +deadlines and output. Successful retry cancels immediately; advancing beyond +both old deadlines produces no weapon result or resource change. Cold loading +retains no retired ownership. + +The extended `TestBrowserPetDismiss` starts a held production-scheduler swing +before real `/pet terminate`. Both native streams must receive StopFight before +Destroy. A real Programs cast creates a new pet; advancing the old deadline +leaves it, the peer, owner resources and ownership unchanged. Both page reloads +and separate fresh-server clients retain the replacement. The setup uses +controlled owners and a held attack, not earned progression or an inferred +original pet combat profile. Evidence and independent checks are retained in +`local/pet-retirement-combat/`. +The live/cold browser phases pass in 24.94/15.47 seconds. The broader pet/threat +suite passes 24 roots/83 results both normally and under race detection; vet and +driver syntax pass. Eight complete native captures have no errors or drops. diff --git a/server/browser_pet_dismiss_test.go b/server/browser_pet_dismiss_test.go @@ -29,6 +29,8 @@ func TestBrowserPetDismiss(t *testing.T) { world = newServerForTest(t) } if !t.Run(phase, func(t *testing.T) { + pet := world.characters[1000001] + var attackDeadline time.Time mux := http.NewServeMux() mux.Handle("/", world.httpHandler()) mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) { @@ -41,7 +43,7 @@ func TestBrowserPetDismiss(t *testing.T) { for pet := range owner.pets { pets = append(pets, pet) } - owners = append(owners, map[string]any{"id": id, "pets": pets, "nano": owner.nano}) + owners = append(owners, map[string]any{"id": id, "pets": pets, "nano": owner.nano, "health": owner.health}) } var rows uint32 if err := world.db.QueryRow("SELECT count(*) FROM pets").Scan(&rows); err != nil { @@ -49,7 +51,30 @@ func TestBrowserPetDismiss(t *testing.T) { http.Error(w, err.Error(), http.StatusInternalServerError) return } - json.NewEncoder(w).Encode(map[string]any{"owners": owners, "savedPets": rows, "nextNPC": world.nextNPC}) + var fighting uint32 + var deadline time.Time + if pet != nil { + fighting, deadline = pet.fighting, pet.nextAttack + } + json.NewEncoder(w).Encode(map[string]any{"owners": owners, "savedPets": rows, "nextNPC": world.nextNPC, + "scheduled": world.fighting[1000001] != nil, "retiredFighting": fighting, "retiredDeadline": deadline}) + }) + // Hold a production-scheduler swing; this does not bind the PT50 weapon. + mux.HandleFunc("POST /test-attack", func(w http.ResponseWriter, r *http.Request) { + world.updateMutex.Lock() + defer world.updateMutex.Unlock() + world.mutex.Lock() + updates := make(map[*worldClient][][]byte) + world.startAttack_locked(pet, world.characters[1], time.Now(), updates) + attackDeadline = pet.nextAttack + world.mutex.Unlock() + world.sendCombatUpdates(updates) + }) + mux.HandleFunc("POST /test-deadline", func(w http.ResponseWriter, r *http.Request) { + world.mutex.Lock() + deadline := attackDeadline + world.mutex.Unlock() + world.advanceCombat(deadline.Add(time.Nanosecond)) }) host := httptest.NewServer(mux) t.Cleanup(host.Close) @@ -85,6 +110,7 @@ func TestBrowserPetDismiss(t *testing.T) { world.mutex.Lock() defer world.mutex.Unlock() if world.characters[1000001] != nil || world.characters[1000002] == nil || world.characters[1000003] == nil || + world.fighting[1000001] != nil || len(world.characters[1].pets) != 1 || len(world.characters[2].pets) != 1 || len(world.petExpiry) != 2 || world.characters[1].nano != 15 || world.characters[2].nano != 25 || world.nextNPC != 1000004 { t.Fatal("dismissal/replacement changed the peer or reused an identity") diff --git a/server/pet_retirement_combat_test.go b/server/pet_retirement_combat_test.go @@ -0,0 +1,98 @@ +package main + +import ( + "bytes" + "encoding/binary" + "fmt" + "testing" + "time" +) + +func TestPetRetirementCancelsCombatOnlyAfterCommit(t *testing.T) { + for _, reason := range []string{"dismissal", "expiry"} { + for _, fault := range []string{"none", "ignored deletion", "cascade failure", "commit failure"} { + t.Run(fmt.Sprintf("%s/%s", reason, fault), func(t *testing.T) { + world, output := newPetSummonWorld(t) + owner, client := world.characters[1], world.clients[1] + world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 0, 0, 53019, 43324})[20:]) + world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) + pet := owner.pets[1000001] + updates := make(map[*worldClient][][]byte) + world.startAttack_locked(pet, owner, time.Now(), updates) + world.startAttack_locked(owner, pet, time.Now(), updates) + pet.threat = map[uint32]int64{owner.id: 10} + pet.nextAttack, owner.nextAttack = pet.pet.expiresAt.Add(time.Second), pet.pet.expiresAt.Add(2*time.Second) + petDeadline, ownerDeadline, health := pet.nextAttack, owner.nextAttack, owner.health + query := "CREATE TRIGGER reject_retirement BEFORE DELETE ON characters WHEN OLD.id=1000001 BEGIN SELECT RAISE(IGNORE); END" + if fault == "cascade failure" { + query = "CREATE TRIGGER reject_retirement BEFORE DELETE ON pets WHEN OLD.npc_id=1000001 BEGIN SELECT RAISE(ABORT,'reject ownership deletion'); END" + } + if fault == "commit failure" { + if _, err := world.db.Exec("CREATE TABLE retirement_commit_failure (id INTEGER REFERENCES characters(id) DEFERRABLE INITIALLY DEFERRED)"); err != nil { + t.Fatal(err) + } + query = "CREATE TRIGGER reject_retirement AFTER DELETE ON characters WHEN OLD.id=1000001 BEGIN INSERT INTO retirement_commit_failure VALUES (999); END" + } + if fault != "none" { + if _, err := world.db.Exec(query); err != nil { + t.Fatal(err) + } + } + retire := func() { + if reason == "expiry" { + world.advanceNanos(pet.pet.expiresAt) + } else if err := world.handlePetCommand(client, petDismissRequest(owner.id)[20:]); err != nil { + t.Fatal(err) + } + } + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + output.packets = nil + + retire() + if fault != "none" { + after, err := readTestItemStore(world) + if err != nil || !bytes.Equal(before, after) || world.characters[pet.id] != pet || owner.pets[pet.id] != pet || + world.fighting[pet.id] != pet || world.fighting[owner.id] != owner || pet.fighting != owner.id || owner.fighting != pet.id || + !pet.nextAttack.Equal(petDeadline) || !owner.nextAttack.Equal(ownerDeadline) || len(output.packets) != 0 { + t.Fatal("failed retirement changed storage, combat or output", err) + } + if _, err := world.db.Exec("DROP TRIGGER reject_retirement"); err != nil { + t.Fatal(err) + } + retire() + } + if world.fighting[pet.id] != nil || world.fighting[owner.id] != nil || pet.fighting != 0 || owner.fighting != 0 || + !pet.nextAttack.IsZero() || !owner.nextAttack.IsZero() { + t.Fatal("committed retirement retained an encounter or future swing") + } + world.advanceCombat(ownerDeadline.Add(time.Second)) + cold := newServerForTest(t) + + if world.characters[pet.id] != nil || owner.pets[pet.id] != nil || cold.characters[pet.id] != nil || len(cold.characters[1].pets) != 0 || + world.fighting[pet.id] != nil || world.fighting[owner.id] != nil || pet.fighting != 0 || owner.fighting != 0 || + !pet.nextAttack.IsZero() || !owner.nextAttack.IsZero() || owner.health != health || owner.nano != 25 || world.nextNPC != 1000002 { + t.Fatal("retired pet retained combat or changed resources/ownership") + } + stopped := map[uint32]bool{} + for _, packet := range output.packets { + opcode := binary.BigEndian.Uint32(packet[16:20]) + if opcode == 0x4a41203e { + stopped[binary.BigEndian.Uint32(packet[24:28])] = true + } + if opcode == 0x36510078 && (!stopped[owner.id] || !stopped[pet.id]) { + t.Fatal("native destruction preceded encounter cancellation") + } + if opcode == 0x46002f16 || opcode == 0x5c654b28 { + t.Fatal("retired encounter emitted a weapon result") + } + } + if len(stopped) != 2 { + t.Fatal("retirement omitted either participant's native stop") + } + }) + } + } +} diff --git a/server/pets.go b/server/pets.go @@ -184,6 +184,7 @@ func (server *server) retirePet_locked(pet *character, updates map[*worldClient] return err } + server.cancelCombat_locked(pet.id, updates) owner := server.characters[pet.pet.owner] delete(owner.pets, pet.id) delete(server.characters, pet.id) diff --git a/tools/client/test_pet_dismiss.mjs b/tools/client/test_pet_dismiss.mjs @@ -47,6 +47,13 @@ try { event.direction === 'framereceived' && event.opcode === '260f3671' && Buffer.from(event.hex, 'hex').readUInt32BE(24) === 1000001)); const start = owner.local().position; await owner.hold('KeyW', 'owner moves three metres with its follower', snapshot => owner.local(snapshot).position[2] > start[2] + 3); + assert((await owner.page.request.post(url + '/test-attack')).ok()); + await Promise.all(games.map(game => game.wait('held pet swing is visible before dismissal', () => actor(game, 1000001).combatTarget === 1))); + evidence.attacking = await state(); + assert.equal(evidence.attacking.scheduled, true); + assert.equal(evidence.attacking.retiredFighting, 1); + await Promise.all(games.map((game, index) => game.save(output + '/attacking-' + index))); + const dismissedSequence = games.map(game => game.sequence); await command('terminate', 10); await Promise.all(games.map(game => game.wait('owned pet retires while the peer remains', () => !actor(game, 1000001) && actor(game, 1000002) && actor(game, 1).stats[458] === 0 && actor(game, 1).stats[251] === 0))); @@ -54,6 +61,15 @@ try { assert.deepEqual(evidence.dismissed.owners.map(owner => owner.pets), [[], [1000002]]); assert.deepEqual(evidence.dismissed.owners.map(owner => owner.nano), [25, 25]); assert.equal(evidence.dismissed.savedPets, 1); + assert.equal(evidence.dismissed.scheduled, false); + assert.equal(evidence.dismissed.retiredFighting, 0); + assert.equal(evidence.dismissed.retiredDeadline, '0001-01-01T00:00:00Z'); + games.forEach((game, index) => { + const transitions = game.events.filter(event => event.sequence > dismissedSequence[index] && + event.direction === 'framereceived' && ['4a41203e', '36510078'].includes(event.opcode) && + Buffer.from(event.hex, 'hex').readUInt32BE(24) === 1000001); + assert.deepEqual(transitions.map(event => event.opcode), ['4a41203e', '36510078']); + }); evidence.removals = games.map(game => game.events.filter(event => { if (event.direction !== 'framereceived' || !['58742a0f', '36510078'].includes(event.opcode)) return false; const packet = Buffer.from(event.hex, 'hex'); @@ -73,6 +89,12 @@ try { await Promise.all(games.map(game => game.wait('replacement uses a new owned identity', () => actor(game, 1000003) && !actor(game, 1000001) && actor(game, 1).stats[458] === 1))); evidence.replacement = await state(); + assert((await owner.page.request.post(url + '/test-deadline')).ok()); + evidence.afterDeadline = await state(); + assert.deepEqual(evidence.afterDeadline, evidence.replacement); + assert.deepEqual(evidence.afterDeadline.owners.map(owner => owner.health), evidence.attacking.owners.map(owner => owner.health)); + games.forEach((game, index) => assert(!game.events.some(event => event.sequence > dismissedSequence[index] && + event.direction === 'framereceived' && ['46002f16', '5c654b28'].includes(event.opcode)))); await Promise.all(games.map(async game => { await game.page.reload(); await game.ready(); await game.snapshot(); })); } await Promise.all(games.map(game => game.wait('replacement and peer replay once', () =>