Hmbown/CodeWhale · error · Error

Saved habitat is invalid. Save a replay file before…

Error message

Saved habitat is invalid. Save a replay file before replacing it.

What it means

Thrown while restoring a persisted habitat from IndexedDB when the saved habitat object fails its structural validation: wrong `petPersistenceVersion`, non-finite/negative/over-limit `seconds`, a `source` outside wild/demo/replay, or non-boolean `still` / non-string `sourceName`. The message suggests saving a replay file before overwriting the broken save.

Solutions

  1. Export a replay file first, then clear the stale IndexedDB habitat so a fresh one is written.
  2. Migrate the saved object to `petPersistenceVersion: 1` with valid `seconds`/`source`/`still`/`sourceName`.
  3. Bump the persistence version and add a migration path if the schema intentionally changed.

Example fix

// before
const h = saved.habitat; // legacy object without petPersistenceVersion
// after
const h = { ...saved.habitat, petPersistenceVersion: 1, source: 'wild', still: false, sourceName: 'Wild' };
Defensive patterns

Strategy: type-guard

Validate before calling

const valid = h && h.petPersistenceVersion === 1 && Number.isFinite(h.seconds) && h.seconds >= 0 && h.seconds <= PET_MAX_SECONDS && ['wild','demo','replay'].includes(h.source) && typeof h.still === 'boolean' && typeof h.sourceName === 'string';

Type guard

function isValidHabitat(h: any): h is SavedHabitat {
  return h?.petPersistenceVersion === 1 && Number.isFinite(h?.seconds) && h.seconds >= 0 && h.seconds <= PET_MAX_SECONDS
    && ['wild','demo','replay'].includes(h.source) && typeof h.still === 'boolean' && typeof h.sourceName === 'string';
}

Try / catch

try { restoreHabitat(saved); } catch (e) { if (e.message.startsWith('Saved habitat is invalid')) { await library.clearHabitat(); startWild(); } }

Prevention

When it happens

Trigger: `library.getHabitat()` returns a record written by a different app version, hand-edited, partially migrated (e.g. missing `petPersistenceVersion: 1`), or with `seconds` beyond `PET_MAX_SECONDS`.

Common situations: Upgrading from an older persistence schema, corrupted IndexedDB entry, manually constructed or copied habitat objects, cross-browser storage imports.

Understand the failure class

Background: Schema validation failed / invalid input schema: payload rejected because its shape doesn't match the expected schema — this error's family across 28 libraries.

Related errors


AI-assisted analysis of Hmbown/CodeWhale@433685b202 (2026-09-15). Data as JSON: /api/errors/ae87d6392abac919. Report an issue: GitHub.

Appendix: source

Thrown at pet/src/ui/pet.ts:286

    accumulator += last ? Math.min(.1, (now - last) / 1000) : 0;
    while (accumulator >= 1 / 30 && (mode.value === 'live' || !tape.length || seconds < duration())) {
      world.step(1 / 30, { motion: !motion.checked, sensitivity: 1 }); seconds = world.frame.timeMs / 1000; play(world.voices); accumulator -= 1 / 30;
    }
    if ((mode.value === 'live' || !tape.length) && seconds >= duration()) seek.max = String(Math.ceil(seconds / 30) * 30 + 30);
    draw();
  }
  last = now; requestAnimationFrame(animate);
}
try {
  const response = await fetch('./whale-points.tsv'); if (!response.ok) throw new Error('Whale point asset is unavailable.');
  points = (await response.text()).trim().split('\n').map(row => row.trim().split(/\s+/).map(Number) as [number, number]);
  if (points.length !== 980 || points.some(p => p.length !== 2 || !p.every(Number.isFinite))) throw new Error('Invalid whale point asset.');
  try {
    const saved = await library.getHabitat();
    if (saved) {
      savedRevision = saved.revision; const h = saved.habitat;
      if (h.petPersistenceVersion !== 1 || !Number.isFinite(h.seconds) || h.seconds < 0 || h.seconds > PET_MAX_SECONDS
        || !['wild', 'demo', 'replay'].includes(h.source) || typeof h.still !== 'boolean' || typeof h.sourceName !== 'string') throw new Error('Saved habitat is invalid. Save a replay file before replacing it.');
      expressionVersion = h.expressionVersion === undefined ? 1 : h.expressionVersion;
      if (![1, 2].includes(expressionVersion) || h.checkpoint && (h.checkpoint.sim?.expressionVersion ?? 1) !== expressionVersion) throw new Error('Saved expression version does not match its checkpoint.');
      const savedWorld = PetWorld.fromRecording(points, { ...h, petReplayVersion: h.petReplayVersion === undefined ? 1 : h.petReplayVersion });
      if (h.checkpoint && savedWorld.frame.timeMs / 1000 !== h.seconds) throw new Error('Saved pet clock does not match its checkpoint.');
      tape = h.tape; interactions = [...h.interactions]; mode.value = h.source; motion.checked = h.still || media.matches;
      source.textContent = h.sourceName;
      seek.max = String(Math.max(h.source === 'demo' ? 80 : h.source === 'replay' ? 90 : 120, savedWorld.endTimeMs / 1000));
      if (h.source === 'replay') {
        mode.querySelector<HTMLOptionElement>('[value="replay"]')!.disabled = false;
      }
      message.textContent = 'Restoring the saved habitat…';
      if (h.checkpoint && h.still === motion.checked) adoptWorld(savedWorld);
      else await rebuild(h.seconds, undefined, savedWorld.recording(false).start);
      message.textContent = 'Habitat restored locally. Sound starts only when you enable it.';
    } else await rebuild();
    persistenceReady = true; void refreshArchives().catch(() => {});
  } catch (error) { persistenceFailed = true; get('persistence').textContent = error instanceof Error ? error.message : 'Local persistence is unavailable.'; await rebuild(); }
  void refreshArchives().catch(() => {});

View on GitHub (pinned to 433685b202)