aorecomp

Anarchy Online classic in the browser

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


server/nano_periodic_test.go (21667B)


      1 package main
      2 
      3 import (
      4 	"ao/server/gamedata"
      5 	_ "embed"
      6 	"encoding/binary"
      7 	"encoding/json"
      8 	"fmt"
      9 	"reflect"
     10 	"slices"
     11 	"sync"
     12 	"testing"
     13 	"time"
     14 )
     15 
     16 //go:embed testdata/periodic-damage-nanos.json
     17 var periodicNanoData []byte
     18 
     19 type periodicNanoFixture struct {
     20 	directDamageNanoFixture
     21 	TickCount    uint32 `json:"tick_count"`
     22 	TickInterval uint32 `json:"tick_interval"`
     23 	Duration     uint32
     24 	NCU, Strain  uint32
     25 }
     26 
     27 func TestPeriodicNanoColdRestoreRetainsPhaseAndPendingOverdueTicks(t *testing.T) {
     28 	for _, checkpoint := range []time.Duration{10 * time.Second, 65 * time.Second} {
     29 		t.Run(checkpoint.String(), func(t *testing.T) {
     30 			world, _ := newPeriodicNanoWorld(t)
     31 			at := castPeriodicNano(t, world, 43376)
     32 			saved := world.savedNPCs[1000000]
     33 			saved.NextSave = at
     34 			world.savedNPCs[1000000] = saved
     35 			// A checkpoint can run before the due-tick visitor, including after expiry.
     36 			if err := world.checkpointWorld(at.Add(checkpoint)); err != nil {
     37 				t.Fatal(err)
     38 			}
     39 			cold := newTestInventoryServer(t)
     40 			target := cold.characters[1000000]
     41 			if target.health != 100 || target.activeNanos[0].ticksLeft != 8 {
     42 				t.Fatal("checkpoint consumed unprocessed damage")
     43 			}
     44 
     45 			cold.advanceNanos(time.Now())
     46 			if target.health != 100 || target.activeNanos[0].ticksLeft != 8 {
     47 				t.Fatal("unobserved NPC processed periodic damage")
     48 			}
     49 			// The caster stays offline; another nearby player activates the NPC.
     50 			cold.characters[2] = &character{id: 2, playfield: target.playfield, position: target.position, health: 100}
     51 			cold.clients[2] = &worldClient{id: 2, ready: true, conn: &combatTestConn{}, npcs: map[uint32]bool{target.id: true}}
     52 			cold.advanceNanos(time.Now())
     53 			if checkpoint == 10*time.Second {
     54 				if target.health != 97 || target.activeNanos[0].ticksLeft != 7 || target.fighting != 0 {
     55 					t.Fatal("restored first tick was lost, duplicated or attacked an offline caster")
     56 				}
     57 				cold.advanceNanos(target.activeNanos[0].expiresAt)
     58 			}
     59 			restored := newTestInventoryServer(t).characters[1000000]
     60 
     61 			if target.health != 76 || restored.health != 76 || len(target.activeNanos) != 0 || len(restored.activeNanos) != 0 ||
     62 				target.damageContributors[damageContributor{player: 1}] != 24 || target.fighting != 0 {
     63 				t.Fatal("cold catch-up changed tick count, contribution or offline retaliation")
     64 			}
     65 		})
     66 	}
     67 }
     68 
     69 func TestPeriodicNanoConcurrentVisitorsApplyEachTickOnce(t *testing.T) {
     70 	world, conn := newPeriodicNanoWorld(t)
     71 	at := castPeriodicNano(t, world, 43376)
     72 	conn.packets = nil
     73 	zone, stop := startTestZone(t, world)
     74 	var workers sync.WaitGroup
     75 
     76 	for range 8 {
     77 		workers.Add(1)
     78 		go func() {
     79 			defer workers.Done()
     80 			if err := zone.call(zoneTestCommand(func(state *server) error { state.advanceNanos(at.Add(22500 * time.Millisecond)); return nil })); err != nil {
     81 				t.Error(err)
     82 			}
     83 		}()
     84 	}
     85 	workers.Wait()
     86 
     87 	var appliedOnce bool
     88 	if err := zone.call(zoneTestCommand(func(state *server) error {
     89 		target := state.characters[1000000]
     90 		appliedOnce = target.health == 91 && target.activeNanos[0].ticksLeft == 5 && len(conn.packets) == 3
     91 		return nil
     92 	})); err != nil {
     93 		t.Fatal(err)
     94 	}
     95 	if !appliedOnce || newTestInventoryServer(t).characters[1000000].health != 100 {
     96 		t.Fatal("concurrent visitors duplicated the three due ticks")
     97 	}
     98 	if err := stop(); err != nil {
     99 		t.Fatal(err)
    100 	}
    101 }
    102 
    103 func TestPeriodicNanoLethalTickClearsEffectsAndAwardsExactlyOneKill(t *testing.T) {
    104 	world, conn := newPeriodicNanoWorld(t)
    105 	player, target := world.characters[1], world.characters[1000000]
    106 	target.health = 7
    107 	at := castPeriodicNano(t, world, 43376)
    108 	conn.packets = nil
    109 
    110 	world.advanceNanos(at.Add(22500 * time.Millisecond))
    111 	world.advanceNanos(at.Add(time.Hour))
    112 	cold := newTestInventoryServer(t)
    113 
    114 	var hits []uint32
    115 	for _, packet := range conn.packets {
    116 		if binary.BigEndian.Uint32(packet[16:20]) == 0x4727213e {
    117 			hits = append(hits, uint32(-int32(binary.BigEndian.Uint32(packet[29:33]))))
    118 		}
    119 	}
    120 	if !slices.Equal(hits, []uint32{3, 3, 1}) || target.health != 0 || len(target.activeNanos) != 0 || target.corpse == nil || target.corpse.looter != 1 ||
    121 		len(world.npcRespawns) != 1 || len(world.corpseExpiry) != 1 || player.experience != target.combatProfile.Experience ||
    122 		cold.characters[1000000].health != 0 || len(cold.characters[1000000].activeNanos) != 0 || cold.characters[1].experience != player.experience {
    123 		t.Fatal("lethal tick duplicated damage, lost its corpse/reward or left a timer")
    124 	}
    125 }
    126 
    127 func TestPeriodicNanosFromDifferentStrainsCatchUpInDeadlineOrder(t *testing.T) {
    128 	world, conn := newPeriodicNanoWorld(t)
    129 	player := world.characters[1]
    130 	player.inventory.LearnedNanos = append(player.inventory.LearnedNanos, 44163)
    131 	at := castPeriodicNano(t, world, 43376)
    132 	player.nanoRechargeUntil = time.Time{}
    133 	if err := world.handleNanoCast(world.clients[1], characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 44163})[20:]); err != nil {
    134 		t.Fatal(err)
    135 	}
    136 	if world.clients[1].nanoCast == nil {
    137 		t.Fatal("independent hostile strain was rejected")
    138 	}
    139 	world.clients[1].nanoCast.readyAt = at.Add(-time.Nanosecond)
    140 	world.advanceNanos(at)
    141 	conn.packets = nil
    142 
    143 	world.advanceNanos(at.Add(24 * time.Second))
    144 
    145 	var hits []uint32
    146 	for _, packet := range conn.packets {
    147 		if binary.BigEndian.Uint32(packet[16:20]) == 0x4727213e {
    148 			hits = append(hits, uint32(-int32(binary.BigEndian.Uint32(packet[29:33]))))
    149 		}
    150 	}
    151 	target := world.characters[1000000]
    152 	if !slices.Equal(hits, []uint32{4, 3, 4, 3, 4, 3, 4}) || target.health != 75 || len(target.activeNanos) != 2 ||
    153 		target.activeNanos[0].ticksLeft != 5 || target.activeNanos[1].ticksLeft != 6 || target.usedNCU() != 0 {
    154 		t.Fatal("catch-up grouped damage by effect instead of its scheduled deadline", hits)
    155 	}
    156 }
    157 
    158 func TestPeriodicNanoRefreshReplacementAndWeakerRejectionShareStrainRules(t *testing.T) {
    159 	world, _ := newPeriodicNanoWorld(t)
    160 	player, target := world.characters[1], world.characters[1000000]
    161 	player.inventory.LearnedNanos = append(player.inventory.LearnedNanos, 44152)
    162 	at := castPeriodicNano(t, world, 43376)
    163 	first := target.activeNanos[0]
    164 	player.nanoRechargeUntil = time.Time{}
    165 
    166 	refreshed := castPeriodicNano(t, world, 43376)
    167 	if len(target.activeNanos) != 1 || target.activeNanos[0].ticksLeft != 8 || !target.activeNanos[0].nextTick.Equal(refreshed.Add(7500*time.Millisecond)) ||
    168 		!target.activeNanos[0].nextTick.After(first.nextTick) || !target.activeNanos[0].expiresAt.Equal(refreshed.Add(time.Minute)) {
    169 		t.Fatal("refresh stacked the effect or kept the previous tick phase")
    170 	}
    171 	player.nanoRechargeUntil = time.Time{}
    172 	upgraded := castPeriodicNano(t, world, 44152)
    173 	stronger := target.activeNanos[0]
    174 	player.nanoRechargeUntil = time.Time{}
    175 	nano := player.nano
    176 	if err := world.handleNanoCast(world.clients[1], characterActionPacket(1, [5]uint32{19, 50000, target.id, 53019, 43376})[20:]); err != nil {
    177 		t.Fatal(err)
    178 	}
    179 	world.advanceNanos(at.Add(time.Second))
    180 
    181 	if target.health != 100 || player.nano != nano || player.nanoReserved != 0 || world.clients[1].nanoCast != nil ||
    182 		len(target.activeNanos) != 1 || target.activeNanos[0] != stronger || stronger.program != 44152 || stronger.ticksLeft != 10 ||
    183 		!stronger.nextTick.Equal(upgraded.Add(6*time.Second)) || target.usedNCU() != 0 {
    184 		t.Fatal("stronger hostile replacement consumed NCU, accepted a downgrade or lost timing")
    185 	}
    186 }
    187 
    188 func periodicNanoFixtures(t *testing.T) []periodicNanoFixture {
    189 	t.Helper()
    190 	var fixtures []periodicNanoFixture
    191 	if err := json.Unmarshal(periodicNanoData, &fixtures); err != nil {
    192 		t.Fatal(err)
    193 	}
    194 	return fixtures
    195 }
    196 
    197 func TestPeriodicNanoSkillAndProfessionGatesApplyToUploadAndCast(t *testing.T) {
    198 	var fixtures []directDamageNanoFixture
    199 	for _, fixture := range periodicNanoFixtures(t) {
    200 		fixtures = append(fixtures, fixture.directDamageNanoFixture)
    201 	}
    202 	checkNanoRequirementBoundaries(t, fixtures)
    203 }
    204 
    205 func newPeriodicNanoWorld(t *testing.T) (*server, *combatTestConn) {
    206 	t.Helper()
    207 	world, conn := newDirectDamageWorld(t, directDamageNanoFixture{Crystal: 43384, Profession: 10})
    208 	if err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]); err != nil {
    209 		t.Fatal(err)
    210 	}
    211 	if !slices.Equal(world.characters[1].inventory.LearnedNanos, []uint32{43376}) {
    212 		t.Fatal("Prototype Biotoxin crystal did not upload")
    213 	}
    214 	conn.packets = nil
    215 	return world, conn
    216 }
    217 
    218 func castPeriodicNano(t *testing.T, world *server, program uint32) time.Time {
    219 	t.Helper()
    220 	client := world.clients[1]
    221 	if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, program})[20:]); err != nil {
    222 		t.Fatal(err)
    223 	}
    224 	if client.nanoCast == nil {
    225 		t.Fatal("qualified periodic cast was rejected", program)
    226 	}
    227 	at := client.nanoCast.readyAt.Add(time.Nanosecond)
    228 	world.advanceNanos(at)
    229 	return at
    230 }
    231 
    232 func TestPeriodicNanoCatalogUsesCompleteOriginalHitDescriptors(t *testing.T) {
    233 	var expectedPrograms, expectedCrystals, programs, crystals []uint32
    234 	for _, fixture := range periodicNanoFixtures(t) {
    235 		expectedPrograms = append(expectedPrograms, fixture.Program)
    236 		if fixture.Crystal != 0 {
    237 			expectedCrystals = append(expectedCrystals, fixture.Crystal)
    238 		}
    239 	}
    240 
    241 	for program := range gamedata.NanoTemplates {
    242 		if damageOverTimeNano(program) != nil {
    243 			programs = append(programs, program)
    244 		}
    245 	}
    246 	for crystal := range gamedata.ItemTemplates {
    247 		if damageOverTimeNano(nanoCrystalProgram(crystal)) != nil {
    248 			crystals = append(crystals, crystal)
    249 		}
    250 	}
    251 	for _, values := range [][]uint32{programs, crystals, expectedPrograms, expectedCrystals} {
    252 		slices.Sort(values)
    253 	}
    254 
    255 	if len(programs) != 60 || len(crystals) != 59 || !slices.Equal(programs, expectedPrograms) || !slices.Equal(crystals, expectedCrystals) {
    256 		t.Fatal("admission differs from the independent original-record census", programs, crystals)
    257 	}
    258 	for _, fixture := range periodicNanoFixtures(t) {
    259 		hit := damageOverTimeNano(fixture.Program)
    260 		if hit.TickCount != fixture.TickCount || hit.TickInterval != fixture.TickInterval ||
    261 			uint32(-*hit.Arguments[1].Integer) != fixture.Minimum || uint32(-*hit.Arguments[2].Integer) != fixture.Maximum ||
    262 			uint32(*hit.Arguments[3].Integer) != fixture.DamageType || nanoStat(fixture.Program, 8) != fixture.Duration ||
    263 			nanoStat(fixture.Program, 54) != fixture.NCU || nanoStat(fixture.Program, 75) != fixture.Strain ||
    264 			nanoStat(fixture.Program, 407) != fixture.NanoCost || nanoStat(fixture.Program, 294) != fixture.AttackDelay ||
    265 			nanoStat(fixture.Program, 210) != fixture.RechargeDelay || nanoStat(fixture.Program, 287) != fixture.Range || directDamageNano(fixture.Program) != nil {
    266 			t.Fatal("periodic damage, timing or complete effect contract changed", fixture.Program)
    267 		}
    268 	}
    269 }
    270 
    271 func TestPeriodicNanoFinishesItsTicksBeforeItsLongerLifetimeExpires(t *testing.T) {
    272 	world, conn := newDirectDamageWorld(t, directDamageNanoFixture{Crystal: 81957, Profession: 5})
    273 	if err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]); err != nil {
    274 		t.Fatal(err)
    275 	}
    276 	target := world.characters[1000000]
    277 	target.health = 1000
    278 	at := castPeriodicNano(t, world, 81939)
    279 	conn.packets = nil
    280 
    281 	world.advanceNanos(at.Add(40500 * time.Millisecond))
    282 	saved := world.savedNPCs[target.id]
    283 	saved.NextSave = at
    284 	world.savedNPCs[target.id] = saved
    285 	if err := world.checkpointWorld(at.Add(40500 * time.Millisecond)); err != nil {
    286 		t.Fatal(err)
    287 	}
    288 	cold := newTestInventoryServer(t).characters[1000000]
    289 	world.advanceNanos(at.Add(45*time.Second - time.Nanosecond))
    290 	if target.health != 847 || len(target.activeNanos) != 1 || target.activeNanos[0].ticksLeft != 0 ||
    291 		cold.health != 847 || len(cold.activeNanos) != 1 || cold.activeNanos[0].ticksLeft != 0 || cold.activeNanos[0].remaining != 4500*time.Millisecond ||
    292 		!cold.activeNanos[0].nextTick.IsZero() || len(conn.packets) != 9 {
    293 		t.Fatal("tick count was inferred from duration or the icon expired after the last tick")
    294 	}
    295 	world.advanceNanos(at.Add(45 * time.Second))
    296 	world.advanceNanos(at.Add(time.Hour))
    297 
    298 	if target.health != 847 || len(target.activeNanos) != 0 || len(conn.packets) != 10 ||
    299 		binary.BigEndian.Uint32(conn.packets[9][29:33]) != 65 || len(newTestInventoryServer(t).characters[1000000].activeNanos) != 0 {
    300 		t.Fatal("effect lifetime added a tenth damage tick or failed to remove the finished effect")
    301 	}
    302 }
    303 
    304 func TestPeriodicNanosLearnCastAndDeliverExactlyTheirAuthoredTicks(t *testing.T) {
    305 	for _, fixture := range periodicNanoFixtures(t) {
    306 		t.Run(fmt.Sprint(fixture.Program), func(t *testing.T) {
    307 			world, conn := newDirectDamageWorld(t, fixture.directDamageNanoFixture)
    308 			player, target, client := world.characters[1], world.characters[1000000], world.clients[1]
    309 			target.health = 1000000
    310 			if fixture.Crystal != 0 {
    311 				if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]); err != nil {
    312 					t.Fatal(err)
    313 				}
    314 				if len(player.inventory.Items) != 0 || !slices.Equal(player.inventory.LearnedNanos, []uint32{fixture.Program}) {
    315 					t.Fatal("ordinary crystal failed its single upload")
    316 				}
    317 			} else {
    318 				player.inventory.LearnedNanos = []uint32{fixture.Program}
    319 			}
    320 			conn.packets = nil
    321 
    322 			at := castPeriodicNano(t, world, fixture.Program)
    323 			if target.health != 1000000 || len(target.activeNanos) != 1 || target.activeNanos[0].ticksLeft != fixture.TickCount || target.usedNCU() != 0 {
    324 				t.Fatal("installation dealt an immediate tick or consumed hostile NCU")
    325 			}
    326 			interval := time.Duration(fixture.TickInterval) * 10 * time.Millisecond
    327 			for tick := uint32(1); tick <= fixture.TickCount; tick++ {
    328 				world.advanceNanos(at.Add(time.Duration(tick) * interval))
    329 			}
    330 			world.advanceNanos(at.Add(time.Hour))
    331 			cold := newTestInventoryServer(t)
    332 
    333 			var count, damage, removed uint32
    334 			for _, packet := range conn.packets {
    335 				if binary.BigEndian.Uint32(packet[16:20]) == 0x4727213e {
    336 					value := uint32(-int32(binary.BigEndian.Uint32(packet[29:33])))
    337 					if value < fixture.Minimum || value > fixture.Maximum || binary.BigEndian.Uint32(packet[33:37]) != fixture.DamageType {
    338 						t.Fatal("tick did not use the authored damage range/type")
    339 					}
    340 					count++
    341 					damage += value
    342 				}
    343 				if binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && binary.BigEndian.Uint32(packet[29:33]) == 65 {
    344 					removed++
    345 				}
    346 			}
    347 			if count != fixture.TickCount || target.health != 1000000-damage || removed != 1 || len(target.activeNanos) != 0 ||
    348 				player.nano != 50000-(fixture.NanoCost-1) || player.nanoReserved != 0 || client.nanoCast != nil || target.fighting != 1 ||
    349 				target.damageContributors[damageContributor{player: 1}] != damage || cold.characters[1000000].health != target.health ||
    350 				len(cold.characters[1000000].activeNanos) != 0 {
    351 				t.Fatalf("tick count, debit, contribution, removal or restore changed: count=%d damage=%d target=%+v", count, damage, target)
    352 			}
    353 		})
    354 	}
    355 }
    356 
    357 func TestPeriodicNanoWaitsForItsDeadlineAndDoesNotWriteBetweenTicks(t *testing.T) {
    358 	world, conn := newPeriodicNanoWorld(t)
    359 	target := world.characters[1000000]
    360 	at := castPeriodicNano(t, world, 43376)
    361 	auditCheckpointWrites(t, world)
    362 	if _, err := world.db.Exec("CREATE TRIGGER audit_nano AFTER UPDATE ON active_nanos BEGIN INSERT INTO checkpoint_writes VALUES ('active_nanos','UPDATE'); END"); err != nil {
    363 		t.Fatal(err)
    364 	}
    365 	conn.packets = nil
    366 
    367 	for offset := time.Duration(0); offset < 7500*time.Millisecond; offset += 50 * time.Millisecond {
    368 		world.advanceNanos(at.Add(offset))
    369 	}
    370 	world.advanceNanos(at.Add(7500*time.Millisecond - time.Nanosecond))
    371 	if target.health != 100 || len(conn.packets) != 0 || len(checkpointWrites(t, world)) != 0 {
    372 		t.Fatal("damage or writes occurred before the next deadline")
    373 	}
    374 	world.advanceNanos(at.Add(7500 * time.Millisecond))
    375 	world.advanceNanos(at.Add(7500 * time.Millisecond))
    376 	cold := newTestInventoryServer(t).characters[1000000]
    377 	var ticks uint32
    378 	var delay time.Duration
    379 	if err := world.db.QueryRow("SELECT ticks_left,next_tick_ns FROM active_nanos WHERE character_id=1000000").Scan(&ticks, &delay); err != nil {
    380 		t.Fatal(err)
    381 	}
    382 
    383 	if target.health != 97 || len(conn.packets) != 1 || ticks != 8 || delay != 7500*time.Millisecond ||
    384 		cold.health != 100 || len(cold.activeNanos) != 1 || cold.activeNanos[0].ticksLeft != 8 || cold.activeNanos[0].remaining != 60*time.Second ||
    385 		len(checkpointWrites(t, world)) != 0 {
    386 		t.Fatal("exact-deadline tick failed to advance in memory without database writes", ticks, delay, checkpointWrites(t, world))
    387 	}
    388 }
    389 
    390 func TestPeriodicNanoNonfatalTicksDoNotWriteToDatabase(t *testing.T) {
    391 	for _, failure := range []struct{ name, statement string }{
    392 		{"health", "CREATE TRIGGER fail_tick BEFORE UPDATE OF health ON characters WHEN NEW.id=1000000 BEGIN SELECT RAISE(FAIL, 'health'); END"},
    393 		{"ignored health", "CREATE TRIGGER fail_tick BEFORE UPDATE OF health ON characters WHEN NEW.id=1000000 BEGIN SELECT RAISE(IGNORE); END"},
    394 		{"NPC", "CREATE TRIGGER fail_tick BEFORE UPDATE ON npcs BEGIN SELECT RAISE(FAIL, 'NPC'); END"},
    395 		{"contribution", "CREATE TRIGGER fail_tick BEFORE INSERT ON npc_damage_contributors BEGIN SELECT RAISE(FAIL, 'credit'); END"},
    396 		{"ignored contribution", "CREATE TRIGGER fail_tick BEFORE INSERT ON npc_damage_contributors BEGIN SELECT RAISE(IGNORE); END"},
    397 		{"timer", "CREATE TRIGGER fail_tick BEFORE UPDATE ON active_nanos BEGIN SELECT RAISE(FAIL, 'timer'); END"},
    398 		{"ignored timer", "CREATE TRIGGER fail_tick BEFORE UPDATE ON active_nanos BEGIN SELECT RAISE(IGNORE); END"},
    399 		{"commit", "CREATE TABLE pending_tick (id INTEGER REFERENCES characters(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_tick AFTER UPDATE ON active_nanos BEGIN INSERT INTO pending_tick VALUES (999999); END"},
    400 	} {
    401 		t.Run(failure.name, func(t *testing.T) {
    402 			world, conn := newPeriodicNanoWorld(t)
    403 			target := world.characters[1000000]
    404 			at := castPeriodicNano(t, world, 43376)
    405 			previous := world.savedNPCs[target.id]
    406 			if _, err := world.db.Exec(failure.statement); err != nil {
    407 				t.Fatal(err)
    408 			}
    409 			conn.packets = nil
    410 
    411 			world.advanceNanos(at.Add(22500 * time.Millisecond))
    412 			cold := newTestInventoryServer(t).characters[1000000]
    413 
    414 			if target.health != 91 || cold.health != 100 || len(conn.packets) != 3 || target.activeNanos[0].ticksLeft != 5 ||
    415 				cold.activeNanos[0].ticksLeft != 8 || !reflect.DeepEqual(world.savedNPCs[target.id], previous) || target.damageContributors[damageContributor{player: 1}] != 9 {
    416 				t.Fatal("nonfatal ticks waited for persistence or advanced the saved basis")
    417 			}
    418 			if _, err := world.db.Exec("DROP TRIGGER fail_tick"); err != nil {
    419 				t.Fatal(err)
    420 			}
    421 			world.advanceNanos(at.Add(22500 * time.Millisecond))
    422 			saved := world.savedNPCs[target.id]
    423 			saved.NextSave = at
    424 			world.savedNPCs[target.id] = saved
    425 			if err := world.checkpointWorld(at.Add(22500 * time.Millisecond)); err != nil {
    426 				t.Fatal(err)
    427 			}
    428 			if target.health != 91 || target.activeNanos[0].ticksLeft != 5 || len(conn.packets) != 3 ||
    429 				target.damageContributors[damageContributor{player: 1}] != 9 || newTestInventoryServer(t).characters[1000000].health != 91 {
    430 				t.Fatal("retry did not apply exactly the three pending ticks")
    431 			}
    432 		})
    433 	}
    434 }
    435 
    436 func TestPeriodicNanoFailedKillRollsBackDamageRemovalCreditAndReward(t *testing.T) {
    437 	for _, failure := range []struct{ name, statement string }{
    438 		{"removal", "CREATE TRIGGER fail_tick BEFORE DELETE ON active_nanos BEGIN SELECT RAISE(FAIL, 'removal'); END"},
    439 		{"ignored removal", "CREATE TRIGGER fail_tick BEFORE DELETE ON active_nanos BEGIN SELECT RAISE(IGNORE); END"},
    440 		{"ignored contribution removal", "CREATE TRIGGER fail_tick BEFORE DELETE ON npc_damage_contributors BEGIN SELECT RAISE(IGNORE); END"},
    441 		{"reward", "CREATE TRIGGER fail_tick BEFORE UPDATE OF experience ON characters WHEN NEW.id=1 BEGIN SELECT RAISE(FAIL, 'reward'); END"},
    442 		{"ignored reward", "CREATE TRIGGER fail_tick BEFORE UPDATE OF experience ON characters WHEN NEW.id=1 BEGIN SELECT RAISE(IGNORE); END"},
    443 		{"commit", "CREATE TABLE pending_tick (id INTEGER REFERENCES characters(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_tick AFTER DELETE ON active_nanos BEGIN INSERT INTO pending_tick VALUES (999999); END"},
    444 	} {
    445 		t.Run(failure.name, func(t *testing.T) {
    446 			world, conn := newPeriodicNanoWorld(t)
    447 			player, target := world.characters[1], world.characters[1000000]
    448 			target.health = 7
    449 			target.damageContributors = map[damageContributor]uint32{{player: 1}: 5}
    450 			target.leadingContributor = damageContributor{player: 1}
    451 			at := castPeriodicNano(t, world, 43376)
    452 			previous := world.savedNPCs[target.id]
    453 			if _, err := world.db.Exec(failure.statement); err != nil {
    454 				t.Fatal(err)
    455 			}
    456 			conn.packets = nil
    457 
    458 			world.advanceNanos(at.Add(22500 * time.Millisecond))
    459 			cold := newTestInventoryServer(t)
    460 
    461 			if target.health != 7 || target.corpse != nil || len(target.activeNanos) != 1 || target.activeNanos[0].ticksLeft != 8 ||
    462 				len(conn.packets) != 0 || len(world.npcRespawns) != 0 || len(world.corpseExpiry) != 0 || player.experience != 0 ||
    463 				!reflect.DeepEqual(world.savedNPCs[target.id], previous) || cold.characters[1000000].health != 7 || cold.characters[1].experience != 0 {
    464 				t.Fatal("failed periodic kill published partial damage, death or reward")
    465 			}
    466 			if _, err := world.db.Exec("DROP TRIGGER fail_tick"); err != nil {
    467 				t.Fatal(err)
    468 			}
    469 			world.advanceNanos(at.Add(22500 * time.Millisecond))
    470 			world.advanceNanos(at.Add(time.Hour))
    471 			if target.health != 0 || len(target.activeNanos) != 0 || target.corpse == nil || target.corpse.looter != 1 ||
    472 				len(world.npcRespawns) != 1 || player.experience != target.combatProfile.Experience || newTestInventoryServer(t).characters[1].experience != player.experience {
    473 				t.Fatal("retry lost or repeated the complete kill")
    474 			}
    475 		})
    476 	}
    477 }