Prompt Ledger. A working library of AI prompts
← All prompts

Save, Persistence & Data Integrity Pass

Stress-test and harden a game’s saves, databases, migrations, transactions, recovery, and persistence so crashes, retries, disconnects, upgrades, concurrent writes, and partial failures don’t corrupt, duplicate, revert, or lose player progress.

Revised 04 Sep 2026 game development save system persistence data integrity database migrations player data transactions recovery serialization multiplayer data safety

You are responsible for a comprehensive save-system, persistence, migration, transaction, recovery, and player-data integrity pass.

Your job is to make the existing game substantially safer against:

  • lost progress;
  • corrupted saves;
  • stale overwrites;
  • duplicated rewards;
  • duplicated items or currency;
  • partial writes;
  • incompatible upgrades;
  • failed migrations;
  • crashes during saving;
  • disconnects during persistence;
  • retries;
  • concurrent updates;
  • malformed data;
  • older valid data;
  • asynchronous writes completing out of order;
  • recovery systems damaging the last known-good state.

The primary question throughout this task is:

What can cause valid player or world state to be lost, duplicated, corrupted, reverted, partially written, or made unloadable?

Then fix those problems.

This is an implementation task, not merely a persistence audit.

Do not stop after:

  • mapping save flows;
  • identifying risky database operations;
  • listing migration concerns;
  • describing transaction problems;
  • recommending atomic saves;
  • documenting corruption scenarios;
  • producing a data-integrity report.

Inspect the actual persistence implementation.

Establish invariants.

Attack failure paths.

Reproduce problems where practical.

Implement robust fixes.

Validate normal behavior and failure behavior.

Then attack the corrected paths again.

Use continuously:

inspect → model invariants → attack failure paths → reproduce → diagnose → implement → validate → attack again

The goal is:

Leave behind the same game, but make its saves and persistent state substantially safer, more recoverable, transactionally sound, and resistant to corruption, duplication, stale writes, incompatible upgrades, and data loss.

Player Data Safety Is the Priority

Prioritize approximately:

  1. permanent player-data loss;
  2. persistent item or currency duplication;
  3. corrupted or unloadable saves;
  4. stale state overwriting newer state;
  5. partial transactions;
  6. destructive migration failures;
  7. incorrect account/character ownership;
  8. retries duplicating consequential outcomes;
  9. disconnect/reconnect persistence races;
  10. overlapping save races;
  11. invalid durable state;
  12. failed recovery behavior;
  13. old-version compatibility problems;
  14. malformed-data handling;
  15. lower-impact persistence inconsistencies.

This ordering is not rigid.

Fix the highest-risk integrity problems actually present.


Core Scope

Inspect only systems that actually exist.

Relevant areas may include:

Local Saves

  • save files;
  • autosaves;
  • manual saves;
  • checkpoints;
  • settings;
  • profiles;
  • character files;
  • world files;
  • temporary save files;
  • backup copies.

Player State

  • account data;
  • character data;
  • inventory;
  • equipment;
  • XP;
  • skills;
  • levels;
  • currency;
  • quests;
  • unlocks;
  • achievements where gameplay state is persisted;
  • cooldowns where persisted;
  • world position;
  • progression state.

World Persistence

  • world objects;
  • resource nodes;
  • doors;
  • NPC/world state;
  • player-built objects;
  • shared world progression;
  • server-owned state.

Databases

  • schemas;
  • queries;
  • transactions;
  • constraints;
  • migrations;
  • indexes where integrity-sensitive;
  • account/character relationships;
  • read-modify-write operations;
  • durable event/reward records where present.

Serialization

  • encoding;
  • decoding;
  • defaults;
  • optional fields;
  • missing fields;
  • enums;
  • references;
  • identifiers;
  • numeric bounds;
  • format versions.

Persistence Lifecycle

  • save triggers;
  • autosaves;
  • logout saves;
  • disconnect saves;
  • server shutdown;
  • zone transitions;
  • character switching;
  • background saves;
  • save queues;
  • retry logic.

Migrations

  • save migrations;
  • schema migrations;
  • field migrations;
  • data conversions;
  • version transitions;
  • migration ordering;
  • repeated migration behavior.

Recovery

  • backups;
  • temp files;
  • previous-good copies;
  • corruption handling;
  • rollback where implemented;
  • restore paths.

Multiplayer Persistence

Where applicable:

  • stale-session writes;
  • reconnect races;
  • concurrent player mutations;
  • authoritative server state;
  • database transactions;
  • overlapping sessions;
  • cloud/local disagreement.

Do not invent persistence systems that do not exist.


Explicitly Out of Scope

This is not primarily:

  • a gameplay redesign;
  • a progression rebalance;
  • an economy rebalance;
  • a networking-stack rewrite;
  • a database-engine migration;
  • a new cloud-save service;
  • a general codebase refactor;
  • repository cleanup;
  • performance optimization;
  • feature expansion;
  • UI redesign.

Small structural changes are allowed when directly required to eliminate a confirmed integrity problem.

Do not replace working persistence architecture merely because another architecture is theoretically cleaner.


Preserve Existing Save Compatibility

Preserve existing valid player data wherever reasonably possible.

Do not casually:

  • change save locations;
  • change identifiers;
  • rename durable fields without migration;
  • change database ownership relationships;
  • invalidate existing files;
  • rewrite migration history;
  • reset progress;
  • discard unknown fields;
  • replace persisted formats.

When a breaking change is genuinely necessary:

  1. establish why;
  2. identify affected existing state;
  3. provide a safe migration path where practical;
  4. validate old → new behavior;
  5. make failure explicit rather than silently destroying data.

Player-data compatibility is more important than architectural elegance.


Core Persistence Invariants

Identify project-specific invariants before making broad changes.

Important examples include:

  • valid progress never silently decreases;
  • newer authoritative state cannot be overwritten by stale state;
  • item ownership remains unambiguous;
  • items are neither accidentally duplicated nor lost;
  • currency is neither accidentally duplicated nor lost;
  • one logical reward persists the intended number of times;
  • failed writes do not masquerade as success;
  • interrupted writes leave old valid state or new valid state rather than half-state;
  • migrations either produce valid target-version data or fail safely;
  • invalid external data does not create impossible durable state;
  • account A cannot overwrite account B;
  • character A cannot overwrite character B;
  • older sessions cannot overwrite newer sessions;
  • save/load round trips preserve supported state.

Treat violations involving permanent player progress as high severity.


Persistence Priority Queue

P0 — Catastrophic Integrity Failure

Examples:

  • permanent save corruption;
  • widespread player-data loss;
  • item or currency duplication;
  • wrong-account data overwrite;
  • destructive migration;
  • stale session overwriting current progress;
  • transaction committing half an ownership transfer;
  • retry granting the same durable reward repeatedly.

Fix immediately.

P1 — Major Data Risk

Examples:

  • autosave can overwrite newer manual state;
  • reconnect races with old-session save;
  • valid older saves fail after upgrade;
  • interrupted writes commonly corrupt state;
  • partial database operations lose items;
  • malformed data causes startup crash loop;
  • backups overwrite newer valid data.

Prioritize heavily.

P2 — Significant Robustness Problem

Examples:

  • optional fields fail to default safely;
  • recovery path is unreliable;
  • non-critical settings can be lost;
  • minor migration edge case;
  • duplicate low-value durable records;
  • stale state possible under unusual timing.

Fix where evidence supports it.

P3 — Finishing Integrity Work

Examples:

  • minor validation gaps;
  • harmless redundant writes;
  • small serializer inconsistencies;
  • low-risk old-version handling.

Address after higher-risk issues.


Establish the Persistence Model

Determine exactly:

  • what is persisted;
  • where it is stored;
  • when it is written;
  • who may write it;
  • what is authoritative;
  • what format is used;
  • what version identifies the format;
  • what can write concurrently;
  • what acknowledges success;
  • what recovery mechanisms exist.

Trace important state through:

gameplay mutation → authoritative in-memory state → persistence request → serialization/query → durable write → acknowledgement → later load

Find every path capable of mutating durable player value.

Do not assume there is only one save path.


Establish Persistence Ownership

For important data ask:

Who owns the authoritative current value?

Potential owners may include:

  • local game state;
  • server session;
  • account service;
  • character service;
  • database;
  • cloud save;
  • world server.

Avoid situations where several layers independently believe they are authoritative.

Distinguish:

  • authoritative state;
  • cached state;
  • replicated state;
  • presentation;
  • durable storage.

Persistence should record truth.

It should not accidentally create a competing truth.


Investigate Before Asking Questions

Use the project as evidence.

Inspect relevant:

  • save/load implementations;
  • serializers;
  • deserializers;
  • database queries;
  • schemas;
  • migrations;
  • transaction boundaries;
  • save queues;
  • retries;
  • session lifecycle;
  • logout/disconnect logic;
  • recovery code;
  • backups;
  • version fields;
  • tests;
  • logs;
  • account/character ownership.

Ask for clarification only when:

  • authoritative ownership genuinely cannot be established;
  • intended compatibility policy is unclear;
  • destructive migration requires product approval;
  • existing live-player holdings materially affect the decision;
  • cloud/local conflict policy cannot be inferred;
  • required production infrastructure is unavailable.

Do not ask questions merely because persistence analysis is difficult.


Capability-Aware Execution

Use the strongest testing environment available.

Where practical use:

  • temporary save directories;
  • test databases;
  • transaction fixtures;
  • migration fixtures;
  • disposable accounts;
  • multi-session tests;
  • intentionally interrupted writes;
  • deterministic failure injection;
  • automated round-trip tests.

Do not perform destructive testing against real production player data unless explicitly authorized.

If full runtime or database access is unavailable:

  • complete the strongest static and automated validation possible;
  • distinguish verified behavior from inferred risk;
  • do not claim recovery or migration succeeded if it was not actually tested.

Implementation Over Auditing

The persistence map exists to create an implementation queue.

Do not spend most of the task producing:

  • giant schema documentation;
  • theoretical corruption scenarios;
  • exhaustive call graphs;
  • long migration reports.

Once a meaningful integrity issue is sufficiently understood:

implement the fix.

Then validate:

  1. normal behavior;
  2. original failure;
  3. retry;
  4. interrupted execution;
  5. stale completion;
  6. old-version behavior where relevant;
  7. analogous paths.

Execution Strategy

Work autonomously where possible.

If the environment supports independent agents, workers, subprocesses, or parallel contexts, use them where useful.

Do not require delegation.

A single capable session must still be able to complete the task sequentially.

Good independent investigation areas may include:

  • local-save serialization;
  • database transactions;
  • migrations;
  • account/character ownership;
  • recovery;
  • persistence lifecycle;
  • multiplayer save races.

Serialize modifications involving shared:

  • schemas;
  • migration infrastructure;
  • authoritative persistence services;
  • account ownership;
  • transaction code;
  • save-version rules.

Do not let independent workstreams invent incompatible persistence semantics.

For high-risk changes involving:

  • inventory;
  • currency;
  • transactions;
  • migrations;
  • account ownership;
  • multiplayer persistence;
  • stale-write prevention;

use additional independent review or fresh-context scrutiny when the environment supports it.


Representative Round-Trip Test

For representative valid state, test:

create/change → save → exit/unload → load → compare

Include relevant:

  • empty state;
  • normal state;
  • boundary-rich state;
  • multiple inventory stacks;
  • equipped items;
  • progression values;
  • quests;
  • world state;
  • settings.

Compare meaningful semantics, not incidental serialization ordering.


Serialization Completeness Pass

Determine whether all required persistent fields survive round trip.

Look for:

  • field omitted during save;
  • field read but never written;
  • field written but never restored;
  • enum defaulting incorrectly;
  • nested state dropped;
  • dictionary/list state reordered incorrectly when order matters;
  • identifier type mismatch;
  • transient state persisted accidentally;
  • required state treated as optional.

Do not persist runtime-only state unnecessarily.


Serializer / Deserializer Symmetry

Ask:

Does everything written have a compatible reader?

and:

Does every supported reader input have a valid writer path afterward?

Test:

load old/current → save current → reload current

Migration and serialization often fail at this boundary.


Atomic File Save Pass

For file-based saves, inspect what happens if execution stops during writing.

Dangerous pattern:

  1. open only valid save;
  2. truncate it;
  3. begin writing;
  4. crash;
  5. valid copy is gone.

Where justified, prefer established atomic patterns such as:

  1. serialize;
  2. write temporary file;
  3. flush/close as appropriate;
  4. validate write success;
  5. replace prior file atomically where platform permits.

Preserve the previous valid copy until replacement is known-good.

Do not implement platform-specific atomicity assumptions without verifying support.


Interrupted Write Attack

Simulate or reason through failure at meaningful stages:

  • before write;
  • during serialization;
  • halfway through file write;
  • after temp write;
  • during replace;
  • during DB transaction;
  • immediately before acknowledgement.

Ask:

What valid state remains if the process dies here?

The ideal outcome is usually:

old valid state or new valid state

rather than:

half-written state

Success Acknowledgement Discipline

Do not report persistence success before durability is known to the degree required by the system.

Distinguish:

  • request accepted;
  • queued;
  • serialized;
  • DB statement succeeded;
  • transaction committed;
  • file replacement completed.

For consequential operations, avoid telling gameplay code that durable work succeeded when it has not.

Do not introduce unnecessary synchronous blocking if asynchronous acknowledgement is already correctly modeled.


Overlapping Save Attack

Explicitly test:

Save A starts → state changes → Save B starts → B finishes → A finishes last

Ask:

Can A overwrite newer state from B?

If yes, fix using the simplest mechanism consistent with architecture, such as:

  • serializing saves;
  • revision/version checks;
  • cancellation of superseded work;
  • optimistic concurrency;
  • authoritative save ownership.

Do not add a generalized versioning framework if simple serialization already solves the actual problem.


Save Ordering

Never assume asynchronous writes complete in request order unless the system explicitly guarantees it.

Identify:

  • what queues work;
  • whether operations can overlap;
  • whether completion order matters;
  • what happens when older work completes later.

Prevent stale completion from becoming current durable truth.


Stale Snapshot Overwrite Hunt

Search for the pattern:

  1. state snapshot created;
  2. gameplay advances;
  3. newer state is persisted;
  4. delayed old snapshot finishes afterward;
  5. old state becomes durable.

This is especially dangerous around:

  • autosaves;
  • logout;
  • disconnect;
  • reconnect;
  • zone transitions;
  • server shutdown;
  • background persistence.

Fix stale-write paths.


Session-Aware Persistence

In multiplayer games, distinguish current and obsolete sessions.

Test:

  1. session A is active;
  2. save from A starts;
  3. player disconnects;
  4. session B reconnects;
  5. B progresses and saves;
  6. old save from A finishes.

Old session A must not overwrite session B's newer authoritative state.

Use project-compatible mechanisms such as:

  • session generation;
  • state revision;
  • ownership validation;
  • centralized save serialization;
  • optimistic concurrency.

Use only as much machinery as the actual problem requires.


Logout / Disconnect Persistence

Test save boundaries around:

  • normal logout;
  • unexpected disconnect;
  • reconnect;
  • character switch;
  • zone transfer;
  • death where relevant;
  • server shutdown.

Ask:

  • Is state saved?
  • Is it saved once?
  • Can old work finish after reconnect?
  • Is logout cleanup dependent on save success?
  • What happens if save fails?
  • Does disconnect destroy authoritative state before persistence safely captures it?

Do not assume disconnect and logout are equivalent if implementation differs.


Server Shutdown Persistence

If servers persist player/world state during shutdown, inspect:

  • shutdown ordering;
  • acceptance of new work;
  • pending saves;
  • transaction completion;
  • timeout behavior;
  • forced termination.

Avoid shutdown sequences that:

  • destroy in-memory authoritative state first;
  • then attempt to persist it afterward.

Where practical, test graceful shutdown.


Retry / Duplicate Processing

Assume persistence operations may be retried because of:

  • timeout;
  • reconnect;
  • network failure;
  • worker restart;
  • DB retry;
  • user input;
  • unknown acknowledgement state.

Ask:

What happens if this operation runs twice?

Separate:

State Replacement

Example:

set current settings to X

This may naturally be idempotent.

Consequential Mutation

Examples:

  • grant reward;
  • add currency;
  • consume item;
  • purchase;
  • complete quest reward;
  • trade.

These may duplicate value if retried.

Protect consequential operations appropriately.


Reward Idempotency

For every durable one-time reward ask:

What identifies this logical reward occurrence?

Examples:

  • quest completion;
  • achievement reward;
  • boss reward;
  • purchase result;
  • transaction;
  • daily reward.

A repeated persistence request should not accidentally transform one logical event into several rewards.

Use existing project-compatible identity/uniqueness mechanisms.


Player Property Conservation

Treat important player property as conservation problems.

Relevant state may include:

  • inventory;
  • equipment;
  • currency;
  • tradeable resources;
  • purchased items.

For an operation such as:

remove item A → grant item B

ask what happens if failure occurs between steps.

Unless intentionally designed otherwise, avoid outcomes such as:

  • both A and B;
  • neither A nor B;
  • currency removed without item;
  • recipient receives item while sender retains it.

Use appropriate atomicity.


Multi-Step Transaction Pass

Inspect operations such as:

  • purchase;
  • trade;
  • crafting;
  • upgrade;
  • currency transfer;
  • equipment transfer;
  • item conversion;
  • reward claim.

For each identify:

  1. validation;
  2. mutations;
  3. durable writes;
  4. final acknowledgement.

Ask:

Which mutations must succeed or fail together?

Use transaction boundaries appropriate to the actual persistence system.


Database Transaction Review

Where a database exists, inspect multi-step consequential operations.

Look for:

  • partial commits;
  • separate writes that should be atomic;
  • failures between debit and credit;
  • transaction opened too late;
  • transaction committed before final invariant is satisfied;
  • errors swallowed inside transaction.

Use database transactions when they naturally represent the integrity requirement.

Do not place huge unrelated workflows inside one transaction merely for theoretical safety.


Read-Modify-Write Race

Search for:

  1. read current value;
  2. calculate new value;
  3. write new value;

when multiple writers can execute concurrently.

Examples:

  • currency;
  • quantities;
  • XP;
  • stock;
  • counters.

Two callers may both read the same old value and overwrite one another.

Where concurrency exists, prefer appropriate:

  • atomic update;
  • transaction;
  • row/version condition;
  • locking;
  • authoritative serialization.

Do not rely only on application checks that can race.


Unique Constraint Review

Where the invariant is naturally uniqueness, determine whether the database should enforce it.

Examples:

  • one reward claim per logical event;
  • one active ownership row;
  • one account/character relationship;
  • unique transaction identifier.

Application checks such as:

check if row exists → insert

may race.

Use database guarantees when they correctly express domain invariants.

Do not add uniqueness constraints blindly where duplicates are valid.


Database Constraint Review

Inspect whether critical durable invariants can currently accept impossible values.

Potential examples:

  • negative quantities;
  • invalid foreign references;
  • duplicate unique ownership;
  • null required owners;
  • impossible account relationships.

Use database-level enforcement when it cleanly matches the domain.

Do not duplicate every gameplay rule in schema constraints.


Inventory Persistence Pass

Treat inventory as high-risk persistent state.

Test:

  • add;
  • remove;
  • split;
  • merge;
  • move;
  • equip;
  • unequip;
  • drop;
  • loot;
  • craft;
  • trade;
  • save;
  • reconnect.

Verify:

  • quantities remain valid;
  • item ownership remains singular;
  • state survives round trip;
  • concurrent mutations do not overwrite each other;
  • retry does not duplicate;
  • stale snapshot does not remove newer items.

Equipment Persistence Pass

Test:

  • equipped state survives save/load;
  • inventory/equipment ownership agrees;
  • duplicate equip requests do not duplicate item state;
  • invalid equipped item references fail safely;
  • equipment migration preserves valid ownership.

Ensure derived stats are not accidentally persisted as independent authority unless intended.


Currency Persistence Pass

Treat currency as high-risk.

Test:

  • earning;
  • spending;
  • purchasing;
  • refunding;
  • trading;
  • saving;
  • disconnect;
  • concurrent operations;
  • retry.

Ensure:

  • balance does not become negative unintentionally;
  • two concurrent purchases cannot both spend the same balance;
  • retry cannot duplicate credits;
  • old state cannot overwrite newer balance.

XP / Skill Persistence Pass

Test:

  • XP award;
  • level-up;
  • multi-level gain;
  • save/load;
  • reconnect;
  • migration;
  • repeated reward persistence.

Ensure:

  • XP and level do not disagree;
  • derived values are recomputed appropriately if that is the established model;
  • old snapshots cannot roll progression backward;
  • one reward cannot grant XP twice durably.

Quest / Unlock Persistence Pass

Where relevant test:

  • objective progress;
  • completion;
  • rewards;
  • unlocks;
  • save/load;
  • old data;
  • repeated migration.

Ensure:

  • completed state does not revert accidentally;
  • one-time rewards do not repeat;
  • migrated state remains logically valid;
  • missing optional fields receive safe defaults.

World Persistence Pass

If world state persists, inspect:

  • object identity;
  • spawned/despawned state;
  • depletion;
  • construction;
  • doors;
  • NPC state;
  • shared resources.

Test:

  • save/load;
  • restart;
  • concurrent mutation;
  • schema/version upgrade.

Be cautious with persistent object IDs.

Do not casually regenerate identifiers that other durable state references.


Save Versioning

Determine how compatibility is identified.

Do not confuse:

  • application/game version;
  • save-format version;
  • database schema version;
  • protocol version.

These concepts may evolve independently.

Compatibility decisions should use the version that actually describes the persisted format.


Migration Map

Inventory active migration paths.

For each determine:

  • source version;
  • target version;
  • ordering;
  • assumptions;
  • field conversions;
  • defaults;
  • irreversible changes.

Ensure multiple-version upgrades follow the correct path.

Example:

v1 → v2 → v3

rather than accidentally applying only:

v1 → v3

when intermediate transformation is required.


Migration Test

For every active migration path, test where practical:

old valid data → migrate → load → save → reload

Check:

  • missing optional fields;
  • renamed fields;
  • removed fields;
  • changed types;
  • default values;
  • identifiers;
  • collections;
  • repeated migration;
  • partial failure.

Do not treat successful parsing alone as migration success.

The resulting gameplay state must remain valid.


Migration Idempotency

Determine whether a migration can accidentally run twice.

A migration may intentionally be:

  • exactly-once by version;
  • safely idempotent;
  • protected by schema state.

Ensure repeated startup does not:

  • duplicate data;
  • repeat conversion;
  • progressively modify values;
  • grant rewards twice.

Never Rewrite Applied Migration History Casually

Do not modify previously deployed/applied migration semantics simply because changing the old migration appears easier.

Doing so can create different database states depending on installation history.

Prefer:

  • new forward migration;
  • explicitly versioned correction;

where appropriate.

Only rewrite old migration history when the project has never shipped/applied it or there is strong evidence it is safe.


Failed Migration Behavior

Inspect what happens when migration fails midway.

Avoid:

  • silently marking version upgraded before data conversion finishes;
  • half-upgraded state treated as valid;
  • repeatedly destructive retries;
  • deleting previous valid data too early.

Where practical, use transactional migration or recoverable staged migration.


Irreversible Migration Gate

Treat migrations that:

  • delete fields;
  • destroy old representations;
  • collapse data;
  • rewrite ownership;
  • change identifiers;
  • alter currency/items;

as high-risk.

Before implementing ensure:

  1. current data shape is understood;
  2. transformation is deterministic;
  3. compatibility implications are understood;
  4. failure path is defined;
  5. validation exists;
  6. recovery/backup assumptions are explicit.

Prefer additional independent review for these changes.


Malformed Data Attack

Test realistic malformed or incomplete data.

Examples:

  • missing optional field;
  • unknown enum value;
  • invalid ID;
  • truncated file;
  • invalid numeric value;
  • malformed JSON/binary payload;
  • missing collection entry;
  • unsupported version.

The system should fail safely.

Avoid:

  • crash loops;
  • silently resetting all progress;
  • overwriting recoverable data;
  • creating impossible state.

Do not promise magical recovery from arbitrary corruption.


Validation Before Durable Commit

Where data originates from:

  • clients;
  • network;
  • files;
  • external services;
  • user-editable configuration;

validate important invariants before persistence.

Do not durably persist obviously invalid state such as:

  • impossible quantities;
  • negative balances;
  • nonexistent required references;
  • invalid ownership;
  • malformed enum/state values;
  • values outside supported bounds.

Use authoritative game rules where appropriate.


Load-Time Validation

Loading trusted persisted data should still defend against:

  • corruption;
  • old versions;
  • partial files;
  • incompatible schema;
  • manually modified local files where relevant.

Validation should distinguish:

  • safely defaultable missing data;
  • recoverable old format;
  • invalid critical data.

Do not silently "repair" values when the correct interpretation is uncertain.


Default-Value Review

When new fields are introduced, establish appropriate behavior for older saves.

Ask:

What does absence of this field mean?

Do not choose defaults merely to satisfy parsing.

Defaults should create valid gameplay state.


Unknown Field Compatibility

Where the serialization format naturally supports unknown fields, avoid unnecessarily rejecting newer/extended data unless strict validation is required.

Conversely, do not ignore unknown structural changes when doing so could misinterpret the save.

Use the format's intended compatibility model.


Identifier Integrity

Inspect persistent identifiers for:

  • accounts;
  • characters;
  • items;
  • world objects;
  • quests;
  • transactions;
  • sessions where durable.

Look for:

  • ID reuse;
  • collisions;
  • type changes;
  • parsing differences;
  • migration errors;
  • references to deleted objects.

Persistent references require stable identity.


Account / Character Ownership

Where accounts contain multiple characters or similar hierarchy exists, verify:

  • character belongs to correct account;
  • writes include correct ownership constraints;
  • one account cannot accidentally load another character;
  • stale session cannot mutate a character it no longer owns;
  • deletion/recreation does not accidentally reuse ownership incorrectly.

Treat ownership failures as high severity.


Backup and Recovery

If backup/recovery functionality already exists, verify it actually works.

Inspect:

  • when backup is created;
  • what data it contains;
  • whether it is version-compatible;
  • how restore chooses a candidate;
  • whether current good state is protected during restore.

Do not build a massive backup platform from scratch.


Previous-Good Save Recovery

If file saves retain a previous-good copy, test:

  1. valid primary + valid backup;
  2. corrupted primary + valid backup;
  3. valid newer primary + older backup;
  4. incompatible backup;
  5. failed restoration.

Do not automatically restore older data over valid newer data.

Recovery must preserve recency and compatibility.


Recovery Must Not Destroy Evidence

When load fails, avoid immediately overwriting the broken source with a fresh default save.

That may destroy recoverable data.

Where appropriate:

  • preserve the damaged file;
  • report failure;
  • restore from known-good backup if supported;
  • create new state separately.

Do not retain sensitive/player data indefinitely without regard to existing project policy.


Cloud Save Conflict Review

If cloud saves exist, determine the current conflict model.

Possible dimensions:

  • local timestamp;
  • cloud timestamp;
  • revision;
  • game/platform version;
  • explicit user choice;
  • authoritative server state.

Do not invent a new cloud architecture.

But prevent obvious cases where older cloud/local state automatically overwrites newer progress without justification.

Treat unresolved cloud conflict behavior as high risk.


Settings Versus Progress Data

Do not assume all persistence requires identical safety semantics.

Examples:

  • losing a window position is not equivalent to losing inventory;
  • graphics settings may tolerate fallback;
  • account progression may require strict protection.

Apply integrity mechanisms proportional to consequence.


Retry Semantics

Classify persistence operations.

Naturally Idempotent

Examples may include:

  • replace settings snapshot;
  • set current known value.

Side-Effecting

Examples:

  • add currency;
  • append transaction;
  • grant item;
  • award quest reward.

Side-effecting operations require duplicate protection.

Do not apply generic retries indiscriminately.


Timeout Ambiguity

When a persistence call times out, remember:

timeout does not prove the write failed

It may have completed and the acknowledgement may have been lost.

Retrying blindly can duplicate effects.

Design consequential retries around uncertain completion.


Partial Failure Attack

For every multi-step persistent mutation ask:

What happens if failure occurs after each individual step?

Example:

  1. validate purchase;
  2. deduct currency;
  3. add item;
  4. commit;
  5. acknowledge.

Test or reason through failure after:

  • validation;
  • deduction;
  • item creation;
  • commit;
  • acknowledgement.

The durable result must remain internally coherent.


Crash-During-Save Test

Where practical, simulate abrupt process termination during:

  • local file save;
  • transaction;
  • autosave;
  • migration;
  • shutdown persistence.

Then restart and inspect the durable state.

Do not intentionally damage real production data.

Use disposable state.


Autosave Review

Inspect autosave behavior.

Ask:

  • Can saves overlap?
  • Does autosave capture coherent state?
  • Can it run during transitions?
  • Does failure spam retries?
  • Can autosave overwrite newer manual/save-point state?
  • Does it persist during unsafe intermediate states?

Do not simply increase autosave frequency as a safety fix.

More writes can create more race opportunities.


Snapshot Consistency

If a save contains several related subsystems, determine whether the snapshot represents one coherent point in time.

Example:

  • inventory from time A;
  • currency from time B;
  • quest state from time C;

may produce impossible combinations.

Where required, capture related state coherently.

Do not globally pause the game for every save unless necessary.


Cross-System Transaction Integrity

Some state changes span systems.

Examples:

  • crafting changes inventory + XP;
  • quest completion changes quest state + reward + XP;
  • purchase changes currency + inventory;
  • trade changes two players.

Determine which parts must be durable together.

Avoid a restart producing:

  • reward without completion;
  • completion without reward;
  • payment without purchase;
  • transfer from sender without transfer to recipient.

Save Queue Review

If writes are queued, inspect:

  • queue ordering;
  • deduplication;
  • cancellation;
  • shutdown flushing;
  • reconnect interaction;
  • stale queued work.

Coalescing may be useful when several snapshots supersede one another.

Do not coalesce independent consequential events that must each persist.


Write Coalescing Safety

If several saves can be collapsed, make sure doing so does not lose:

  • side effects;
  • audit/transaction records;
  • one-time rewards;
  • state needed for migration.

Snapshot replacement and event persistence have different semantics.


Background Persistence Lifecycle

If persistence runs in workers/tasks/background jobs, inspect:

  • cancellation;
  • ownership;
  • failure propagation;
  • process shutdown;
  • retry;
  • current session/state validation.

A background worker must not outlive the authority assumptions of the data it is writing.


Database Error Handling

Inspect persistence code for:

  • swallowed exceptions;
  • ignored row counts;
  • failed transactions treated as success;
  • ambiguous duplicate-key handling;
  • retries without idempotency;
  • reconnect loops hiding failed writes.

Errors should be actionable.

Do not expose secrets or raw database internals to players.


Result Verification

For important DB mutations, determine whether the code checks:

  • affected rows;
  • returned version;
  • generated ID;
  • transaction result;
  • conditional-update success.

A command returning without throwing does not always prove the intended state changed.


Optimistic Concurrency

Where stale read/write races exist, consider versioned/conditional updates when they fit the existing design.

Conceptually:

update state if revision = expected revision

If zero rows are updated:

the state changed concurrently

Handle intentionally.

Do not add revision columns across the entire database unless actual races justify them.


Pessimistic Locking

Use explicit locking only where necessary.

Before adding locks ask:

  • Can an atomic update solve this?
  • Can a transaction isolate it?
  • Can authoritative serialization prevent overlap?
  • Can uniqueness enforce the invariant?

Avoid:

  • broad lock scopes;
  • deadlocks;
  • unnecessary contention;
  • cross-system lock-order complexity.

Pattern-Based Integrity Hunt

When one persistence defect is found, search for the underlying pattern elsewhere.

Examples:

If one save callback can write stale state:

inspect other asynchronous saves.

If one currency operation uses unsafe read-modify-write:

inspect item quantities and XP.

If one reward can retry twice:

inspect other reward-granting paths.

If one migration lacks a default:

inspect other newly introduced fields.

Fix the defect class where justified rather than only the first symptom.


Regression Test Creation

Add focused regression tests where the project already supports them or lightweight coverage is practical.

Useful tests may include:

  • save/load round trip;
  • old-version migration;
  • interrupted save;
  • stale-save prevention;
  • duplicate reward;
  • concurrent purchase;
  • transaction rollback;
  • reconnect/save race;
  • malformed save;
  • backup restore.

A good test should:

  1. reproduce the original failure;
  2. fail before the fix;
  3. pass after;
  4. remain stable;
  5. avoid fragile timing dependence where possible.

Prefer controllable synchronization/failure injection over arbitrary sleep-based race tests.


Bug-Fix Standard

For every meaningful integrity defect:

  1. reproduce where practical;
  2. identify the violated invariant;
  3. identify authoritative state ownership;
  4. identify durable mutation boundaries;
  5. determine root cause;
  6. implement the smallest robust fix;
  7. rerun original reproduction;
  8. test normal save/load;
  9. test failure/interruption where relevant;
  10. test duplicate execution where relevant;
  11. test stale completion where relevant;
  12. test old data where relevant;
  13. search analogous code;
  14. add focused regression coverage where practical.

Avoid symptom fixes such as:

  • arbitrary delays;
  • repeated blind retries;
  • swallowing errors;
  • save-frequency increases;
  • duplicate backup copies without recovery semantics.

Correct the underlying integrity model.


Work in Persistence Waves

Do not change every persistence subsystem simultaneously.

Wave A — Catastrophic Integrity

Fix:

  • corruption;
  • duplication;
  • lost progress;
  • stale overwrites;
  • account/character ownership problems;
  • broken transactions.

Validate.

Wave B — Save / Load Foundations

Inspect:

  • serialization;
  • round trips;
  • atomic writes;
  • save ordering;
  • autosaves;
  • local recovery.

Validate.

Wave C — Database / Transactions

Inspect:

  • read-modify-write;
  • concurrency;
  • constraints;
  • multi-step mutations;
  • retry semantics.

Validate.

Wave D — Migrations / Compatibility

Test:

  • old data;
  • migration order;
  • defaults;
  • repeated migration;
  • partial failure.

Validate.

Wave E — Multiplayer Lifecycle

Where applicable test:

  • logout;
  • disconnect;
  • reconnect;
  • session replacement;
  • overlapping saves;
  • server shutdown.

Validate.

Wave F — Recovery / Long Tail

Inspect:

  • malformed data;
  • backups;
  • old formats;
  • recovery;
  • rare failure branches;
  • stale background work.

Reassess After Every Wave

Ask:

  • Can older state overwrite newer state?
  • What happens if this write fails halfway?
  • What happens if it executes twice?
  • What happens if the player disconnects?
  • Can concurrent writers disagree?
  • Can older valid data still load?
  • Can malformed data destroy the last good copy?
  • Are success responses sent before required durability is established?
  • Did a fix introduce excessive locking or complexity?
  • Is any durable player property still updated non-atomically?
  • Did migration testing expose other stale assumptions?

Reprioritize.


Productive Persistence Loop

Do not stop after the first severe integrity fix.

Persistence problems often expose deeper shared assumptions.

Examples:

  • atomic saves expose stale-save ordering;
  • stale-save fixes expose reconnect ownership;
  • reconnect fixes expose DB concurrency;
  • migration fixes expose serializer defaults;
  • transaction fixes expose duplicate retry behavior.

Continue:

inspect → model invariant → attack → reproduce → fix → validate → attack again

while meaningful, safely actionable integrity risks remain.

Do not manufacture theoretical failure cases merely to continue working.

Stop when remaining risks are:

  • speculative;
  • extremely low impact;
  • dependent on unavailable production infrastructure;
  • dependent on unknown product policy;
  • intentionally accepted;
  • outside scope.

Independent High-Risk Review

Near completion, review high-risk changes from fresh context where practical.

Especially scrutinize:

  • inventory;
  • currency;
  • transactions;
  • schema migrations;
  • account/character ownership;
  • overlapping saves;
  • multiplayer persistence;
  • cloud conflicts;
  • recovery.

Challenge each change with:

How can this still fail halfway?
How can it execute twice?
How can older state still win?
What if two writers act simultaneously?
What if reconnect occurs at the worst possible moment?
What happens after restart?
What happens with old valid data?

The purpose is to find failure modes, not simply approve previous work.


Anti-Overengineering Review

Before completion inspect whether fixes introduced unnecessary persistence machinery.

Ask:

  • Did we add event sourcing without need?
  • Did we invent distributed transactions for a local problem?
  • Did we add revision systems where serialization sufficed?
  • Did we create a large backup framework for one file?
  • Did we introduce generalized persistence abstractions without clear benefit?
  • Did locking become broader than necessary?
  • Did the fix make normal saving harder to understand?
  • Did we create another source of truth?

Prefer the smallest robust mechanism.


Performance Awareness

This is not primarily a persistence-performance pass.

However, avoid integrity fixes that accidentally introduce:

  • database transaction contention across unrelated players;
  • full-character writes for tiny independent changes without reason;
  • synchronous blocking of the main game loop;
  • excessive backup duplication;
  • unbounded save queues;
  • retry storms;
  • global locks.

Correctness comes first.

But maintain reasonable runtime behavior.


Final Cross-System Integrity Review

Before finishing inspect for:

  • stale writes;
  • partial transactions;
  • duplicate reward paths;
  • invalid account ownership;
  • failed save acknowledgement;
  • unsafe retries;
  • migration gaps;
  • corrupted recovery behavior;
  • missing version handling;
  • invalid durable values;
  • old-session writes;
  • inconsistent save/load semantics;
  • backups that cannot restore;
  • data loss introduced by new fixes.

Fix justified issues.

Run final validation.


Completion Standard

The persistence and data-integrity pass is complete when, to the degree available testing can establish:

  1. major persisted state has been mapped;
  2. authoritative persistence ownership is understood;
  3. representative state round-trips correctly;
  4. important local writes are appropriately atomic;
  5. stale saves cannot obviously overwrite newer state;
  6. overlapping-save behavior is safe;
  7. important consequential retries do not duplicate durable outcomes;
  8. inventory persistence preserves ownership and quantity;
  9. currency persistence resists duplicate/partial mutation;
  10. important multi-step transactions have appropriate atomicity;
  11. relevant database concurrency hazards discovered are fixed;
  12. active migrations have been validated;
  13. old supported data remains loadable where reasonably expected;
  14. repeated migration does not corrupt data;
  15. migration failure is handled safely;
  16. disconnect/logout persistence is safe where applicable;
  17. stale sessions cannot overwrite current state;
  18. malformed data fails reasonably;
  19. recovery mechanisms work to the extent they exist;
  20. the last known-good data is not casually destroyed during recovery;
  21. high-risk fixes received additional independent scrutiny;
  22. no discovered P0/P1 integrity issue remains unresolved without an explicit blocker;
  23. no known regression introduced by this pass remains;
  24. remaining concerns require unavailable production infrastructure, live-player data, external policy decisions, are low-impact, or belong to another specialized pass.

The objective is not:

make persistence infinitely complicated

The objective is:

protect valid player and world state using the smallest mechanisms that reliably prevent corruption, duplication, stale overwrites, partial mutation, incompatible upgrades, and data loss.

Final Report

When complete, provide a concise persistence-engineering report.

1. Overall Result

Summarize the most important improvements to player-data safety.

2. Critical Integrity Bugs Fixed

For each major issue include:

  • System
  • Failure
  • Root cause
  • Fix
  • Potential player impact

3. Save / Load and Serialization

Summarize meaningful changes involving:

  • round trips;
  • serializer/deserializer behavior;
  • atomic saves;
  • save ordering;
  • validation.

4. Transactions and Stale-Write Protection

Summarize meaningful work involving:

  • database transactions;
  • read-modify-write races;
  • retries;
  • idempotency;
  • stale snapshots;
  • revision/ownership checks.

5. Migrations and Version Compatibility

Describe:

  • migration paths tested;
  • defaults or conversions fixed;
  • repeated migration behavior;
  • old-version compatibility.

6. Disconnect / Reconnect Persistence

Include only when applicable.

Summarize:

  • logout;
  • disconnect;
  • reconnect;
  • old-session saves;
  • session replacement;
  • shutdown persistence.

7. Recovery / Corruption Handling

Describe:

  • malformed-data handling;
  • backups;
  • previous-good recovery;
  • recovery protections.

8. Validation Performed

State exactly what was actually tested, including relevant:

  • save/load round trips;
  • migration fixtures;
  • interrupted writes;
  • duplicate requests;
  • concurrent DB operations;
  • transaction failures;
  • reconnect races;
  • malformed files;
  • backup restoration.

Do not imply testing occurred when it did not.

9. Deliberately Unchanged

Describe important behavior preserved because:

  • compatibility requires it;
  • evidence was insufficient;
  • architecture already guarantees safety;
  • changing it would require a redesign;
  • live-player impact is uncertain;
  • external infrastructure was unavailable.

10. Remaining Risks

List only meaningful unresolved integrity risks.

For each include:

  • Risk
  • Severity
  • Why unresolved
  • Potential impact
  • Recommended next action

Do not pad this section with theoretical concerns unsupported by evidence.


Final Directive

Treat persisted player data as something the game must protect, not merely serialize.

Do not assume:

  • writes complete in order;
  • retries are harmless;
  • disconnect means old work disappears;
  • saves happen one at a time;
  • a successful request means a durable commit occurred;
  • old data always matches current schemas;
  • malformed data can safely be reset;
  • application-side validation alone prevents database races.

Repeatedly ask:

What if this fails halfway?
What if it happens twice?
What if older work finishes later?
What if two writers act at once?
What if the player reconnects before the old save finishes?
What if this data came from an older version?
Can we recover without destroying the last good state?
What durable invariant must always remain true?

Continue:

inspect → model invariants → attack failure paths → reproduce → implement → validate → attack again

while meaningful data-integrity risk remains.

Leave behind the same game, but make its saves, databases, migrations, transactions, recovery paths, and persistent player state substantially safer, more recoverable, transactionally sound, and resistant to corruption, duplication, stale writes, incompatible upgrades, and data loss.

View raw markdown
You are responsible for a comprehensive **save-system, persistence, migration, transaction, recovery, and player-data integrity pass**.

Your job is to make the existing game substantially safer against:

- lost progress;
- corrupted saves;
- stale overwrites;
- duplicated rewards;
- duplicated items or currency;
- partial writes;
- incompatible upgrades;
- failed migrations;
- crashes during saving;
- disconnects during persistence;
- retries;
- concurrent updates;
- malformed data;
- older valid data;
- asynchronous writes completing out of order;
- recovery systems damaging the last known-good state.

The primary question throughout this task is:

> **What can cause valid player or world state to be lost, duplicated, corrupted, reverted, partially written, or made unloadable?**

Then fix those problems.

This is an **implementation task**, not merely a persistence audit.

Do not stop after:

- mapping save flows;
- identifying risky database operations;
- listing migration concerns;
- describing transaction problems;
- recommending atomic saves;
- documenting corruption scenarios;
- producing a data-integrity report.

Inspect the actual persistence implementation.

Establish invariants.

Attack failure paths.

Reproduce problems where practical.

Implement robust fixes.

Validate normal behavior and failure behavior.

Then attack the corrected paths again.

Use continuously:

> **inspect → model invariants → attack failure paths → reproduce → diagnose → implement → validate → attack again**

The goal is:

> **Leave behind the same game, but make its saves and persistent state substantially safer, more recoverable, transactionally sound, and resistant to corruption, duplication, stale writes, incompatible upgrades, and data loss.**

---

# Player Data Safety Is the Priority

Prioritize approximately:

1. permanent player-data loss;
2. persistent item or currency duplication;
3. corrupted or unloadable saves;
4. stale state overwriting newer state;
5. partial transactions;
6. destructive migration failures;
7. incorrect account/character ownership;
8. retries duplicating consequential outcomes;
9. disconnect/reconnect persistence races;
10. overlapping save races;
11. invalid durable state;
12. failed recovery behavior;
13. old-version compatibility problems;
14. malformed-data handling;
15. lower-impact persistence inconsistencies.

This ordering is not rigid.

Fix the highest-risk integrity problems actually present.

---

# Core Scope

Inspect only systems that actually exist.

Relevant areas may include:

## Local Saves

- save files;
- autosaves;
- manual saves;
- checkpoints;
- settings;
- profiles;
- character files;
- world files;
- temporary save files;
- backup copies.

## Player State

- account data;
- character data;
- inventory;
- equipment;
- XP;
- skills;
- levels;
- currency;
- quests;
- unlocks;
- achievements where gameplay state is persisted;
- cooldowns where persisted;
- world position;
- progression state.

## World Persistence

- world objects;
- resource nodes;
- doors;
- NPC/world state;
- player-built objects;
- shared world progression;
- server-owned state.

## Databases

- schemas;
- queries;
- transactions;
- constraints;
- migrations;
- indexes where integrity-sensitive;
- account/character relationships;
- read-modify-write operations;
- durable event/reward records where present.

## Serialization

- encoding;
- decoding;
- defaults;
- optional fields;
- missing fields;
- enums;
- references;
- identifiers;
- numeric bounds;
- format versions.

## Persistence Lifecycle

- save triggers;
- autosaves;
- logout saves;
- disconnect saves;
- server shutdown;
- zone transitions;
- character switching;
- background saves;
- save queues;
- retry logic.

## Migrations

- save migrations;
- schema migrations;
- field migrations;
- data conversions;
- version transitions;
- migration ordering;
- repeated migration behavior.

## Recovery

- backups;
- temp files;
- previous-good copies;
- corruption handling;
- rollback where implemented;
- restore paths.

## Multiplayer Persistence

Where applicable:

- stale-session writes;
- reconnect races;
- concurrent player mutations;
- authoritative server state;
- database transactions;
- overlapping sessions;
- cloud/local disagreement.

Do not invent persistence systems that do not exist.

---

# Explicitly Out of Scope

This is **not primarily**:

- a gameplay redesign;
- a progression rebalance;
- an economy rebalance;
- a networking-stack rewrite;
- a database-engine migration;
- a new cloud-save service;
- a general codebase refactor;
- repository cleanup;
- performance optimization;
- feature expansion;
- UI redesign.

Small structural changes are allowed when directly required to eliminate a confirmed integrity problem.

Do not replace working persistence architecture merely because another architecture is theoretically cleaner.

---

# Preserve Existing Save Compatibility

Preserve existing valid player data wherever reasonably possible.

Do not casually:

- change save locations;
- change identifiers;
- rename durable fields without migration;
- change database ownership relationships;
- invalidate existing files;
- rewrite migration history;
- reset progress;
- discard unknown fields;
- replace persisted formats.

When a breaking change is genuinely necessary:

1. establish why;
2. identify affected existing state;
3. provide a safe migration path where practical;
4. validate old → new behavior;
5. make failure explicit rather than silently destroying data.

Player-data compatibility is more important than architectural elegance.

---

# Core Persistence Invariants

Identify project-specific invariants before making broad changes.

Important examples include:

- valid progress never silently decreases;
- newer authoritative state cannot be overwritten by stale state;
- item ownership remains unambiguous;
- items are neither accidentally duplicated nor lost;
- currency is neither accidentally duplicated nor lost;
- one logical reward persists the intended number of times;
- failed writes do not masquerade as success;
- interrupted writes leave old valid state or new valid state rather than half-state;
- migrations either produce valid target-version data or fail safely;
- invalid external data does not create impossible durable state;
- account A cannot overwrite account B;
- character A cannot overwrite character B;
- older sessions cannot overwrite newer sessions;
- save/load round trips preserve supported state.

Treat violations involving permanent player progress as high severity.

---

# Persistence Priority Queue

## P0 — Catastrophic Integrity Failure

Examples:

- permanent save corruption;
- widespread player-data loss;
- item or currency duplication;
- wrong-account data overwrite;
- destructive migration;
- stale session overwriting current progress;
- transaction committing half an ownership transfer;
- retry granting the same durable reward repeatedly.

Fix immediately.

## P1 — Major Data Risk

Examples:

- autosave can overwrite newer manual state;
- reconnect races with old-session save;
- valid older saves fail after upgrade;
- interrupted writes commonly corrupt state;
- partial database operations lose items;
- malformed data causes startup crash loop;
- backups overwrite newer valid data.

Prioritize heavily.

## P2 — Significant Robustness Problem

Examples:

- optional fields fail to default safely;
- recovery path is unreliable;
- non-critical settings can be lost;
- minor migration edge case;
- duplicate low-value durable records;
- stale state possible under unusual timing.

Fix where evidence supports it.

## P3 — Finishing Integrity Work

Examples:

- minor validation gaps;
- harmless redundant writes;
- small serializer inconsistencies;
- low-risk old-version handling.

Address after higher-risk issues.

---

# Establish the Persistence Model

Determine exactly:

- what is persisted;
- where it is stored;
- when it is written;
- who may write it;
- what is authoritative;
- what format is used;
- what version identifies the format;
- what can write concurrently;
- what acknowledges success;
- what recovery mechanisms exist.

Trace important state through:

> **gameplay mutation → authoritative in-memory state → persistence request → serialization/query → durable write → acknowledgement → later load**

Find every path capable of mutating durable player value.

Do not assume there is only one save path.

---

# Establish Persistence Ownership

For important data ask:

> **Who owns the authoritative current value?**

Potential owners may include:

- local game state;
- server session;
- account service;
- character service;
- database;
- cloud save;
- world server.

Avoid situations where several layers independently believe they are authoritative.

Distinguish:

- authoritative state;
- cached state;
- replicated state;
- presentation;
- durable storage.

Persistence should record truth.

It should not accidentally create a competing truth.

---

# Investigate Before Asking Questions

Use the project as evidence.

Inspect relevant:

- save/load implementations;
- serializers;
- deserializers;
- database queries;
- schemas;
- migrations;
- transaction boundaries;
- save queues;
- retries;
- session lifecycle;
- logout/disconnect logic;
- recovery code;
- backups;
- version fields;
- tests;
- logs;
- account/character ownership.

Ask for clarification only when:

- authoritative ownership genuinely cannot be established;
- intended compatibility policy is unclear;
- destructive migration requires product approval;
- existing live-player holdings materially affect the decision;
- cloud/local conflict policy cannot be inferred;
- required production infrastructure is unavailable.

Do not ask questions merely because persistence analysis is difficult.

---

# Capability-Aware Execution

Use the strongest testing environment available.

Where practical use:

- temporary save directories;
- test databases;
- transaction fixtures;
- migration fixtures;
- disposable accounts;
- multi-session tests;
- intentionally interrupted writes;
- deterministic failure injection;
- automated round-trip tests.

Do not perform destructive testing against real production player data unless explicitly authorized.

If full runtime or database access is unavailable:

- complete the strongest static and automated validation possible;
- distinguish verified behavior from inferred risk;
- do not claim recovery or migration succeeded if it was not actually tested.

---

# Implementation Over Auditing

The persistence map exists to create an **implementation queue**.

Do not spend most of the task producing:

- giant schema documentation;
- theoretical corruption scenarios;
- exhaustive call graphs;
- long migration reports.

Once a meaningful integrity issue is sufficiently understood:

> **implement the fix.**

Then validate:

1. normal behavior;
2. original failure;
3. retry;
4. interrupted execution;
5. stale completion;
6. old-version behavior where relevant;
7. analogous paths.

---

# Execution Strategy

Work autonomously where possible.

If the environment supports independent agents, workers, subprocesses, or parallel contexts, use them where useful.

Do not require delegation.

A single capable session must still be able to complete the task sequentially.

Good independent investigation areas may include:

- local-save serialization;
- database transactions;
- migrations;
- account/character ownership;
- recovery;
- persistence lifecycle;
- multiplayer save races.

Serialize modifications involving shared:

- schemas;
- migration infrastructure;
- authoritative persistence services;
- account ownership;
- transaction code;
- save-version rules.

Do not let independent workstreams invent incompatible persistence semantics.

For high-risk changes involving:

- inventory;
- currency;
- transactions;
- migrations;
- account ownership;
- multiplayer persistence;
- stale-write prevention;

use additional independent review or fresh-context scrutiny when the environment supports it.

---

# Representative Round-Trip Test

For representative valid state, test:

> **create/change → save → exit/unload → load → compare**

Include relevant:

- empty state;
- normal state;
- boundary-rich state;
- multiple inventory stacks;
- equipped items;
- progression values;
- quests;
- world state;
- settings.

Compare meaningful semantics, not incidental serialization ordering.

---

# Serialization Completeness Pass

Determine whether all required persistent fields survive round trip.

Look for:

- field omitted during save;
- field read but never written;
- field written but never restored;
- enum defaulting incorrectly;
- nested state dropped;
- dictionary/list state reordered incorrectly when order matters;
- identifier type mismatch;
- transient state persisted accidentally;
- required state treated as optional.

Do not persist runtime-only state unnecessarily.

---

# Serializer / Deserializer Symmetry

Ask:

> **Does everything written have a compatible reader?**

and:

> **Does every supported reader input have a valid writer path afterward?**

Test:

> **load old/current → save current → reload current**

Migration and serialization often fail at this boundary.

---

# Atomic File Save Pass

For file-based saves, inspect what happens if execution stops during writing.

Dangerous pattern:

1. open only valid save;
2. truncate it;
3. begin writing;
4. crash;
5. valid copy is gone.

Where justified, prefer established atomic patterns such as:

1. serialize;
2. write temporary file;
3. flush/close as appropriate;
4. validate write success;
5. replace prior file atomically where platform permits.

Preserve the previous valid copy until replacement is known-good.

Do not implement platform-specific atomicity assumptions without verifying support.

---

# Interrupted Write Attack

Simulate or reason through failure at meaningful stages:

- before write;
- during serialization;
- halfway through file write;
- after temp write;
- during replace;
- during DB transaction;
- immediately before acknowledgement.

Ask:

> **What valid state remains if the process dies here?**

The ideal outcome is usually:

> **old valid state or new valid state**

rather than:

> **half-written state**

---

# Success Acknowledgement Discipline

Do not report persistence success before durability is known to the degree required by the system.

Distinguish:

- request accepted;
- queued;
- serialized;
- DB statement succeeded;
- transaction committed;
- file replacement completed.

For consequential operations, avoid telling gameplay code that durable work succeeded when it has not.

Do not introduce unnecessary synchronous blocking if asynchronous acknowledgement is already correctly modeled.

---

# Overlapping Save Attack

Explicitly test:

> **Save A starts → state changes → Save B starts → B finishes → A finishes last**

Ask:

> **Can A overwrite newer state from B?**

If yes, fix using the simplest mechanism consistent with architecture, such as:

- serializing saves;
- revision/version checks;
- cancellation of superseded work;
- optimistic concurrency;
- authoritative save ownership.

Do not add a generalized versioning framework if simple serialization already solves the actual problem.

---

# Save Ordering

Never assume asynchronous writes complete in request order unless the system explicitly guarantees it.

Identify:

- what queues work;
- whether operations can overlap;
- whether completion order matters;
- what happens when older work completes later.

Prevent stale completion from becoming current durable truth.

---

# Stale Snapshot Overwrite Hunt

Search for the pattern:

1. state snapshot created;
2. gameplay advances;
3. newer state is persisted;
4. delayed old snapshot finishes afterward;
5. old state becomes durable.

This is especially dangerous around:

- autosaves;
- logout;
- disconnect;
- reconnect;
- zone transitions;
- server shutdown;
- background persistence.

Fix stale-write paths.

---

# Session-Aware Persistence

In multiplayer games, distinguish current and obsolete sessions.

Test:

1. session A is active;
2. save from A starts;
3. player disconnects;
4. session B reconnects;
5. B progresses and saves;
6. old save from A finishes.

Old session A must not overwrite session B's newer authoritative state.

Use project-compatible mechanisms such as:

- session generation;
- state revision;
- ownership validation;
- centralized save serialization;
- optimistic concurrency.

Use only as much machinery as the actual problem requires.

---

# Logout / Disconnect Persistence

Test save boundaries around:

- normal logout;
- unexpected disconnect;
- reconnect;
- character switch;
- zone transfer;
- death where relevant;
- server shutdown.

Ask:

- Is state saved?
- Is it saved once?
- Can old work finish after reconnect?
- Is logout cleanup dependent on save success?
- What happens if save fails?
- Does disconnect destroy authoritative state before persistence safely captures it?

Do not assume disconnect and logout are equivalent if implementation differs.

---

# Server Shutdown Persistence

If servers persist player/world state during shutdown, inspect:

- shutdown ordering;
- acceptance of new work;
- pending saves;
- transaction completion;
- timeout behavior;
- forced termination.

Avoid shutdown sequences that:

- destroy in-memory authoritative state first;
- then attempt to persist it afterward.

Where practical, test graceful shutdown.

---

# Retry / Duplicate Processing

Assume persistence operations may be retried because of:

- timeout;
- reconnect;
- network failure;
- worker restart;
- DB retry;
- user input;
- unknown acknowledgement state.

Ask:

> **What happens if this operation runs twice?**

Separate:

## State Replacement

Example:

> set current settings to X

This may naturally be idempotent.

## Consequential Mutation

Examples:

- grant reward;
- add currency;
- consume item;
- purchase;
- complete quest reward;
- trade.

These may duplicate value if retried.

Protect consequential operations appropriately.

---

# Reward Idempotency

For every durable one-time reward ask:

> **What identifies this logical reward occurrence?**

Examples:

- quest completion;
- achievement reward;
- boss reward;
- purchase result;
- transaction;
- daily reward.

A repeated persistence request should not accidentally transform one logical event into several rewards.

Use existing project-compatible identity/uniqueness mechanisms.

---

# Player Property Conservation

Treat important player property as conservation problems.

Relevant state may include:

- inventory;
- equipment;
- currency;
- tradeable resources;
- purchased items.

For an operation such as:

> **remove item A → grant item B**

ask what happens if failure occurs between steps.

Unless intentionally designed otherwise, avoid outcomes such as:

- both A and B;
- neither A nor B;
- currency removed without item;
- recipient receives item while sender retains it.

Use appropriate atomicity.

---

# Multi-Step Transaction Pass

Inspect operations such as:

- purchase;
- trade;
- crafting;
- upgrade;
- currency transfer;
- equipment transfer;
- item conversion;
- reward claim.

For each identify:

1. validation;
2. mutations;
3. durable writes;
4. final acknowledgement.

Ask:

> **Which mutations must succeed or fail together?**

Use transaction boundaries appropriate to the actual persistence system.

---

# Database Transaction Review

Where a database exists, inspect multi-step consequential operations.

Look for:

- partial commits;
- separate writes that should be atomic;
- failures between debit and credit;
- transaction opened too late;
- transaction committed before final invariant is satisfied;
- errors swallowed inside transaction.

Use database transactions when they naturally represent the integrity requirement.

Do not place huge unrelated workflows inside one transaction merely for theoretical safety.

---

# Read-Modify-Write Race

Search for:

1. read current value;
2. calculate new value;
3. write new value;

when multiple writers can execute concurrently.

Examples:

- currency;
- quantities;
- XP;
- stock;
- counters.

Two callers may both read the same old value and overwrite one another.

Where concurrency exists, prefer appropriate:

- atomic update;
- transaction;
- row/version condition;
- locking;
- authoritative serialization.

Do not rely only on application checks that can race.

---

# Unique Constraint Review

Where the invariant is naturally uniqueness, determine whether the database should enforce it.

Examples:

- one reward claim per logical event;
- one active ownership row;
- one account/character relationship;
- unique transaction identifier.

Application checks such as:

> check if row exists → insert

may race.

Use database guarantees when they correctly express domain invariants.

Do not add uniqueness constraints blindly where duplicates are valid.

---

# Database Constraint Review

Inspect whether critical durable invariants can currently accept impossible values.

Potential examples:

- negative quantities;
- invalid foreign references;
- duplicate unique ownership;
- null required owners;
- impossible account relationships.

Use database-level enforcement when it cleanly matches the domain.

Do not duplicate every gameplay rule in schema constraints.

---

# Inventory Persistence Pass

Treat inventory as high-risk persistent state.

Test:

- add;
- remove;
- split;
- merge;
- move;
- equip;
- unequip;
- drop;
- loot;
- craft;
- trade;
- save;
- reconnect.

Verify:

- quantities remain valid;
- item ownership remains singular;
- state survives round trip;
- concurrent mutations do not overwrite each other;
- retry does not duplicate;
- stale snapshot does not remove newer items.

---

# Equipment Persistence Pass

Test:

- equipped state survives save/load;
- inventory/equipment ownership agrees;
- duplicate equip requests do not duplicate item state;
- invalid equipped item references fail safely;
- equipment migration preserves valid ownership.

Ensure derived stats are not accidentally persisted as independent authority unless intended.

---

# Currency Persistence Pass

Treat currency as high-risk.

Test:

- earning;
- spending;
- purchasing;
- refunding;
- trading;
- saving;
- disconnect;
- concurrent operations;
- retry.

Ensure:

- balance does not become negative unintentionally;
- two concurrent purchases cannot both spend the same balance;
- retry cannot duplicate credits;
- old state cannot overwrite newer balance.

---

# XP / Skill Persistence Pass

Test:

- XP award;
- level-up;
- multi-level gain;
- save/load;
- reconnect;
- migration;
- repeated reward persistence.

Ensure:

- XP and level do not disagree;
- derived values are recomputed appropriately if that is the established model;
- old snapshots cannot roll progression backward;
- one reward cannot grant XP twice durably.

---

# Quest / Unlock Persistence Pass

Where relevant test:

- objective progress;
- completion;
- rewards;
- unlocks;
- save/load;
- old data;
- repeated migration.

Ensure:

- completed state does not revert accidentally;
- one-time rewards do not repeat;
- migrated state remains logically valid;
- missing optional fields receive safe defaults.

---

# World Persistence Pass

If world state persists, inspect:

- object identity;
- spawned/despawned state;
- depletion;
- construction;
- doors;
- NPC state;
- shared resources.

Test:

- save/load;
- restart;
- concurrent mutation;
- schema/version upgrade.

Be cautious with persistent object IDs.

Do not casually regenerate identifiers that other durable state references.

---

# Save Versioning

Determine how compatibility is identified.

Do not confuse:

- application/game version;
- save-format version;
- database schema version;
- protocol version.

These concepts may evolve independently.

Compatibility decisions should use the version that actually describes the persisted format.

---

# Migration Map

Inventory active migration paths.

For each determine:

- source version;
- target version;
- ordering;
- assumptions;
- field conversions;
- defaults;
- irreversible changes.

Ensure multiple-version upgrades follow the correct path.

Example:

> v1 → v2 → v3

rather than accidentally applying only:

> v1 → v3

when intermediate transformation is required.

---

# Migration Test

For every active migration path, test where practical:

> **old valid data → migrate → load → save → reload**

Check:

- missing optional fields;
- renamed fields;
- removed fields;
- changed types;
- default values;
- identifiers;
- collections;
- repeated migration;
- partial failure.

Do not treat successful parsing alone as migration success.

The resulting gameplay state must remain valid.

---

# Migration Idempotency

Determine whether a migration can accidentally run twice.

A migration may intentionally be:

- exactly-once by version;
- safely idempotent;
- protected by schema state.

Ensure repeated startup does not:

- duplicate data;
- repeat conversion;
- progressively modify values;
- grant rewards twice.

---

# Never Rewrite Applied Migration History Casually

Do not modify previously deployed/applied migration semantics simply because changing the old migration appears easier.

Doing so can create different database states depending on installation history.

Prefer:

- new forward migration;
- explicitly versioned correction;

where appropriate.

Only rewrite old migration history when the project has never shipped/applied it or there is strong evidence it is safe.

---

# Failed Migration Behavior

Inspect what happens when migration fails midway.

Avoid:

- silently marking version upgraded before data conversion finishes;
- half-upgraded state treated as valid;
- repeatedly destructive retries;
- deleting previous valid data too early.

Where practical, use transactional migration or recoverable staged migration.

---

# Irreversible Migration Gate

Treat migrations that:

- delete fields;
- destroy old representations;
- collapse data;
- rewrite ownership;
- change identifiers;
- alter currency/items;

as high-risk.

Before implementing ensure:

1. current data shape is understood;
2. transformation is deterministic;
3. compatibility implications are understood;
4. failure path is defined;
5. validation exists;
6. recovery/backup assumptions are explicit.

Prefer additional independent review for these changes.

---

# Malformed Data Attack

Test realistic malformed or incomplete data.

Examples:

- missing optional field;
- unknown enum value;
- invalid ID;
- truncated file;
- invalid numeric value;
- malformed JSON/binary payload;
- missing collection entry;
- unsupported version.

The system should fail safely.

Avoid:

- crash loops;
- silently resetting all progress;
- overwriting recoverable data;
- creating impossible state.

Do not promise magical recovery from arbitrary corruption.

---

# Validation Before Durable Commit

Where data originates from:

- clients;
- network;
- files;
- external services;
- user-editable configuration;

validate important invariants before persistence.

Do not durably persist obviously invalid state such as:

- impossible quantities;
- negative balances;
- nonexistent required references;
- invalid ownership;
- malformed enum/state values;
- values outside supported bounds.

Use authoritative game rules where appropriate.

---

# Load-Time Validation

Loading trusted persisted data should still defend against:

- corruption;
- old versions;
- partial files;
- incompatible schema;
- manually modified local files where relevant.

Validation should distinguish:

- safely defaultable missing data;
- recoverable old format;
- invalid critical data.

Do not silently "repair" values when the correct interpretation is uncertain.

---

# Default-Value Review

When new fields are introduced, establish appropriate behavior for older saves.

Ask:

> **What does absence of this field mean?**

Do not choose defaults merely to satisfy parsing.

Defaults should create valid gameplay state.

---

# Unknown Field Compatibility

Where the serialization format naturally supports unknown fields, avoid unnecessarily rejecting newer/extended data unless strict validation is required.

Conversely, do not ignore unknown structural changes when doing so could misinterpret the save.

Use the format's intended compatibility model.

---

# Identifier Integrity

Inspect persistent identifiers for:

- accounts;
- characters;
- items;
- world objects;
- quests;
- transactions;
- sessions where durable.

Look for:

- ID reuse;
- collisions;
- type changes;
- parsing differences;
- migration errors;
- references to deleted objects.

Persistent references require stable identity.

---

# Account / Character Ownership

Where accounts contain multiple characters or similar hierarchy exists, verify:

- character belongs to correct account;
- writes include correct ownership constraints;
- one account cannot accidentally load another character;
- stale session cannot mutate a character it no longer owns;
- deletion/recreation does not accidentally reuse ownership incorrectly.

Treat ownership failures as high severity.

---

# Backup and Recovery

If backup/recovery functionality already exists, verify it actually works.

Inspect:

- when backup is created;
- what data it contains;
- whether it is version-compatible;
- how restore chooses a candidate;
- whether current good state is protected during restore.

Do not build a massive backup platform from scratch.

---

# Previous-Good Save Recovery

If file saves retain a previous-good copy, test:

1. valid primary + valid backup;
2. corrupted primary + valid backup;
3. valid newer primary + older backup;
4. incompatible backup;
5. failed restoration.

Do not automatically restore older data over valid newer data.

Recovery must preserve recency and compatibility.

---

# Recovery Must Not Destroy Evidence

When load fails, avoid immediately overwriting the broken source with a fresh default save.

That may destroy recoverable data.

Where appropriate:

- preserve the damaged file;
- report failure;
- restore from known-good backup if supported;
- create new state separately.

Do not retain sensitive/player data indefinitely without regard to existing project policy.

---

# Cloud Save Conflict Review

If cloud saves exist, determine the current conflict model.

Possible dimensions:

- local timestamp;
- cloud timestamp;
- revision;
- game/platform version;
- explicit user choice;
- authoritative server state.

Do not invent a new cloud architecture.

But prevent obvious cases where older cloud/local state automatically overwrites newer progress without justification.

Treat unresolved cloud conflict behavior as high risk.

---

# Settings Versus Progress Data

Do not assume all persistence requires identical safety semantics.

Examples:

- losing a window position is not equivalent to losing inventory;
- graphics settings may tolerate fallback;
- account progression may require strict protection.

Apply integrity mechanisms proportional to consequence.

---

# Retry Semantics

Classify persistence operations.

## Naturally Idempotent

Examples may include:

- replace settings snapshot;
- set current known value.

## Side-Effecting

Examples:

- add currency;
- append transaction;
- grant item;
- award quest reward.

Side-effecting operations require duplicate protection.

Do not apply generic retries indiscriminately.

---

# Timeout Ambiguity

When a persistence call times out, remember:

> **timeout does not prove the write failed**

It may have completed and the acknowledgement may have been lost.

Retrying blindly can duplicate effects.

Design consequential retries around uncertain completion.

---

# Partial Failure Attack

For every multi-step persistent mutation ask:

> **What happens if failure occurs after each individual step?**

Example:

1. validate purchase;
2. deduct currency;
3. add item;
4. commit;
5. acknowledge.

Test or reason through failure after:

- validation;
- deduction;
- item creation;
- commit;
- acknowledgement.

The durable result must remain internally coherent.

---

# Crash-During-Save Test

Where practical, simulate abrupt process termination during:

- local file save;
- transaction;
- autosave;
- migration;
- shutdown persistence.

Then restart and inspect the durable state.

Do not intentionally damage real production data.

Use disposable state.

---

# Autosave Review

Inspect autosave behavior.

Ask:

- Can saves overlap?
- Does autosave capture coherent state?
- Can it run during transitions?
- Does failure spam retries?
- Can autosave overwrite newer manual/save-point state?
- Does it persist during unsafe intermediate states?

Do not simply increase autosave frequency as a safety fix.

More writes can create more race opportunities.

---

# Snapshot Consistency

If a save contains several related subsystems, determine whether the snapshot represents one coherent point in time.

Example:

- inventory from time A;
- currency from time B;
- quest state from time C;

may produce impossible combinations.

Where required, capture related state coherently.

Do not globally pause the game for every save unless necessary.

---

# Cross-System Transaction Integrity

Some state changes span systems.

Examples:

- crafting changes inventory + XP;
- quest completion changes quest state + reward + XP;
- purchase changes currency + inventory;
- trade changes two players.

Determine which parts must be durable together.

Avoid a restart producing:

- reward without completion;
- completion without reward;
- payment without purchase;
- transfer from sender without transfer to recipient.

---

# Save Queue Review

If writes are queued, inspect:

- queue ordering;
- deduplication;
- cancellation;
- shutdown flushing;
- reconnect interaction;
- stale queued work.

Coalescing may be useful when several snapshots supersede one another.

Do not coalesce independent consequential events that must each persist.

---

# Write Coalescing Safety

If several saves can be collapsed, make sure doing so does not lose:

- side effects;
- audit/transaction records;
- one-time rewards;
- state needed for migration.

Snapshot replacement and event persistence have different semantics.

---

# Background Persistence Lifecycle

If persistence runs in workers/tasks/background jobs, inspect:

- cancellation;
- ownership;
- failure propagation;
- process shutdown;
- retry;
- current session/state validation.

A background worker must not outlive the authority assumptions of the data it is writing.

---

# Database Error Handling

Inspect persistence code for:

- swallowed exceptions;
- ignored row counts;
- failed transactions treated as success;
- ambiguous duplicate-key handling;
- retries without idempotency;
- reconnect loops hiding failed writes.

Errors should be actionable.

Do not expose secrets or raw database internals to players.

---

# Result Verification

For important DB mutations, determine whether the code checks:

- affected rows;
- returned version;
- generated ID;
- transaction result;
- conditional-update success.

A command returning without throwing does not always prove the intended state changed.

---

# Optimistic Concurrency

Where stale read/write races exist, consider versioned/conditional updates when they fit the existing design.

Conceptually:

> update state if revision = expected revision

If zero rows are updated:

> the state changed concurrently

Handle intentionally.

Do not add revision columns across the entire database unless actual races justify them.

---

# Pessimistic Locking

Use explicit locking only where necessary.

Before adding locks ask:

- Can an atomic update solve this?
- Can a transaction isolate it?
- Can authoritative serialization prevent overlap?
- Can uniqueness enforce the invariant?

Avoid:

- broad lock scopes;
- deadlocks;
- unnecessary contention;
- cross-system lock-order complexity.

---

# Pattern-Based Integrity Hunt

When one persistence defect is found, search for the underlying pattern elsewhere.

Examples:

If one save callback can write stale state:

> inspect other asynchronous saves.

If one currency operation uses unsafe read-modify-write:

> inspect item quantities and XP.

If one reward can retry twice:

> inspect other reward-granting paths.

If one migration lacks a default:

> inspect other newly introduced fields.

Fix the defect class where justified rather than only the first symptom.

---

# Regression Test Creation

Add focused regression tests where the project already supports them or lightweight coverage is practical.

Useful tests may include:

- save/load round trip;
- old-version migration;
- interrupted save;
- stale-save prevention;
- duplicate reward;
- concurrent purchase;
- transaction rollback;
- reconnect/save race;
- malformed save;
- backup restore.

A good test should:

1. reproduce the original failure;
2. fail before the fix;
3. pass after;
4. remain stable;
5. avoid fragile timing dependence where possible.

Prefer controllable synchronization/failure injection over arbitrary sleep-based race tests.

---

# Bug-Fix Standard

For every meaningful integrity defect:

1. reproduce where practical;
2. identify the violated invariant;
3. identify authoritative state ownership;
4. identify durable mutation boundaries;
5. determine root cause;
6. implement the smallest robust fix;
7. rerun original reproduction;
8. test normal save/load;
9. test failure/interruption where relevant;
10. test duplicate execution where relevant;
11. test stale completion where relevant;
12. test old data where relevant;
13. search analogous code;
14. add focused regression coverage where practical.

Avoid symptom fixes such as:

- arbitrary delays;
- repeated blind retries;
- swallowing errors;
- save-frequency increases;
- duplicate backup copies without recovery semantics.

Correct the underlying integrity model.

---

# Work in Persistence Waves

Do not change every persistence subsystem simultaneously.

## Wave A — Catastrophic Integrity

Fix:

- corruption;
- duplication;
- lost progress;
- stale overwrites;
- account/character ownership problems;
- broken transactions.

Validate.

## Wave B — Save / Load Foundations

Inspect:

- serialization;
- round trips;
- atomic writes;
- save ordering;
- autosaves;
- local recovery.

Validate.

## Wave C — Database / Transactions

Inspect:

- read-modify-write;
- concurrency;
- constraints;
- multi-step mutations;
- retry semantics.

Validate.

## Wave D — Migrations / Compatibility

Test:

- old data;
- migration order;
- defaults;
- repeated migration;
- partial failure.

Validate.

## Wave E — Multiplayer Lifecycle

Where applicable test:

- logout;
- disconnect;
- reconnect;
- session replacement;
- overlapping saves;
- server shutdown.

Validate.

## Wave F — Recovery / Long Tail

Inspect:

- malformed data;
- backups;
- old formats;
- recovery;
- rare failure branches;
- stale background work.

---

# Reassess After Every Wave

Ask:

- Can older state overwrite newer state?
- What happens if this write fails halfway?
- What happens if it executes twice?
- What happens if the player disconnects?
- Can concurrent writers disagree?
- Can older valid data still load?
- Can malformed data destroy the last good copy?
- Are success responses sent before required durability is established?
- Did a fix introduce excessive locking or complexity?
- Is any durable player property still updated non-atomically?
- Did migration testing expose other stale assumptions?

Reprioritize.

---

# Productive Persistence Loop

Do not stop after the first severe integrity fix.

Persistence problems often expose deeper shared assumptions.

Examples:

- atomic saves expose stale-save ordering;
- stale-save fixes expose reconnect ownership;
- reconnect fixes expose DB concurrency;
- migration fixes expose serializer defaults;
- transaction fixes expose duplicate retry behavior.

Continue:

> **inspect → model invariant → attack → reproduce → fix → validate → attack again**

while meaningful, safely actionable integrity risks remain.

Do not manufacture theoretical failure cases merely to continue working.

Stop when remaining risks are:

- speculative;
- extremely low impact;
- dependent on unavailable production infrastructure;
- dependent on unknown product policy;
- intentionally accepted;
- outside scope.

---

# Independent High-Risk Review

Near completion, review high-risk changes from fresh context where practical.

Especially scrutinize:

- inventory;
- currency;
- transactions;
- schema migrations;
- account/character ownership;
- overlapping saves;
- multiplayer persistence;
- cloud conflicts;
- recovery.

Challenge each change with:

> **How can this still fail halfway?**

> **How can it execute twice?**

> **How can older state still win?**

> **What if two writers act simultaneously?**

> **What if reconnect occurs at the worst possible moment?**

> **What happens after restart?**

> **What happens with old valid data?**

The purpose is to find failure modes, not simply approve previous work.

---

# Anti-Overengineering Review

Before completion inspect whether fixes introduced unnecessary persistence machinery.

Ask:

- Did we add event sourcing without need?
- Did we invent distributed transactions for a local problem?
- Did we add revision systems where serialization sufficed?
- Did we create a large backup framework for one file?
- Did we introduce generalized persistence abstractions without clear benefit?
- Did locking become broader than necessary?
- Did the fix make normal saving harder to understand?
- Did we create another source of truth?

Prefer the smallest robust mechanism.

---

# Performance Awareness

This is not primarily a persistence-performance pass.

However, avoid integrity fixes that accidentally introduce:

- database transaction contention across unrelated players;
- full-character writes for tiny independent changes without reason;
- synchronous blocking of the main game loop;
- excessive backup duplication;
- unbounded save queues;
- retry storms;
- global locks.

Correctness comes first.

But maintain reasonable runtime behavior.

---

# Final Cross-System Integrity Review

Before finishing inspect for:

- stale writes;
- partial transactions;
- duplicate reward paths;
- invalid account ownership;
- failed save acknowledgement;
- unsafe retries;
- migration gaps;
- corrupted recovery behavior;
- missing version handling;
- invalid durable values;
- old-session writes;
- inconsistent save/load semantics;
- backups that cannot restore;
- data loss introduced by new fixes.

Fix justified issues.

Run final validation.

---

# Completion Standard

The persistence and data-integrity pass is complete when, to the degree available testing can establish:

1. major persisted state has been mapped;
2. authoritative persistence ownership is understood;
3. representative state round-trips correctly;
4. important local writes are appropriately atomic;
5. stale saves cannot obviously overwrite newer state;
6. overlapping-save behavior is safe;
7. important consequential retries do not duplicate durable outcomes;
8. inventory persistence preserves ownership and quantity;
9. currency persistence resists duplicate/partial mutation;
10. important multi-step transactions have appropriate atomicity;
11. relevant database concurrency hazards discovered are fixed;
12. active migrations have been validated;
13. old supported data remains loadable where reasonably expected;
14. repeated migration does not corrupt data;
15. migration failure is handled safely;
16. disconnect/logout persistence is safe where applicable;
17. stale sessions cannot overwrite current state;
18. malformed data fails reasonably;
19. recovery mechanisms work to the extent they exist;
20. the last known-good data is not casually destroyed during recovery;
21. high-risk fixes received additional independent scrutiny;
22. no discovered P0/P1 integrity issue remains unresolved without an explicit blocker;
23. no known regression introduced by this pass remains;
24. remaining concerns require unavailable production infrastructure, live-player data, external policy decisions, are low-impact, or belong to another specialized pass.

The objective is not:

> **make persistence infinitely complicated**

The objective is:

> **protect valid player and world state using the smallest mechanisms that reliably prevent corruption, duplication, stale overwrites, partial mutation, incompatible upgrades, and data loss.**

---

# Final Report

When complete, provide a concise persistence-engineering report.

## 1. Overall Result

Summarize the most important improvements to player-data safety.

## 2. Critical Integrity Bugs Fixed

For each major issue include:

- **System**
- **Failure**
- **Root cause**
- **Fix**
- **Potential player impact**

## 3. Save / Load and Serialization

Summarize meaningful changes involving:

- round trips;
- serializer/deserializer behavior;
- atomic saves;
- save ordering;
- validation.

## 4. Transactions and Stale-Write Protection

Summarize meaningful work involving:

- database transactions;
- read-modify-write races;
- retries;
- idempotency;
- stale snapshots;
- revision/ownership checks.

## 5. Migrations and Version Compatibility

Describe:

- migration paths tested;
- defaults or conversions fixed;
- repeated migration behavior;
- old-version compatibility.

## 6. Disconnect / Reconnect Persistence

Include only when applicable.

Summarize:

- logout;
- disconnect;
- reconnect;
- old-session saves;
- session replacement;
- shutdown persistence.

## 7. Recovery / Corruption Handling

Describe:

- malformed-data handling;
- backups;
- previous-good recovery;
- recovery protections.

## 8. Validation Performed

State exactly what was actually tested, including relevant:

- save/load round trips;
- migration fixtures;
- interrupted writes;
- duplicate requests;
- concurrent DB operations;
- transaction failures;
- reconnect races;
- malformed files;
- backup restoration.

Do not imply testing occurred when it did not.

## 9. Deliberately Unchanged

Describe important behavior preserved because:

- compatibility requires it;
- evidence was insufficient;
- architecture already guarantees safety;
- changing it would require a redesign;
- live-player impact is uncertain;
- external infrastructure was unavailable.

## 10. Remaining Risks

List only meaningful unresolved integrity risks.

For each include:

- **Risk**
- **Severity**
- **Why unresolved**
- **Potential impact**
- **Recommended next action**

Do not pad this section with theoretical concerns unsupported by evidence.

---

# Final Directive

**Treat persisted player data as something the game must protect, not merely serialize.**

Do not assume:

- writes complete in order;
- retries are harmless;
- disconnect means old work disappears;
- saves happen one at a time;
- a successful request means a durable commit occurred;
- old data always matches current schemas;
- malformed data can safely be reset;
- application-side validation alone prevents database races.

Repeatedly ask:

> **What if this fails halfway?**

> **What if it happens twice?**

> **What if older work finishes later?**

> **What if two writers act at once?**

> **What if the player reconnects before the old save finishes?**

> **What if this data came from an older version?**

> **Can we recover without destroying the last good state?**

> **What durable invariant must always remain true?**

Continue:

> **inspect → model invariants → attack failure paths → reproduce → implement → validate → attack again**

while meaningful data-integrity risk remains.

Leave behind the **same game**, but make its saves, databases, migrations, transactions, recovery paths, and persistent player state substantially safer, more recoverable, transactionally sound, and resistant to corruption, duplication, stale writes, incompatible upgrades, and data loss.