aorecomp

Anarchy Online classic in the browser

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


commit 74933ebbf38ec4e5ace8ba0cabe5a40f32cf12eb
parent 35e5477ed3a60d9ad462d4c6ae2b8d165ec30078
Author: anon <anon@example.com>
Date:   Wed,  4 Nov 2026 22:43:45 +0000

Close stale backpack splits after nonstackable source replacement

Diffstat:
MTODO.md | 12++++++++++++
Mdocs/backpacks.md | 23+++++++++++++++++++++++
Mserver/backpacks.go | 9+++++++--
Aserver/browser_replaced_backpack_split_test.go | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/replaced_backpack_split_test.go | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/client/test_replaced_backpack_split.mjs | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 284 insertions(+), 2 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -4556,6 +4556,18 @@ and server restarts. Turn every reproduced bug into a focused regression test. checks pass 44 roots/124 results, focused race checks pass 5/19, and ten native traces are clean. See [session and destination refusals](docs/backpacks.md#session-and-destination-policy-refusals) and `local/backpack-refusals/verification-summary.json`. +- [x] [P0] Correct an optimistic split after an open backpack's stack is replaced + by a nonstackable item. Reproduction: retain the original three-charge native + row while a controlled earlier transfer swaps its source with a retained + pistol, then Ctrl-click that stale row. Check: close the stale window without + allocating a clone or changing either item's ownership, permit normal reopening + and use of both actual sources, and retain exact IDs, charges and loaded + ammunition after page reconnect and cold loading. The unchanged native handler + reproduces the phantom; contents alone do not correct it. Session/window closure + now passes the 19.47-second WASM check, both slot boundaries and repeated + refusal with an unchanged pending equip/deadline and no writes/allocation. + This is a focused disappearance-audit fixture, not earned progression. See + [replaced split sources](docs/backpacks.md#optimistic-splits-after-source-replacement). - [x] [P0] Correct an optimistic backpack split after its server session closes. A controlled stale native window sends action52, leaves an unowned child row and holds its selected source, while durable ownership still has the original diff --git a/docs/backpacks.md b/docs/backpacks.md @@ -346,6 +346,29 @@ Ten related roots / 40 results and two focused race roots / 13 results pass, along with maintained-package vet. An independent packet/ownership audit checks both native recoveries and all eight error/drop-free stage traces. +### Optimistic splits after source replacement + +An open bag can retain a three-charge stack's native row after a controlled +earlier transfer replaces that source with a nonstackable pistol. Real Ctrl-click +then creates an unowned split row. The original handler silently ignored it; +an authoritative contents refresh alone also leaves the selected split and clone. +The server now closes that known bag's session/window before the pending-equipment +guard. Repeated refusal preserves all ownership, allocation and any separate +equipment move/deadline without checkpoint writes. + +`TestBrowserReplacedBackpackSplit` reproduces the failure on the unchanged handler +in 20.95 seconds. The corrected check takes 19.47 seconds: normal placement +refusal clears the selected stale source, ordinary Use reopens the actual pistol, +and normal withdrawals recover both it and the original stack from the other bag. +Page replay and cold loading retain four exact IDs, three laboratory charges and +three loaded rounds. Public-handler checks cover slots 0/20 and a separate +admitted equip. These are controlled missed-refresh fixtures, not earned +progression or evidence of original-server refusal packets. The retained baseline, +refresh-only failure and final captures are under `local/replaced-backpack-split/`. +Related Go coverage passes 49 roots / 339 results; focused race checks pass +three roots / 18 results. The independent audit matches the exact close packet, +native identities, selected endpoints and four clean stage traces. + ## Stale withdrawal sources A known carried bag can have an empty slot behind a stale native window. The diff --git a/server/backpacks.go b/server/backpacks.go @@ -448,14 +448,19 @@ func (server *server) handleBackpackAction_locked(client *worldClient, body []by } return nil } + items := player.inventory.Containers[handle.id] + index := slices.IndexFunc(items, func(item ownedItem) bool { return item.Slot == position&65535 }) + if action == 52 && index >= 0 && !items[index].isStackable() { + // Contents alone cannot remove an optimistic split of a replaced source. + client.backpacks[position>>16] = backpackHandle{handle.id, false} + return client.send(backpackClosePacket(client.id, handle.id)) + } if client.equipment != nil { if action == 52 { return server.syncStackPage_locked(client, 107, handle.id) } return nil } - items := player.inventory.Containers[handle.id] - index := slices.IndexFunc(items, func(item ownedItem) bool { return item.Slot == position&65535 }) if action == 53 && binary.BigEndian.Uint32(body[28:32]) == 107 { // A missed merge refresh can leave either side in the open bag's old view. otherPosition := binary.BigEndian.Uint32(body[32:36]) diff --git a/server/browser_replaced_backpack_split_test.go b/server/browser_replaced_backpack_split_test.go @@ -0,0 +1,95 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "testing" + "time" +) + +func TestBrowserReplacedBackpackSplit(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for replaced backpack split") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/replaced-backpack-split", time.Now().Format("20060102-150405")) + world := newTestServer(t) + player := world.newCharacter() + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("replaced-backpack-split"))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + inventory := playerInventory{LastID: 4, Items: []ownedItem{ + {ID: 1, Type: 51017, Template: 99228, Quality: 1, Slot: 64, Count: 1}, + {ID: 3, Type: 51017, Template: 99228, Quality: 1, Slot: 65, Count: 1}}, + Containers: map[uint32][]ownedItem{1: { + {ID: 2, Type: 51005, Template: 25812, Quality: 2, Slot: 0, Count: 3}}, 3: { + {ID: 4, Type: 51018, Template: 123742, Quality: 2, Slot: 0, Count: 1, Ammo: 3}}}} + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + 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{"inventory": player.inventory, "open": world.clients[1].backpacks[1].open}) + }) + // Commit an earlier transfer while retaining the old native source view. + mux.HandleFunc("POST /test-move-source", func(w http.ResponseWriter, r *http.Request) { + world.updateMutex.Lock() + defer world.updateMutex.Unlock() + world.mutex.Lock() + defer world.mutex.Unlock() + inventory := player.inventory + inventory.Containers = map[uint32][]ownedItem{1: slices.Clone(inventory.Containers[3]), 3: slices.Clone(inventory.Containers[1])} + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Error(err) + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + }) + host := httptest.NewServer(mux) + t.Cleanup(host.Close) + closeTestBrowserStreams(t, world) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_replaced_backpack_split.mjs"), host.URL, output) + command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr + err := command.Run() + + t.Logf("Browser artifacts: %s", output) + if err != nil { + t.Fatal(err) + } + cold := newTestInventoryServer(t) + expected := []ownedItem{{ID: 1, Type: 51017, Template: 99228, Quality: 1, Slot: 64, Count: 1}, + {ID: 2, Type: 51005, Template: 25812, Quality: 2, Slot: 67, Count: 3}, + {ID: 3, Type: 51017, Template: 99228, Quality: 1, Slot: 65, Count: 1}, + {ID: 4, Type: 51018, Template: 123742, Quality: 2, Slot: 66, Count: 1, Ammo: 3}} + for _, current := range []*character{player, cold.characters[1]} { + if len(current.inventory.Items) != 4 || len(current.inventory.Containers) != 0 || + current.inventory.Credits != 0 || current.inventory.LastID != 4 { + t.Fatal("stale split changed quantities, cash or allocation", current.inventory) + } + for _, item := range expected { + if !slices.Contains(current.inventory.Items, item) { + t.Fatal("stale split recovery lost an exact instance", current.inventory) + } + } + } + if world.nextItem != 4 || cold.nextItem != 4 { + t.Fatal("refused split allocated an identity or retry repeated allocation") + } +} diff --git a/server/replaced_backpack_split_test.go b/server/replaced_backpack_split_test.go @@ -0,0 +1,63 @@ +package main + +import ( + "bytes" + "fmt" + "reflect" + "testing" +) + +func TestReplacedBackpackSplitClosesWithoutWriting(t *testing.T) { + for _, slot := range []uint32{0, 20} { + for _, pending := range []bool{false, true} { + t.Run(fmt.Sprintf("slot%d/pending%v", slot, pending), func(t *testing.T) { + world, output := newStackWorld(t) + player, client := world.characters[1], world.clients[1] + inventory := playerInventory{LastID: 5, Items: []ownedItem{ + {ID: 1, Type: 51017, Template: 99228, Quality: 1, Slot: 64, Count: 1}, + {ID: 3, Type: 51017, Template: 99228, Quality: 1, Slot: 65, Count: 1}, + {ID: 5, Type: 51018, Template: 121567, Quality: 1, Slot: 66, Count: 1}}, + Containers: map[uint32][]ownedItem{ + 1: {{ID: 4, Type: 51018, Template: 123742, Quality: 2, Slot: slot, Count: 1, Ammo: 3}}, + 3: {{ID: 2, Type: 51005, Template: 25812, Quality: 2, Slot: 0, Count: 3}}}} + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]); err != nil { + t.Fatal(err) + } + var move *equipmentMove + if pending { + if err := world.handleInventory(client, inventoryMovePacket(1, 66, 6)[20:]); err != nil || client.equipment == nil { + t.Fatal("fixture did not admit its separate weapon move", err) + } + copy := *client.equipment + move = &copy + } + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + auditCheckpointWrites(t, world) + output.packets = nil + request := characterActionPacket(1, [5]uint32{52, 107, 65536 + slot, 0, 1})[20:] + + for range 2 { + if err := world.handleInventory(client, request); err != nil { + t.Fatal(err) + } + } + after, err := readTestItemStore(world) + cold := newTestInventoryServer(t) + + close := targetPacket(backpackClosePacket(1, 1)) + if err != nil || !bytes.Equal(before, after) || len(checkpointWrites(t, world)) != 0 || + !reflect.DeepEqual(player.inventory, cold.characters[1].inventory) || !reflect.DeepEqual(client.equipment, move) || + world.nextItem != 5 || cold.nextItem != 5 || client.backpacks[1] != (backpackHandle{1, false}) || + !reflect.DeepEqual(output.packets, [][]byte{close, close}) { + t.Fatal("replaced-source split changed storage, allocation, handle or authoritative correction", err) + } + }) + } + } +} diff --git a/tools/client/test_replaced_backpack_split.mjs b/tools/client/test_replaced_backpack_split.mjs @@ -0,0 +1,84 @@ +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']}); +let game; +const evidence = {}; +try { + const context = await browser.newContext({viewport: {width: 1024, height: 768}}); + await context.addCookies([{name: 'ao_client', value: 'replaced-backpack-split', url}]); + const page = await context.newPage(); + game = await GameTest.attach(page); + await page.goto(url); + await game.ready(); + const server = async () => (await page.request.get(url + '/test-state')).json(); + const cell = position => game.state.grids.flatMap(grid => grid.cells).find(cell => + cell.identity[0] === 107 && cell.identity[1] === position && !cell.dummy); + const click = async source => { + assert(source, 'the exact native source must be usable'); + await game.click((source.bounds[0] + source.bounds[2]) / 2, (source.bounds[1] + source.bounds[3]) / 2); + }; + await game.key('KeyI'); + await game.click(681, 45, 'right'); + await game.wait('original stack opens', () => cell(65536)); + evidence.initial = await server(); + assert((await page.request.post(url + '/test-move-source')).ok()); + evidence.replaced = await server(); + assert.equal(evidence.replaced.open, true); + assert.equal(evidence.replaced.inventory.Containers[1][0].ID, 4); + assert.equal(evidence.replaced.inventory.Containers[3][0].ID, 2); + const sequence = game.sequence; + await page.keyboard.down('Control'); + try { await click(cell(65536)); } finally { await page.keyboard.up('Control'); } + await game.wait('real split from the replaced source', () => game.events.some(event => event.sequence > sequence && + event.direction === 'framesent' && event.opcode === '5e477770' && Buffer.from(event.hex, 'hex').readUInt32BE(29) === 52)); + await game.save(output + '/requested'); + await game.wait('replaced-source split window closes', state => + !state.grids.some(grid => grid.cells.some(cell => cell.identity[0] === 107))); + assert(game.events.some(event => event.sequence > sequence && event.direction === 'framereceived' && event.opcode === '2049527c')); + if (game.state.dragged[0] !== 0) { + await game.click(789, 45); + await game.wait('selected stale source placement refuses', state => state.dragged[0] === 0); + } + evidence.refused = await server(); + assert.deepEqual(evidence.refused, {...evidence.replaced, open: false}); + await game.save(output + '/refused'); + + // Reopen current contents and withdraw both actual items through normal input. + await game.click(681, 45, 'right'); + await game.wait('actual replacement pistol opens', () => cell(65536)); + assert(!cell(65537)); + await click(cell(65536)); + await game.click(789, 45); + await game.wait('actual replacement pistol withdrawn', state => game.local(state).inventory.some(item => + item.id === 4 && item.slot === 50 && item.count === 1)); + await game.click(735, 45, 'right'); + await game.wait('retained stack opens in its actual bag', () => cell(131072)); + await click(cell(131072)); + await click(game.state.grids.find(grid => grid.totalCells === 30).cells.find(cell => cell.identity[0] === 0)); + await game.wait('retained three-charge stack withdrawn', state => game.local(state).inventory.some(item => + item.id === 2 && item.slot === 51 && item.count === 3)); + evidence.recovered = await server(); + assert.equal(evidence.recovered.inventory.Containers, null); + assert.equal(evidence.recovered.inventory.LastID, 4); + await game.save(output + '/recovered'); + await page.reload(); + await game.ready(); + assert.deepEqual(game.local().inventory.map(item => [item.id, item.slot, item.quality, item.count]).sort((a, b) => a[0] - b[0]), + [[1, 48, 1, 1], [2, 51, 2, 3], [3, 49, 1, 1], [4, 50, 2, 1]]); + assert.deepEqual((await server()).inventory, evidence.recovered.inventory); + assert.deepEqual(game.errors, []); + console.log('PASS: replaced-source split closes its stale window and retains four IDs, three charges and three loaded rounds through reopening, normal withdrawals and page/cold recovery'); +} finally { + try { + await fs.mkdir(output, {recursive: true}); + await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2) + '\n'); + if (game) await game.save(output + '/final'); + } finally { await browser.close(); } +}