aorecomp

Anarchy Online classic in the browser

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


commit d4f613f6ade51ac7a271a7effa262bdddafc6055
parent 14c934ec0df51be80efb5b867874c3ef9801c467
Author: anon <anon@example.com>
Date:   Wed, 28 Oct 2026 04:13:46 +0000

Verify atomic skill saves and earned reward progression

Diffstat:
MTODO.md | 17+++++++++++++++++
Mdocs/ip-training.md | 42++++++++++++++++++++++++++++++++++++++++++
Mdocs/starter-progression.md | 37+++++++++++++++++++++++++++++++++++++
Aserver/ip_training_persistence_test.go | 77+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/mission_reward_progression_test.go | 150+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/users.go | 11++++++++++-
6 files changed, 333 insertions(+), 1 deletion(-)

diff --git a/TODO.md b/TODO.md @@ -1178,6 +1178,16 @@ introduction and starting-item gameplay remain open below. 153 categories but do not establish their stock. Research online for shop inventories, categories and QL ranges where the game data is insufficient, and verify that the evidence applies to 14.9.1. Do not infer stock from names. +- [ ] [P1] Restore the Secondhand Peddler and reusable NPC shop interactions in + the original training grounds. Funcom's + [14.7.10 notes](https://worthplaying.com/article/2003/2/26/news/8473-anarchy-online-update-patch-available-now/) + introduced this vendor while moving some stock out of the newbie terminal. + Original shop template 209286 selects category 105 and requires level > 1. + Recover its placement, NPC interaction/dialogue and dated stock membership; + reuse current quote, inventory and atomic purchase/sale rules. Test native + opening, cancellation, ownership, range/lifecycle revalidation, insufficient + funds/space and cold recovery. Later Arete or starter-island vendors do not + establish this original backyard's stock. - [ ] [P2] Supply trusted expansion entitlement stat 389 and its native BitAnd evaluation. Five placed vending templates require Notum Wars mask 1 and currently stay closed. Use one authoritative entitlement source for server @@ -2708,6 +2718,13 @@ and server restarts. Turn every reproduced bug into a focused regression test. locked slots, occupied destinations, swaps, repeated actions, interruptions, full inventory and attempts to manipulate another player's items. Rejection must restore a usable native UI without losing or duplicating an item. + A public-handler regression now follows a kill-earned level and IP through + mission reward rejection, actual ability training, failed-save/retry, + wear/remove/re-wear and cold recovery of that same reward. Separate fault + tests cover ignored/rewritten/deleted training rows and commit failure without + spending IP or changing ownership. The seeded-XP/one-hit fixture does not + complete the ordinary equipment purchase gate; see + [training and earned rewards](docs/ip-training.md#training-earned-rewards-and-persistence-failures). - [ ] [P2] Audit rapid native equipment input after online ability edits and reconnects. Check: an existing item becomes immediately usable when its wear requirements are met. Some scripted right-clicks emitted no request during diff --git a/docs/ip-training.md b/docs/ip-training.md @@ -82,6 +82,14 @@ failure-status opcode has been established. Malformed packet framing ends the connection; well-framed invalid purchases receive the unchanged authoritative snapshot. Database failures publish no successful update. +The shared character-save transaction verifies every written profile and vital +column after its final statement and before commit. The check uses the same +column list and bound values as the write. A successful UPDATE count alone does +not prove that later statements retained the intended skills, IP and resources. +An absent or changed row rolls back without advancing saved-state caches or +publishing the tentative training. Position checkpoints keep their existing +cadence; this check adds no per-movement writes. + ## Explicit limits of the reconstruction The server totals exact tenths of IP and rounds the accepted batch up once to @@ -102,6 +110,40 @@ skill seeds and starting IP remain unverified; see The shared [solo kill progression](kill-experience.md) now awards XP, advances levels and grants IP. Its historical reward policies and IP Reset remain open. +## Training, earned rewards and persistence failures + +`server/mission_reward_progression_test.go` connects a kill award to actual +training and equipment handlers. Its Atrox fixture starts immediately below the +first XP threshold. Level 1 rejects Agility 11 without spending IP. The kill +earns level 2 and 4000 IP without raising the trained ability or current HP. +Mission hand-in retains its promised QL2 glove despite the level change. Wear +still fails at Agility 9; the accepted Agility 11 batch costs exactly 38 IP and +then permits wear, removal and re-wear. A failed training transaction preserves +the reward and earned IP, and retry succeeds. Cold loads retain item identity, +effects, credits, XP and unrelated corpse loot at every equipment step. + +This is an integration fixture with seeded XP, a one-hit victim and arranged +positions. It tests the earned-cap dependency and conservation, not ordinary +combat balance, travel or a complete equipment-purchase loop. The separate +[ordinary mission run](starter-progression.md#earned-fixed-mission-reward) +provides native evidence for the current level-1 reward and rejected wear. + +`server/ip_training_persistence_test.go` injects ignored updates, rewritten +abilities/IP, later skill/health changes, deletion and deferred commit failure. +Each failure must retain live and cold stats, IP, health, nano and owned items, +emit no success packets and leave saved-profile caches unchanged. Removing the +fault and repeating the same native request twice trains once at the original +price. Four late-write cases reproduce successful acknowledgement with divergent +saved state before the final verification was added. The regression records are +retained under `local/earned-armor/`. + +The candidate passes `go test ./server/... ./tools/data/export_gamedata -count=1` +with 1615 top-level tests and 16011 individual results. The separate training and +earned-reward race run passes 16 top-level tests and 73 results. `go vet +./server/...` passes. Normal native training, page reconnect and an unchanged-DB +cold restart retain the accepted raw skill, IP and exact owned items; see the +[issued buff and training run](starter-progression.md#issued-buff-and-durable-training). + ## Verification `client/tests/ip_training.c` executes the unchanged lifted implementations diff --git a/docs/starter-progression.md b/docs/starter-progression.md @@ -392,3 +392,40 @@ and 115 results; transaction rollback/concurrency race checks pass 5 roots and assertions are retained in `local/earned-armor/`. The owned browser is closed; the earned character is retained for the continuing progression test. One LAN preview remains on the default ports. + +### Issued buff and durable training + +The same Enforcer spent 126 IP to raise Intelligence from 3 to 6 and raw +Psychological Modification/Sensory Improvement from 5 to 8. This qualified its +issued Thug's Delight crystal (20). Native upload consumed that exact crystal +and learned program 43371; normal self-casting applied the authored +14 1H Blunt. +Maximum nano became 22 through the trained ability's ordinary trickle. No +crystal, program, skill, resource or NCU grant was supplied. + +An ordinary fourth full-health Leet kill left 23/84 HP and raised XP to 400. +Opening its corpse collected 3 credits, giving 26. Native pickup moved its QL1 +Monster Part (27) to main inventory slot 68. Self-targeted seated recovery +restored resources, leaving 11 laboratory charges. The earned glove (26), bat +(19), shirt (22), map, board and three First Aid charges retained their identities +and quantities. The consumed crystal's learned program remained available. + +On the character-save candidate, native IP training then raised raw 1H Blunt +from 5 to 10 for 35 IP, leaving 1177. The native skill window changed from 22 to +27 with the same buff; page reconnect and a cold server/client restart retained +that value, all eight exact item instances, 400 XP and 26 credits. The comparison +uses raw SQL/native training requests separately from the effective skill shown +in the window. No page exception or adapter abort occurred. This verifies normal +successful training on the persistence fix, alongside its injected-failure +regressions in [IP training](ip-training.md#training-earned-rewards-and-persistence-failures). +It does not complete the remaining level-up or funded equipment-purchase gate. + +Four further ordinary full-health Leet kills brought this character to 800 XP +and 42 credits without a death. The glove and collected Monster Part retained +their exact identities. A second generated part expired on an uncollected corpse; +it is excluded from owned-loot accounting. Recovery after the eighth kill used +the final two laboratory charges, removing that empty instance. Normal seated +recovery then restored 84/84 HP and 22/22 nano. All seven remaining items and the +three unused First Aid charges are accounted for in +`local/earned-armor/hunt-verification.json`. This further exposes the sustained +recovery cost; missing health stims and hit/evade rules remain open, and no +provisional enemy balance was changed to complete the run. diff --git a/server/ip_training_persistence_test.go b/server/ip_training_persistence_test.go @@ -0,0 +1,77 @@ +package main + +import ( + "slices" + "testing" +) + +func TestSkillTrainingRejectsIncompleteWritesAndRetries(t *testing.T) { + for _, scenario := range []struct { + name, sql string + }{ + {"ignored update", `CREATE TRIGGER fault_training BEFORE UPDATE OF abilities_agility ON characters + WHEN NEW.id=1 BEGIN SELECT RAISE(IGNORE); END`}, + {"rewritten ability", `CREATE TRIGGER fault_training AFTER UPDATE OF abilities_agility ON characters + WHEN NEW.id=1 AND NEW.abilities_agility=12 BEGIN UPDATE characters SET abilities_agility=10 WHERE id=1; END`}, + {"rewritten IP", `CREATE TRIGGER fault_training AFTER UPDATE OF improvement_points ON characters + WHEN NEW.id=1 AND NEW.improvement_points=1440 BEGIN UPDATE characters SET improvement_points=1500 WHERE id=1; END`}, + {"late skill rewrite", `CREATE TRIGGER fault_training AFTER UPDATE OF last_character_id ON world + BEGIN UPDATE characters SET ranged_pistol=5 WHERE id=1; END`}, + {"late health rewrite", `CREATE TRIGGER fault_training AFTER UPDATE OF last_character_id ON world + BEGIN UPDATE characters SET health=1 WHERE id=1; END`}, + {"late player deletion", `CREATE TRIGGER fault_training AFTER UPDATE OF last_character_id ON world + BEGIN DELETE FROM characters WHERE id=1; END`}, + {"commit failure", `CREATE TRIGGER fault_training AFTER UPDATE OF abilities_agility ON characters + WHEN NEW.id=1 BEGIN INSERT INTO training_commit_failure VALUES(9999999); END`}, + } { + t.Run(scenario.name, func(t *testing.T) { + world, output := newTrainingWorld(t) + player, client := world.characters[1], world.clients[1] + before := player.stats + items := slices.Clone(player.inventory.Items) + health, nano := player.health, player.nano + trained := player.baseStats() + trained.Abilities.Agility, trained.Ranged.Pistol = 12, 8 + request := skillTrainingRequest(trained)[20:] + if _, err := world.db.Exec(`CREATE TABLE training_commit_failure ( + player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED)`); err != nil { + t.Fatal(err) + } + if _, err := world.db.Exec(scenario.sql); err != nil { + t.Fatal(err) + } + + failure := world.handleSkillTraining(client, request) + cold := newTestInventoryServer(t) + + if failure == nil || len(output.packets) != 0 || player.stats != before || player.savedProfile.Stats != before { + t.Fatal("incomplete training published success or changed live IP/stats", failure, player.stats) + } + for _, current := range []*server{world, cold} { + owner := current.characters[1] + if owner == nil || owner.stats != before || owner.health != health || owner.nano != nano || + !slices.Equal(owner.inventory.Items, items) { + t.Fatal("incomplete training changed durable ownership, resources or IP/stats", owner) + } + } + + if _, err := world.db.Exec("DROP TRIGGER fault_training"); err != nil { + t.Fatal(err) + } + for range 2 { + if err := world.handleSkillTraining(client, request); err != nil { + t.Fatal(err) + } + } + cold = newTestInventoryServer(t) + + for _, current := range []*server{world, cold} { + owner := current.characters[1] + if owner.stats.Abilities.Agility != 12 || owner.stats.Ranged.Pistol != 8 || owner.stats.ImprovementPoints != 1440 || + owner.health != health || owner.nano != nano || !slices.Equal(owner.inventory.Items, items) { + t.Fatal("training retry/replay changed price, resources or unrelated ownership", owner.stats, owner.inventory) + } + } + }) + } +} diff --git a/server/mission_reward_progression_test.go b/server/mission_reward_progression_test.go @@ -0,0 +1,150 @@ +package main + +import ( + "ao/server/gamedata" + "slices" + "testing" + "time" +) + +func TestMissionRewardWearRequiresLevelThenDurableAbilityTraining(t *testing.T) { + world, client, _ := enteredMissionEncounterWorld(t) + player, npc := world.characters[1], world.characters[2000004] + + // Keep a concrete promised item in the otherwise cash-only mission fixture. + player.missions[0].offer.definition.RewardItem = 85596 + player.missions[0].offer.definition.RewardQuality = 2 + world.missionExpiry[0] = player.missions[0] + if _, err := world.db.Exec("UPDATE missions SET reward_item=85596, reward_quality=2 WHERE id=?", player.missions[0].id); err != nil { + t.Fatal(err) + } + + // Use the starter's trained abilities and IP immediately below its first level. + player.appearance = player.appearance&^(7<<4) | 4<<4 + player.profession = 9 + player.stats = defaultCharacterStats(4) + player.stats.Abilities = characterAbilitiesStats{15, 9, 13, 3, 3, 3} + player.stats.Body.BodyDevelopment = 10 + player.stats.NanoAiding.Treatment = 9 + player.stats.ImprovementPoints = 1338 + player.health, player.nano = 84, 20 + player.experience = 1400 + player.position = npc.position + player.position[2]-- + + // Isolate the earned level boundary; this one-hit fixture does not test balance. + npc.health = 1 + world.combatRoll = func(uint32) uint32 { return 0 } + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + + trained := player.baseStats() + trained.Abilities.Agility = 11 + + if err := world.handleSkillTraining(client, skillTrainingRequest(trained)[20:]); err != nil { + t.Fatal(err) + } + cold := reloadMissionEntranceWorld(t) + + if player.level != 1 || player.stats.Abilities.Agility != 9 || player.stats.ImprovementPoints != 1338 || + cold.characters[1].stats != player.stats || player.maximumHealth() != 84 { + t.Fatal("level-one ability cap changed training, IP or its durable state", player.stats) + } + + if err := world.handleCombat(client, attackPacket(1, npc.id)[20:]); err != nil { + t.Fatal(err) + } + world.advanceCombat(player.nextAttack) + cold = reloadMissionEntranceWorld(t) + + if npc.health != 0 || player.level != 2 || player.experience != 50 || player.stats.ImprovementPoints != 5338 || + player.stats.Abilities.Agility != 9 || player.health != 84 || player.maximumHealth() != 91 || + cold.characters[1].level != 2 || cold.characters[1].experience != 50 || cold.characters[1].stats != player.stats { + t.Fatalf("earned kill boundary: level=%d XP=%d HP=%d/%d stats=%+v cold=%+v", + player.level, player.experience, player.health, player.maximumHealth(), player.stats, cold.characters[1].stats) + } + + // Let the killing swing finish recharging before isolating the wear requirement. + time.Sleep(time.Until(player.rechargeUntil)) + // Fixture positions isolate pickup and hand-in; native tests cover the journey. + player.position = world.worldItems[3].position + if err := world.handleInventory(client, worldPickupRequest(1, 3)); err != nil { + t.Fatal(err) + } + destination := player.userData() + destination.Playfield, destination.Position = 3000, gamedata.MissionBooths[3221228472].Position + if err := world.updateUser_locked(destination); err != nil { + t.Fatal(err) + } + world.clients[1], client.ready, client.loading = client, true, false + if err := world.handleMissionReturn(client, missionReturnRequest(1)); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(client, inventoryMovePacket(1, 65, 24)[20:]); err != nil { + t.Fatal(err) + } + cold = reloadMissionEntranceWorld(t) + + expected := []ownedItem{ + {ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 64, Count: 1}, + {ID: 5, Type: 51022, Template: 85596, Quality: 2, Slot: 65, Count: 1}, + } + if client.equipment != nil || !slices.Equal(player.inventory.Items, expected) || !slices.Equal(cold.characters[1].inventory.Items, expected) || + player.inventory.Credits != 24 || player.experience != 50 || player.stats.ImprovementPoints != 5338 || + len(player.missions) != 0 || !cold.missionExpiry[0].completed { + t.Fatal("level-up changed the promised reward or untrained wear lost it", player.inventory, player.stats) + } + + if _, err := world.db.Exec(`CREATE TRIGGER reject_reward_training BEFORE UPDATE OF abilities_agility ON characters + WHEN NEW.id=1 AND NEW.abilities_agility=11 BEGIN SELECT RAISE(ABORT, 'training failure'); END`); err != nil { + t.Fatal(err) + } + trained = player.baseStats() + trained.Abilities.Agility = 11 + + failure := world.handleSkillTraining(client, skillTrainingRequest(trained)[20:]) + cold = reloadMissionEntranceWorld(t) + + if failure == nil || player.stats.Abilities.Agility != 9 || player.stats.ImprovementPoints != 5338 || + cold.characters[1].stats != player.stats || !slices.Equal(player.inventory.Items, expected) || + !slices.Equal(cold.characters[1].inventory.Items, expected) { + t.Fatal("failed training spent earned IP, changed abilities or lost the reward", failure, player.stats) + } + + if _, err := world.db.Exec("DROP TRIGGER reject_reward_training"); err != nil { + t.Fatal(err) + } + if err := world.handleSkillTraining(client, skillTrainingRequest(trained)[20:]); err != nil { + t.Fatal(err) + } + for _, move := range [][2]uint32{{65, 24}, {24, 65}, {65, 24}} { + request := inventoryMovePacket(1, move[0], move[1]) + if move[0] < 64 { + request = itemMovePacket(1, move[0], move[1]) + } + if err := world.handleInventory(client, request[20:]); err != nil || client.equipment == nil { + t.Fatal("earned training did not permit reward wear/remove", move, err, player.stats.Abilities, player.inventory, player.rechargeUntil) + } + world.advanceEquipment(client.equipment.readyAt) + expected[1].Slot = move[1] + cold = reloadMissionEntranceWorld(t) + + armor := int32(0) + if move[1] == 24 { + armor = 2 + } + for _, current := range []*server{world, cold} { + owner := current.characters[1] + if !slices.Equal(owner.inventory.Items, expected) || owner.stats.Abilities.Agility != 11 || owner.stats.ImprovementPoints != 5300 || + owner.level != 2 || owner.experience != 50 || owner.health != 84 || owner.inventory.Credits != 24 || + owner.inventory.equipmentBonus(91) != armor || current.nextItem != 5 || + current.items[4].Template != 42640 || current.itemPlacements[4] != (itemPlacement{Corpse: 2000004}) { + t.Fatal("trained reward lifecycle changed identities, effects, earned state or unclaimed loot", move, owner.inventory, owner.stats) + } + } + } +} diff --git a/server/users.go b/server/users.go @@ -218,12 +218,21 @@ func (server *server) saveUser_locked(character *character) error { return err } vitals := character.vitals() - if err := updateRecord(tx, "characters", character.id, profileColumns+", "+vitalColumns, append(profile.fields(), vitals.fields()...)); err != nil { + columns := profileColumns + ", " + vitalColumns + fields := append(profile.fields(), vitals.fields()...) + if err := updateRecord(tx, "characters", character.id, columns, fields); err != nil { return err } if _, err := tx.Exec("UPDATE world SET last_character_id = max(last_character_id, ?) WHERE id = 1", character.id); err != nil { return err } + + // Verify the final profile and vitals before committing their transaction. + var savedID uint32 + query := "SELECT id FROM characters WHERE id=? AND (" + columns + ") IS (?" + strings.Repeat(", ?", len(fields)-1) + ")" + if err := tx.QueryRow(query, append([]any{character.id}, fields...)...).Scan(&savedID); err != nil { + return fmt.Errorf("character %d profile and resources were not saved: %w", character.id, err) + } if err := tx.Commit(); err != nil { return err }