Skip to main content
Version: v10.0.0

Debugging the DB

The db decides a lot on its own: which loader serves a query, which rows it holds, which socket topics it opens. When something looks wrong, the answer is almost always in one of those decisions, and every one of them can be read. This guide starts with the tools that show them, then walks through the problems people hit most, as symptom, cause and fix.

What you'll learn
  1. How to read a query's plan with explain(), and the whole db with inspect().
  2. How to watch the db in HyperFlow.
  3. How to catch every failure with db.onError.
  4. How to fix the most common compile errors.
  5. How to fix stale, missing, extra and flashing rows, and extra requests.

The tools​

explain(): one query​

db.postSummary.where((post) => and(eq(post.teamId, "t1"), gt(post.likes, 10))).explain();
FieldTells you
kindlist, one, local, or error when no loader can serve the query
loaderWhich loader serves it, as its index in the collection's chain
sentThe conditions sent to the backend
localThe conditions run on the returned rows
answeredLocallyWhether held rows answer it with no request
syncsThe socket topics keeping it live, once the query is mounted
errorWhy the query cannot be served

inspect() and onChange(): the whole db​

const snapshot = db.inspect();
// snapshot.collections: rows, pending optimistic layers and loaded subsets (fresh, live, loading, error, observers)
// snapshot.queries: every live query with its subscribers, status and plan
// snapshot.outbox: writes waiting to be replayed

db.onChange(() => console.log(db.inspect()));

HyperFlow​

Pass the db to the devtools plugin, and the DB Inspector shows the same snapshot live:

import { DevtoolsPlugin } from "@hyper-fetch/plugin-devtools";

client.addPlugin(DevtoolsPlugin({ appName: "Teamboard", dbs: [db] }));

db.onError: every failure in one place​

Requests, writes and queries never throw. Everything that fails reaches one listener:

db.onError(({ type, error, collection }) => {
console.error(`[db] ${type} failed in ${collection ?? "db"}`, error);
});

Wire it to your error reporting early. A load or sync error usually means a rows or row mapping met a response it did not expect, which stays invisible in the UI until rows go missing.


Compile errors​

A query does not compile​

Symptom: useLiveQuery(db.postSummary.where(...)) or .get() is a type error about the query.

Cause: no loader of the collection can serve the query. Either the query does not set a loader's required filter as a top-level eq, or the only loader that fits is paginated and cannot send one of the query's conditions or orders.

Fix:

db.postSummary.where((post) => or(eq(post.teamId, "t1"), eq(post.teamId, "t2")));
db.postSummary.where((post) => eq(post.teamId, "t1"));
  • Set the required filter with eq at the top level, or inside a top-level and. Inside or or not it does not count.
  • For a paginated loader, declare every field the query filters and sorts by, or drop that condition.
  • To read only rows other queries loaded, use .local(), which needs no loader.

createDb does not compile​

Symptom: createDb({ post: Post }) is a type error, or .load() and .sync() are missing after an earlier call in the chain.

Cause: a loader, sync, ingest, normalize or mutate produced rows that are not exactly the schema's rows, so the chain returned a RowMismatch. Hover the collection to see received and expected.

Fix: map the rows in that step. The most common case is a socket message with fields the collection lacks:

collection(PostSummarySchema, { key: "id" })
.sync(onPostChanged, { type: "update" })
.sync(onPostChanged, { type: "update", row: ({ body, ...changes }) => changes });

The db never reads schemas at runtime, so it cannot drop body for you, and a summary must never gain a field it does not declare.


Rows that do not update​

A socket event never shows​

Check, in this order:

  1. Is the query mounted? Syncs start with the first subscriber. explain().syncs is empty for a query nobody subscribes to, and .local() queries never start syncs.
  2. Does a sync cover this subset? A sync with where covers only the values it maps. onPostChanged for team t1 does not cover a query for team t2. Compare the topic in explain().syncs with the topic your server sends to.
  3. Does the collection hold the row? An update for a row the collection does not hold is ignored. Add incomplete: "refetch" to load such rows by key.
  4. Did the mapping fail? A row or key mapping that throws is reported as type: "sync" in db.onError, and the next events still apply.
  5. Is the socket connected? While it is not, the query reports stale: true.

A write to post does not show in the feed​

Cause: the feed reads postSummary. An optimistic change reaches another collection only through a link.

Fix: createDb(collections, { links: [["post", "postSummary"]] }). See List and Detail Views.

The old value flashes back after a write​

Cause: the response is not the updated row, or a list response sent before the write arrived after it, with no version to order the two.

Fix:

  • If the server changes more than you sent, use onSuccess: "refetch", which keeps the change on screen until the reload lands.
  • If a socket event confirms every write, use onSuccess: "sync".
  • Add version: "updatedAt" to collections with syncs. Ordering by the server's version is the most robust option.

A new row is missing from a paginated list​

Cause: a new row joins a paginated list only when it sorts inside the loaded pages, or anywhere once the backend has no more pages. Without orderBy, the db cannot know where it belongs.

Fix: give paginated queries an orderBy the loader can send. See Pagination and Infinite Scroll.


Rows that do not belong​

A list shows rows another query loaded​

Symptom: drafts appear in a feed whose endpoint only returns published posts.

Cause: a list that is not paginated shows every held row that matches its conditions, whichever subset loaded it. The endpoint filters by status on its own, and the db does not know.

Fix: declare it with fixed: { status: "published" } on that loader. See Loaders.

A filtered list is wrong, but only sometimes​

Cause: the query was answered from held rows on a field the backend compares differently, such as case-insensitive or locale-aware titles. The client compares exactly.

Fix: mark the field serverOnly: ["title"] on the loader, so queries on it always go to the backend. See Search and Server-side Filters for what that does and does not cover.

Data from the previous user after signing out​

Fix: call await db.clear() on sign-out. It removes rows, loaded subsets, pending writes and the persisted data of the scope, in every tab. With persistence, give each user their own scope. See Offline-First Apps.


Writes that resolve with an error​

result.errorCause
"post" already holds a row with the key ...An insert of a key the collection holds
An update cannot change the key of a row in "post"An update whose changes include a different key
Schema issues, with type: "validation" in db.onErrorThe write did not pass the collection's schema
DependencyErrorAn earlier write to the same row, or one in dependsOn, failed
An insert that leaves the key to the server cannot be made offlineOffline writes need client keys
The failed response's errorThe server rejected the request

All of these except the last one resolve without sending a request.


Requests you did not expect​

SymptomCause and fix
Every filter value sends a requestThe loader declares the filter, so each value is its own subset. Leave it out if the list is small.
A list refetches on every window focusIts subset is stale: no full sync coverage and staleTime passed. Raise staleTime or add syncs.
A list reloads after a reconnectExpected: events may have been missed. Use resumes: true if your server replays them.
The same endpoint is called by a hook and the dbuseFetch and a collection keep separate copies. Read that data through one of them.
A query loads again after leaving and returningIts subset was released after gcTime. Raise gcTime in createDb to keep it longer.

Runtime errors in your own code​

  • TypeError: Cannot assign to read only property: stored rows are frozen, because every query and component shares them. Copy before changing: { ...post, title }.
  • A field is still set after update(key, { field: undefined }): undefined means "no value". Send null to clear a field.

Debugged!

You know where to look when the db surprises you.

  • You can read a query's plan with explain(), and the whole db with inspect() or HyperFlow.
  • You can catch every failure with db.onError.
  • You can fix queries that do not compile and RowMismatch errors.
  • You can trace a missing socket update, a foreign row or a flashing value to its cause.
  • You can tell expected requests from unexpected ones.

Next steps​

Common Mistakes
Short wrong-versus-right pairs for the patterns that trip people up most.