commit 25965496cb9924c773eda36d02ddd952ce8ab344
parent c1c9852540f1bd473762f6538d250123943ae909
Author: anon <anon@example.com>
Date: Wed, 28 Oct 2026 17:44:23 +0000
Persist mission encounter progress with combat outcomes
Diffstat:
7 files changed, 655 insertions(+), 3 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -1736,6 +1736,14 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md).
Shared combat visibility now rejects obstructions; broader encounter and
navigation coverage remains separate. See
[mission encounters](docs/mission-encounters.md).
+- [ ] [P0] Verify and fix native targeting of every fixed-mission placement.
+ The ordinary earned-character run could fight the encounters at Z28, Z36
+ and Z43, but could not select the far-wall Z48 encounter through Tab or a
+ visible-body click. Its native root settled near Z48.26 while the saved root
+ remained Z48. Diagnose room admission, mesh/body placement and native picking
+ before changing the placement or visibility rules. Verify every enemy can be
+ selected and defeated without provisioning; retain negative wall/LOS checks.
+ Captures are under `local/mission-kill-progress/`.
- [x] [P0] Route indoor combatants around actual mesh obstructions. A bounded
shared search probes candidate steps with the actor's original body, room,
floor, wall, slope and gravity handling. Pursuit and exact return-home routes
@@ -1767,6 +1775,13 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md).
using the persistent faction counters. Cover strict token/level/faction gates,
upgrades, all companion bonuses, removal and cold recovery. Redemption alone
does not establish board upgrade effects or broader event admission.
+- [x] Retain each accepted mission's concrete population and deaths independently
+ of corpse lifetime. Acceptance saves NPC identities and selected levels; the
+ shared killing outcome records each death once with its costs, loot and XP.
+ Cold restoration, seven killing actions, capped-XP kills, private-world/guest
+ isolation, completion/retirement and SQL failure/ignored-write/commit retries
+ have focused checks. These raw facts do not establish token eligibility or
+ completion XP; see [mission progress](docs/mission-progress.md).
- [ ] [P0] Recover token/XP eligibility and implement atomic eligible mission
rewards. The original offer details qualify XP with "Which you get when you
receive a token." Period notes increase token chance with kills; completion
@@ -1774,8 +1789,9 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md).
exceptions and XP arithmetic before awarding completion XP/tokens. Original
faction token Use descriptors recover level-dependent value and Unique/side
checks, but do not establish mission eligibility. Keep token acquisition and
- right-click upload distinct. Commit any required mission kill-progress ledger
- with the shared kill outcome; expiring corpses must not erase earned eligibility. Cover full inventory and failed-commit/retry; see
+ right-click upload distinct. Use the persisted population/death facts without
+ assuming every recorded enemy qualifies. Cover full inventory and
+ failed-commit/retry; see
[token evidence](docs/mission-encounters.md#completion-token-evidence).
- [ ] [P1] Extend return-item submission to native carried-backpack sources after
verifying their original producer/callback. Main-inventory hand-in is verified;
diff --git a/docs/mission-progress.md b/docs/mission-progress.md
@@ -0,0 +1,93 @@
+# Mission population and kill progress
+
+Every newly accepted concrete encounter has one `mission_encounters` row with
+its NPC identity, assignment, selected level and a death flag. Acceptance saves
+the rows with the assignment, key, doors, NPCs and identity allocation.
+
+The first living-to-dead transition marks the matching row in the shared NPC
+outcome transaction. Ordinary weapons, specials, direct nanos and periodic
+damage therefore commit progress with health, loot, XP and the killing action's
+costs. A missing or mismatched encounter row, ignored write, changed result or
+failed commit rejects that outcome. Repeated attacks and ordinary checkpoints
+do not mark the death again or rewrite the population.
+
+Rows reference the assignment rather than the live character table. Corpse
+expiry can remove the actor and unclaimed loot while retaining the population
+and death facts. Objective completion retains them with the completed instance.
+Abandonment or instance expiry removes them through the assignment's existing
+transaction and foreign-key cascade. A failed retirement retains both the
+assignment and progress for retry. Separate private worlds retain separate rows;
+a guest's kill records a death in the world it actually occurred in.
+
+These are raw facts, including deaths that award no kill XP. They do not decide
+which enemies qualify, a token chance, or conditional completion XP. Extra
+spawned creatures, grey-enemy eligibility, minimum kills, rounding, neutral and
+Unique-token interactions still require reward rules. No new completion reward
+or token-chance feedback is emitted by this bookkeeping.
+
+## Evidence boundary
+
+The [original 14.0 release text](https://www.gamereactor.no/anarchy-online-oppdaterer-til-v140/)
+and a [contemporary September 2002 player review](https://gamefaqs.gamespot.com/pc/913777-anarchy-online/reviews/40336)
+establish kill-dependent token chances. The review gives an illustrative
+proportion; it does not establish thresholds or all exceptions. The later
+[2007 player guide](https://gamefaqs.gamespot.com/pc/913777-anarchy-online/faqs/46197)
+describes a minimum approximately, and distinguishes ordinary and extra enemies.
+It cannot select an exact 14.9.1 predicate. The bounded follow-up search did not
+recover that predicate. Earlier source limits remain in
+[completion token evidence](mission-encounters.md#completion-token-evidence).
+
+The initial rows describe this fixed contract's admitted population. Their
+count is not proof of the original reward denominator. Persisting original
+selected levels also does not establish the historical grey cutoff. The rows
+preserve the available facts while those policies remain unresolved.
+
+## Verification
+
+`server/mission_progress_test.go` uses public acceptance, combat, inventory,
+objective return and retirement handlers. It covers seven killing actions,
+repeated requests, cold restoration after corpse deletion, exact selected levels,
+one progress write per death, capped-XP kills, guest/world isolation, completed
+instance retention and abandonment/expiry. Faults cover aborted or ignored
+population writes, deleted or rewritten rows, progress undo/rewrites, later loot
+and XP failures, deferred commit failures, and retirement failures. A failed
+periodic death retains the same due tick for retry.
+
+The full server/export regression passed 1,641 test roots and 16,154 results;
+focused race checks passed 18 roots and 91 results. Vet and the preview build
+passed. Subsequent focused checks also verify capped-XP kills and cold-loaded
+ammunition/nano costs across failure and retry. Fling retains its existing
+pre-15.5.5 ammunition rule.
+
+GPU WASM testing resumed the earned level-2 Enforcer with its existing bat,
+trained skills, buff and purchased laboratory. Four encounters began at their
+full 100 HP and died through ordinary native combat, each awarding 100 kill XP.
+The database retained five population rows and four deaths while normal corpse
+expiry removed the dead actors. The third corpse awarded five credits and
+displayed its Monster Part; right-clicking that item did not transfer it to the
+inventory, and it was allowed to expire unclaimed. No character, enemy, cash
+or equipment was provisioned for this run.
+
+The far-wall encounter remains alive. Its native root settled near Z48.26 while
+the saved root remained Z48, and Tab/visible-body clicks did not select it from
+the tested approaches. This is an explicit P0 placement/selection follow-up,
+not proof of a fully clearable room. A north-side book click selected the open
+door instead; approaching the visible book from the south allowed normal
+R/Pick Up into slot70. Neither observation changes reward eligibility policy.
+
+Returning that bound book through the native terminal interaction completed the
+assignment, removed the key/book, awarded 20 credits and a QL2 Metaplast glove,
+and retained all five population rows and four deaths. Native cumulative XP
+remained 2000 (550 within level2); completion did not invent a token or XP award.
+Ten purchased laboratory charges were used across recovery between fights.
+
+After all four corpses expired, a cold server restart retained the exact five
+population rows, completed assignment, one surviving enemy, 29 credits, both
+earned QL2 gloves, 39 laboratory charges, XP, IP and learned programs. Database
+integrity and foreign-key checks passed. A fresh GPU WASM client showed
+91/91 HP, 24 nano, level2, 2000 cumulative XP, 5139 IP, 29 credits and the
+retained inventory with both QL2 glove icons and 39 laboratory charges. No
+browser exceptions or adapter aborts were recorded. Owned test clients were
+closed, leaving the sole default-port HTTPS preview available.
+
+Automated logs and native evidence are retained in `local/mission-kill-progress/`.
diff --git a/server/item_database.go b/server/item_database.go
@@ -201,6 +201,14 @@ func (server *server) persistItems_locked(store itemStore) error {
if err := writeNPCState_locked(tx, npc, &state); err != nil {
return err
}
+ if err := insertRow(tx, "mission_encounters", "npc_id, mission_id, level", []any{npc.id, store.mission.id, npc.level}); err != nil {
+ return err
+ }
+ var savedID uint32
+ if err := tx.QueryRow("SELECT npc_id FROM mission_encounters WHERE npc_id=? AND mission_id=? AND level=? AND killed=0",
+ npc.id, store.mission.id, npc.level).Scan(&savedID); err != nil {
+ return fmt.Errorf("mission %d encounter %d was not saved: %w", store.mission.id, npc.id, err)
+ }
savedNPCs[npc.id] = savedNPC{State: state, NextSave: time.Now().Add(20 * time.Second)}
}
}
diff --git a/server/mission_progress_test.go b/server/mission_progress_test.go
@@ -0,0 +1,513 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "encoding/binary"
+ "fmt"
+ "testing"
+ "time"
+)
+
+func TestMissionEncounterProgressRetainsEachSelectedLevel(t *testing.T) {
+ world, _ := newMissionEncounterOfferWorld(t)
+ client := world.clients[1]
+ client.missionOffer.definition.Encounters = []gamedata.MissionEncounter{
+ {Definition: "950/district/2/group/0/authored_point", Level: 1, Positions: [][3]float32{{15, .011, 48}}},
+ {Definition: "950/district/2/group/0/authored_point", Level: 2, Positions: [][3]float32{{15, .011, 43}}},
+ }
+
+ if err := world.handleMissionAcceptance(client, missionAcceptanceRequest(*client.missionOffer)); err != nil {
+ t.Fatal(err)
+ }
+ cold := reloadMissionEntranceWorld(t)
+
+ for _, expected := range []struct {
+ id uint32
+ level uint16
+ }{{2000000, 1}, {2000001, 2}} {
+ var level uint16
+ if err := cold.db.QueryRow("SELECT level FROM mission_encounters WHERE npc_id=?", expected.id).Scan(&level); err != nil {
+ t.Fatal(err)
+ }
+ if level != expected.level || cold.characters[expected.id].level != expected.level {
+ t.Fatal("population progress lost the accepted encounter level", expected.id, level)
+ }
+ }
+}
+
+func newMissionProgressCombatWorld(t *testing.T, attack string) (*server, *worldClient, *character, *combatTestConn) {
+ t.Helper()
+ world, client, output := enteredMissionEncounterWorld(t)
+ player, npc := world.characters[1], world.characters[2000003]
+ player.position, npc.health = [3]float32{15, .011, 27}, 1
+ player.stats = testCharacterStats()
+ world.combatRoll = func(uint32) uint32 { return 0 }
+ if attack == "axe" || attack == "fast" || attack == "pistol" || attack == "fling" {
+ weapon := ownedItem{ID: world.nextItem + 1, Type: 51018, Template: 209283, Quality: 1, Slot: 6, Count: 1}
+ if attack == "pistol" || attack == "fling" {
+ weapon.Template, weapon.Ammo = 123742, 3
+ }
+ player.inventory.Items = append(player.inventory.Items, weapon)
+ player.inventory.LastID = weapon.ID
+ }
+ if attack == "nano" || attack == "dot" {
+ player.profession, player.nano = 8, 30
+ player.stats.NanoAiding.PsychologicalModification, player.stats.NanoAiding.MatterCreation = 7, 6
+ player.inventory.LearnedNanos = []uint32{29618}
+ if attack == "dot" {
+ player.profession = 10
+ player.stats.NanoAiding.BiologicalMetamorphosis, player.stats.NanoAiding.MatterCreation = 9, 8
+ player.inventory.LearnedNanos = []uint32{43376}
+ }
+ }
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.saveInventory_locked(player, player.inventory); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ output.packets = nil
+ return world, client, npc, output
+}
+
+func missionProgressAttack(world *server, attack string) error {
+ client, npc := world.clients[1], world.characters[2000003]
+ switch attack {
+ case "fast":
+ return world.handleWeaponSpecial(client, fastAttackRequest(1, npc.id)[20:])
+ case "fling":
+ return world.handleWeaponSpecial(client, flingShotRequest(1, npc.id)[20:])
+ case "nano", "dot":
+ program := uint32(29618)
+ if attack == "dot" {
+ program = 43376
+ }
+ if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, npc.id, 53019, program})[20:]); err != nil {
+ return err
+ }
+ if client.nanoCast == nil {
+ return fmt.Errorf("mission progress fixture's cast was rejected")
+ }
+ world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond))
+ if attack == "dot" && len(npc.activeNanos) != 0 {
+ world.advanceNanos(npc.activeNanos[0].nextTick)
+ }
+ default:
+ if err := world.handleCombat(client, attackPacket(1, npc.id)[20:]); err != nil {
+ return err
+ }
+ world.advanceCombat(world.characters[1].nextAttack)
+ }
+ return nil
+}
+
+func TestMissionEncounterProgressSurvivesDeathAndCorpseExpiry(t *testing.T) {
+ world, client, output := enteredMissionEncounterWorld(t)
+ player, npc := world.characters[1], world.characters[2000003]
+ player.position = [3]float32{15, .011, 27}
+ npc.health = 1
+ world.combatRoll = func(uint32) uint32 { return 0 }
+ var initial, dead int
+ if err := world.db.QueryRow("SELECT count(*),sum(killed) FROM mission_encounters WHERE mission_id=?", player.missions[0].id).Scan(&initial, &dead); err != nil {
+ t.Fatal(err)
+ }
+ if initial != 5 || dead != 0 {
+ t.Fatal("acceptance did not record the concrete initial population", initial, dead)
+ }
+
+ if err := world.handleCombat(client, attackPacket(player.id, npc.id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceCombat(player.nextAttack)
+ if npc.health != 0 || npc.corpse == nil {
+ t.Fatal("fixture did not complete its killing swing")
+ }
+ world.advanceCorpseExpiry(npc.corpse.expiresAt)
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ cold := reloadMissionEntranceWorld(t)
+
+ if err := cold.db.QueryRow("SELECT count(*),sum(killed) FROM mission_encounters WHERE mission_id=?", player.missions[0].id).Scan(&initial, &dead); err != nil {
+ t.Fatal(err)
+ }
+ var remaining int
+ if err := cold.db.QueryRow("SELECT count(*) FROM characters WHERE id=?", npc.id).Scan(&remaining); err != nil {
+ t.Fatal(err)
+ }
+ if initial != 5 || dead != 1 || remaining != 0 || cold.characters[npc.id] != nil || cold.characters[player.id].experience != 100 {
+ t.Fatal("corpse cleanup lost the mission kill or recreated its enemy", initial, dead, remaining)
+ }
+ for _, packet := range output.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x5f2e1b19 {
+ t.Fatal("recording a kill completed the objective")
+ }
+ }
+}
+
+func TestMissionEncounterProgressCountsADeathOnce(t *testing.T) {
+ world, client, _ := enteredMissionEncounterWorld(t)
+ player, npc := world.characters[1], world.characters[2000003]
+ player.position = [3]float32{15, .011, 27}
+ npc.health = 1
+ world.combatRoll = func(uint32) uint32 { return 0 }
+ if _, err := world.db.Exec("CREATE TABLE progress_writes (count INTEGER); INSERT INTO progress_writes VALUES(0); CREATE TRIGGER count_progress AFTER UPDATE ON mission_encounters BEGIN UPDATE progress_writes SET count=count+1; END"); err != nil {
+ t.Fatal(err)
+ }
+
+ request := attackPacket(player.id, npc.id)[20:]
+ if err := world.handleCombat(client, request); err != nil {
+ t.Fatal(err)
+ }
+ at := player.nextAttack
+ world.advanceCombat(at)
+ if err := world.handleCombat(client, request); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceCombat(at.Add(time.Minute))
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+
+ var killed int
+ if err := world.db.QueryRow("SELECT sum(killed) FROM mission_encounters WHERE mission_id=?", player.missions[0].id).Scan(&killed); err != nil {
+ t.Fatal(err)
+ }
+ var writes int
+ if err := world.db.QueryRow("SELECT count FROM progress_writes").Scan(&writes); err != nil {
+ t.Fatal(err)
+ }
+ if killed != 1 || writes != 1 || player.experience != 100 || npc.health != 0 {
+ t.Fatal("repeat attack or checkpoint counted a second mission kill", killed, player.experience)
+ }
+}
+
+func TestMissionEncounterProgressAcceptanceFailureRollsBackAndRetries(t *testing.T) {
+ for _, fault := range []struct{ name, sql string }{
+ {"abort", "CREATE TRIGGER fail_population BEFORE INSERT ON mission_encounters BEGIN SELECT RAISE(FAIL,'population'); END"},
+ {"ignore", "CREATE TRIGGER fail_population BEFORE INSERT ON mission_encounters BEGIN SELECT RAISE(IGNORE); END"},
+ {"delete", "CREATE TRIGGER fail_population AFTER INSERT ON mission_encounters BEGIN DELETE FROM mission_encounters WHERE npc_id=NEW.npc_id; END"},
+ {"rewrite", "CREATE TRIGGER fail_population AFTER INSERT ON mission_encounters BEGIN UPDATE mission_encounters SET level=level+1 WHERE npc_id=NEW.npc_id; END"},
+ {"commit", "CREATE TABLE pending_population (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_population AFTER INSERT ON mission_encounters BEGIN INSERT INTO pending_population VALUES(999999); END"},
+ } {
+ t.Run(fault.name, func(t *testing.T) {
+ world, output := newMissionEncounterOfferWorld(t)
+ client := world.clients[1]
+ request := missionAcceptanceRequest(*client.missionOffer)
+ beforeItem, beforeNPC := world.nextItem, world.nextNPC
+ if _, err := world.db.Exec(fault.sql); err != nil {
+ t.Fatal(err)
+ }
+
+ err := world.handleMissionAcceptance(client, request)
+ cold := reloadMissionEntranceWorld(t)
+
+ var count int
+ if failure := cold.db.QueryRow("SELECT count(*) FROM mission_encounters").Scan(&count); failure != nil {
+ t.Fatal(failure)
+ }
+ if err == nil || count != 0 || client.missionOffer == nil || len(world.characters[1].missions) != 0 || len(cold.missionExpiry) != 0 ||
+ world.nextItem != beforeItem || world.nextNPC != beforeNPC || len(world.characters) != 2 || len(cold.characters) != 2 || len(output.packets) != 0 {
+ t.Fatal("failed population write leaked an assignment, actors, identities or success", count, err)
+ }
+
+ // The same offer can commit once after the fault is removed.
+ if _, err := world.db.Exec("DROP TRIGGER fail_population"); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleMissionAcceptance(client, request); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.db.QueryRow("SELECT count(*) FROM mission_encounters WHERE killed=0 AND level=1").Scan(&count); err != nil {
+ t.Fatal(err)
+ }
+ if count != 5 || world.nextItem != beforeItem+1 || world.nextNPC != beforeNPC+5 || len(world.characters) != 7 {
+ t.Fatal("acceptance retry lost or repeated population identities", count, world.nextItem, world.nextNPC)
+ }
+ })
+ }
+}
+
+func TestMissionEncounterProgressIsolatesWorldsAndRetiresWithItsAssignment(t *testing.T) {
+ for _, reason := range []string{"abandon", "expire"} {
+ t.Run(reason, func(t *testing.T) {
+ world, _ := newMissionBoundaryWorld(t)
+ npc := world.characters[2000001]
+ npc.health = 1
+ world.combatRoll = func(uint32) uint32 { return 0 }
+ first, second := world.characters[1].missions[0], world.characters[2].missions[0]
+
+ if err := world.handleCombat(world.clients[3], attackPacket(3, npc.id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceCombat(world.characters[3].nextAttack)
+
+ for _, expected := range []struct {
+ mission uint32
+ kills int
+ }{{first.id, 1}, {second.id, 0}} {
+ var killed int
+ if err := world.db.QueryRow("SELECT sum(killed) FROM mission_encounters WHERE mission_id=?", expected.mission).Scan(&killed); err != nil {
+ t.Fatal(err)
+ }
+ if killed != expected.kills {
+ t.Fatal("guest kill counted toward another private world", expected.mission, killed)
+ }
+ }
+ if reason == "abandon" {
+ if err := world.handleMissionRemoval(world.clients[1], missionRemovalPacket(1, first.id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ world.advanceMissions(first.expiresAt)
+ }
+ var firstRows, secondRows int
+ if err := world.db.QueryRow("SELECT count(*) FROM mission_encounters WHERE mission_id=?", first.id).Scan(&firstRows); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.db.QueryRow("SELECT count(*) FROM mission_encounters WHERE mission_id=?", second.id).Scan(&secondRows); err != nil {
+ t.Fatal(err)
+ }
+ if firstRows != 0 || secondRows != 5 {
+ t.Fatal("retirement retained old progress or erased another world's population", firstRows, secondRows)
+ }
+ })
+ }
+}
+
+func TestMissionEncounterProgressSharesAllKillingActions(t *testing.T) {
+ for _, attack := range []string{"unarmed", "axe", "pistol", "fast", "fling", "nano", "dot"} {
+ t.Run(attack, func(t *testing.T) {
+ world, _, npc, _ := newMissionProgressCombatWorld(t, attack)
+
+ if err := missionProgressAttack(world, attack); err != nil {
+ t.Fatal(err)
+ }
+ cold := reloadMissionEntranceWorld(t)
+
+ var count, killed int
+ if err := cold.db.QueryRow("SELECT count(*),sum(killed) FROM mission_encounters").Scan(&count, &killed); err != nil {
+ t.Fatal(err)
+ }
+ if count != 5 || killed != 1 || npc.health != 0 || npc.corpse == nil || cold.characters[1].experience != 100 {
+ t.Fatal("killing action lost population, kill progress or its ordinary reward", count, killed, npc.health)
+ }
+ })
+ }
+}
+
+func TestMissionEncounterProgressFailureRollsBackTheDeathAndRetries(t *testing.T) {
+ for _, attack := range []string{"unarmed", "pistol", "fast", "fling", "nano"} {
+ for _, fault := range []struct{ name, sql string }{
+ {"abort", "CREATE TRIGGER fail_progress BEFORE UPDATE ON mission_encounters BEGIN SELECT RAISE(FAIL,'progress'); END"},
+ {"ignore", "CREATE TRIGGER fail_progress BEFORE UPDATE ON mission_encounters BEGIN SELECT RAISE(IGNORE); END"},
+ {"undo", "CREATE TRIGGER fail_progress AFTER UPDATE ON mission_encounters BEGIN UPDATE mission_encounters SET killed=0 WHERE npc_id=NEW.npc_id; END"},
+ {"rewrite", "CREATE TRIGGER fail_progress AFTER UPDATE ON mission_encounters BEGIN UPDATE mission_encounters SET level=level+1 WHERE npc_id=NEW.npc_id; END"},
+ {"loot", "CREATE TRIGGER fail_progress BEFORE INSERT ON items BEGIN SELECT RAISE(FAIL,'loot'); END"},
+ {"XP", "CREATE TRIGGER fail_progress BEFORE UPDATE OF experience ON characters WHEN NEW.id=1 AND NEW.experience>OLD.experience BEGIN SELECT RAISE(FAIL,'XP'); END"},
+ {"commit", "CREATE TABLE pending_progress (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_progress AFTER UPDATE ON mission_encounters BEGIN INSERT INTO pending_progress VALUES(999999); END"},
+ } {
+ t.Run(attack+"/"+fault.name, func(t *testing.T) {
+ world, _, npc, output := newMissionProgressCombatWorld(t, attack)
+ before := world.nextItem
+ if _, err := world.db.Exec(fault.sql); err != nil {
+ t.Fatal(err)
+ }
+
+ err := missionProgressAttack(world, attack)
+ cold := reloadMissionEntranceWorld(t)
+
+ if (attack == "fast" || attack == "fling") && err == nil {
+ t.Fatal("failed special returned success")
+ }
+ var killed int
+ if err := cold.db.QueryRow("SELECT sum(killed) FROM mission_encounters").Scan(&killed); err != nil {
+ t.Fatal(err)
+ }
+ if killed != 0 || npc.health != 1 || npc.corpse != nil || cold.characters[npc.id].health != 1 || world.characters[1].experience != 0 ||
+ cold.characters[1].experience != 0 || world.nextItem != before || cold.nextItem != before {
+ t.Fatal("failed outcome leaked kill progress, death, XP or an item allocation", killed, npc.health)
+ }
+ if attack == "pistol" || attack == "fling" {
+ for _, player := range []*character{world.characters[1], cold.characters[1]} {
+ if player.inventory.Items[len(player.inventory.Items)-1].Ammo != 3 {
+ t.Fatal("failed progress consumed a round")
+ }
+ }
+ }
+ if attack == "nano" && (world.characters[1].nano != 30 || world.characters[1].nanoReserved != 0 || cold.characters[1].nano != 30 || cold.characters[1].nanoReserved != 0) {
+ t.Fatal("failed progress retained a nano cost or reservation")
+ }
+ for _, packet := range output.packets {
+ switch binary.BigEndian.Uint32(packet[16:20]) {
+ case 0x46002f16, 0x754f1115, 0x4727213e, 0x4f474e05, 0x7f405a16:
+ t.Fatalf("failed outcome published damage, death or XP: %x", packet)
+ case 0x5e477770:
+ if binary.BigEndian.Uint32(packet[29:33]) == 99 {
+ t.Fatal("failed outcome published a death action")
+ }
+ }
+ }
+
+ // Retry the public action after removing the transactional fault.
+ if _, err := world.db.Exec("DROP TRIGGER fail_progress"); err != nil {
+ t.Fatal(err)
+ }
+ if err := missionProgressAttack(world, attack); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.db.QueryRow("SELECT sum(killed) FROM mission_encounters").Scan(&killed); err != nil {
+ t.Fatal(err)
+ }
+ if killed != 1 || npc.health != 0 || world.characters[1].experience != 100 || world.nextItem != before+1 {
+ t.Fatal("retry failed to commit one kill and its ordinary reward", killed, npc.health, world.characters[1].experience)
+ }
+ cold = reloadMissionEntranceWorld(t)
+ if attack == "pistol" || attack == "fling" {
+ for _, player := range []*character{world.characters[1], cold.characters[1]} {
+ if attack == "pistol" && player.inventory.Items[len(player.inventory.Items)-1].Ammo != 2 || attack == "fling" && player.inventory.Items[len(player.inventory.Items)-1].Ammo != 3 {
+ t.Fatal("progress retry changed ammunition beyond the killing action's cost")
+ }
+ }
+ }
+ if attack == "nano" && (world.characters[1].nano != 21 || world.characters[1].nanoReserved != 0 || cold.characters[1].nano != 21 || cold.characters[1].nanoReserved != 0) {
+ t.Fatal("progress retry did not consume exactly one nano cost")
+ }
+ })
+ }
+ }
+}
+
+func TestMissionEncounterProgressFailedPeriodicDeathRetriesTheSameTick(t *testing.T) {
+ world, client, npc, _ := newMissionProgressCombatWorld(t, "dot")
+ if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, npc.id, 53019, 43376})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if client.nanoCast == nil {
+ t.Fatal("fixture did not start the periodic program")
+ }
+ world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond))
+ if len(npc.activeNanos) != 1 {
+ t.Fatal("fixture did not install the periodic effect")
+ }
+ tick := npc.activeNanos[0].nextTick
+ if _, err := world.db.Exec("CREATE TRIGGER fail_tick BEFORE UPDATE ON mission_encounters BEGIN SELECT RAISE(FAIL,'tick'); END"); err != nil {
+ t.Fatal(err)
+ }
+
+ world.advanceNanos(tick)
+
+ var killed int
+ if err := world.db.QueryRow("SELECT sum(killed) FROM mission_encounters").Scan(&killed); err != nil {
+ t.Fatal(err)
+ }
+ if killed != 0 || npc.health != 1 || npc.corpse != nil || len(npc.activeNanos) != 1 || npc.activeNanos[0].ticksLeft != 8 || !npc.activeNanos[0].nextTick.Equal(tick) || world.characters[1].experience != 0 {
+ t.Fatal("failed periodic death consumed the tick or published its kill", killed, npc.activeNanos)
+ }
+ if _, err := world.db.Exec("DROP TRIGGER fail_tick"); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceNanos(tick.Add(time.Nanosecond))
+ if err := world.db.QueryRow("SELECT sum(killed) FROM mission_encounters").Scan(&killed); err != nil {
+ t.Fatal(err)
+ }
+ if killed != 1 || npc.health != 0 || len(npc.activeNanos) != 0 || npc.corpse == nil || world.characters[1].experience != 100 {
+ t.Fatal("retry failed to commit the original lethal tick exactly once", killed, npc.health)
+ }
+}
+
+func TestMissionEncounterProgressRetirementFailureKeepsThePopulationForRetry(t *testing.T) {
+ for _, operation := range []string{"FAIL,'retirement'", "IGNORE"} {
+ t.Run(operation, func(t *testing.T) {
+ world, client, _ := enteredMissionEncounterWorld(t)
+ mission := world.characters[1].missions[0]
+ if _, err := world.db.Exec("CREATE TRIGGER fail_retirement BEFORE DELETE ON mission_encounters BEGIN SELECT RAISE(" + operation + "); END"); err != nil {
+ t.Fatal(err)
+ }
+
+ err := world.handleMissionRemoval(client, missionRemovalPacket(1, mission.id)[20:])
+ cold := reloadMissionEntranceWorld(t)
+
+ var count int
+ if failure := cold.db.QueryRow("SELECT count(*) FROM mission_encounters WHERE mission_id=?", mission.id).Scan(&count); failure != nil {
+ t.Fatal(failure)
+ }
+ if err == nil || count != 5 || len(world.characters[1].missions) != 1 || len(cold.characters[1].missions) != 1 || len(world.mobileNPCs[mission.world]) != 5 {
+ t.Fatal("failed retirement erased progress or the active assignment", count, err)
+ }
+ if _, err := world.db.Exec("DROP TRIGGER fail_retirement"); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleMissionRemoval(client, missionRemovalPacket(1, mission.id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.db.QueryRow("SELECT count(*) FROM mission_encounters WHERE mission_id=?", mission.id).Scan(&count); err != nil {
+ t.Fatal(err)
+ }
+ if count != 0 || len(world.characters[1].missions) != 0 || len(world.mobileNPCs[mission.world]) != 0 {
+ t.Fatal("retirement retry retained the population", count)
+ }
+ })
+ }
+}
+
+func TestMissionEncounterProgressDoesNotDependOnReceivingKillXP(t *testing.T) {
+ world, _, npc, _ := newMissionProgressCombatWorld(t, "unarmed")
+ player := world.characters[1]
+ player.level = 200
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := missionProgressAttack(world, "unarmed"); err != nil {
+ t.Fatal(err)
+ }
+ cold := reloadMissionEntranceWorld(t)
+
+ var killed int
+ if err := cold.db.QueryRow("SELECT sum(killed) FROM mission_encounters").Scan(&killed); err != nil {
+ t.Fatal(err)
+ }
+ if killed != 1 || npc.health != 0 || player.experience != 0 || cold.characters[1].experience != 0 || cold.characters[1].level != 200 {
+ t.Fatal("raw kill history depended on XP award eligibility", killed, npc.health, player.experience)
+ }
+}
+
+func TestMissionEncounterProgressCompletionRetainsHistoryUntilExpiry(t *testing.T) {
+ world, client, _, _ := killedMissionEncounterWorld(t)
+ player := world.characters[1]
+ mission := player.missions[0]
+ player.position = world.worldItems[mission.objective].position
+ if err := world.handleInventory(client, worldPickupRequest(1, mission.objective)); 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)
+ }
+ cold := reloadMissionEntranceWorld(t)
+
+ var count, killed int
+ if err := cold.db.QueryRow("SELECT count(*),sum(killed) FROM mission_encounters WHERE mission_id=?", mission.id).Scan(&count, &killed); err != nil {
+ t.Fatal(err)
+ }
+ if count != 5 || killed != 1 || !cold.missionExpiry[0].completed || cold.characters[1].experience != 100 || cold.characters[1].inventory.Credits != 24 {
+ t.Fatal("objective completion lost kill history or changed its reward policy", count, killed)
+ }
+ world.advanceMissions(mission.expiresAt)
+ if err := world.db.QueryRow("SELECT count(*) FROM mission_encounters WHERE mission_id=?", mission.id).Scan(&count); err != nil {
+ t.Fatal(err)
+ }
+ if count != 0 {
+ t.Fatal("completed instance expiry retained its population history", count)
+ }
+}
diff --git a/server/npc_navigation_test.go b/server/npc_navigation_test.go
@@ -313,7 +313,7 @@ func TestMissionNPCFailedDeathCancelsItsDetourAndReturnsAlive(t *testing.T) {
t.Fatal("failed death did not cancel the old detour and return a living NPC", npc.health, npc.position, npc.motion)
}
for _, packet := range output.packets {
- if binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && binary.BigEndian.Uint32(packet[24:28]) == npc.id {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && binary.BigEndian.Uint32(packet[24:28]) == npc.id && binary.BigEndian.Uint32(packet[29:33]) == 99 {
t.Fatal("failed death published a corpse")
}
}
diff --git a/server/npc_outcome.go b/server/npc_outcome.go
@@ -20,6 +20,20 @@ func (server *server) writeNPCOutcome_locked(tx *sql.Tx, target *character, now
if err := writeNPCState_locked(tx, target, &state); err != nil {
return state, err
}
+ // Record the first death with its outcome, independently of corpse lifetime.
+ if target.health == 0 && server.characters[target.id].health != 0 {
+ if mission := server.missionWorld_locked(target.playfield); mission != nil {
+ var savedID uint32
+ if err := tx.QueryRow("UPDATE mission_encounters SET killed=1 WHERE npc_id=? AND mission_id=? AND level=? AND killed=0 RETURNING npc_id",
+ target.id, mission.id, target.level).Scan(&savedID); err != nil {
+ return state, fmt.Errorf("mission %d encounter %d death: %w", mission.id, target.id, err)
+ }
+ if err := tx.QueryRow("SELECT npc_id FROM mission_encounters WHERE npc_id=? AND mission_id=? AND level=? AND killed=1",
+ target.id, mission.id, target.level).Scan(&savedID); err != nil {
+ return state, fmt.Errorf("mission %d encounter %d death was not saved: %w", mission.id, target.id, err)
+ }
+ }
+ }
// Death, generated ownership and identity reservation share the outcome transaction.
for _, item := range drops {
if err := insertRow(tx, "items", "id, type, template, quality, count, ammo", []any{item.ID, item.Type, item.Template, item.Quality, item.Count, item.Ammo}); err != nil {
diff --git a/server/world.sql b/server/world.sql
@@ -254,6 +254,14 @@ CREATE TABLE IF NOT EXISTS mission_doors (
template INTEGER NOT NULL,
UNIQUE (mission_id, passage)
);
+-- Encounter identities survive corpse removal until their mission is retired.
+CREATE TABLE IF NOT EXISTS mission_encounters (
+ npc_id INTEGER PRIMARY KEY CHECK (npc_id BETWEEN 1000000 AND 4294967295),
+ mission_id INTEGER NOT NULL REFERENCES missions(id) ON DELETE CASCADE,
+ level INTEGER NOT NULL CHECK (level BETWEEN 1 AND 65535),
+ killed INTEGER NOT NULL DEFAULT 0 CHECK (killed IN (0, 1))
+);
+CREATE INDEX IF NOT EXISTS mission_encounters_mission ON mission_encounters(mission_id);
CREATE TABLE IF NOT EXISTS chat_history (
id INTEGER PRIMARY KEY,
owner INTEGER NOT NULL,