commit 93b6e60b8bb96910ab37a7a4ad4fdff21b902963
parent 3241e6afbdada88c1c710d46d5aeefc8bf2a475b
Author: anon <anon@example.com>
Date: Wed, 4 Nov 2026 19:47:30 +0000
Clear stale corpse rows after another looter commits pickup
Diffstat:
7 files changed, 281 insertions(+), 3 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -4757,6 +4757,15 @@ and server restarts. Turn every reproduced bug into a focused regression test.
untaken gloves expired before pickup committed. Evidence:
[earned creature upgrades](docs/earned-creature-upgrade.md) and
`local/earned-creature-upgrade/`.
+- [x] [P0] Remove stale corpse source rows after another entitled player collects
+ an item. Reproduction: two native team members open one corpse, then one
+ collects its item while the other's mouse gesture is pending. An empty
+ contents refresh left the old row selectable and repeated clicks still
+ issued pickup requests. Explicit removal now follows the ownership commit.
+ Failed-write retention, nonzero-slot isolation, stale-request correction,
+ same-window native retry and exact page/cold ownership pass. The focused WASM
+ check takes26 seconds; the broader corpse audit stays open. See
+ [other open loot windows](docs/corpse-loot.md#other-open-loot-windows).
- [x] [P0] Roll back corpse cash collection when a required NPC checkpoint write
is ignored. The baseline committed wallet 373 while cold corpse cash remained 123,
enabling another award after restart. Require returned rows from both prepared
diff --git a/docs/corpse-loot.md b/docs/corpse-loot.md
@@ -165,6 +165,35 @@ same-window retry; page replay and cold loading retain the first looter's
31 instances and the original corpse credit. This is controlled failure-path evidence,
rather than earned-progression evidence.
+## Other open loot windows
+
+An InventoryUpdate for an already open corpse does not remove rows absent from
+its new contents. Two entitled native members reproduced a selectable phantom:
+after member2 collected the only item, member1 received an empty update but a
+later click still emitted a pickup request. Neither durable ownership nor cash
+was duplicated; the stale native source remained usable until corrected.
+
+Successful pickup now sends CharacterAction112/page107/exact source slot to
+other eligible open windows before refreshing their remaining contents. Both
+messages follow the ownership commit. A request for an already empty slot gets
+146 to cancel its drag, then112 to remove the stale row, then the contents update.
+Full-inventory and pending-equipment refusals retain their actually owned source.
+
+`TestCorpsePeerPickupClearsOnlyTheCommittedSource` verifies ignored-write
+retention, nonzero-slot removal, remaining contents and exact cold item/cash
+ownership. `TestLootStaleSlotCancelsPickupWithoutDuplicatingTransfer` checks the
+stale-request correction. `TestBrowserCorpsePeerPickupClearsNativeSource` uses
+two native clients and one controlled corpse: member2 collects during member1's
+real mouse gesture; release and another click must emit no phantom pickup.
+The window stays open, page replay retains exact identity/quality/count/location,
+and Go cold loading accounts for the item, both wallets and the allocator.
+This is controlled-fixture evidence, not earned progression or historical loot
+probability. Captures and the baseline are in `local/corpse-peer-pickup/`.
+The related Go suite passes121 roots/672 results in168.645 seconds; race checks
+pass11 roots/19 results in133.787 seconds. The final native check passes in25.63
+seconds, compared with the16.06-second failing baseline. All six baseline/final
+captures have no native errors or dropped events. Vet and driver syntax pass.
+
A pickup arriving during an admitted equipment move also receives
CharacterAction146 and refreshed contents, without changing the equipment
deadline or closing the corpse. Ignoring it leaves the native source icon
diff --git a/server/browser_corpse_peer_pickup_test.go b/server/browser_corpse_peer_pickup_test.go
@@ -0,0 +1,94 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "slices"
+ "testing"
+ "time"
+)
+
+func TestBrowserCorpsePeerPickupClearsNativeSource(t *testing.T) {
+ if os.Getenv("AO_GAME_TEST") != "1" {
+ t.Skip("set AO_GAME_TEST=1 for native concurrent corpse pickup")
+ }
+
+ _, source, _, _ := runtime.Caller(0)
+ root := filepath.Dir(filepath.Dir(source))
+ output := filepath.Join(root, "local/corpse-peer-pickup", time.Now().Format("20060102-150405"))
+ world := newTestServer(t)
+ players := make(map[uint32]*character)
+ for index, x := range []float32{958, 962} {
+ player := world.newCharacter()
+ player.name = fmt.Sprintf("Lootpeer%d", index+1)
+ player.playfield, player.position = 705, [3]float32{x, 16.5, 511}
+ player.rotation = [4]float32{0, 0, 0, 1}
+ player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprintf("corpse-peer-%d", player.id))))
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ players[player.id] = player
+ }
+ world.characters = players
+ if err := world.saveTeam_locked(nil, &playerTeam{leader: 1, members: []uint32{1, 2}}); err != nil {
+ t.Fatal(err)
+ }
+ world.characters[1000000] = &character{id: 1000000, name: "Shared Leet", npc: true, level: 1,
+ playfield: 705, position: [3]float32{960, 16.5, 514}, rotation: [4]float32{0, 0, 0, 1}, health: 1,
+ appearance: 229, monsterData: 17655, npcDefinitionID: "950/district/2/group/0/authored_point",
+ combatProfile: gamedata.NPCCombatProfiles[17655][1]}
+ world.clients[1] = &worldClient{id: 1, target: true, ready: true, conn: &combatTestConn{}, npcs: map[uint32]bool{1000000: true}}
+ world.combatRoll = func(uint32) uint32 { return 0 }
+ if err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceCombat(players[1].nextAttack)
+ corpse := world.characters[1000000].corpse
+ if corpse == nil || len(corpse.items) != 1 {
+ t.Fatal("controlled killing blow did not generate one item")
+ }
+ item := corpse.items[0]
+ corpse.expiresAt = time.Now().Add(10 * time.Minute)
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ delete(world.clients, 1)
+ mux := http.NewServeMux()
+ mux.Handle("/", world.httpHandler())
+ mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) {
+ world.mutex.Lock()
+ defer world.mutex.Unlock()
+ json.NewEncoder(w).Encode(map[string]any{"first": players[1].inventory, "second": players[2].inventory,
+ "items": corpse.items, "credits": corpse.credits})
+ })
+ host := httptest.NewServer(mux)
+ t.Cleanup(host.Close)
+ closeTestBrowserStreams(t, world)
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
+ defer cancel()
+
+ t.Logf("Browser artifacts: %s", output)
+ command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_corpse_peer_pickup.mjs"), host.URL, output)
+ command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr
+ err := command.Run()
+
+ if err != nil {
+ t.Fatal(err)
+ }
+ cold := newTestInventoryServer(t)
+ item.Slot = 64
+ if len(cold.characters[1].inventory.Items) != 0 || !slices.Equal(cold.characters[2].inventory.Items, []ownedItem{item}) ||
+ cold.characters[1].inventory.Credits != 1 || cold.characters[2].inventory.Credits != 0 ||
+ len(cold.characters[1000000].corpse.items) != 0 || cold.characters[1000000].corpse.credits != 0 || cold.nextItem != item.ID {
+ t.Fatal("peer pickup changed exact cold ownership, cash or allocation")
+ }
+}
diff --git a/server/corpse_peer_pickup_test.go b/server/corpse_peer_pickup_test.go
@@ -0,0 +1,57 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "slices"
+ "testing"
+)
+
+func TestCorpsePeerPickupClearsOnlyTheCommittedSource(t *testing.T) {
+ world := newTeamLootWorld(t)
+ corpse := world.characters[1000000]
+ corpse.corpse.items = append(corpse.corpse.items, ownedItem{ID: 18, Type: 51005, Template: 42640, Quality: 2, Slot: 7, Count: 1})
+ world.nextItem = 18
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ for _, id := range []uint32{1, 2} {
+ if err := world.handleLootUse(world.clients[id], teamLootUse(id, 1)); err != nil {
+ t.Fatal(err)
+ }
+ world.clients[id].conn.(*combatTestConn).packets = nil
+ }
+ if _, err := world.db.Exec("CREATE TRIGGER ignore_peer_pickup BEFORE DELETE ON item_locations WHEN OLD.item_id=18 BEGIN SELECT RAISE(IGNORE); END"); err != nil {
+ t.Fatal(err)
+ }
+ request := teamLootTake(2)
+ binary.BigEndian.PutUint32(request[20:24], 7)
+
+ failed := world.handleInventory(world.clients[2], request)
+ if failed == nil || len(corpse.corpse.items) != 2 || len(world.characters[2].inventory.Items) != 0 ||
+ len(world.clients[1].conn.(*combatTestConn).packets) != 0 || len(world.clients[2].conn.(*combatTestConn).packets) != 0 {
+ t.Fatal("failed pickup removed a native source or changed ownership", failed)
+ }
+ if _, err := world.db.Exec("DROP TRIGGER ignore_peer_pickup"); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleInventory(world.clients[2], request); err != nil {
+ t.Fatal(err)
+ }
+ cold := newTestInventoryServer(t)
+
+ remaining := []ownedItem{{ID: 17, Type: 51005, Template: 42640, Quality: 1, Count: 1}}
+ for _, current := range []*server{world, cold} {
+ if !slices.Equal(current.characters[1000000].corpse.items, remaining) ||
+ !slices.Equal(current.characters[2].inventory.Items, []ownedItem{{ID: 18, Type: 51005, Template: 42640, Quality: 2, Slot: 64, Count: 1}}) ||
+ len(current.characters[1].inventory.Items) != 0 || current.characters[1].inventory.Credits != 123 ||
+ current.characters[2].inventory.Credits != 0 || current.characters[1000000].corpse.credits != 0 || current.nextItem != 18 {
+ t.Fatal("peer pickup changed the remaining source, physical owner, cash or allocator")
+ }
+ }
+ packets := world.clients[1].conn.(*combatTestConn).packets
+ if len(packets) != 2 || !bytes.Equal(packets[0], targetPacket(characterActionPacket(1, [5]uint32{112, 107, 7}))) ||
+ !bytes.Equal(packets[1], targetPacket(lootInventoryPacket(1, corpse, false))) {
+ t.Fatal("other open window did not remove only the committed row before refreshing its remaining contents")
+ }
+}
diff --git a/server/loot.go b/server/loot.go
@@ -229,6 +229,9 @@ func (server *server) takeLoot_locked(client *worldClient, body []byte) error {
if err := client.send(characterActionPacket(client.id, [5]uint32{146, 107, binary.BigEndian.Uint32(body[20:24])})); err != nil {
return err
}
+ if err := client.send(characterActionPacket(client.id, [5]uint32{112, 107, binary.BigEndian.Uint32(body[20:24])})); err != nil {
+ return err
+ }
return client.send(lootInventoryPacket(client.id, corpse, false))
}
player := server.characters[client.id]
@@ -287,6 +290,11 @@ func (server *server) takeLoot_locked(client *worldClient, body []byte) error {
// Other eligible open windows must lose the same icon after the commit.
for _, other := range server.clients {
if other != client && other.ready && !other.loading && other.lootCorpse == corpse.id && server.canLoot_locked(other, corpse) {
+ // Contents updates do not remove absent rows from an already open Chest.
+ if err := other.send(characterActionPacket(other.id, [5]uint32{112, 107, binary.BigEndian.Uint32(body[20:24])})); err != nil {
+ other.disconnect(other.conn)
+ continue
+ }
if err := other.send(lootInventoryPacket(other.id, corpse, false)); err != nil {
other.disconnect(other.conn)
}
diff --git a/server/loot_refusal_test.go b/server/loot_refusal_test.go
@@ -121,13 +121,14 @@ func TestLootStaleSlotCancelsPickupWithoutDuplicatingTransfer(t *testing.T) {
!slices.Equal(cold.characters[1].inventory.Items, expected) || len(cold.characters[1000000].corpse.items) != 0 {
t.Fatal("stale pickup duplicated, lost or changed its already transferred item", err)
}
- if client.lootCorpse != 1000000 || len(conn.packets) != 2 ||
+ if client.lootCorpse != 1000000 || len(conn.packets) != 3 ||
binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x5e477770 ||
binary.BigEndian.Uint32(conn.packets[0][29:33]) != 146 ||
binary.BigEndian.Uint32(conn.packets[0][33:37]) != 107 ||
binary.BigEndian.Uint32(conn.packets[0][37:41]) != 2 ||
- binary.BigEndian.Uint32(conn.packets[1][16:20]) != 0x4e536976 ||
- binary.BigEndian.Uint32(conn.packets[1][29:33]) != 1009 {
+ !bytes.Equal(conn.packets[1], targetPacket(characterActionPacket(1, [5]uint32{112, 107, 2}))) ||
+ binary.BigEndian.Uint32(conn.packets[2][16:20]) != 0x4e536976 ||
+ binary.BigEndian.Uint32(conn.packets[2][29:33]) != 1009 {
t.Fatal("stale pickup did not cancel the pending move and refresh its empty source")
}
}
diff --git a/tools/client/test_corpse_peer_pickup.mjs b/tools/client/test_corpse_peer_pickup.mjs
@@ -0,0 +1,80 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+import {createRequire} from 'node:module';
+import {GameTest} from './game_test.mjs';
+
+const {chromium} = createRequire(import.meta.url)('playwright');
+const [url, output] = process.argv.slice(2);
+const browser = await chromium.launch({executablePath: '/usr/bin/chromium',
+ args: ['--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage',
+ '--disable-background-timer-throttling', '--disable-renderer-backgrounding']});
+const games = [];
+const evidence = {};
+try {
+ for (let id = 1; id <= 2; ++id) {
+ const context = await browser.newContext({viewport: {width: 1024, height: 768}});
+ await context.addCookies([{name: 'ao_client', value: 'corpse-peer-' + id, url}]);
+ const page = await context.newPage();
+ const game = await GameTest.attach(page);
+ games.push(game);
+ await page.goto(url);
+ await game.ready();
+ await game.click(...await game.pick(51050, 1000000), 'right');
+ await game.wait('shared corpse source', state => state.grids.some(grid => grid.cells.some(cell =>
+ cell.identity[0] === 107 && cell.identity[1] === 0 && !cell.dummy)));
+ }
+ const [first, second] = games;
+ const server = async () => (await first.page.request.get(url + '/test-state')).json();
+ evidence.before = await server();
+ assert.equal(evidence.before.items.length, 1);
+
+ // The other native client commits pickup during this real mouse gesture.
+ const point = await first.point(30, 45);
+ await first.page.bringToFront();
+ await first.page.mouse.move(point.x, point.y);
+ const sequence = first.sequence;
+ await first.page.mouse.down();
+ try {
+ await first.waitInput(sequence, 1025);
+ await second.click(30, 45);
+ await second.wait('recipient owns the item', state => second.local(state).inventory.length === 1);
+ await first.wait('other open window receives committed contents', () => first.events.some(event =>
+ event.sequence > sequence && event.direction === 'framereceived' && event.opcode === '4e536976' &&
+ Buffer.from(event.hex, 'hex').readUInt32BE(29) === 1009));
+ } finally {
+ const release = first.sequence;
+ await first.page.mouse.up();
+ await first.waitInput(release, 1026);
+ }
+
+ // An empty refresh must remove the selectable source, not leave a phantom.
+ await first.click(30, 45);
+ await first.snapshot();
+ evidence.staleRequests = first.events.filter(event => event.sequence > sequence &&
+ event.direction === 'framesent' && event.opcode === '47537a24').length;
+ evidence.after = await server();
+ await first.save(output + '/empty-peer-window');
+ assert.equal(evidence.staleRequests, 0, 'The collected source must no longer issue pickup requests');
+ assert.equal(first.local().inventory.length, 0);
+ assert(first.state.regions.some(region => region[0] === 0 && region[1] === 0 && region[2] === 178 && region[3] === 128));
+ assert.deepEqual(evidence.after.items, []);
+ assert.equal(evidence.after.first.Credits, 1);
+ assert.equal(evidence.after.second.Credits, 0);
+ assert.deepEqual(evidence.after.second.Items.map(item => item.ID), evidence.before.items.map(item => item.ID));
+
+ for (const game of games) {
+ await game.page.reload();
+ await game.ready();
+ assert.deepEqual(game.local().inventory.map(item =>
+ [item.type, item.id, item.slot, item.quality, item.templates, item.count]),
+ game === second ? [[51005, 1, 48, 1, [42640, 42640], 1]] : []);
+ assert.deepEqual(game.errors, []);
+ }
+ console.log('PASS: peer pickup clears a selectable corpse source during a native mouse gesture; page/cold ownership stays exact');
+} finally {
+ try {
+ await fs.mkdir(output, {recursive: true});
+ await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2) + '\n');
+ for (let index = 0; index < games.length; ++index) await games[index].save(output + '/final-' + (index + 1));
+ } finally { await browser.close(); }
+}