aorecomp

Anarchy Online classic in the browser

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


commit d092e0212ed675494880cd4445ffdf113dfc8cec
parent 42856dad06aaf6bf30175ad78481673deb77fae9
Author: anon <anon@example.com>
Date:   Wed,  4 Nov 2026 23:16:58 +0000

Correct stale equal-count backpack splits

Diffstat:
MTODO.md | 10++++++++++
Mdocs/backpacks.md | 25+++++++++++++++++++++++++
Mdocs/inventory-stacks.md | 9++++++---
Mserver/backpacks_test.go | 8+++++++-
Aserver/browser_depleted_backpack_split_test.go | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/depleted_backpack_split_test.go | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/stacks.go | 5+++++
Atools/client/test_depleted_backpack_split.mjs | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
8 files changed, 280 insertions(+), 4 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -4556,6 +4556,16 @@ 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 a stale backpack split whose retained count equals the actual + source count. Reproduction: retain a three-charge native laboratory after a + controlled earlier consumption leaves one charge, then Ctrl-split the old row. + The unchanged no-reply branch leaves an unowned clone. Exact known-bag closure + now passes a 19.52-second native check without allocation or ownership changes; + normal reopening/withdrawal and page/cold recovery retain the exact remaining + charge. Both slot boundaries and repeated refusals perform no checkpoint + writes. Accepted split/duplicate/reopen/join/delete preserves its original + identities and allocation count; ordinary/bank stack and race checks pass. + See [stale stack quantities](docs/backpacks.md#stale-quantities-and-repeated-retained-counts). - [x] [P0] Correct an optimistic backpack split refused during pending equipment. Reproduction: Ctrl-split an owned three-charge stack while a separate real equip awaits held server completion. The unchanged contents-only refusal leaves diff --git a/docs/backpacks.md b/docs/backpacks.md @@ -420,6 +420,31 @@ Related Go checks pass 50 roots / 344 results in 63.029 seconds. Focused race checks pass four roots / 23 results; the independent audit checks the original empty refresh, both native recoveries and eight clean stage traces. +### Stale quantities and repeated retained counts + +A cached three-charge laboratory can send retained count 1 after a controlled +earlier consumption has already left one actual charge. The old equal-count +no-op sends no reply and leaves an unowned two-charge clone in the native bag. +Known backpack equal-count requests now close their session/window without +changing ownership or allocating an item. This also corrects immediate repeated +accepted splits; ordinary and bank no-op handling is unchanged. The protocol +carries no previous-count or operation token to distinguish these cases. + +`TestDepletedBackpackSplitClosesWithoutWriting` covers both slot boundaries, +repeated exact closure, zero checkpoint writes and normal reopen/withdrawal with +cold ownership. `TestBackpackStackSplitJoinAndDelete` reopens after the repeated +accepted split before joining/deleting, retaining its original identities and +allocation count. The focused `TestBrowserDepletedBackpackSplit` reproduces the +unchanged native failure in 21.28 seconds and passes in 19.52 after correction. +The exact QL2 laboratory and one remaining charge survive normal withdrawal, +page replay and cold loading, alongside the same bag and unchanged counter 2. +This is controlled missed-consumption-refresh evidence, not earned progression +or an original-server refusal policy. Evidence: `local/depleted-backpack-split/`. +Related ordinary, bank and backpack Go checks pass 63 roots / 497 results +in 87.677 seconds. +Focused race checks pass five roots / nine results; the independent audit checks +the baseline, exact close, one-charge reopening and four clean native traces. + ## Stale withdrawal sources A known carried bag can have an empty slot behind a stale native window. The diff --git a/docs/inventory-stacks.md b/docs/inventory-stacks.md @@ -104,9 +104,12 @@ newly allocated ID together, after saving successfully. A split requires `1 <= retained < currentCount` and an empty ordinary slot. The server gives the new stack the first free slot and a fresh global ID. -An immediate repeated retained count is a no-op. A repeated join finds the -removed slot empty. The wire cannot distinguish every replay after subsequent -slot reuse or a later merge; it has no previous-count or operation token. +An immediate repeated retained count preserves ownership. A known carried bag +closes its window: the same request can also come from a stale quantity and an +unowned optimistic clone. Ordinary and bank pages retain their no-op handling. +A repeated join finds the removed slot empty. The wire cannot distinguish every +replay after subsequent slot reuse or a later merge; it has no previous-count or +operation token. Every accepted operation still conserves the total quantity. ### Reviewed family anchors diff --git a/server/backpacks_test.go b/server/backpacks_test.go @@ -294,11 +294,17 @@ func TestBackpackStackSplitJoinAndDelete(t *testing.T) { return n3Packet(0x5e477770, 50000, 1, body)[20:] } - for _, request := range [][]byte{action(52, 1<<16, 0, 1), action(52, 1<<16, 0, 1), action(53, 1<<16, 107, 1<<16|1)} { + for _, request := range [][]byte{action(52, 1<<16, 0, 1), action(52, 1<<16, 0, 1)} { if err := world.handleInventory(client, request); err != nil { t.Fatal(err) } } + if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 66, 2)[20:]); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(client, action(53, 1<<16, 107, 1<<16|1)); err != nil { + t.Fatal(err) + } joined := newTestInventoryServer(t).characters[1].inventory err := world.handleInventory(client, action(112, 1<<16, 152030, 152030)) restarted := newTestInventoryServer(t).characters[1] diff --git a/server/browser_depleted_backpack_split_test.go b/server/browser_depleted_backpack_split_test.go @@ -0,0 +1,87 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "testing" + "time" +) + +func TestBrowserDepletedBackpackSplit(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for depleted backpack split") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/depleted-backpack-split", time.Now().Format("20060102-150405")) + world := newTestServer(t) + player := world.newCharacter() + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("depleted-backpack-split"))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + inventory := playerInventory{LastID: 2, Items: []ownedItem{ + {ID: 1, Type: 51017, Template: 99228, Quality: 1, Slot: 64, Count: 1}}, + Containers: map[uint32][]ownedItem{1: { + {ID: 2, Type: 51005, Template: 25812, Quality: 2, Slot: 0, Count: 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 earlier consumption without refreshing the native three-charge row. + mux.HandleFunc("POST /test-deplete-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 + contents := slices.Clone(inventory.Containers[1]) + contents[0].Count = 1 + inventory.Containers = map[uint32][]ownedItem{1: contents} + 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_depleted_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: 65, Count: 1}} + for _, current := range []*character{player, cold.characters[1]} { + if !slices.Equal(current.inventory.Items, expected) || len(current.inventory.Containers) != 0 || + current.inventory.Credits != 0 || current.inventory.LastID != 2 { + t.Fatal("depleted split or recovery changed ownership, charges or allocation", current.inventory) + } + } + if world.nextItem != 2 || cold.nextItem != 2 { + t.Fatal("refused depleted split allocated an identity") + } +} diff --git a/server/depleted_backpack_split_test.go b/server/depleted_backpack_split_test.go @@ -0,0 +1,65 @@ +package main + +import ( + "bytes" + "fmt" + "reflect" + "slices" + "testing" +) + +func TestDepletedBackpackSplitClosesWithoutWriting(t *testing.T) { + for _, slot := range []uint32{0, 20} { + t.Run(fmt.Sprint(slot), func(t *testing.T) { + world, output := newStackWorld(t) + player, client := world.characters[1], world.clients[1] + inventory := playerInventory{LastID: 2, Items: []ownedItem{ + {ID: 1, Type: 51017, Template: 99228, Quality: 1, Slot: 64, Count: 1}}, + Containers: map[uint32][]ownedItem{1: { + {ID: 2, Type: 51005, Template: 25812, Quality: 2, Slot: slot, Count: 1}}}} + 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) + } + 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) || world.nextItem != 2 || cold.nextItem != 2 || + client.backpacks[1] != (backpackHandle{1, false}) || !reflect.DeepEqual(output.packets, [][]byte{close, close}) { + t.Fatal("equal-count split changed storage, allocation or exact source-window closure", err) + } + + if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 2)[20:]); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(client, backpackMoveRequest(107, 65536+slot, 50000, 1, 111)[20:]); 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: 65, Count: 1}} + if !slices.Equal(player.inventory.Items, expected) || !slices.Equal(cold.characters[1].inventory.Items, expected) || + len(cold.characters[1].inventory.Containers) != 0 || player.inventory.LastID != 2 || cold.nextItem != 2 { + t.Fatal("normal reopen/withdrawal lost the exact remaining charge or allocated a clone") + } + }) + } +} diff --git a/server/stacks.go b/server/stacks.go @@ -34,6 +34,11 @@ func (server *server) changeStack_locked(client *worldClient, index int, body [] // Action 52 carries the count retained in the original, already split locally. retained := binary.BigEndian.Uint32(body[32:36]) if retained == uint32(items[index].Count) && binary.BigEndian.Uint32(body[28:32]) == 0 { + if bag != 0 { + // The same retained count can also come from a stale native row. + client.backpacks[binary.BigEndian.Uint32(body[24:28])>>16] = backpackHandle{bag, false} + return client.send(backpackClosePacket(client.id, bag)) + } return nil } if binary.BigEndian.Uint32(body[28:32]) != 0 || retained == 0 || retained > uint32(items[index].Count) { diff --git a/tools/client/test_depleted_backpack_split.mjs b/tools/client/test_depleted_backpack_split.mjs @@ -0,0 +1,75 @@ +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: 'depleted-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 = slot => game.state.grids.flatMap(grid => grid.cells).find(cell => + cell.identity[0] === 107 && cell.identity[1] === (65536 | slot) && !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 three-charge source opens', () => cell(0)); + evidence.initial = await server(); + assert((await page.request.post(url + '/test-deplete-source')).ok()); + evidence.depleted = await server(); + assert.equal(evidence.depleted.open, true); + assert.equal(evidence.depleted.inventory.Containers[1][0].Count, 1); + const sequence = game.sequence; + await page.keyboard.down('Control'); + try { await click(cell(0)); } finally { await page.keyboard.up('Control'); } + await game.wait('actual stale native split', () => game.events.some(event => event.sequence > sequence && + event.direction === 'framesent' && event.opcode === '5e477770' && Buffer.from(event.hex, 'hex').readUInt32BE(29) === 52)); + evidence.requested = await server(); + await game.save(output + '/requested'); + await game.wait('unowned split clone removed', () => !cell(1)); + if (game.state.dragged[0] !== 0) { + await game.click(735, 45); + await game.wait('stale selected source placement refuses', state => state.dragged[0] === 0); + } + evidence.refused = await server(); + assert.deepEqual(evidence.refused.inventory, evidence.depleted.inventory); + await game.save(output + '/refused'); + + // Normal reopening and withdrawal must deliver the one actual remaining charge. + if (!cell(0)) await game.click(681, 45, 'right'); + await game.wait('actual one-charge source usable without a clone', () => cell(0) && !cell(1)); + await click(cell(0)); + await game.click(735, 45); + await game.wait('exact one-charge stack withdrawn', state => game.local(state).inventory.some(item => + item.id === 2 && item.slot === 49 && item.quality === 2 && item.count === 1)); + evidence.recovered = await server(); + assert.equal(evidence.recovered.inventory.Containers, null); + assert.equal(evidence.recovered.inventory.LastID, 2); + await game.save(output + '/recovered'); + await page.reload(); + await game.ready(); + assert.deepEqual(game.local().inventory.map(item => [item.id, item.slot, item.templates, item.quality, item.count]), [ + [1, 48, [99228, 99228], 1, 1], [2, 49, [25812, 25811], 2, 1]]); + assert.deepEqual((await server()).inventory, evidence.recovered.inventory); + assert.deepEqual(game.errors, []); + console.log('PASS: stale equal-count split removes its phantom without allocation and recovers the exact remaining charge through normal withdrawal and page/cold loading'); +} 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(); } +}