aorecomp

Anarchy Online classic in the browser

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


commit 757732b221ea6843b3aa4427840a036d4c8de230
parent 99bd2d9de997b9f1989107d9cddf6f116be90cc6
Author: anon <anon@example.com>
Date:   Wed,  4 Nov 2026 00:41:19 +0000

Restore owned stacks after joins target an empty stale slot

Diffstat:
MTODO.md | 8++++++++
Mdocs/inventory-stacks.md | 34++++++++++++++++++++++++++++++++++
Aserver/browser_stale_stack_join_test.go | 86+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/inventory.go | 14++++++++++++++
Aserver/stale_stack_join_test.go | 92+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/client/test_stale_stack_join.mjs | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 319 insertions(+), 0 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -4041,6 +4041,14 @@ and server restarts. Turn every reproduced bug into a focused regression test. both directions during wear/removal without writes or deadline changes. No product defect reproduced on this path; see [backpack joins](docs/backpacks.md#stack-join-during-pending-equipment). +- [x] [P0] Restore a still-owned ordinary stack after joining onto a stale empty + target. A controlled earlier merge without native refresh leaves a seven-charge + source hidden after its real join receives no reply, although storage retains + all fifteen charges. Source restoration and authoritative selected-QL rows now + pass without writes or false join success. A17.74-second WASM check verifies a + same-window valid retry, page and cold recovery of the final identity and all + charges; invalid/unowned sources remain ignored. See + [stale stack joins](docs/inventory-stacks.md#stale-ordinary-join-targets). - [x] Explicitly refuse owned-item Use during pending equipment. Reproduction: real backpack Use after the local equip animation receives no response while server completion remains pending. Completion: matching Use failure, unchanged diff --git a/docs/inventory-stacks.md b/docs/inventory-stacks.md @@ -238,6 +238,40 @@ vet is clean. The native check completes in 19.25 seconds with three clean, complete traces. Captures, baseline failures, source hashes and limits are in `local/pending-stack/verification-summary.json`. +## Stale ordinary join targets + +A controlled missed refresh reproduces a hidden ordinary source without changing +ownership. Three QL2 laboratories start with3/5/7 charges. An earlier committed +merge retires ID1 into ID2, leaving8 charges in slot65 and ID3's7 charges in slot66. +The native window still shows the old target in slot64. Dragging the real source +onto it sends action53 and empties the cursor, but the missing target previously +caused a silent return. The seven-charge source stayed dummy/hidden; both surviving +instances and all fifteen charges remained in storage. + +The handler now validates the removed source as an owned ordinary stack, restores +its GUI entry through the existing two ContainerAddItem swaps, then uses the +ordinary-stack rebuild described above. This removes the stale target and sends +the authoritative selected endpoints, QL and counts. It writes no inventory or +allocation state and sends no successful join acknowledgement. Unknown, +individual-item, foreign-page and out-of-range sources remain ignored. Pending +equipment retains its separate refusal path. This uses recovered native +operations, without establishing the original server's refusal sequence. + +`TestStaleStackJoinRestoresOwnedSourceWithoutWrites` checks repeated requests, +source validation, ordered restoration, exact selected endpoints, no writes and +cold ownership. `TestBrowserStaleStackJoin` uses real inventory gestures to +reproduce the missing source, restore usable8/7-charge rows and immediately retry +against the correct target. Only that retry receives a successful action53; ID2 +then retains15 charges through page replay and cold Go loading, with allocation +still3. The earlier merge is controlled fixture state, not earned progression. +The native check passed in17.74s with five clean traces. Baseline and corrected +captures are in `local/stale-stack-join/20261103-163358/` and +`local/stale-stack-join/20261103-163641/`. +Related checks pass16 Go roots/164 results in50.918s; the focused race run passes +3 roots/15 results in98.219s, including individual-source rejection. Vet and Node +syntax checks pass. Independent request/reply, selected-contract and source-hash +checks are retained in `local/stale-stack-join/validation.json`. + ## Verification `server/stacks_test.go` exercises grant quantities, merge direction, source diff --git a/server/browser_stale_stack_join_test.go b/server/browser_stale_stack_join_test.go @@ -0,0 +1,86 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "testing" + "time" +) + +func TestBrowserStaleStackJoin(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for stale ordinary stack joins") + } + + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/stale-stack-join", time.Now().Format("20060102-150405")) + world := newTestServer(t) + player := world.newCharacter() + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("stale-stack-join"))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + for range 3 { + if granted, err := world.grantItem_locked(player, 25812); err != nil || !granted { + t.Fatal(granted, err) + } + } + for index, count := range []uint16{3, 5, 7} { + player.inventory.Items[index].Quality = 2 + player.inventory.Items[index].Count = count + } + if err := world.saveInventory_locked(player, 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(player.inventory) + }) + // Controlled checkpoint: an earlier committed merge has no native refresh. + mux.HandleFunc("POST /test-stale-view", 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.Items = slices.Clone(inventory.Items[1:]) + inventory.Items[0].Count = 8 + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Error(err) + http.Error(w, err.Error(), http.StatusInternalServerError) + } + }) + 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_stale_stack_join.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: 2, Type: 51005, Template: 25812, Quality: 2, Slot: 65, Count: 15}} + if !slices.Equal(player.inventory.Items, expected) || !slices.Equal(cold.characters[1].inventory.Items, expected) || + world.nextItem != 3 || cold.nextItem != 3 { + t.Fatal("stale join correction or retry changed ownership, quantity or allocation") + } +} diff --git a/server/inventory.go b/server/inventory.go @@ -335,6 +335,20 @@ func (server *server) handleInventory(client *worldClient, body []byte) error { sourceSlot >= 64 && sourceSlot < 94 && index < 0 { return server.syncStacks_locked(client) } + if index < 0 && key == 0x5e477770 && binary.BigEndian.Uint32(body[16:20]) == 53 && + sourceType == 104 && sourceSlot >= 64 && sourceSlot < 94 && binary.BigEndian.Uint32(body[28:32]) == 104 { + // A stale join target must not leave its still-owned removed source hidden. + removedSlot := binary.BigEndian.Uint32(body[32:36]) + removed := slices.IndexFunc(character.inventory.Items, func(item ownedItem) bool { return item.Slot == removedSlot }) + if removedSlot >= 64 && removedSlot < 94 && removed >= 0 && character.inventory.Items[removed].isStackable() { + for _, packet := range equipmentCorrectionPackets(client.id, removedSlot) { + if err := client.send(packet); err != nil { + return err + } + } + return server.syncStacks_locked(client) + } + } if index < 0 || (sourceSlot >= 64 && sourceType != 104) || (sourceSlot > 0 && sourceSlot < 16 && sourceType != 101) || (sourceSlot >= 33 && sourceSlot <= 45 && sourceType != 103) || diff --git a/server/stale_stack_join_test.go b/server/stale_stack_join_test.go @@ -0,0 +1,92 @@ +package main + +import ( + "bytes" + "encoding/binary" + "reflect" + "slices" + "testing" +) + +func TestStaleStackJoinRestoresOwnedSourceWithoutWrites(t *testing.T) { + for _, scenario := range []string{"owned source", "individual source", "unknown source", "foreign source page", "target outside inventory", "source outside inventory"} { + t.Run(scenario, func(t *testing.T) { + world, conn := newStackWorld(t) + player, client := world.characters[1], world.clients[1] + for index := range player.inventory.Items { + player.inventory.Items[index].Template = 25812 + player.inventory.Items[index].Quality = 2 + } + player.inventory.Items[1].Count = 5 + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(client, stackActionPacket(1, 53, 65, 64)[20:]); err != nil { + t.Fatal(err) + } + request := stackActionPacket(1, 53, 64, 65)[20:] + switch scenario { + case "individual source": + player.inventory.Items[0] = ownedItem{ID: 2, Type: 51018, Template: 209283, Quality: 1, Slot: 65, Count: 1} + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + case "unknown source": + binary.BigEndian.PutUint32(request[32:36], 66) + case "foreign source page": + binary.BigEndian.PutUint32(request[28:32], 105) + case "target outside inventory": + binary.BigEndian.PutUint32(request[24:28], 94) + case "source outside inventory": + binary.BigEndian.PutUint32(request[32:36], 94) + } + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + auditCheckpointWrites(t, world) + conn.packets = nil + + for range 2 { + if err := world.handleInventory(client, request); err != nil { + t.Fatal(err) + } + } + after, err := readTestItemStore(world) + cold := newTestInventoryServer(t) + + expected := []ownedItem{{ID: 2, Type: 51005, Template: 25812, Quality: 2, Slot: 65, Count: 8}} + if scenario == "individual source" { + expected = []ownedItem{{ID: 2, Type: 51018, Template: 209283, Quality: 1, Slot: 65, Count: 1}} + } + if err != nil || !bytes.Equal(before, after) || len(checkpointWrites(t, world)) != 0 || + !slices.Equal(player.inventory.Items, expected) || !slices.Equal(cold.characters[1].inventory.Items, expected) || + world.nextItem != 2 || cold.nextItem != 2 { + t.Fatal("stale join refusal wrote inventory, changed allocation or lost charges", err) + } + if scenario != "owned source" { + if len(conn.packets) != 0 { + t.Fatal("invalid source or target created correction traffic") + } + return + } + if len(conn.packets) < 4 || !bytes.Equal(conn.packets[0], targetPacket(itemMovePacket(1, 65, 64))) || + !bytes.Equal(conn.packets[1], targetPacket(itemMovePacket(1, 64, 65))) { + t.Fatal("stale join omitted ordered source restoration") + } + var additions [][4]uint32 + for _, packet := range conn.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x052e2f0c { + additions = append(additions, [4]uint32{binary.BigEndian.Uint32(packet[29:33]), + binary.BigEndian.Uint32(packet[33:37]), binary.BigEndian.Uint32(packet[37:41]), binary.BigEndian.Uint32(packet[41:45])}) + } + if binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && binary.BigEndian.Uint32(packet[29:33]) == 53 { + t.Fatal("refusal falsely acknowledged a successful join") + } + } + if !reflect.DeepEqual(additions, [][4]uint32{{25812, 25811, 2, 8}, {25812, 25811, 2, 8}}) { + t.Fatal("repeated stale joins did not restore the authoritative selected contract", additions) + } + }) + } +} diff --git a/tools/client/test_stale_stack_join.mjs b/tools/client/test_stale_stack_join.mjs @@ -0,0 +1,85 @@ +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: 'stale-stack-join', url}]); + const page = await context.newPage(); + game = await GameTest.attach(page); + const server = async () => (await page.request.get(url + '/test-state')).json(); + const cell = slot => game.state.grids.flatMap(grid => grid.cells).find(cell => + cell.identity[0] === 104 && cell.identity[1] === slot && !cell.dummy); + const click = async slot => { + const source = cell(slot); + assert(source, `ordinary slot ${slot} must be usable`); + await game.click((source.bounds[0] + source.bounds[2]) / 2, (source.bounds[1] + source.bounds[3]) / 2); + }; + await page.goto(url); + await game.ready(); + await page.waitForFunction(() => touchRegion(500, 400)?.world === true); + await game.snapshot(); + await game.key('i'); + await game.wait('three ordinary stacks', () => cell(48) && cell(49) && cell(50)); + evidence.initial = await server(); + assert((await page.request.post(url + '/test-stale-view')).ok()); + evidence.stale = await server(); + await game.save(output + '/stale'); + + // A real join targets the removed stack while hiding its still-owned source. + const start = game.sequence; + await click(50); + await click(48); + await game.wait('actual stale ordinary join', () => game.events.some(event => event.sequence > start && + event.direction === 'framesent' && event.opcode === '5e477770' && + Buffer.from(event.hex, 'hex').readUInt32BE(29) === 53)); + await game.save(output + '/requested'); + await game.wait('authoritative stacks restored with usable sources', state => + cell(49) && cell(50) && !cell(48) && state.dragged[0] === 0 && + JSON.stringify(game.local(state).inventory.map(item => [item.slot, item.quality, item.count, ...item.templates]) + .sort((a, b) => a[0] - b[0])) === JSON.stringify([ + [49, 2, 8, 25812, 25811], [50, 2, 7, 25812, 25811]])); + evidence.refused = await server(); + assert.deepEqual(evidence.refused, evidence.stale); + await game.save(output + '/refused'); + + // The same open inventory can immediately merge into the surviving target. + const retry = game.sequence; + await click(50); + await click(49); + await game.wait('valid retry retains fifteen charges', state => cell(49) && !cell(50) && + game.local(state).inventory.some(item => item.slot === 49 && item.count === 15)); + evidence.joined = await server(); + assert.deepEqual(evidence.joined.Items.map(item => [item.ID, item.Slot, item.Quality, item.Count]), [[2, 65, 2, 15]]); + const acknowledgements = game.events.filter(event => event.sequence > start && event.direction === 'framereceived' && + event.opcode === '5e477770' && Buffer.from(event.hex, 'hex').readUInt32BE(29) === 53); + assert.equal(acknowledgements.length, 1); + assert(acknowledgements[0].sequence > retry); + await game.save(output + '/joined'); + + await page.reload(); + await game.ready(); + await page.waitForFunction(() => touchRegion(500, 400)?.world === true); + await game.snapshot(); + assert.deepEqual(game.local().inventory.map(item => [item.id, item.slot, item.quality, item.count, ...item.templates]), + [[2, 49, 2, 15, 25812, 25811]]); + evidence.replayed = await server(); + assert.deepEqual(evidence.replayed, evidence.joined); + assert.deepEqual(game.errors, []); + console.log('PASS: stale join resynchronization, usable source, same-window retry and page recovery preserve fifteen charges'); +} 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(); } +}