commit 8a21d4172c60d8ec29f96f6a9e8c6395e857b8c7
parent b4b55fa5548f3936bb230cb53787350f728725ae
Author: anon <anon@example.com>
Date: Sat, 24 Oct 2026 02:19:50 +0000
Respect simulation cadence and skip unchanged checkpoint writes
Diffstat:
10 files changed, 264 insertions(+), 21 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -806,11 +806,16 @@ and server restarts. Turn every reproduced bug into a focused regression test.
and ownership rollback. Combat outcome saves also reserve freshly persisted
NPC IDs, including a new replacement killed before a checkpoint. The broader
pursuit/recovery audit remains open.
-- [ ] Audit idle checkpoint database churn. Count item, player, vital, learned
- nano and lock writes as well as NPC writes. `checkpointWorld` still routes
- through the full inventory store every second; unchanged unrelated state
- should not be rewritten merely to checkpoint simulation. Keep important
- inventory/reward changes atomic and immediate, and movement on its cadence.
+- [x] Audit idle checkpoint database churn. SQL triggers count item, player,
+ vital, learned nano, lock, NPC and world-header writes. Routine checkpoints
+ respect the separate player simulation cadence and skip unchanged world
+ headers. A five-second idle preview sample fell from 235 row writes to zero.
+ Tests cover an idle minute, exact resource/position deadlines, failed saves
+ and retry, initial population creation, and immediate charge/lock saves.
+- [ ] Audit unrelated player writes during inventory actions. The full
+ inventory transaction still saves resources and inventory metadata for every
+ persisted player. Limit those writes to the transaction's actual changes
+ without weakening atomic transfers, equipment resource clamps or rewards.
- [ ] Audit death, resurrection, insurance and reclaim. Cover each supported
item policy, saved/unsaved locations, repeated return/retrieval, full inventory,
failed persistence and restart at each transition.
diff --git a/docs/world-state.md b/docs/world-state.md
@@ -25,7 +25,12 @@ reject two items in an occupied slot. Backpacks cannot contain backpacks.
The connection uses WAL, full synchronous commits and foreign keys. Inventory
changes, corpse loot transfers and cash transfers commit atomically before
success is published. Profiles and admin clock changes save immediately.
-Player movement saves at staggered 20-second intervals. NPC state is checked
+Player movement and routine vitals save at staggered 20-second intervals. The
+one-second world checkpoint does not rewrite player resources, inventory
+metadata, learned programs or treatment locks. Inventory actions still save
+their significant changes immediately. The world header is updated only when
+its counters, clock or population-initialization state change.
+NPC state is checked
on the one-second world tick, but routine writes occur at least 20 seconds
apart, with random starting phases, only in zones with a connected player.
The last player leaving a zone triggers one final snapshot. Unchanged rows
@@ -79,3 +84,23 @@ All 28 records and locations were unchanged after that round-trip, and all
sixteen native top-level entries matched SQLite before and after reconnect.
No page or adapter errors occurred. The checks and screenshots are retained in
`local/control-inventory-smoke/verification.json` and its sibling files.
+
+Checkpoint write audits use SQL triggers across characters, players, items,
+locations, learned programs, treatment locks, NPCs/contributors and the world
+header. `server/checkpoint_test.go` verifies zero writes over an unchanged
+simulated minute, player position/health/nano saved only at their deadline,
+rollback and retry after a failed save, one initial population snapshot, and
+immediate charge/cooldown persistence after a routine checkpoint. Existing
+corpse/container tests verify that periodic expiry cleanup still retains or
+removes the appropriate contents.
+
+On the normal HTTPS preview with 23 stored players, a five-second idle sample
+fell from 235 row writes to zero. A separate five-second idle observation left
+the WAL file's size and modification time unchanged. In a hardware-rendered
+WASM session, movement remained in memory for about 15 seconds until its
+scheduled checkpoint; two player snapshots were 20.016 seconds apart. The pistol's exact instance moved
+from right-hand equipment to inventory and back through native actions, keeping
+its 18 loaded rounds and the separate 100-round stack through reconnect. The
+fixture profile and all 192 item records and placements were restored. No page
+errors occurred. The full server suite and focused race checks pass. Evidence
+is retained in `local/checkpoint-churn-research/`.
diff --git a/server/armor_quality_persistence_test.go b/server/armor_quality_persistence_test.go
@@ -159,7 +159,7 @@ func TestInterpolatedArmorPendingWearRechecksAndRollsBack(t *testing.T) {
if scenario == "changed requirement" {
player.stats.Abilities.Strength = 235
} else {
- if _, err := world.db.Exec("CREATE TRIGGER reject_interpolated_wear BEFORE UPDATE ON world BEGIN SELECT RAISE(ABORT, 'write failed'); END"); err != nil {
+ if _, err := world.db.Exec("CREATE TRIGGER reject_interpolated_wear BEFORE INSERT ON item_locations BEGIN SELECT RAISE(ABORT, 'write failed'); END"); err != nil {
t.Fatal(err)
}
}
diff --git a/server/checkpoint_test.go b/server/checkpoint_test.go
@@ -0,0 +1,206 @@
+package main
+
+import (
+ "net/http"
+ "net/url"
+ "reflect"
+ "testing"
+ "time"
+)
+
+func newCheckpointWorld(t *testing.T) *server {
+ t.Helper()
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ response := postControlForm(world, "/control/users", url.Values{"name": {"Explorer"}})
+ if response.Code != http.StatusSeeOther {
+ t.Fatal(response.Body.String())
+ }
+ player := world.characters[1]
+ player.playfield, player.position = 950, [3]float32{52, 14, 56}
+ player.health, player.nano = 30, 20
+ if err := world.savePosition_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ if granted, err := world.grantItem_locked(player, 121567); !granted || err != nil {
+ t.Fatal(granted, err)
+ }
+ inventory := player.inventory
+ inventory.Credits, inventory.LearnedNanos = 42, []uint32{43324}
+ inventory.FirstAidLockedUntil = time.Now().Add(time.Minute)
+ inventory.TreatmentLocks = map[uint32]time.Time{1: time.Now().Add(time.Minute)}
+ if err := world.saveInventory_locked(player, inventory); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ return world
+}
+
+func auditCheckpointWrites(t *testing.T, world *server) {
+ t.Helper()
+ if _, err := world.db.Exec("CREATE TABLE checkpoint_writes (table_name TEXT, operation TEXT)"); err != nil {
+ t.Fatal(err)
+ }
+ for _, table := range []string{"world", "characters", "players", "learned_nanos", "treatment_locks", "items", "item_locations", "npcs", "npc_damage_contributors"} {
+ for _, operation := range []string{"INSERT", "UPDATE", "DELETE"} {
+ query := "CREATE TRIGGER audit_" + table + "_" + operation + " AFTER " + operation + " ON " + table +
+ " BEGIN INSERT INTO checkpoint_writes VALUES ('" + table + "','" + operation + "'); END"
+ if _, err := world.db.Exec(query); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+}
+
+func checkpointWrites(t *testing.T, world *server) map[string]int {
+ t.Helper()
+ rows, err := world.db.Query("SELECT table_name, operation, count(*) FROM checkpoint_writes GROUP BY table_name, operation")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rows.Close()
+ counts := make(map[string]int)
+ for rows.Next() {
+ var table, operation string
+ var count int
+ if err := rows.Scan(&table, &operation, &count); err != nil {
+ t.Fatal(err)
+ }
+ counts[table+"/"+operation] = count
+ }
+ if err := rows.Err(); err != nil {
+ t.Fatal(err)
+ }
+ return counts
+}
+
+func TestIdleWorldCheckpointsDoNotRewriteDurableState(t *testing.T) {
+ world := newCheckpointWorld(t)
+ auditCheckpointWrites(t, world)
+ now := time.Now()
+ world.characters[1].nextPositionSave = now.Add(20 * time.Second)
+
+ for second := 1; second <= 60; second++ {
+ at := now.Add(time.Duration(second) * time.Second)
+ if err := world.checkpointWorld(at); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.flushPositions(at); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ if writes := checkpointWrites(t, world); len(writes) != 0 {
+ t.Fatalf("idle checkpoints rewrote unchanged state: %v", writes)
+ }
+}
+
+func TestWorldCheckpointsRespectPlayerSimulationCadence(t *testing.T) {
+ world := newCheckpointWorld(t)
+ auditCheckpointWrites(t, world)
+ player := world.characters[1]
+ now := time.Now()
+ player.nextPositionSave = now.Add(20 * time.Second)
+ player.position, player.health, player.nano = [3]float32{53, 14, 57}, 17, 11
+
+ if err := world.checkpointWorld(now.Add(19 * time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.flushPositions(now.Add(19 * time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ var beforePosition float32
+ var beforeHealth, beforeNano uint32
+ if err := world.db.QueryRow("SELECT position_x,health,nano FROM characters WHERE id=1").Scan(&beforePosition, &beforeHealth, &beforeNano); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.flushPositions(now.Add(20 * time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.checkpointWorld(now.Add(21 * time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ restored := newTestInventoryServer(t).characters[1]
+
+ if beforePosition != 52 || beforeHealth != 30 || beforeNano != 20 {
+ t.Fatalf("simulation state reached SQLite before its checkpoint: position=%g health=%d nano=%d", beforePosition, beforeHealth, beforeNano)
+ }
+ if restored.position != [3]float32{53, 14, 57} || restored.health != 17 || restored.nano != 11 || player.savedVitals != player.vitals() ||
+ !reflect.DeepEqual(checkpointWrites(t, world), map[string]int{"characters/UPDATE": 1}) {
+ t.Fatal("the due player checkpoint failed to save simulation once without unrelated writes")
+ }
+}
+
+func TestWorldCheckpointInitialPopulationCommitsOnlyOnce(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ auditCheckpointWrites(t, world)
+ now := time.Now()
+
+ if err := world.checkpointWorld(now); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.checkpointWorld(now.Add(time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ restored := newTestInventoryServer(t)
+
+ if len(restored.characters) != 1 || restored.characters[1000000] == nil || restored.nextNPC != 1000001 ||
+ !reflect.DeepEqual(checkpointWrites(t, world), map[string]int{"characters/INSERT": 1, "npcs/INSERT": 1, "world/UPDATE": 1}) {
+ t.Fatal("initial checkpoint failed to commit one authored population and reserve its identities")
+ }
+}
+
+func TestFailedPlayerCheckpointPreservesSavedBasisAndRetries(t *testing.T) {
+ world := newCheckpointWorld(t)
+ auditCheckpointWrites(t, world)
+ player := world.characters[1]
+ now := time.Now()
+ player.nextPositionSave = now.Add(20 * time.Second)
+ player.position, player.health, player.nano = [3]float32{53, 14, 57}, 17, 11
+ if _, err := world.db.Exec("CREATE TRIGGER reject_checkpoint BEFORE UPDATE ON characters WHEN NEW.id=1 BEGIN SELECT RAISE(ABORT, 'test checkpoint failure'); END"); err != nil {
+ t.Fatal(err)
+ }
+
+ failed := world.flushPositions(now.Add(20 * time.Second))
+ savedPosition, savedVitals := player.savedPosition, player.savedVitals
+ if err := world.checkpointWorld(now.Add(21 * time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ before := newTestInventoryServer(t).characters[1]
+ if _, err := world.db.Exec("DROP TRIGGER reject_checkpoint"); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.flushPositions(now.Add(40 * time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ after := newTestInventoryServer(t).characters[1]
+
+ if failed == nil || savedPosition.Position != [3]float32{52, 14, 56} || savedVitals.Health != 30 || savedVitals.Nano != 20 ||
+ before.position != [3]float32{52, 14, 56} || before.health != 30 || before.nano != 20 {
+ t.Fatal("failed checkpoint advanced the saved basis or the world checkpoint bypassed its cadence")
+ }
+ if after.position != [3]float32{53, 14, 57} || after.health != 17 || after.nano != 11 ||
+ !reflect.DeepEqual(checkpointWrites(t, world), map[string]int{"characters/UPDATE": 1}) {
+ t.Fatal("next scheduled checkpoint did not commit the current simulation once")
+ }
+}
+
+func TestInventoryUseAfterWorldCheckpointStillCommitsImmediately(t *testing.T) {
+ world, _ := newNanoKitWorld(t)
+ now := time.Now()
+ world.characters[1].nextPositionSave = now.Add(20 * time.Second)
+ if err := world.checkpointWorld(now); err != nil {
+ t.Fatal(err)
+ }
+
+ err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:])
+ restored := newTestInventoryServer(t).characters[1]
+
+ if err != nil || restored.inventory.Items[0].Count != 24 || restored.inventory.FirstAidLockedUntil.Before(now.Add(40*time.Second)) ||
+ !restored.inventory.FirstAidLockedUntil.Equal(world.characters[1].inventory.FirstAidLockedUntil) {
+ t.Fatal("world checkpoint deferred or lost an important charge/lock save", err)
+ }
+}
diff --git a/server/control_data_test.go b/server/control_data_test.go
@@ -316,7 +316,7 @@ func TestControlCharacterDocumentRollsBackAllSections(t *testing.T) {
postControlForm(world, "/control/users", url.Values{"name": {"Explorer"}})
postControlForm(world, "/control/items", url.Values{"template": {"121567"}})
postControlForm(world, "/control/items", url.Values{"template": {"85557"}})
- if _, err := world.db.Exec("CREATE TRIGGER reject_editor BEFORE UPDATE ON world BEGIN SELECT RAISE(ABORT, 'write failed'); END"); err != nil {
+ if _, err := world.db.Exec("CREATE TRIGGER reject_editor BEFORE UPDATE OF name ON characters WHEN NEW.id=1 BEGIN SELECT RAISE(ABORT, 'write failed'); END"); err != nil {
t.Fatal(err)
}
contents := "name: Changed\nposition: [53, 14, 60]\ninventory:\n credits: 913\n slots: {inventory_slot_7: 1}\nequipment: {clothes_head: 2}\n"
diff --git a/server/database_test.go b/server/database_test.go
@@ -199,13 +199,13 @@ func TestWorldDatabaseRollsBackCorpseCashWithInventory(t *testing.T) {
if err := world.saveInventory_locked(world.characters[1], world.characters[1].inventory); err != nil {
t.Fatal(err)
}
- if _, err := world.db.Exec("CREATE TRIGGER reject_world BEFORE UPDATE ON world BEGIN SELECT RAISE(ABORT, 'write failed'); END"); err != nil {
+ if _, err := world.db.Exec("CREATE TRIGGER reject_cash BEFORE UPDATE ON npcs WHEN NEW.id=1000000 AND NEW.credits=0 BEGIN SELECT RAISE(ABORT, 'write failed'); END"); err != nil {
t.Fatal(err)
}
saveErr := world.handleLootUse(world.clients[1], lootUseRequest(1))
restarted := newTestInventoryServer(t)
- if _, err := world.db.Exec("DROP TRIGGER reject_world"); err != nil {
+ if _, err := world.db.Exec("DROP TRIGGER reject_cash"); err != nil {
t.Fatal(err)
}
if err := world.handleLootUse(world.clients[1], lootUseRequest(2)); err != nil {
diff --git a/server/item_database.go b/server/item_database.go
@@ -35,6 +35,10 @@ func (server *server) persistItems_locked(store itemStore) error {
for _, entry := range inventory.Reclaim {
placements[entry.Item.ID] = itemPlacement{Player: id, Slot: entry.Item.Slot, ReclaimAt: entry.AvailableAt.UTC().Format(time.RFC3339Nano)}
}
+ // Player simulation has its own cadence; inventory actions save immediately.
+ if !store.checkpointAt.IsZero() {
+ continue
+ }
player := *server.characters[id]
if store.edited != nil && store.edited.id == id {
player = *store.edited
@@ -149,7 +153,10 @@ func (server *server) persistItems_locked(store itemStore) error {
if started.IsZero() {
started = time.Now()
}
- if _, err := tx.Exec("UPDATE world SET last_item_id=?, last_character_id=max(last_character_id, ?), last_npc_id=?, game_seconds=?, clock_started=?, npcs_initialized=1 WHERE id=1",
+ if _, err := tx.Exec(`UPDATE world SET last_item_id=?1, last_character_id=max(last_character_id, ?2),
+ last_npc_id=?3, game_seconds=?4, clock_started=?5, npcs_initialized=1
+ WHERE id=1 AND (last_item_id, last_character_id, last_npc_id, game_seconds, clock_started, npcs_initialized)
+ IS NOT (?1, max(last_character_id, ?2), ?3, ?4, ?5, 1)`,
store.LastID, server.nextCharacter, server.nextNPC, server.gameSeconds, started.UTC().Format(time.RFC3339Nano)); err != nil {
return err
}
diff --git a/server/item_store.go b/server/item_store.go
@@ -40,13 +40,13 @@ type characterItemReferences struct {
}
type itemStore struct {
- LastID uint32 `yaml:"last_id"`
- Items map[uint32]itemRecord `yaml:"items"`
- Players map[uint32]characterItemReferences `yaml:"players"`
- Corpses map[uint32][]ownedItem
- edited *character
- npcSaveAt time.Time
- flushNPCs bool
+ LastID uint32 `yaml:"last_id"`
+ Items map[uint32]itemRecord `yaml:"items"`
+ Players map[uint32]characterItemReferences `yaml:"players"`
+ Corpses map[uint32][]ownedItem
+ edited *character
+ checkpointAt time.Time
+ flushNPCs bool
}
func emptyItemSlots(count uint32) map[string]*uint32 {
diff --git a/server/portable_container_loot_test.go b/server/portable_container_loot_test.go
@@ -74,7 +74,7 @@ func TestFilledLootContainerPickupFailurePreservesBothLocations(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if _, err := world.db.Exec("CREATE TRIGGER reject_container_loot BEFORE UPDATE ON world BEGIN SELECT RAISE(ABORT, 'write failed'); END"); err != nil {
+ if _, err := world.db.Exec("CREATE TRIGGER reject_container_loot BEFORE INSERT ON item_locations WHEN NEW.item_id=17 BEGIN SELECT RAISE(ABORT, 'write failed'); END"); err != nil {
t.Fatal(err)
}
diff --git a/server/world_store.go b/server/world_store.go
@@ -85,7 +85,7 @@ func (server *server) writeNPCs_locked(tx *sql.Tx, store itemStore, zones map[ui
defer npcWrite.Close()
// Routine checkpoints are staggered; unobserved zones retain their last snapshot.
- now := store.npcSaveAt
+ now := store.checkpointAt
if now.IsZero() {
now = time.Now()
}
@@ -254,6 +254,6 @@ func (server *server) checkpointWorld(now time.Time) error {
if err != nil {
return err
}
- store.npcSaveAt = now
+ store.checkpointAt = now
return server.writeItemStore_locked(store)
}