commit 7986a18e2d57f51dd502363df138aba88c8ded85
parent bdd18afae1c40076ebd98fe900f4c1076df1dcda
Author: anon <anon@example.com>
Date: Thu, 5 Nov 2026 00:25:06 +0000
Correct stale ordinary stack splits without changing ownership
Diffstat:
7 files changed, 264 insertions(+), 2 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 an ordinary stale split whose retained count equals the actual
+ source count. Reproduction: the native laboratory still shows three charges
+ after controlled earlier consumption leaves one; real Ctrl-click requests
+ retained count1 and the no-reply branch leaves an unowned two-charge clone.
+ Ordinary stack resynchronization now removes that clone without storage writes
+ or allocation. Boundary/repeated handler checks retain all item properties;
+ the 18-second native check preserves the worn axe, permits same-page placement
+ and exact last-charge Use, then verifies page replay and cold ownership.
+ See [stale ordinary quantities](docs/inventory-stacks.md#stale-ordinary-quantities)
+ and `local/depleted-stack-split/`.
- [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.
diff --git a/docs/inventory-stacks.md b/docs/inventory-stacks.md
@@ -106,12 +106,35 @@ 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 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.
+unowned optimistic clone. The ordinary page rebuilds its supported stacks for
+the same reason, preserving individual items and worn modifiers. The bank page
+retains its no-op handling; its native UI does not establish the same gesture.
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.
+### Stale ordinary quantities
+
+A native three-charge laboratory can optimistically split after an earlier
+controlled consumption has left only one authoritative charge. Its action52
+retains one, so the old equality branch sent no correction and left an unowned
+two-charge clone beside the real source. The ordinary equality branch now uses
+the existing stack-page correction, retaining individual items and worn effects
+while removing optimistic clones. It performs no ownership writes or allocation;
+duplicate requests remain idempotent for storage.
+
+`TestDepletedStackSplitCorrectsWithoutWriting` checks both ordinary slot
+boundaries, repeated requests, exact selected endpoints/count/placement and zero
+checkpoint writes. `TestBrowserDepletedStackSplit` reproduces the old phantom
+with real Ctrl-click input. The fixed 18-second check permits normal cursor
+placement and immediate same-page Use of the one remaining QL2 charge, healing
+1 -> 38 and retiring only that laboratory. Page replay and a separate database
+load preserve the worn axe and final item counter 2. The stale consumption is
+controlled setup, not earned progression or a claim about period timing.
+Baseline/native captures and an independent trace audit are retained under
+`local/depleted-stack-split/`.
+
### Reviewed family anchors
Same-QL stacks identified by opposite endpoints of one reviewed family now join
diff --git a/server/browser_depleted_stack_split_test.go b/server/browser_depleted_stack_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 TestBrowserDepletedStackSplit(t *testing.T) {
+ if os.Getenv("AO_GAME_TEST") != "1" {
+ t.Skip("set AO_GAME_TEST=1 for the depleted ordinary-stack split")
+ }
+ _, source, _, _ := runtime.Caller(0)
+ root := filepath.Dir(filepath.Dir(source))
+ output := filepath.Join(root, "local/depleted-stack-split", time.Now().Format("20060102-150405"))
+ world := newTestServer(t)
+ player := world.newCharacter()
+ player.stats = testCharacterStats()
+ player.stats.Abilities = characterAbilitiesStats{80, 80, 80, 80, 80, 80}
+ player.stats.NanoAiding.Treatment = 100
+ player.health = 1
+ player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("depleted-stack-split")))
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ inventory := playerInventory{LastID: 2, Items: []ownedItem{
+ {ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 6, Count: 1},
+ {ID: 2, Type: 51005, Template: 25812, Quality: 2, Slot: 64, 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, "health": player.health})
+ })
+ // Isolate an earlier committed consumption with a stale three-charge native 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
+ inventory.Items = slices.Clone(inventory.Items)
+ inventory.Items[1].Count = 1
+ 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_stack_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: 51018, Template: 209283, Quality: 1, Slot: 6, Count: 1}}
+ for _, current := range []*character{player, cold.characters[1]} {
+ if !slices.Equal(current.inventory.Items, expected) || current.health != 38 || current.inventory.LastID != 2 {
+ t.Fatal("depleted split correction/use changed equipment, ownership or health", current.inventory, current.health)
+ }
+ }
+ if world.nextItem != 2 || cold.nextItem != 2 {
+ t.Fatal("depleted split allocated an identity")
+ }
+}
diff --git a/server/depleted_stack_split_test.go b/server/depleted_stack_split_test.go
@@ -0,0 +1,65 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "reflect"
+ "testing"
+)
+
+func TestDepletedStackSplitCorrectsWithoutWriting(t *testing.T) {
+ for _, slot := range []uint32{64, 93} {
+ 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: 51018, Template: 209283, Quality: 1, Slot: 6, Count: 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)
+ }
+ before, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+ auditCheckpointWrites(t, world)
+ request := stackActionPacket(1, 52, slot, 1)[20:]
+
+ for range 2 {
+ output.packets = nil
+ if err := world.handleInventory(client, request); err != nil {
+ t.Fatal(err)
+ }
+
+ count := 31
+ if slot == 93 {
+ count++
+ }
+ if len(output.packets) != count {
+ t.Fatal("equal-count split did not rebuild the exact ordinary stack page", len(output.packets))
+ }
+ for index := range 30 {
+ if !bytes.Equal(output.packets[index], targetPacket(characterActionPacket(1, [5]uint32{112, 104, uint32(64 + index)}))) {
+ t.Fatal("correction did not clear only ordinary stack/empty slots", index)
+ }
+ }
+ add := output.packets[30]
+ if binary.BigEndian.Uint32(add[16:20]) != 0x052e2f0c ||
+ !bytes.Equal(add[29:45], []byte{0, 0, 100, 212, 0, 0, 100, 211, 0, 0, 0, 2, 0, 0, 0, 1}) {
+ t.Fatal("correction lost selected laboratory endpoints, quality or remaining charge")
+ }
+ if slot == 93 && !bytes.Equal(output.packets[31], targetPacket(itemMovePacket(1, 64, 93))) {
+ t.Fatal("correction did not restore the last logical slot")
+ }
+ }
+ after, err := readTestItemStore(world)
+ cold := newTestInventoryServer(t)
+ if err != nil || !bytes.Equal(before, after) || len(checkpointWrites(t, world)) != 0 ||
+ !reflect.DeepEqual(player.inventory, inventory) || !reflect.DeepEqual(cold.characters[1].inventory, inventory) ||
+ world.nextItem != 2 || cold.nextItem != 2 {
+ t.Fatal("equal-count correction changed storage, ownership, ammunition or allocation", err)
+ }
+ })
+ }
+}
diff --git a/server/stacks.go b/server/stacks.go
@@ -39,6 +39,9 @@ func (server *server) changeStack_locked(client *worldClient, index int, body []
client.backpacks[binary.BigEndian.Uint32(body[24:28])>>16] = backpackHandle{bag, false}
return client.send(backpackClosePacket(client.id, bag))
}
+ if page == 104 {
+ return server.syncStacks_locked(client)
+ }
return nil
}
if binary.BigEndian.Uint32(body[28:32]) != 0 || retained == 0 || retained > uint32(items[index].Count) {
diff --git a/server/stacks_test.go b/server/stacks_test.go
@@ -61,7 +61,7 @@ func TestStackJoinSplitRepeatAndRestartPreserveQuantities(t *testing.T) {
expected := []ownedItem{{ID: 2, Type: 51005, Template: 152030, Quality: 42, Slot: 65, Count: 2}, {ID: 3, Type: 51005, Template: 152030, Quality: 42, Slot: 64, Count: 4}}
if !reflect.DeepEqual(player.inventory.Items, expected) || !reflect.DeepEqual(restarted.inventory.Items, expected) || restarted.inventory.LastID != 3 ||
- player.inventory.LastID != 3 || world.nextItem != 3 || len(conn.packets) != 2 {
+ player.inventory.LastID != 3 || world.nextItem != 3 || len(conn.packets) != 34 {
t.Fatalf("split lost quantities or repeated allocation: %+v restart %+v packets %d", player.inventory, restarted.inventory, len(conn.packets))
}
if binary.BigEndian.Uint16(packet[41:43]) != 1 || binary.BigEndian.Uint16(packet[43:45]) != 2 ||
diff --git a/tools/client/test_depleted_stack_split.mjs b/tools/client/test_depleted_stack_split.mjs
@@ -0,0 +1,74 @@
+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-stack-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();
+ await game.key('KeyI');
+ evidence.initial = await server();
+ assert((await page.request.post(url + '/test-deplete-source')).ok());
+ evidence.depleted = await server();
+ assert.equal(evidence.depleted.inventory.Items[1].Count, 1);
+ const sequence = game.sequence;
+ await page.keyboard.down('Control');
+ try { await game.click(681, 45); } finally { await page.keyboard.up('Control'); }
+ await game.wait('actual equal-count stale 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('only the actual remaining charge survives', snapshot => game.local(snapshot).inventory.length === 2 &&
+ game.local(snapshot).inventory.some(item => item.slot === 48 && item.count === 1));
+ assert.deepEqual(await server(), evidence.depleted);
+ if (game.state.dragged[0] !== 0) {
+ await game.click(735, 45);
+ await game.wait('corrected selected stack places normally', snapshot => snapshot.dragged[0] === 0);
+ }
+ await game.wait('corrected exact source icon is usable', snapshot => snapshot.grids.some(grid => grid.cells.some(cell =>
+ cell.identity[0] === 104 && cell.identity[1] === 48 && !cell.dummy)));
+ await game.save(output + '/corrected');
+ const restored = game.local().inventory.find(item => item.slot === 48);
+ assert.deepEqual([restored.quality, restored.count, ...restored.templates], [2, 1, 25812, 25811]);
+ assert.deepEqual(await server(), evidence.depleted);
+
+ // The corrected one-charge source must still heal through ordinary native Use.
+ if (!game.state.grids.some(grid => grid.cells.some(cell => cell.identity[0] === 104))) await game.key('KeyI');
+ await game.key('F1');
+ await game.key('KeyX');
+ await game.wait('seated laboratory user', snapshot => game.local(snapshot).stats[430] === 2);
+ const source = game.state.grids.flatMap(grid => grid.cells).find(cell =>
+ cell.identity[0] === 104 && cell.identity[1] === 48 && !cell.dummy);
+ assert(source);
+ await game.click((source.bounds[0] + source.bounds[2]) / 2, (source.bounds[1] + source.bounds[3]) / 2, 'right');
+ await game.wait('actual last charge heals and retires', snapshot => game.local(snapshot).stats[27] === 38 &&
+ game.local(snapshot).inventory.length === 1);
+ evidence.used = await server();
+ assert.equal(evidence.used.health, 38);
+ assert.equal(evidence.used.inventory.LastID, 2);
+ await game.save(output + '/used');
+ await page.reload();
+ await game.ready();
+ assert.deepEqual(game.local().inventory.map(item => [item.id, item.slot]), [[1, 6]]);
+ assert.deepEqual(await server(), evidence.used);
+ assert.deepEqual(game.errors, []);
+ console.log('PASS: equal-count stale split corrects its phantom, retains equipment and permits exact one-charge use with page/cold conservation');
+} 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(); }
+}