Worlds, AI and multiplayer · 6 MIN READ
Save files are untrusted input: version them, migrate forward, validate and write atomically
Design a versioned JSON save format, migrate v1 saves to v2, reject unknown fields and out-of-range values, and replace a save file without ever leaving it half-written.
A save file outlives the build that wrote it, sits in a folder the player can edit and gets shared on forums. A loader that unmarshals it straight into game state will eventually meet a save from an older version, a save from a newer version, a file truncated by a crash and a hand-edited file with 999 health. Each of those needs a deliberate answer, and none of them should be a panic.
gamedev · A MAP OF THE IDEA
- Read version first
- Migrate step by step
- Decode strict, validate
- Write temp, sync, rename
Useful when
- Old saves keep loading as the format evolves.
- A crash during saving never destroys progress.
Watch out
- os.Rename is not atomic on non-Unix platforms.
- Checksums catch corruption, not deliberate tampering.
Implementation & operation cost: A struct and a migration function per format version, one fixture per release, and a few extra system calls on every save.
Four ways a naive loader fails
Old files: a field was renamed or restructured, the new struct silently decodes it as zero, and a v1 player loads with 0 health. Newer files: a player downgrades or copies a save from a newer build, the old build drops fields it does not know and then overwrites the file with less data than it read. Torn files: the game crashes or the device loses power during a write, and the only save is part old and part new. Crafted files: someone sets an inventory count to a billion or adds an item that does not exist, and the game indexes past a slice or grants a debug item. The answers are a version field read first, pure migration functions, strict decoding followed by explicit validation, and an atomic replace when writing.
Decode the version, migrate, then validate
The program loads a v1 save (flat hp, a position array and a list of item names) and migrates it to v2 (structured health, a position object and item stacks). It loads a valid v2 save, then feeds the loader six bad files: an unknown field, impossible health, a position outside the map, an unknown item, a newer version and a file with a second JSON value appended. Finally it writes the last good save atomically into a fresh directory under os.TempDir, reloads it and confirms that no temporary file was left behind.
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
const (
currentVersion = 2
maxSaveBytes = 64 << 10
mapW, mapH = 640.0, 480.0
)
// SaveV1 is the format shipped by the first release: flat fields, one string per item.
type SaveV1 struct {
Version int `json:"version"`
Name string `json:"name"`
HP int `json:"hp"`
Pos [2]float64 `json:"pos"`
Items []string `json:"items"`
}
// Save is the current format (version 2).
type Save struct {
Version int `json:"version"`
Name string `json:"name"`
Health Health `json:"health"`
Position Position `json:"position"`
Inventory []Stack `json:"inventory"`
}
type Health struct {
Current int `json:"current"`
Max int `json:"max"`
}
type Position struct {
X float64 `json:"x"`
Y float64 `json:"y"`
}
type Stack struct {
Item string `json:"item"`
Count int `json:"count"`
}
var catalog = map[string]bool{"potion": true, "rope": true, "lantern": true}
// migrateV1 is a pure function: old struct in, new struct out.
func migrateV1(old SaveV1) Save {
s := Save{
Version: 2,
Name: old.Name,
Health: Health{Current: old.HP, Max: 100}, // v1 had an implicit cap of 100
Position: Position{X: old.Pos[0], Y: old.Pos[1]},
}
for _, item := range old.Items { // group in first-seen order, not map order
found := false
for i := range s.Inventory {
if s.Inventory[i].Item == item {
s.Inventory[i].Count++
found = true
}
}
if !found {
s.Inventory = append(s.Inventory, Stack{Item: item, Count: 1})
}
}
return s
}
func decodeStrict(data []byte, v any) error {
dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
return dec.Decode(v)
}
func Load(r io.Reader) (s Save, fromVersion int, err error) {
data, err := io.ReadAll(io.LimitReader(r, maxSaveBytes+1))
if err != nil {
return Save{}, 0, err
}
if len(data) > maxSaveBytes {
return Save{}, 0, errors.New("save is larger than 64 KiB")
}
var head struct {
Version int `json:"version"`
}
if err := json.Unmarshal(data, &head); err != nil { // also rejects trailing data
return Save{}, 0, err
}
switch {
case head.Version == 1:
var old SaveV1
if err := decodeStrict(data, &old); err != nil {
return Save{}, 1, err
}
s = migrateV1(old)
case head.Version == currentVersion:
if err := decodeStrict(data, &s); err != nil {
return Save{}, head.Version, err
}
case head.Version > currentVersion:
return Save{}, head.Version, fmt.Errorf("version %d is newer than this build supports (%d)", head.Version, currentVersion)
default:
return Save{}, head.Version, fmt.Errorf("unknown version %d", head.Version)
}
if err := Validate(s); err != nil {
return Save{}, head.Version, err
}
return s, head.Version, nil
}
// Validate checks every invariant the game relies on after loading.
func Validate(s Save) error {
if s.Name == "" || len(s.Name) > 24 {
return errors.New("name must be 1 to 24 bytes")
}
if s.Health.Max < 1 || s.Health.Max > 500 || s.Health.Current < 0 || s.Health.Current > s.Health.Max {
return fmt.Errorf("health %d/%d out of range", s.Health.Current, s.Health.Max)
}
if !(s.Position.X >= 0 && s.Position.X < mapW && s.Position.Y >= 0 && s.Position.Y < mapH) {
return fmt.Errorf("position (%.1f,%.1f) is outside the map", s.Position.X, s.Position.Y)
}
if len(s.Inventory) > 20 {
return errors.New("more than 20 inventory stacks")
}
for _, st := range s.Inventory {
if !catalog[st.Item] {
return fmt.Errorf("unknown item %q", st.Item)
}
if st.Count < 1 || st.Count > 99 {
return fmt.Errorf("stack of %d %s out of range", st.Count, st.Item)
}
}
return nil
}
// WriteAtomic leaves either the old file or the complete new one, never half of each.
func WriteAtomic(path string, s Save) (n int, err error) {
data, err := json.MarshalIndent(s, "", " ")
if err != nil {
return 0, err
}
tmp, err := os.CreateTemp(filepath.Dir(path), ".save-*.tmp")
if err != nil {
return 0, err
}
defer func() {
if err != nil {
tmp.Close()
os.Remove(tmp.Name())
}
}()
if n, err = tmp.Write(data); err != nil {
return 0, err
}
if err = tmp.Sync(); err != nil {
return 0, err
}
if err = tmp.Close(); err != nil {
return 0, err
}
return n, os.Rename(tmp.Name(), path)
}
func describe(s Save) string {
var items []string
for _, st := range s.Inventory {
items = append(items, fmt.Sprintf("%s x%d", st.Item, st.Count))
}
return fmt.Sprintf("%s health %d/%d at (%.1f,%.1f) [%s]", s.Name,
s.Health.Current, s.Health.Max, s.Position.X, s.Position.Y, strings.Join(items, ", "))
}
func main() {
inputs := []string{
`{"version":1,"name":"scout","hp":42,"pos":[120.5,64],"items":["potion","rope","potion"]}`,
`{"version":2,"name":"scout","health":{"current":42,"max":100},"position":{"x":120.5,"y":64},"inventory":[{"item":"lantern","count":1}]}`,
`{"version":2,"name":"scout","health":{"current":42,"max":100},"position":{"x":1,"y":1},"inventory":[],"godMode":true}`,
`{"version":2,"name":"scout","health":{"current":999,"max":100},"position":{"x":1,"y":1},"inventory":[]}`,
`{"version":2,"name":"scout","health":{"current":5,"max":100},"position":{"x":-40,"y":1},"inventory":[]}`,
`{"version":2,"name":"scout","health":{"current":5,"max":100},"position":{"x":1,"y":1},"inventory":[{"item":"debug-key","count":1}]}`,
`{"version":3,"name":"scout"}`,
`{"version":2}{"version":2}`,
}
var last Save
for _, in := range inputs {
s, from, err := Load(strings.NewReader(in))
if err != nil {
fmt.Println("reject:", err)
continue
}
fmt.Printf("load v%d as v%d: %s\n", from, s.Version, describe(s))
last = s
}
dir, err := os.MkdirTemp("", "savegame-")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "slot1.json")
n, err := WriteAtomic(path, last)
if err != nil {
panic(err)
}
f, err := os.Open(path)
if err != nil {
panic(err)
}
reloaded, _, err := Load(f)
f.Close()
if err != nil {
panic(err)
}
leftovers, _ := filepath.Glob(filepath.Join(dir, ".save-*.tmp"))
fmt.Printf("atomic write: %d bytes, reload matches: %t, temp files left: %d\n",
n, describe(reloaded) == describe(last), len(leftovers))
}Load caps the input at 64 KiB with io.LimitReader before parsing anything. json.Unmarshal into a struct holding only the version reads the version and, because Unmarshal requires exactly one JSON value, also rejects the file with trailing data; a json.Decoder alone would stop after the first value and never notice it. The switch then decodes with a Decoder whose DisallowUnknownFields turns godMode into an error instead of silently ignoring it. migrateV1 is a pure function that groups items into stacks in first-seen order rather than through a map, so its output is stable. Validate checks every invariant the game relies on; the negated range test for position also rejects NaN produced by a buggy migration. WriteAtomic writes a temporary file in the destination directory, syncs it, closes it and renames it over the target, and the deferred cleanup removes the temporary file if any step fails.
Migrate forward in small, pure steps
Each release that changes the format gets a new struct and one function from the previous version to the next. Loading a v1 file in a v4 build runs v1 to v2, v2 to v3 and v3 to v4, so each migration is written and tested once against its own fixtures and never needs to know about later versions. Migrations choose defaults explicitly: v1 had no maximum health, so the function writes 100 rather than letting a zero value slip through. Refuse versions newer than the build supports, because a downgraded game that loads a v3 file into v2 structs and saves it back destroys progress. Do not rewrite the original file on load; write the migrated save on the next normal save through the atomic path, and keep the previous file as a backup slot until the new one has loaded successfully once. Note that encoding/json matches field names case-insensitively and lets a repeated key overwrite the earlier one; the strict JSON lesson shows the encoding/json/v2 options that reject both when a format needs it.
Atomic replace: what rename does and does not promise
Writing a save in place truncates the file first, so a crash mid-write leaves neither version. Writing a temporary file in the same directory and renaming it over the old one gives readers either the complete old file or the complete new one, because on POSIX file systems rename replaces the directory entry in one step. The temporary file must live in the same directory, since a rename across file systems fails. Call Sync before Close so the bytes are durable before the name points at them, and on Unix also sync the directory if the rename itself must survive a power cut. The os.Rename documentation states that on non-Unix platforms it is not atomic even within one directory, so a Windows build should keep a backup slot and verify the new file on load. Console and mobile platforms usually provide save APIs with their own guarantees; prefer them there.
// After os.Rename succeeds on Unix, persist the directory entry itself.
dir, err := os.Open(filepath.Dir(path))
if err != nil {
return err
}
defer dir.Close()
return dir.Sync()This fragment belongs at the end of a function like WriteAtomic, runs in your own native environment and applies to Unix systems. Opening the parent directory and calling Sync asks the file system to persist the directory entry that rename changed; without it, a power loss right after the rename can bring back the old name on some file systems. It does not replace the Sync on the file itself, which persists the contents.
Validate after decoding, and test the loader like a parser
Decoding proves only that the bytes matched the struct shape. Validation proves the game can use the result: ranges for every number, existence for every reference such as item IDs or level names, limits on every collection, and cross-field rules such as current health at most maximum health. Decide per field whether to reject the save or repair it with a logged clamp; rejecting is safer for anything that indexes memory, repairing is kinder for cosmetic settings. A checksum detects accidental corruption but is not tamper protection, because any key shipped in the client can be extracted; competitive or economy data belongs on a server. Keep a fixture directory with one real save from every released version and load all of them in CI, then fuzz the loader with those fixtures as the seed corpus.
func FuzzLoad(f *testing.F) {
for _, data := range fixtureSaves(f) { // one real save per released version
f.Add(data)
}
f.Fuzz(func(t *testing.T, data []byte) {
s, _, err := Load(bytes.NewReader(data))
if err == nil {
if verr := Validate(s); verr != nil {
t.Fatalf("Load accepted an invalid save: %v", verr)
}
}
})
}This test fragment lives in a _test.go file in your own module and runs with go test -fuzz=FuzzLoad on your machine; fixtureSaves is your helper that reads the fixture directory. The property is simple and strong: for any bytes, Load either returns an error or returns a save that passes Validate, and it never panics, hangs or allocates without bound. Crashing inputs found by the fuzzer are written under testdata/fuzz and become permanent regression cases.
TAKE THIS WITH YOU
Read the version first, migrate with pure per-version functions, decode strictly and validate every invariant, refuse newer formats, and replace saves by renaming a synced temporary file from the same directory.
Check your understanding
Why does the save code write to a temporary file in the same directory and then rename it over the old save?
Go to the source
Progress stays in this browser. No account needed.