Navigate

pyric/firestore compatibility matrix

98.9% of the public API supported

182 of 184 public API

Status legend

Conforming — sandbox matches prod, locked by a passing probe Diverged (documented) — intentional difference with a written reason Bug — should match prod but doesn't; failing probe pins it

getFirestore(target) — initializer

getFirestore(target)getFirestore(ctx) returns a tagged sandbox-target handle (frozen identity)
getFirestore(target)getFirestore(sandbox) returns a tagged sandbox-live handle (per-op identity)
getFirestore(target)Package resolution owns production selection: direct pyric/firestore rejects a real FirebaseApp, while inactive canonical firebase/firestore imports remain the real Firebase SDK
unit:package-resolution.test.ts, node-register:register-child.test.ts (inactive canonical imports are not rewritten)
getFirestore(target)getFirestore(undefined) is wrapped in the playground preview to default to the sandbox; production's unactivated canonical SDK still throws app/no-app, while a direct mirror call rejects the missing sandbox owner
playground:firestore-bare-getfirestore — fix from PR #397 + oracle: packages/conformance/observations/firestore/firestore-bare-getfirestore-no-default-app.json (code: 'app/no-app' against digame-mas, fb-js-sdk 12.19.0 — confirms prod throw shape)
(wrap)
getFirestore(target)Two getFirestore(sandbox) calls share state (same underlying LocalEnvironment)
unit:sandbox-live-identity.test.ts ("two handles share the same sandbox")
getFirestore(target)Handle dispatch by TARGET_SYMBOL brand — refs/queries route to their owning target via refToTarget WeakMap
unit:sandbox-target.test.ts ("throws TypeError for refs not produced by this package")

Named databases

In production getFirestore(app, databaseId) selects a named database with its own documents, and rules see that id in the database path variable. Pyric models one database per app, (default). When firebase.json declares firestore as an array, pyric serves the (default) entry’s rules and prints a startup warning for each named entry.

getFirestore(app, databaseId)In the sandbox, getFirestore(app, databaseId) ignores the database id and returns the app's (default) handle, so documents written under one id are read under every other id.
packages/pyric/test/firestore/named-database.test.ts asserts two database ids return the (default) handle and that a document written under one id reads back under another. (Structured evidence: firestore-named-database-absent)
every database id resolves to (default)
getFirestore(app, databaseId) (served mode)The served firebase/firestore entry ignores the database id: the worker path returns the app's one handle and the in-page fallback delegates to the sandbox getFirestore(app). The worker protocol carries no database id.
packages/cli/test/serve/worker/composite-filters-served-entry.test.ts imports the served entry over a worker host, asserts getFirestore(app, 'reports') returns the app's handle, and reads the (default) documents through it.
every database id resolves to (default)
pyric-admin getFirestore(app, databaseId)pyric-admin getFirestore takes no database id; a second argument is ignored and the handle reads and writes (default). The Admin SDK's getFirestore(app, databaseId) selects the named database.
packages/pyric-admin/test/firestore/named-database.test.ts writes through getFirestore(app, 'reports') and reads the document through getFirestore(app) and getFirestore(app, 'archive'). (Structured evidence: firestore-named-database-admin-mixing)
no database id parameter; every call resolves to (default)
Rules match /databases/{database}/documentsRules evaluate the database path variable as (default) for every request, whatever database id the handle was created with. Production binds the named database's id.
packages/pyric/test/firestore/named-database.test.ts writes through a handle created for reports: a rule requiring database == '(default)' allows the write and a rule requiring database == 'reports' denies it. (Structured evidence: firestore-named-database-rules-api, firestore-named-database-cross-database)
database is always (default)

Path constructors — doc / collection / collectionGroup

Path constructorsdoc(db, path) returns a tagged DocumentReference with id / path
Path constructorsdoc(db, 'a', 'b', 'c', 'd') joins variadic path segments
Path constructorscollection(db, path) returns a tagged CollectionReference
Path constructorsdoc(coll, id) appends under a collection ref
Path constructorsdoc(coll) (no id) mints an auto-id DocumentReference
Path constructorscollection(docRef, name) builds a subcollection ref
Path constructorscollectionGroup(db, id) returns a query spanning every collection with that id; onSnapshot on it delivers the initial snapshot and every later write to a collection with that id at any depth
unit:sandbox-target.test.ts ("gathers documents across every parent collection"). UPDATED, 2026-10-07: oracle packages/conformance/observations/firestore/firestore-collection-group-listener.json, captured with the Web SDK against temporarily deployed production rules that were restored afterwards. Under match /{path=**}/<id>/{id}, a listener on collectionGroup(db, id) fired once with the existing document, once with added for a write in a subcollection with that id, once with added for a write in the root collection with that id, and not at all for a write in a sibling collection; a listener on a collection id that only a concrete match governs received permission-denied. unit:firestore/oracle-conformance.test.ts replays the capture in the sandbox; unit:firestore/collection-group-rules.test.ts pins the same sequence, the denial routed to the error callback, and query constraints on the listener; cli:serve/worker/collection-group-listener.test.ts pins the same delivery and denial through the worker bridge.
Path constructorsUnknown ref (not produced by this package) → TypeError with "unrecognized reference"
Path constructorsHeld doc/coll ref under sandbox-live re-resolves to the chainable under the current user at op time (via rebuild closure)
unit:sandbox-live-identity.test.ts ("held doc ref re-resolves under the current user")

getDoc(ref) — single-doc read

getDoc(ref)Returns DocumentSnapshot with id, exists (method form), data()
getDoc(ref)snap.exists is normalized to method form (snap.exists() returns boolean) to match the modular SDK
playground:firestore-onsnapshot (bundled, assertion-shape compat) + playground:firestore-row-17-snap-exists-method (one-claim)
getDoc(ref)snap.data() returns undefined for missing doc
getDoc(ref)snap.ref is tagged so it routes through targetOf in follow-up ops
getDoc(ref)Re-evaluates rules under current user on every call (sandbox-live) — read denied throws permission-denied
unit:sandbox-live-identity.test.ts ("doc read denied when current user lacks read access"), oracle: packages/conformance/observations/firestore/firestore-read-denied-error-code.json (prod getDoc on a denied path throws a FirebaseError with .code === 'permission-denied', .message === 'Missing or insufficient permissions.', instanceof Error) (Structured evidence: query-rules-enforcement.test.ts)
getDoc(ref)Rules-denied modular writes throw a FirebaseError('permission-denied'), matching the production error class and code
Oracle-locked by packages/conformance/observations/firestore/firestore-rules-denied-error.json: prod throws a FirebaseError (name + constructor name both FirebaseError), .code === 'permission-denied', and the value is an instanceof FirebaseError and Error. oracle:firestore#21 replays the same denied modular write against the sandbox and asserts that complete class shape. (Structured evidence: oracle-conformance.test.ts)

getDocs(query) — bulk read

getDocs(query)Returns QuerySnapshot with size, empty, docs (QueryDocumentSnapshot[])
unit:sandbox-target.test.ts, playground:firestore-query (Structured evidence: oracle-conformance.test.ts)
getDocs(query)QuerySnapshot.forEach(callback, thisArg) calls callback.call(thisArg, doc) once per document, in query order, with the document alone, and DocumentSnapshot.get(fieldPath) returns the stored field at a dotted string or FieldPath (undefined when absent), for getDocs (with or without a converter, and the empty getDocsFromCache miss), getDoc and listener snapshots, in the in-page sandbox and through the served worker client, which the client SDKs in a Node host server process use.
unit:query-snapshot-for-each-once.test.ts asserts the modular getDocs snapshot with and without a converter, a listener snapshot and the Admin-shaped query snapshot each visit every document once with thisArg bound and one argument, and that a write inside the callback runs once; unit:sandbox/admin-firestore/error-translation-calls-once.test.ts asserts the proxy calls a method once for each kind of return value; before the fix the sandbox's error-translation proxy fell back to a second call when a method returned undefined, so forEach visited every document twice. packages/cli/test/serve/worker/query-snapshot-for-each.test.ts asserts the served getDocs and listener snapshots visit the same documents in the same order and read the same fields as the in-page snapshots, and that a served getDoc snapshot reads a nested field and rejects an invalid field path with invalid-argument. App scenario test/apps/create-pyric-node-template scaffolds the create-pyric node template, whose src/app.ts calls snap.forEach on a getDocs result, and runs its dev script (#1203). (Structured evidence: scenario.ts)
getDocs(query)Each snap.docs[i].ref is tagged for follow-up ops
getDocs(query)Sandbox-live: re-evaluates filters under the current user (different docs visible per identity)
unit:sandbox-live-identity.test.ts ("query results re-evaluate under the current user")
getDocs(query)Query reads enforce security rules (FS-B1) — a deny-all / auth-gated rule set throws permission-denied. Pre-FS-B1 query reads went through the rules-bypassing listDocuments and returned the whole collection.
unit:admin-compat/query-rules-enforcement.test.ts (deny-all + auth-gated getDocs/aggregate), unit:admin-compat/per-op-auth.test.ts ("Query.get enforces rules")
getDocs(query)Enforcement follows the query-proof model within the supported equality subset (RULES-B11; scope limits in 24c) — "rules are not filters": a doc-data-dependent list rule (resource.data.visibility == 'public', resource.data.owner == request.auth.uid) is ALLOWED when the query's where() equalities discharge it and the whole query is permission-denied otherwise — never silently truncated to the readable subset. Per-doc get rules do NOT filter query results (the list rule alone governs queries — granular-operations docs). Applies to getDocs, aggregates, and onSnapshot alike. Pre-fix: rules-as-filters (per-doc get omission) + blanket denial of every doc-data-dependent list, even provable ones.
Local query support: unit:firestore/query-proof-application.test.ts covers finite membership, guardian array membership, pinned lookup paths, auth and limit controls, and adversarial array/lookup cases. Upstream semantics: firebase.google.com/docs/firestore/security/rules-query and firebase.google.com/docs/firestore/query-data/queries. Local diagnostic contract (#583): unit:firestore/query-proof-diagnostics.test.ts pins dynamic membership rejection, fallback attribution, constraint/residual distinctions, modular listener context, captured lifecycle errors, and immutable operation-summary proof metadata; this adds no production observation. unit:firestore/query-proof-enforcement.test.ts (provable/unprovable getDocs + onSnapshot, owner-pinned uid, get-rules-don't-filter, request.query.limit; verified failing pre-fix), unit:simulator/local-environment.test.ts (Slice 6 — flipped from per-doc-filter assertions); prod truth: firebase.google.com/docs/firestore/security/rules-query
getDocs(query)Query-proof scope remains conservative. Equality and finite scalar in filters can pin candidate fields; array-contains proves the corresponding membership fact, not the whole array. Helpers and positive OR branches reduce to sufficient, candidate-independent residuals. Every finite combination (up to 30) must pass auth, query limits, and any lookup whose path is pinned by the query. Unpinned fields, candidate identity, dynamic document-dependent collections, unbounded range guarantees, and unsupported syntax remain deny-only gaps. Queries are never authorized by filtering stored rows. A collection-group query is authorized only by a top-level list or read rule at match /{path=}/<collectionId>/{id} or match /{document=} whose condition reads no path binding; any other shape, including a match nested in match /{document=**}, denies the query. This expanded local support has unit evidence and upstream documented semantics, but no new hosted observation.
Local query support: unit:firestore/query-proof-application.test.ts covers finite membership, guardian array membership, pinned lookup paths, auth and limit controls, and adversarial array/lookup cases. Upstream semantics: firebase.google.com/docs/firestore/security/rules-query and firebase.google.com/docs/firestore/query-data/queries. Local diagnostic contract (#583): unit:firestore/query-proof-diagnostics.test.ts pins dynamic membership rejection, fallback attribution, constraint/residual distinctions, modular listener context, captured lifecycle errors, and immutable operation-summary proof metadata; this adds no production observation. unit:rules/simulator/query-proof.test.ts (function-inlining provable cases; full-accounting rejections for mixed equality + in/get/hasOnly/range/is shapes in inline and helper form; fail-closed classifier probes: bracket-access resource['data'], exists() keyed by resource.data through path-literal segments, slice access, resource.id, and an unrecognized node shape), unit:firestore/query-proof-enforcement.test.ts (seeded end-to-end denials of the demonstrated attacks: forbidden-field absence check in member and bracket form, banned-owner exists() lookup, slice conjunct, each returning zero documents). Collection-group scope: unit:firestore/collection-group-rules.test.ts authorizes getDocs(collectionGroup(db, 'items')) under match /{path=**}/items/{id}, proves a data-gated rule from the query's equality, and denies under a rule for another collection id, a rule that reads the recursive binding, and concrete collection rules; unit:firestore/sandbox/collection-group-rule-proof.test.ts pins the projection. Upstream semantics: firebase.google.com/docs/firestore/security/rules-query#secure_and_query_documents_based_on_collection_groups. No hosted collection-group query is captured; the production matcher verdicts for the same rule shape, from the Rules Test API, live in oracle:rules-firestore-hierarchical-match-cascade.
getDocs(query)Empty result for a collection with no docs (size === 0, empty === true)

setDoc(ref, data[, options]) — full write

setDoc(ref, data[, options])No options → replaces the existing document entirely
unit:sandbox-target.test.ts ("setDoc default replaces")
setDoc(ref, data[, options]){ merge: true } → deep-merges nested maps (FS-B6), preserving unspecified fields at every level: setDoc({a:{b:2}}, {merge:true}) over {a:{c:1}} yields {a:{b:2,c:1}}. Pre-FS-B6 the wrapper shallow-replaced the whole a map.
unit:sandbox-target.test.ts, unit:admin-compat/field-path-merge.test.ts (FS-B6 nested deep-merge; verified failing pre-fix)
setDoc(ref, data[, options]){ mergeFields: [...] } → writes only the listed dot-separated field paths into the existing doc (FS-B6); other keys in data are ignored, other fields in the existing doc preserved. mergeFields: ['a.b'] reaches into a nested map.
unit:sandbox-target.test.ts, unit:admin-compat/field-path-merge.test.ts (dotted mergeField); mask edges (delete/transform outside mask, empty mask, deleteField in mask): unit:upstream-write-aggregate-probes.test.ts
setDoc(ref, data[, options])Passing both merge and mergeFields — mergeFields wins on sandbox (matches JS SDK effective behavior)
setDoc(ref, data[, options])Sentinels (serverTimestamp, increment, arrayUnion, arrayRemove, deleteField) resolve in the same call
unit:sandbox-target.test.ts, playground:firestore-sentinels, oracle: packages/conformance/observations/firestore/firestore-row-30-sentinels-in-setdoc.json — setDoc({createdAt: serverTimestamp(), count: 5, tags: ['a']}) followed by getDoc returns createdAt as a Timestamp instance (constructor name Timestamp, has seconds + nanoseconds), count === 5 (number), tags === ['a']. Sentinels resolve server-side and the follow-up read sees concrete values, not the sentinel placeholders.
setDoc(ref, data[, options])Converter (via withConverter) runs toFirestore(data) before the write
unit:sandbox-target.test.ts ("withConverter on a DocumentReference round-trips")
setDoc(ref, data[, options])Rules-denied setDoc throws a FirebaseError with code permission-denied, matching production
unit:sandbox-target.test.ts ("getDoc denies when rules reject"), playground:rules-data-validation, oracle: packages/conformance/observations/firestore/firestore-write-denied-error-code.json (prod setDoc on a denied path throws a FirebaseError with .code === 'permission-denied', .message === '7 PERMISSION_DENIED: Missing or insufficient permissions.', instanceof Error); oracle:firestore#32 pins the sandbox error shape (Structured evidence: oracle-conformance.test.ts)

updateDoc(ref, data) — partial write

updateDoc(ref, data)Merges data into the existing doc; missing fields preserved. Top-level keys are dot-separated FieldPaths (FS-B5): updateDoc({'a.b': 2}) sets the nested leaf a.b (preserving a.c), not a literal "a.b" key; a single-segment map value replaces that field wholesale; deleteField() at a dotted path removes the nested leaf.
unit:sandbox-target.test.ts, unit:admin-compat/field-path-merge.test.ts (FS-B5 dot-path nested write + delete; verified failing pre-fix) (Structured evidence: firestore-updatedoc-dotpath-fieldpath)
updateDoc(ref, data)Throws not-found (sandbox) / FirebaseError('not-found') (prod) on missing doc
unit:sandbox-target.test.ts (implicit in writes-fail-on-missing tests), oracle: packages/conformance/observations/firestore/firestore-updatedoc-missing-error.json (prod throws FirebaseError with code: 'not-found', message "5 NOT_FOUND: No document to update: …")
updateDoc(ref, data)Does NOT run a converter — partial updates don't have a typed home (matches JS SDK)
(documented in withConverter block)
updateDoc(ref, data)Sentinels resolve mid-update (increment(1) against an existing numeric field, etc.)
unit:sandbox-target.test.ts, playground:firestore-sentinels, oracle: packages/conformance/observations/firestore/firestore-row-36-sentinels-in-updatedoc.json — after setDoc({count: 5, tags: ['a'], oldField: 'keep-then-remove'}) then updateDoc({count: increment(3), tags: arrayUnion('b'), oldField: deleteField()}), the follow-up getDoc returns count: 8, tags: ['a', 'b'], and oldField absent from the doc (the deleteField sentinel actually removes the key). All three sentinels apply in one mid-update commit.
updateDoc(ref, data)Sandbox-live: each call re-evaluates auth (alice → bob between writes uses bob's auth)
unit:sandbox-live-identity.test.ts ("updateDoc re-evaluates auth per call")

deleteDoc(ref)

deleteDoc(ref)Removes the document; subsequent getDoc returns exists()===false
deleteDoc(ref)Idempotent — deleteDoc on missing doc resolves without throwing (matches JS SDK)
unit:deletedoc-missing.test.ts, playground:firestore-deletedoc-missing, oracle: packages/conformance/observations/firestore/firestore-deletedoc-missing.json
deleteDoc(ref)Rules-denied delete throws permission-denied
unit:sandbox-target.test.ts (rules-reject branch), oracle: packages/conformance/observations/firestore/firestore-delete-denied-error-code.json (prod deleteDoc on a denied path throws a FirebaseError with .code === 'permission-denied', .message === '7 PERMISSION_DENIED: Missing or insufficient permissions.', instanceof Error)

addDoc(coll, data) — auto-id write

addDoc(coll, data)Returns a tagged DocumentReference with auto-id
addDoc(coll, data)Returned ref is usable in subsequent ops (getDoc, setDoc, onSnapshot)
unit:sandbox-target.test.ts, oracle: packages/conformance/observations/firestore/firestore-row-42-adddoc-returned-ref-usable.json — addDoc(coll, {v:1}) returned a ref whose .id is a 20-char auto-id; getDoc(ref) returned {v:1} (round-trip), setDoc(ref, {v:2}) overwrote without error, follow-up getDoc returned {v:2}, and onSnapshot(ref, cb) registered cleanly and fired once with {exists:true, v:2}. All four follow-up ops succeed on the returned ref without re-tagging.
addDoc(coll, data)Sandbox-live: returned ref is a live ref (rebuild closure recorded) so follow-ups re-resolve auth
unit:sandbox-live-identity.test.ts ("addDoc result is a tagged live ref")
addDoc(coll, data)Converter on the parent collection propagates onto the returned ref
unit:sandbox-target.test.ts ("addDoc through a converted collection")
addDoc(coll, data)Auto-id format — production and sandbox mint 20-character IDs from [A-Za-z0-9]
Oracle-locked: packages/conformance/observations/firestore/firestore-adddoc-autoid-format.json records production's 20-character alphanumeric shape; packages/pyric/test/firestore/oracle-conformance.test.ts generates 25 sandbox IDs and checks both invariants against that observation.

withConverter — typed refs

withConverterwithConverter(docRef, converter) returns a shell that runs toFirestore on writes, fromFirestore on reads
withConverterwithConverter(collRef, converter) propagates onto doc(typedColl, id)
withConverterwithConverter(collRef, converter) propagates through query(typedColl, …) + getDocs()
withConverterwithConverter(ref, null) strips the converter, returns the underlying untyped view
withConverterOriginal untyped ref keeps its identity after withConverter(ref, c) (two views, one path)
withConvertersetDoc through a converted ref invokes toFirestore(data)
withConvertergetDoc through a converted ref invokes fromFirestore(snapshot); .data() returns the typed model
withConverterupdateDoc through a converted ref does NOT invoke the converter
(documented constraint; matches JS SDK)
withConverterCollectionReference.withConverter(c) is an instance method on collection() and collectionGroup() values; the converter reaches doc(typedColl, id), doc(typedColl), query(), addDoc, getDocs, and onSnapshot
withConverterQuery.withConverter(c) is an instance method on query() values; withConverter(null) on a collection or query removes the converter, and collection(typedDocRef, id) stays untyped

Query construction — query / where / or / and / orderBy / limit

Query constructionquery(coll, where(…), orderBy(…), limit(…)) composes constraints in order
unit:sandbox-target.test.ts, playground:firestore-query
Query constructionwhere(field, op, value) — all 10 ops: <, <=, ==, >=, >, !=, in, not-in, array-contains, array-contains-any
unit:sandbox-target.test.ts (canonical query test); membership ops + OR/in/array-contains composites: unit:upstream-query-probes.test.ts
Query constructionExistence + null filter guards (FS-B7) — a doc missing the filter field is never returned by ==/</<=/>/>=/in/!=/not-in; != and not-in additionally exclude null-valued docs and require the field to exist; a null in a not-in operand list matches nothing. Pre-FS-B7, !=/not-in matched missing-field and null docs.
Query constructionor(...) composite — at least one sub-filter matches
unit:sandbox-target.test.ts ("or() matches docs where any sub-filter matches"), oracle: packages/conformance/observations/firestore/firestore-or-composite.json (4 seeded docs; or(where('x','==',1), where('y','==',2)) returned the exact union {match-both, match-x, match-y} — no implicit index required against cloud Firestore)
Query constructionand(...) composite — every sub-filter matches
unit:sandbox-target.test.ts ("and() requires every sub-filter"), oracle: packages/conformance/observations/firestore/firestore-and-composite.json (4 seeded docs; and(where('x','==',1), where('y','==',2)) returned only the intersection {match-both})
Query constructionNested or / and — full composite tree
unit:sandbox-target.test.ts ("nested or/and — the canonical composite pattern"), oracle: packages/conformance/observations/firestore/firestore-nested-or-and-composite.json (6 seeded docs; or(and(where('x','==',1), where('y','==',2)), where('z','==',3)) returned {inner-and-match, outer-z-match, both-branches} — exact boolean union as predicted)
Query constructionorderBy(field, 'asc'|'desc') — direction parameter
Query constructionCanonical type-order comparison (FS-B3) — orderBy + range filters compare by Firestore's canonical type order (null < bool < number < timestamp < string < bytes < ref < geopoint < array < map), then within-type; numbers sort numerically (not lexicographically), NaN sorts as the smallest number, and range filters (</<=/>/>=) only match same-type values. Pre-FS-B3 the comparator fell back to String(a).localeCompare(String(b)).
unit:firestore/sandbox/query-value-order.test.ts (cross-type ranking, numeric sort, NaN, timestamps, arrays; verified failing pre-fix)
Query constructionorderBy excludes missing-field docs (FS-B3) — a doc lacking an orderBy field is omitted from the result (matches prod); pre-fix it was sorted in via compareValues(undefined, …).
unit:firestore/sandbox/query-value-order.test.ts ("excludes the missing-field doc")
Query constructionImplicit orderBy + __name__ tiebreak (FS-B8) — the query's sort is normalized to: explicit orderBy clauses, then an implicit order on each inequality-filtered field, then a final document-key (__name__) clause. Equal-valued docs sort deterministically by key; a where('x','>',v) with no explicit orderBy returns docs ordered by x. Mirrors clones/.../core/query.ts:queryNormalizedOrderBy. Pre-FS-B8 equal-valued docs were nondeterministic and inequality results came back in insertion order.
unit:admin-compat/implicit-order-name.test.ts (key tiebreak, snapshot-cursor disambiguation, implicit inequality order; verified failing pre-fix)
Query constructionlimit(n) — caps result count
Query constructionlimitToLast(n) returns the trailing n documents in an ordered result; without orderBy, it throws a FirestoreError with production's unimplemented code
Oracle-locked by packages/conformance/observations/firestore/firestore-limittolast-preconditions.json: production's no-orderBy precondition throws code unimplemented, while ordered trailing-window semantics return ["b"]. oracle:firestore#61 replays both claims. Cursor composition + descending: unit:upstream-query-probes.test.ts; cursor/empty-snapshot preconditions: unit:sandbox-target.test.ts + unit:admin-compat/cursors.test.ts. (Structured evidence: oracle-conformance.test.ts)
Query constructionComposite filters AND with other constraints — query(coll, or(...), orderBy(...), limit(...))
Query constructionPassing orderBy / limit into or() / and() → TypeError
Query constructionZero-arg or() / and() → TypeError
Query constructionChained queries re-tag for further constraints (query(query(coll, where), orderBy))
unit:sandbox-target.test.ts ("chained queries are taggable")
Query constructionIndex validation against firestore.indexes.json — sandbox uses LocalEnvironment's lint pass; prod has its own server-side validation
divergence: sandbox can mis-pass a query that prod would reject at the server with failed-precondition if no index exists

Cursor pagination — startAt / startAfter / endAt / endBefore

Cursor paginationstartAt(...values) — inclusive value cursor (one positional per orderBy clause)
unit:sandbox-target.test.ts, oracle: packages/conformance/observations/firestore/firestore-cursor-startat-inclusive.json (5 seeded docs at pos=[1..5]; query(c, orderBy('pos'), startAt(3)) returned exactly [pos-3, pos-4, pos-5] — the cursor doc IS included)
Cursor paginationstartAfter(...values) — exclusive value cursor
unit:sandbox-target.test.ts, oracle: packages/conformance/observations/firestore/firestore-cursor-startafter-exclusive.json (5 seeded docs at pos=[1..5]; query(c, orderBy('pos'), startAfter(3)) returned exactly [pos-4, pos-5] — the cursor doc is EXCLUDED)
Cursor paginationendAt(...values) — inclusive end cursor
unit:sandbox-target.test.ts, oracle: packages/conformance/observations/firestore/firestore-cursor-endat-inclusive.json (5 seeded docs at pos=[1..5]; query(c, orderBy('pos'), endAt(3)) returned exactly [pos-1, pos-2, pos-3] — the cursor doc IS included)
Cursor paginationendBefore(...values) — exclusive end cursor
unit:sandbox-target.test.ts, oracle: packages/conformance/observations/firestore/firestore-cursor-endbefore-exclusive.json (5 seeded docs at pos=[1..5]; query(c, orderBy('pos'), endBefore(3)) returned exactly [pos-1, pos-2] — the cursor doc is EXCLUDED)
Cursor paginationstartAt(snapshot) overload — extracts orderBy field values from the snapshot, positioning against the NORMALIZED orderBy (implicit __name__), so it disambiguates equal-valued docs and is legal without an explicit orderBy (FS-B8). A VALUE cursor with more values than explicit orderBy clauses throws invalid-argument ("Too many arguments").
unit:sandbox-target.test.ts, unit:admin-compat/implicit-order-name.test.ts (snapshot cursor w/o orderBy), unit:admin-compat/cursors.test.ts (value-cursor too-many-args throws with .code) (Structured evidence: firestore-startat-snapshot-implicit-name)
Cursor paginationendAt(snapshot) overload
unit:sandbox-target.test.ts ("endAt(snapshot) trims to-and-including the anchor")
Cursor paginationstartAfter + limit — canonical pagination pattern

Aggregates — getCountFromServer / getAggregateFromServer / count / sum / average

AggregatesgetCountFromServer(query) returns { data: () => ({ count: N }) }
AggregatesgetCountFromServer honors where filters
AggregatesgetAggregateFromServer(query, spec) returns { data: () => Record<alias, number|null> } in the in-page sandbox, on a served page and in a registered Node process
In-page: unit:sandbox-target.test.ts; collectionGroup + nested paths: unit:upstream-write-aggregate-probes.test.ts. Production: oracle:firestore-aggregate-field-semantics key countOnly ({ n: 4 }), replayed through the served surface export and through the worker client and host in unit:cli/serve/worker/oracle-captures/firestore-served-surface.test.ts; that scenario's other keys are pinned under FL-27, FL-28 and FL-30. A served page and a registered Node process aggregate over the host in test/apps/client-sdk-under-register.
Aggregatescount() / sum(field) / average(field) compose under one spec — field may be a dotted nested path
Aggregatesaverage returns null on empty input (matches JS SDK)
AggregatesAggregates count documents server-side without paying read cost per doc in prod; sandbox computes locally (no cost model)
divergence: cost behavior differs, observable shape identical. Oracle-locked: packages/conformance/observations/firestore/firestore-count-aggregate-shape.json — getCountFromServer().data() returns { count: <number> } (single key, no other fields). Empty query returns count: 0 (not null/undefined); seeded 3 docs returns count: 3; filtered query honors the where constraint (count: 2).

onSnapshot(refOrQuery, …) — listeners

onSnapshot(refOrQuery, …)onSnapshot(docRef, cb) fires the initial snapshot asynchronously — never synchronously during the registering call. Prod empirically lands after a setTimeout(0) macrotask (the fire travels the network listener channel); the sandbox defers through its delivery scheduler (microtask). The matrix contract is "asynchronous, never during register", not "exactly the next microtask"
Aligned via the listener delivery scheduler (src/sandbox/firestore/local-environment.ts): the initial fire is enqueued and delivered on a microtask, never during register — closing the divergence this row previously documented (the sandbox used to fire synchronously during registration; the sync-body tests were migrated to the flush/await idiom). Machine-checked against packages/conformance/observations/firestore/firestore-row-80-onsnapshot-fires-initial.json (firstFireSyncDuringRegister: false, fire count + contents) in oracle-conformance.test.ts; also unit:sandbox-target.test.ts, playground:firestore-onsnapshot (bundled) + playground:firestore-row-80-onsnapshot-fires-initial (one-claim).
onSnapshot(refOrQuery, …)onSnapshot(query, cb) fires on collection writes; QuerySnapshot.docChanges() reports added / modified / removed with oldIndex / newIndex
unit:sandbox-target.test.ts, oracle: packages/conformance/observations/firestore/firestore-row-81-onsnapshot-query-fires-on-write.json — listener on query(coll) saw 1 initial fire (empty, size:0), then one fire per write: addDoc → size:1, setDoc(coll, 'known-id') → size:2, deleteDoc(addedRef) → size:1. Total 4 fires, each reflecting the current collection state. Every collection-level write produces a distinct fire. (Note: this oracle used a filterless query(coll), which masked FS-B2 — see row 81a.) Modular docChanges indexes: unit:upstream-transform-txn-listener-probes.test.ts. The served worker client computes docChanges() in the page from consecutive snapshot frames with the change computation the in-page snapshot uses (computeDocumentChanges and createDocChanges in snapshot-listeners.ts); unit:query-snapshot-doc-changes.test.ts covers added, modified and removed with oldIndex and newIndex, the initial all-added snapshot, a collection-group listener, and identical change lists from the served and in-page planes for the same writes and a sign-in that re-establishes the listener (Structured evidence: trigger-attribution.test.ts, delivery-ordering.test.ts)
onSnapshot(refOrQuery, …)Filtered listeners honor where / orderBy / limit (FS-B2) — onSnapshot(query(coll, where(…), orderBy(…), limit(…)), cb) delivers the same membership as getDocs(sameQuery): non-matching docs are excluded on the initial fire and on writes; ordering + limit are applied. Pre-FS-B2 the SnapshotTarget dropped all constraints and delivered the whole collection.
unit:onsnapshot-query-constraints.test.ts (filtered/ordered/limited listeners; verified failing pre-fix)
onSnapshot(refOrQuery, …)Listener .data() matches getDoc shape (FS-B10) — the onSnapshot doc + query snapshot path runs the same read-path translation as getDoc/getDocs, so snap.data().createdAt is a compat Timestamp ({seconds, nanoseconds}), not the rules-internal wrapper ({seconds, nanos} + typeName, no nanoseconds). Pre-FS-B10 a listener leaked the internal shape while the single-doc read returned the compat shape.
unit:simulator/listener-read-translation.test.ts (doc + query listener Timestamp shape; verified failing pre-fix)
onSnapshot(refOrQuery, …)Initial fire for a missing doc has exists() === false and data() === undefined
playground:firestore-onsnapshot (bundled) + playground:firestore-row-82-onsnapshot-missing-initial (one-claim), oracle: packages/conformance/observations/firestore/firestore-row-82-onsnapshot-missing-initial.json — single initial fire with snap.exists() === false, snap.data() === undefined, hasPendingWrites: false, fromCache: false. The missing-doc fire is server-confirmed, not a cache speculation.
onSnapshot(refOrQuery, …)Returned Unsubscribe stops further fires
unit:sandbox-target.test.ts, oracle: packages/conformance/observations/firestore/firestore-row-83-unsubscribe-stops-fires.json — pre-unsubscribe write fired the listener (initial fire + write fire = 2 fires); after unsub(), a subsequent setDoc produced 0 additional fires (postUnsubFireCount: 0). Unsubscribe is durable; no fires arrive on the released callback after a 1.5s settle window.
onSnapshot(refOrQuery, …)Observer object form {next, error, complete} works alongside the function form. Partial observers are accepted — { error: fn } with no next registers and routes denials to error (FS-B14, isPartialObserver semantics from upstream api/observer.ts); pre-fix it was misrouted as SnapshotListenOptions and threw "missing next handler".
oracle: packages/conformance/observations/firestore/firestore-row-84-observer-object-form.json — registered two listeners on the same doc: one as a bare function (snap) => …, one as {next, error, complete}. Both fired once on initial ({v:0}) and again after a write ({v:1}), capturing identical data. error never fired (no rule denial), complete never fired on unsub() (Firebase treats unsubscribe as a teardown, not a "complete" signal — the observer's complete callback is reserved for terminal stream end, which onSnapshot does not produce). The two registration shapes are interchangeable for fire dispatch. unit:onsnapshot-observer-discriminator.test.ts (error-only observer; verified failing pre-fix)
onSnapshot(refOrQuery, …)SnapshotListenOptions.includeMetadataChanges — one write yields the pending-write local echo (hasPendingWrites: true) then, for metadata listeners, the settled ack fire: default listener 2 fires, metadata listener 3
Aligned via the listener delivery scheduler (src/sandbox/firestore/local-environment.ts + snapshot-listeners.ts): the write echo carries hasPendingWrites: true and includeMetadataChanges listeners receive the settled metadata-only ack, reproducing prod's recorded 2/3-fire sequences exactly. Machine-checked against packages/conformance/observations/firestore/firestore-include-metadata-changes.json in oracle-conformance.test.ts (fire counts and per-fire hasPendingWrites sequence asserted from the capture). The served worker forwards includeMetadataChanges with the subscription and hasPendingWrites with each snapshot frame, so a served listener receives the same 2/3-fire sequence and metadata: unit:query-snapshot-doc-changes.test.ts. Known divergence in served mode: one sandbox serves every tab, Studio and every native client, and the sandbox marks every write echo pending whichever session wrote it, so a served listener reports hasPendingWrites: true for a write made by another tab, by Studio or by a native client, where production reports false for writes from other clients (Structured evidence: metadata-ack.test.ts)
onSnapshot(refOrQuery, …)Snapshot's .ref / .docs[i].ref are tagged so consumer code can pass them to follow-up ops
onSnapshot(refOrQuery, …)Sandbox-live: listener registered as alice keeps emitting alice's view after setUser → bob (identity frozen at subscribe)
unit:sandbox-live-identity.test.ts ("listener registered as alice keeps emitting alice's view")
onSnapshot(refOrQuery, …)Sandbox-live: listener registered as anonymous keeps firing after sign-in (anonymous → signed-in identity persists per listener)
unit:sandbox-live-identity.test.ts ("listener registered as anonymous on /public keeps firing after sign-in")
onSnapshot(refOrQuery, …)Snapshot's ref is usable in follow-up ops under the new user (the ref is live, the listener identity is frozen — distinct)
unit:sandbox-live-identity.test.ts ("snapshot ref is usable in subsequent ops under the new user"), oracle: packages/conformance/observations/firestore/firestore-row-89-snapshot-ref-usable.json — captured snap.ref from a docRef listener's first fire and snap.docs[0].ref from a query listener's first fire; both refs round-trip via getDoc (returning the same data) and setDoc (writes succeed and a follow-up getDoc confirms the new payload). snap.ref.path equals the original doc(coll, id).path. Both snap-ref shapes are first-class refs in prod, matching sandbox's tagged-ref guarantee.
onSnapshot(refOrQuery, …)Preview tree mounts the user's component exactly once per session load — no observer subscriptions leak across parallel AppPreview instances. Root cause: PlaygroundPage rendered both WorkspacePanel's and the mobile AppPanel's AppPreview unconditionally (the latter md:hidden on desktop but still mounted), producing two live preview trees subscribing in parallel. Fixed by gating AppPanel on useIsMobile() && mobileTab === 'app'.
playground:preview-single-mount

runTransaction(db, fn)

runTransaction(db, fn)Atomic read-write — all reads in fn see a consistent snapshot, writes commit together
unit:sandbox-target.test.ts, playground:firestore-transaction; get-missing/deleted + empty txn + nested update: unit:upstream-transform-txn-listener-probes.test.ts
runTransaction(db, fn)Identity is frozen at runTransaction start — mid-transaction setUser does NOT re-auth in-flight reads
unit:firestore/sandbox-live-identity.test.ts changes the live session from alice to bob inside the callback; the transaction still reads and commits under alice's captured identity.
runTransaction(db, fn)Retry behavior — a read-document conflict reruns the callback against fresh data; maxAttempts bounds persistent contention
Oracle: packages/conformance/observations/firestore/firestore-transaction-contention-retries.json — two production Web SDK clients force one retry ([0, 40], final 42) and persistent contention with maxAttempts: 2 runs exactly twice then throws failed-precondition. packages/pyric/test/firestore/oracle-conformance.test.ts replays both cases through the sandbox. (Structured evidence: sandbox-target.test.ts)
runTransaction(db, fn)Throws FirebaseError('permission-denied') on rule denial inside the transaction (the inner write's denial — not a generic aborted). Sandbox throws FirestoreCompatError with the same code: 'permission-denied'
unit:sandbox-target.test.ts (writes-reject branch), oracle: packages/conformance/observations/firestore/firestore-transaction-rules-denied-error.json (prod throws FirebaseError with code: 'permission-denied', NOT aborted; the inner callback ran once and the rules-rejected write surfaces as a regular permission-denied at commit)

writeBatch(db)

writeBatch(db)batch.set / batch.update / batch.delete queue mutations
unit:sandbox-target.test.ts, playground:firestore-batch
writeBatch(db)batch.commit() applies all queued writes atomically — success path commits all queued mutations together; failure path (one write violating rules) rejects the whole batch with no partial application
unit:sandbox-target.test.ts, oracle: packages/conformance/observations/firestore/firestore-row-96-batch-commit-atomic.json — success path: a batch with set (fresh doc), update (existing doc), and delete (existing doc) all land in a single commit (allApplied: true). Failure path: a batch with one write targeting a path outside pyric_oracle/* rejects with code: 'permission-denied' and leaves the would-have-set doc absent and the would-have-updated doc at its original value (noPartialApply: true) — atomicity verified end-to-end.
writeBatch(db)Batch is tagged on construction and remains bound to the sandbox owner that created it
unit:firestore/sandbox-live-identity.test.ts constructs a batch from sandbox A with a reference from sandbox B and proves the commit remains isolated to A.
writeBatch(db)Batch identity is frozen at construction (per current implementation)
unit:firestore/sandbox-live-identity.test.ts constructs under alice, switches the live session to bob, and proves commit still succeeds under alice's captured identity.

Sentinels — serverTimestamp / increment / arrayUnion / arrayRemove / deleteField / FieldValue / Timestamp

SentinelsserverTimestamp() resolves to a Timestamp after the write commits
unit:sandbox-target.test.ts, playground:firestore-sentinels (bundled) + playground:firestore-row-99-servertimestamp-resolves (one-claim), oracle: packages/conformance/observations/firestore/firestore-row-99-servertimestamp-resolves-to-timestamp.json — setDoc({at: serverTimestamp()}) then getDoc yields at instanceof Timestamp === true, constructor.name === 'Timestamp', with both .seconds (number) and .nanoseconds (number) present.
Sentinelsincrement(n) atomically bumps a numeric field; null/missing field starts from 0
unit:sandbox-target.test.ts, playground:firestore-sentinels (bundled) + playground:firestore-row-100-increment-bumps-numeric (one-claim), oracle: packages/conformance/observations/firestore/firestore-row-100-increment-bumps-numeric.json — setDoc with no count field then updateDoc({count: increment(5)}) yields count === 5 (starts from 0). Follow-up increment(3) → 8, then increment(-2) → 6 (negative deltas apply, increments accumulate). Merge-create + int↔double + batch-across-docs: unit:upstream-transform-txn-listener-probes.test.ts
SentinelsarrayUnion(...values) de-dupes against existing members and against duplicate args within the same call
unit:sandbox-target.test.ts, playground:firestore-sentinels (bundled) + playground:firestore-row-101-arrayunion-dedupes (one-claim), oracle: packages/conformance/observations/firestore/firestore-row-101-arrayunion-dedupes.json — setDoc({tags: ['a','b']}) then updateDoc({tags: arrayUnion('b','c')}) yields ['a','b','c'] (single b, not double). Follow-up updateDoc({tags: arrayUnion('d','d','a')}) yields ['a','b','c','d'] — both inline duplicate args and existing-member duplicates are de-duped. Merge-path + object members: unit:upstream-transform-txn-listener-probes.test.ts
SentinelsarrayRemove(...values) strips matching members; values not present in the array are silent no-ops
unit:sandbox-target.test.ts, playground:firestore-sentinels (bundled) + playground:firestore-row-102-arrayremove-strips (one-claim), oracle: packages/conformance/observations/firestore/firestore-row-102-arrayremove-strips.json — setDoc({tags: ['a','b','c']}) then updateDoc({tags: arrayRemove('b','d')}) yields ['a','c']: 'b' removed, 'd' (absent) was a silent no-op (no error). Merge-path: unit:upstream-transform-txn-listener-probes.test.ts
SentinelsdeleteField() removes a field on update — the field is fully absent from the returned data, not merely undefined-valued. Legal at the top level or via a dot-path ({'a.b': deleteField()} removes the nested leaf — FS-B5). Nested inside a map literal ({a: {b: deleteField()}}) it throws invalid-argument (FS-B13) instead of destroying the sibling map.
playground:firestore-sentinels (bundled) + playground:firestore-row-103-deletefield-removes-field (one-claim), oracle: packages/conformance/observations/firestore/firestore-row-103-deletefield-removes-field.json — setDoc({keep:1, remove:2}) then updateDoc({remove: deleteField()}) yields a doc whose data() has keys ['keep'] only, keep === 1 preserved; unit:admin-compat/nested-delete-field.test.ts (nested → invalid-argument; dot-path + top-level still valid; verified failing pre-fix)
SentinelsTimestamp shape ({seconds, nanoseconds}) is identical between prod and sandbox — round-trips cleanly
SentinelsTimestamp nanos normalization + value API (FS-B12) — fromMillis/fromDate/now derive nanoseconds as floor((ms - seconds1000) 1e6) so it is always non-negative; fromMillis(-500).toMillis() round-trips to -500 (was -1500). The class ships isEqual / toString / toJSON / valueOf, mirroring clones/.../lite-api/timestamp.ts.
unit:admin-compat/timestamp-api.test.ts (negative-millis round-trip + value API; pre-fix lacked the methods and mis-normalized)
SentinelsUnified Timestamp storage (FS-B4) — a Timestamp written directly via the modular SDK (setDoc({createdAt: Timestamp.now()})) is stored as the same rules-internal Timestamp that serverTimestamp()/Date resolve to. Pre-FS-B4 a user-written Timestamp was the compat class only (not a RulesValue), so request.resource.data.createdAt is timestamp returned false for it while a serverTimestamp() write passed the same rule, and the two paths stored two different classes. A write-boundary converter now normalizes both.
unit:firestore/sandbox-converters/user-timestamp.test.ts (is timestamp passes for a user Timestamp; unified storage class; range-filter regression guard — verified failing pre-fix by removing the converter registration)
SentinelsFieldValue re-exported from pyric-admin (alias of ChainFieldValue)
type-only smoke
SentinelsSentinel overwrite on type mismatch (FS-B11) — increment(n) on a non-numeric (or absent) prior OVERWRITES using a base value of 0 (result n); arrayUnion/arrayRemove on a non-array prior coerce the base to []. Pre-FS-B11 these threw and surfaced as invalid-argument denials. Mirrors clones/.../model/transform_operation.ts (computeTransformOperationBaseValue, coercedFieldValuesArray).
unit:simulator/converters/fieldvalue.test.ts (FS-B11 overwrite block + flipped unit/integration/batch cases; verified failing pre-fix)

Scalar types — Bytes / GeoPoint / FieldPath / documentId

Scalar typesThe sandbox mirror owns compatible scalar constructors — Bytes.fromUint8Array(...), new GeoPoint(lat, lng), new FieldPath(...), and documentId() — without importing firebase/firestore
Scalar typesdocumentId() works in where(documentId(), …) / orderBy(documentId()) against the sandbox — string ids, DocumentReference operands, ranges, and id sort
unit:upstream-query-probes.test.ts (documentId() filters + orderBy); modular where/orderBy accept FieldPath
Scalar typesFieldPath (nested) works in queries against sandbox
Scalar typesBytes round-trip through the sandbox wire encoder — Bytes written via setDoc reads back as a Bytes instance with the same base64 representation
unit:packages/pyric/test/sandbox/firestore/wire-encoder-bytes-geopoint.test.ts + unit:packages/pyric/test/firestore/sandbox-target.test.ts ("Bytes + GeoPoint round-trip"), oracle: packages/conformance/observations/firestore/firestore-row-109-bytes-roundtrip.json — setDoc({payload: Bytes.fromUint8Array([1,2,3,4])}) then getDoc yields payload instanceof Bytes === true, payload.constructor.name === 'Bytes', payload.toBase64() === 'AQIDBA==', and payload.toUint8Array() returns [1,2,3,4] against digame-mas. The sandbox converter stores the rules Bytes wrapper; pyric/firestore finalizes reads into its locally owned Bytes class with the same observed methods and values.
Scalar typesGeoPoint round-trip through the sandbox wire encoder — GeoPoint written via setDoc reads back as a GeoPoint instance with the same latitude / longitude
unit:packages/pyric/test/sandbox/firestore/wire-encoder-bytes-geopoint.test.ts + unit:packages/pyric/test/firestore/sandbox-target.test.ts ("Bytes + GeoPoint round-trip"), oracle: packages/conformance/observations/firestore/firestore-row-110-geopoint-roundtrip.json — setDoc({loc: new GeoPoint(37.7749, -122.4194)}) then getDoc yields loc instanceof GeoPoint === true, loc.constructor.name === 'GeoPoint', loc.latitude === 37.7749, loc.longitude === -122.4194 against digame-mas. Sandbox storage uses the rules LatLng wrapper; pyric/firestore finalizes reads into its locally owned GeoPoint class.
Scalar typesVector value type (vector() + VectorValue) round-trip: a vector written via setDoc reads back as a VectorValue with the same components
unit:sandbox-target.test.ts ("Bytes + GeoPoint + VectorValue round-trip", top-level + nested). The locally owned vector() / VectorValue preserve Firebase's observable value shape; the sandbox converter stores the rules Vector wrapper and pyric/firestore finalizes reads back to VectorValue. Oracle observation to follow (cf. #109/#110). CLIENT surface only: the web SDK exposes vector() + VectorValue (read/write) but has NO findNearest and NO FieldValue.vector; vector SEARCH is admin/server-only (firebase-admin Query/CollectionReference.findNearest + FieldValue.vector()), out of scope for this client matrix; the admin surface is tracked in the design rationale.

Equality helpers — refEqual / queryEqual / snapshotEqual

Equality helpersrefEqual(a, b) — true when paths match under the same target
Equality helpersrefEqual is true for cross-flavor sandbox vs sandbox-live refs at the same path
unit:sandbox-live-identity.test.ts ("refEqual returns true for live and frozen refs at the same path")
Equality helpersrefEqual is false for refs at different paths
Equality helpersrefEqual(sandboxRef, foreignRef) throws TypeError — references not created by this sandbox mirror are unrecognized
unit:sandbox-target.test.ts (foreign refs throw unrecognized-reference TypeError)
Equality helpersqueryEqual(a, b) structurally compares collection and collection-group scope, filter/order/limit/cursor constraint structure, converter identity, and construction-time Firestore value snapshots for both equality and execution without re-observing caller objects. Snapshots cover maps/arrays, scalar objects, references (including raw and converted addDoc() results), and vectors; normalize Date to Timestamp; preserve the distinction between -0 and 0; compare snapshot and explicit bounds for all four cursor overloads by value without invoking snapshot converters, including across live-target rebuilds; reject undefined, bigint, nested arrays for ordinary and array-membership operands, and recursively nested cross-database references during query construction; and preserve Firebase's nested-array allowance for in/not-in candidate lists.
Oracle-locked by packages/conformance/observations/firestore/firestore-queryequal-structural.json: collection and collection-group scope, order sequence/direction, limits, composite filters, cursor values/inclusivity, converters, and Firestore operands all distinguish equal from changed queries as production does. The capture executes mutable maps, Timestamp, Bytes, GeoPoint, DocumentReference (including raw and converted addDoc() results), and Vector queries; proves Bytes/Vector source-array mutation cannot change existing or new queries; proves all four snapshot cursor overloads compare with explicit bounds and execute twice without invoking a consumer converter; and locks recursive foreign-reference rejection, Date/Timestamp normalization, and -0 handling. firestore-query-nested-array-validation.json separately pins the production SDK's client-side rejection of nested arrays without implying a cloud round trip. The replay forces live-target identity rebuilds for every snapshot cursor overload. oracle:firestore#116 replays every claimed fact. (Structured evidence: oracle-conformance.test.ts, equality.test.ts)
Equality helperssnapshotEqual(a, b) follows production snapshot state. A query's first one-shot read differs from the next identical read, then repeated settled reads (including an independently built equivalent query) compare structurally until query state changes and settles again. Listener snapshots compare query, documents, changes, and metadata. Document snapshots compare path, existence, Firestore-typed data, converter identity, and snapshot kind, so two gets of the same document are equal while a query-child snapshot and a direct get are distinct; scalar-shaped plain maps remain distinct from Timestamp, reference, GeoPoint, and Vector values.
Oracle-locked by packages/conformance/observations/firestore/firestore-snapshotequal-structural.json: sequential and equivalent-query reads prove the initial-to-settled transition; a changed result restarts that transition; listener sensitivity cases vary query, documents/change history, and metadata-only state; direct document cases vary path, existence, data, converter, and snapshot kind; and four collision probes distinguish scalar-shaped maps from their Timestamp, reference, GeoPoint, and Vector counterparts. oracle:firestore#117 replays every reachable fact. JSON reconstruction remains raw characterization only because Pyric does not expose that separate API. (Structured evidence: oracle-conformance.test.ts, equality.test.ts)
Equality helpersCross-flavor refEqual via QuerySnapshot.docs[i].ref works
unit:sandbox-live-identity.test.ts ("cross-flavor refEqual via QuerySnapshot doc refs")

connectFirestoreEmulator

connectFirestoreEmulatorNo-op on sandbox-target handles (the sandbox already IS a local emulator)
connectFirestoreEmulatorProduction does not enter the mirror: inactive package resolution leaves Firebase's connectFirestoreEmulator implementation unchanged
node-register:register-child.test.ts (inactive canonical Firestore is not rewritten)
connectFirestoreEmulatorThe sandbox mirror accepts Firebase's mockUserToken option shape as an inert compatibility argument; production uses Firebase's untouched implementation
type-only smoke

Offline / persistence / network family

Offline / persistence / network family (continued)

enableIndexedDbPersistenceResolves before Firestore starts and rejects with failed-precondition after any operation has started the service
Real Chromium: firestore-browser-lifecycle.json; replayed through the public modular API by oracle-conformance.test.ts and focused lifecycle coverage. Served planes: an accepted no-op that resolves after first use (FP-9). (Structured evidence: persistence-network.test.ts, firestore-served-surface.test.ts)
an accepted no-op on the served planes (FP-9)
enableMultiTabIndexedDbPersistenceEnables multi-client shared persistence before first use, permits two clients to opt in, and rejects initialization after a client has started with failed-precondition
Real Chromium: firestore-browser-lifecycle.json exercises fresh, after-use, and two-client initialization; replayed through public APIs by oracle-conformance.test.ts and focused persistence tests. (Structured evidence: persistence-network.test.ts)
clearIndexedDbPersistenceMaps to Sandbox.clearPersistence() — actually wipes the persisted blob (honest, not a no-op); already a no-op when persistence was never enabled
enableNetwork / disableNetworkDisabling network exposes local mutations with cache/pending-write metadata while holding write acknowledgement until network is re-enabled
Real Chromium: firestore-browser-lifecycle.json; replayed through the public modular API by oracle-conformance.test.ts and focused network coverage. Served planes: accepted no-ops, so an offline write commits at once (FP-9). (Structured evidence: persistence-network.test.ts, firestore-served-surface.test.ts)
an accepted no-op on the served planes (FP-9)
waitForPendingWritesWaits for outstanding offline write acknowledgements and resolves when network re-enable drains them
Real Chromium: firestore-browser-lifecycle.json; replayed through the public modular API by oracle-conformance.test.ts and focused pending-write coverage. (Structured evidence: persistence-network.test.ts)
terminateTerminates only the selected Firestore service instance: held refs reject with failed-precondition, owned listeners stop, and sibling Firestore or Auth services remain usable
Real Chromium: packages/conformance/observations/firestore/firestore-browser-lifecycle.json records failed-precondition on the terminated instance while Auth and a sibling Firestore instance continue. Replayed by oracle-conformance.test.ts; focused ownership coverage in terminate.test.ts. SharedWorker: a no-op, so held refs keep working (FP-9).
a no-op over the SharedWorker (FP-9)

Tier-1 cache-init + get-from-* family

Tier-1 cache-init + get-from-* family (continued)

initializeFirestoreDelegates to sandbox getFirestore(app) and returns the same handle. Accepts the settings argument (so the explicit-init pattern doesn't crash at import) but no-ops the cache/network settings — persistence is always on
settings accepted but cache/network settings are no-ops
persistentLocalCache / memoryLocalCache / persistentSingleTabManager / persistentMultipleTabManager / memoryEagerGarbageCollector / memoryLruGarbageCollectorConfig token accepted, inert — each returns a small tagged object so identity/usage doesn't crash. Persistence is the sandbox default; there is no cache tier left to configure
inert config tokens; no cache tier to configure
getDocFromServer / getDocsFromServerDelegates to getDoc / getDocs in the sandbox mirror — the sandbox store IS the authoritative source, so there is no separate server round-trip to force and no observable divergence from the default read
getDocFromCache / getDocsFromCacheExplicit cache reads distinguish cold and warm state: cold document reads reject with unavailable, cold queries return empty, and server/default reads populate subsequent cache reads
Real Chromium: firestore-browser-lifecycle.json captures cold and warm document and query cache behavior; oracle-conformance.test.ts replays it through public APIs. Served planes: reads the store, so a cold read resolves (FP-9). (Structured evidence: tier1-cache-init-align.test.ts, firestore-served-surface.test.ts)
reads the store on the served planes (FP-9)
setLogLevelAccepted no-op. The sandbox has no modular-SDK-style logger to wire a level into. It uses host-level console logging directly, gated by pyric sandbox's own flags, not this call
accepted no-op; no sandbox logger wired
onSnapshotsInSyncEmits an initial in-sync signal, batches another signal after snapshot listener delivery, and stops after unsubscribe
Real Chromium: firestore-browser-lifecycle.json records initial sync, write snapshot, then sync; replayed by oracle-conformance.test.ts and focused listener tests. (Structured evidence: tier1-cache-init-align.test.ts)
Runtime ES Classes / Constructor TokensExports ES classes and constructor tokens matching structural type handles for instanceof checks and prototype inheritance
unit:firestore/tier1-cache-init-align.test.ts (Structured evidence: runtime-classes.test.ts)
PersistentCacheIndexManager / Index auto-creationConfig tokens and index manager controller accepted as honest inert runtime tokens without failing execution
unit:firestore/tier1-cache-init-align.test.ts (Structured evidence: persistence-tokens.test.ts)
loadBundle / namedQueryDecodes string/ArrayBuffer bundle payloads into local sandbox store and registers named queries
unit:firestore/tier1-cache-init-align.test.ts (Structured evidence: bundles.test.ts)
documentSnapshotFromJSON / querySnapshotFromJSON / onSnapshotResumeDeserializes JSON snapshot objects into active Pyric snapshot wrappers and attaches resume listener
unit:firestore/tier1-cache-init-align.test.ts (Structured evidence: ssr-snapshots.test.ts)
aggregateFieldEqual / aggregateQuerySnapshotEqualCompares aggregate descriptors and snapshot data for value equality
unit:firestore/tier1-cache-init-align.test.ts (Structured evidence: runtime-classes.test.ts)
ensureFirestoreConfigured / executeWriteValidates sandbox initialization and executes write callback within mutation evaluation pipeline
unit:firestore/tier1-cache-init-align.test.ts (Structured evidence: writes-plumbing.test.ts)

Rules engine (via setRules from pyric/sandbox/firestore)

Rules-engine behavior is technically pyric-admin’s LocalEnvironment, but it’s the most-tested surface for divergence — request.auth, cross-doc reads via get(), data validation. These rows pin the shape consumer code depends on.

Every rules-checked request evaluates the ruleset of the latest setRules call. A write, a batched write, a document read, a list read, and simulate() on a compiled ruleset share one parse per ruleset source, and the next setRules call replaces it for the next request (unit:sandbox/firestore/rules-parse-count.test.ts, unit:sandbox/firestore/rules-state.test.ts).

request.auth.uid reads through to sandbox.currentUser?.uid on sandbox-live
playground:auth-anonymous, playground:rules-cross-doc-get
request.auth == null when sandbox.currentUser is null (anonymous path)
unit:sandbox-live-identity.test.ts ("anonymous fallback")
Cross-doc get(/databases/$(database)/documents/...) in rules works under sandbox; get() of a missing doc ERRORS (guard with exists()), and get(p).id / get(p).__name__ expose the doc identity (RULES-B8)
playground:rules-cross-doc-get, unit:rules/simulator/evaluator.test.ts (RULES-B8 block)
request.resource.data.<field> field validation in rules works under sandbox; an undefined field read ERRORS (deny), it does NOT read as null (RULES-B2) — guard with 'f' in data / data.get('f', d)
playground:rules-data-validation, unit:rules/simulator/evaluator.test.ts (RULES-B2 block)
resource.data.<field> (existing doc on writes) works under sandbox; undefined-field reads ERROR (RULES-B2)
playground:rules-resource-data-field, unit:rules/simulator/evaluator.test.ts (RULES-B2 block)
Custom claims in request.auth.token.<claim>
playground:rules-custom-claims
Tri-state error semantics: field access of a missing key, by dot (resource.data.typo) or by index (resource.data['typo'], resource.data[field]), a list index out of bounds, access on null/undefined, undefined variables, and get()-of-missing ERROR → deny; &&/|| absorb operand errors commutatively (CEL: error || true → true, error && false → false). A key present with a null value reads null. Use key in map or map.get(key, default) for a may-be-absent key. (RULES-B2/B3/B8)
unit:rules/simulator/evaluator.test.ts (RULES-B2 / RULES-B3 / RULES-B8 blocks) covers dotted and index access, null access, undefined variables, get() of a missing document and error absorption. Production capture, 2026-09-28: oracle:rules-firestore-undefined-field-access records production denying index access of a missing key on resource.data, request.resource.data and request.auth.token under ==, !=, == null, !, is, in, .size(), a nested map, a computed key, a path variable key and a let that is used; allowing under || true, !(... && false), an unused let, an in guard, a key present with null and get(key, null); and denying a list index past either end and a string key on a list. The simulator returned null for a missing index key and allowed 16 of those denials; it now reads index access through rules/simulator/index-access.ts, shared with the Storage evaluator, and matches production on all 41 cases (replayed by unit:rules/oracle-conformance.test.ts; unit:rules/index-access.test.ts runs each shape through both engines).
matches() is a full-string anchored RE2 test; replace()/split() take regexes (replace = all occurrences) (RULES-B4)
No JS prototype-chain leakage: 'toString' in data → false, data.constructor errors; in/hasAll/get use own keys only (RULES-B7)
Type-strict operators: + requires supported operand types ('a' + 1 and [1] + [2] error; list.concat(list) joins lists); ordered compares (< > <= >=) error across types; list membership uses value equality; is map excludes MapDiff/Set (RULES-B6 partial / B9 / B12 partial)
unit:rules/simulator/evaluator.test.ts (RULES-B6 / B9 / B12 blocks)
FirestoreSet VALUE equality: diff.addedKeys() == [uid].toSet() compares set contents (order-insensitive); set == list is false, not an error (RULES-B13). Pre-fix, ANY two sets compared EQUAL (generic-object deep-equals saw no enumerable keys) — a false-PERMISSIVE divergence found by joining validation
unit:rules/simulator/set-equality.test.ts; live validation: 10/10 both engines
update exposes request.resource.data / getAfter() as the existing doc merged with the payload via the writeMode: { kind: 'update' } path (the agent-facing simulate() opt-in); a sparse no-writeMode payload that drops a field now ERRORS on that field (RULES-B2) rather than silently reading null (RULES-B10)
A single-document write exposes request.resource.data as the document the write stores. updateDoc(ref, {'board.c1r1': 'x'}) shows rules a nested board.c1r1 beside the existing board keys, not a top-level field named "board.c1r1"; a dotted deleteField() removes the nested leaf; setDoc(ref, data, {merge: true}) deep-merges a nested map and keeps its sibling keys, and {mergeFields} writes only the listed paths. The field-and-value form carries each field path as literal segments: updateDoc(ref, new FieldPath('a.b'), 'x') writes a top-level field 'a.b', new FieldPath('board', 'c1.r1') writes a dotted key inside board, and a dotted string field is a nested path, through updateDoc, WriteBatch.update, Transaction.update, the Admin-shaped update, and the served worker. resource.data is unchanged by the projection.
oracle:firestore-write-request-resource (captured 2026-10-07 against deployed production rules with the Web SDK, stable across two runs). Each case is one client write to a seeded document, and each predicate over request.resource.data or request.resource.data.diff(resource.data) is a separate guarded rule, so the allow or deny of the write reads out what production built. Production exposes the stored document: updateDoc(ref, {'board.c1r1': 'x'}) gives request.resource.data.board.c1r1 == 'x' with board.c2r2 and the top-level fields kept, no 'board.c1r1' key, and affectedKeys() and changedKeys() equal to ['board']; a dotted deleteField() removes only the nested leaf; setDoc with merge deep-merges (affectedKeys() is ['board', 'extra']); mergeFields writes only the listed path; updateDoc(ref, {board: {c1r1: 'x'}}) replaces the whole board map; non-merge setDoc drops the unlisted top-level field (removedKeys() is ['keep']); resource.data is unchanged by the write; the field-and-value form updateDoc(ref, new FieldPath('a.b'), 'x') writes a literal top-level key 'a.b' ('a.b' in request.resource.data, !('a' in request.resource.data), affectedKeys() == ['a.b']) and new FieldPath('board', 'c1.r1') writes a literal dotted key inside board (affectedKeys() == ['board']). The sandbox replays every verdict, the literal-dot field-path cases included (unit:firestore/oracle-conformance.test.ts, 58 predicates over 10 writes). Update field paths travel as segment vectors: the served worker protocol and the remote Admin arm carry fields: [{ path: string[], value }], and inside the engine an update payload is keyed by a Pyric-internal encoding that backtick-quotes a segment containing .. That encoding stays in the engine: request events, write events, errors and denial context carry the update's fields as nested maps plus updateMask (its field paths as segment vectors), and replay rebuilds the update from the two. packages/pyric-admin/test/remote/remote-firestore.test.ts covers the remote Admin arm. unit:firestore/update-field-paths.test.ts covers updateDoc, WriteBatch.update, Transaction.update, a transform and deleteField() at a literal-dot path, and the Admin-shaped DocumentReference.update, WriteBatch.update and Transaction.update; packages/cli/test/serve/worker/update-field-paths.test.ts covers the served worker, including rules that read the literal key. Argument validation is client-side SDK code with no server round trip, so its messages follow the Web SDK parseUpdateVarargs / fieldPathFromArgument and the Admin SDK WriteBatch.update sources: an odd field-and-value count, an empty segment, a reserved character, a non-string field, and an undefined value each throw the SDK's message. The Rules Test API takes request.resource as input and cannot show any of this, so the capture uses a client write. unit:firestore/sandbox/rules-test-case.test.ts, unit:sandbox/firestore/simulator/local-environment.test.ts, and unit:sandbox/firestore/simulator/project-after-state.test.ts pin the local projection.
Int/float distinction (1.5 is int→false, 1 is float→false, 1.0 is float→true) + integer division (10 / 4 == 2) + int div/mod-by-zero ERRORS (RULES-B5); strict int('12abc')/float('abc') parsing (RULES-B6 rest); bool() is not a Firestore rules function, so bool('true') is "Function not found error: Name: [bool]" and denies; string(1.0)→"1.0" (RULES-B12 rest)
unit:rules/simulator/evaluator.test.ts (RULES-B5 + "RULES-B6 remainder" blocks); unit:rules/simulator/handler.test.ts ("RULES-B5 end-to-end" block). Production's missing bool() is recorded by Firestore Rules row firestore-rules#191, whose capture rules-firestore-ast-strictness-and-unsupported-casts shows the error.
Strict boolean control flow matches production: non-booleans in &&, ||, or a ternary condition error and deny. Firestore double payloads retain float identity in the simulator (fractional JSON numbers are revived directly; { __type:'float', value } preserves an explicitly tagged double). On create, resource == null denies while request.resource exposes the incoming document.
Production behavior is recorded by Firestore Rules rows firestore-rules#188, firestore-rules#167, and firestore-rules#166. Direct evaluator/handler tests guard strict operands, fractional-number revival, the explicit float tag, and create-time resource verdicts on the SDK-facing simulator path. (Structured evidence: evaluator.test.ts, handler.test.ts)
Query-proof EVALUATION — the rules-side decision ("rules are not filters"): given a list rule + query constraints, decide provable-or-reject (a doc-dependent rule like resource.data.visibility == 'public' is provable ONLY with a matching where('visibility','==','public'); otherwise the whole query is rejected) (RULES-B11 rules-side)
Query-proof ENFORCEMENT wiring — RulesReadEngine routes one-shot and listener lists through RulesListAuthorizer and proveListQuery. Residual evaluation uses only the projected provable rules and query-pinned resource fields. Rejected-rule evidence remains available for denial diagnostics even when a provable fallback evaluates false. Full filter identity is diagnostic metadata; only supported constraints participate in proof. request.query.{limit,offset,orderBy} is populated on list test cases (RULES-B11; scope caveat: row 24c).
Local query support: unit:firestore/query-proof-application.test.ts covers finite membership, guardian array membership, pinned lookup paths, auth and limit controls, and adversarial array/lookup cases. Upstream semantics: firebase.google.com/docs/firestore/security/rules-query and firebase.google.com/docs/firestore/query-data/queries. Local diagnostic contract (#583): unit:firestore/query-proof-diagnostics.test.ts pins dynamic membership rejection, fallback attribution, constraint/residual distinctions, modular listener context, captured lifecycle errors, and immutable operation-summary proof metadata; this adds no production observation. unit:firestore/query-proof-enforcement.test.ts (both paths; verified failing pre-fix); prover scope caveat: row 24c

Calls in flight when the hosted connection drops

The web hosted client talks to the Node host over one WebSocket. When that socket drops, a call the socket had already taken is in flight: the host may or may not have run it (ADR-0019 decision 7). Each row here states what becomes of such a call, against what the production Web SDK does when its own connection drops.

Writes and reads in flight at a hosted connection drop (web hosted client)A Firestore write (setDoc, updateDoc, deleteDoc, a batch commit) or read (getDoc, getDocs) the web hosted client's socket had taken when it dropped fails once with unavailable and the message "The hosted sandbox connection was lost. Requests already sent may have completed; check state before retrying." It is not sent again. In production the Firestore Web SDK keeps a write in its mutation queue and sends it again on the next write stream until the backend acknowledges it, and answers a getDoc from its local cache, with fromCache, or fails it with unavailable when the document is not cached.
Production behavior read from @firebase/firestore 4.14.1, as recorded in ADR-0019 ("Reads and writes are treated alike, unlike production"). packages/cli/test/serve/worker/hosted-reconnect-hold.test.ts drops a real loopback socket with setDoc, getDoc and batchCommit in flight and asserts each fails once with that message and reaches the host once. The Realtime Database follows its SDK here instead (row rtdb-modular#HD1, #1088).
a write in flight fails instead of being sent again; pyric has no local cache to answer a read from

Client SDKs in a registered server process

A server process started with node --import @pyric/cli/register and PYRIC_SANDBOX=remote, remote:<url>, 1 or true runs the client SDKs against the Node host (#1082): firebase/app, firebase/database, firebase/firestore, firebase/auth and firebase/storage resolve to @pyric/cli’s Node client, which reaches the host over its own hosted connection with the process’s own signed-in session, so the host’s rules apply as they do for any other client. Off the Node host every call fails instead of running against a private in-process sandbox, and the client services with no path to the host refuse. PYRIC_SANDBOX=local keeps the in-process sandbox. In production the client SDKs run in Node and reach the project.

getFirestore(app) in a registered server processUnder a remote register activation on the Node host, firebase/firestore in a server process reads and writes the host's documents under its rules as the process's signed-in user. An open listener keeps the process up; a finished write releases it at once. A CommonJS require('firebase/firestore') resolves the same client. An app whose options differ from the host's gets each call rejected with app/multiple-configs-not-supported, and nothing throws past the call. When the host is not the Node host, every call fails with failed-precondition and a message naming the Node host (pyric sandbox --hosted or pyric({ hosted: true })); when no host is found, with the discovery error pyric-admin gets. No call falls back to an in-process sandbox.
App scenario test/apps/client-sdk-under-register runs the client SDKs under node --import @pyric/cli/register against a hosted Vite dev server, reads back with firebase-admin and a page, and asserts a write the page and firebase-admin read, a CommonJS require, an app with other options rejected per call, and that a listener holds the process while a finished write does not. On main (942cb175) it failed: the calls ran against a private in-process sandbox, so an upload returned a data: URL and firebase-admin read nothing they wrote. packages/cli/test/register/node-origin.test.ts runs the served surfaces under a Node origin whose host is not the Node host, or cannot be found, and asserts every call fails, useWorker stays true, the served app entry's placeholder sandbox stays empty, and a pyric/* mirror resolved from the app refuses. mapping.test.ts pins the mapping per activation value.. (Structured evidence: register-child.test.ts)
a finished write releases the process at once, where production holds it until the write stream's 60 s idle timeout; one configuration per runtime

Server-rendered modules under vite dev

Modules Vite loads for server rendering under vite dev with pyric() (server.ssrLoadModule, a runnable environment, a framework’s SSR entry and loaders) get the modules a registered server process gets (#1123): the client SDKs reach the dev server’s own Node host as one signed-in SSR session per dev server process, and firebase-admin reaches it as admin. This holds with Vite’s default externalization and with ssr.noExternal. A SharedWorker dev server refuses them, naming pyric({ hosted: true }), and a server environment Vite does not run in its own process (workerd) gets a module that throws when it loads. In production these modules run the Firebase SDKs in the server’s runtime and reach the project.

getFirestore(app) in a server-rendered module under vite devOn a hosted dev server, firebase/firestore in a server-rendered module reads and writes the host's documents under its rules as the SSR session's user: a write the rules deny for that user fails with permission-denied. ssrLoadModule, the environment runner and every ssr.noExternal setting share one app and one session. On a SharedWorker dev server every call fails with failed-precondition and a message naming pyric({ hosted: true }). No call reaches production or an in-process sandbox.
App scenario test/apps/vite-ssr-client-sdk writes and reads the SSR user's own document, is denied another user's, reads the writes back with firebase-admin in SSR and in a process on the host, with each externalization setting, and refuses on a SharedWorker dev server. On main (ba2c0bf0a) the scenario failed: SSR sign-in rejected with auth/network-request-failed from the network guard, and the RTDB, Firestore and Storage writes did not settle, because the imports loaded the real SDK. vite-module-swap.test.ts pins the routing per specifier, AI mode and environment (Vite 5's ssr option, a runnable environment, a non-runnable one), vite-ssr-activation.test.ts the host, the restart hand-over and the SharedWorker refusal, and vite-plugin-firestore.test.ts runs Vite with firebase installed, so it takes the externalized path. (Structured evidence: scenario.ts)
one SSR session per dev server process, as one Node server process has one auth state; per-request identity (initializeServerApp) is unsupported
firebase-admin/firestore in a server-rendered module under vite devOn a hosted dev server, firebase-admin/firestore in a server-rendered module reads and writes the dev server host's documents as admin, past the rules, as a firebase-admin process on the host does. On a SharedWorker dev server its first call fails with failed-precondition and a message naming pyric({ hosted: true }).
App scenario test/apps/vite-ssr-client-sdk reads a document the rules let only the SSR user read with firebase-admin in SSR through both loaders and with each externalization setting. On main (ba2c0bf0a) firebase-admin in SSR was the real SDK. ambient-init.test.ts pins the ambient binding. (Structured evidence: scenario.ts)
admin reads and writes bypass the rules, as firebase-admin's do

Behavior checked against production captures

Each row cites a production capture from the SDK behavior hunt. A bug row states production’s behavior and pyric’s; its test holds both answers until the fix lands.

getAggregateFromServer(query, { n: count(), s: sum(field) })Production: when count() is paired with sum(y), count includes only the docs that have y (3 of 4). Pyric counts every doc in the query (4). FL-27.
sum(field) / average(field) over NaN or InfinityProduction: sum and average over a field holding NaN return NaN, and over Infinity return Infinity. Pyric skips the non-finite values (sum 3 and average 1.5; sum 1 and average 1). FL-28.
getDocs / getAggregateFromServer on a shape that needs a composite indexProduction fails a query or multi-field aggregation that needs a missing composite index with failed-precondition. Pyric runs it by design; only the served dev chip signals it, and two-range, OR and aggregate shapes get no signal. FL-30.
oracle:firestore-query-composite-index-required (four shapes and two controls) and oracle:firestore-aggregate-field-semantics keys multi and nullField. Decided 2026-10-27: fix where production is clear; until then this row says they differ. (Structured evidence: firestore-query-composite-index-required.test.ts, firestore-aggregate-field-semantics.test.ts)
where(field, 'in' | 'not-in' | 'array-contains-any', values) / or(...)Production: getDocs fails with invalid-argument for in with 31 values, not-in with 11, array-contains-any with 31, or() with 31 branches, and 36 terms after normalization; 30 and 10 values succeed. Pyric runs every one. FL-29.
where(field, '==' | '!=', 0) with a -0 value stored-0 equals 0 in == and != but not in in, as in production. FL-31.
onSnapshot: per-doc metadata.hasPendingWrites on the local-write echoProduction: the echo of a local write reports hasPendingWrites true on the doc, for a doc listener and for the doc inside a query snapshot, and only on the written doc. Pyric reports false on the doc. FL-20.
QuerySnapshot.docChanges({ includeMetadataChanges: true }) on the ack snapshotProduction: the snapshot that acknowledges a local write lists the doc as modified with hasPendingWrites false. Pyric's list is empty. FL-21.
setDoc past the documented write limitsProduction fails with invalid-argument past its write limits (1 MiB docs, reserved or 1,501-byte ids and field names, 501 transforms, 26 nested maps); pyric stores them. FW-14.
writeBatch / runTransaction: delete then update of one docA batch or transaction that deletes and then updates one doc fails with invalid-argument and leaves the doc unchanged, as production does. Set then update and update then delete commit. Only the error text differs. The capture refuted hunt finding FW-19.
runTransaction when the update function swallows a read-after-write errorProduction: runTransaction rejects invalid-argument and writes nothing, even when the update function catches the read-after-write error and returns. Pyric resolves with the returned value and commits the write. FW-6.
runTransaction error codesProduction fails read-after-write and update-after-missing-read with invalid-argument; pyric gives failed-precondition and not-found. FW-7.
oracle:firestore-transaction-client-checks keys readAfterWrite and updateAfterReadMissing. (Structured evidence: firestore-transaction-client-checks.test.ts)
serverTimestamp() read from the pending local echoProduction's pending serverTimestamp echo is pending and reads null, or the estimate or prior value by option; pyric reads a resolved Timestamp. FW-10; also #1355.
setDoc that the rules deny, made while the network is disabledProduction keeps a denied offline write pending with a local event, then rejects after reconnect; pyric rejects at once. FW-17.
NaN, Infinity, -Infinity and -0 on the served planesProduction keeps NaN, Infinity, -Infinity and -0 on a server read, and == NaN matches only the NaN doc. The in-page sandbox agrees. On the SharedWorker and Node host planes they read back as null and 0. FP-1.
QueryDocumentSnapshot.metadata.hasPendingWrites on the served planesProduction: only the doc with a pending write reports hasPendingWrites true. The served planes report each doc's own value from the in-page engine, which reports false on the written doc (FL-20), and they skip the first snapshot from the cache (#1355). FP-5 is fixed.

Current gaps

Documented divergences

Known differences between Pyric and production Firebase. Each remains tracked as a non-conforming row.

getFirestore(app, databaseId)In the sandbox, getFirestore(app, databaseId) ignores the database id and returns the app's (default) handle, so documents written under one id are read under every other id.
packages/pyric/test/firestore/named-database.test.ts asserts two database ids return the (default) handle and that a document written under one id reads back under another. (Structured evidence: firestore-named-database-absent)
getFirestore(app, databaseId) (served mode)The served firebase/firestore entry ignores the database id: the worker path returns the app's one handle and the in-page fallback delegates to the sandbox getFirestore(app). The worker protocol carries no database id.
packages/cli/test/serve/worker/composite-filters-served-entry.test.ts imports the served entry over a worker host, asserts getFirestore(app, 'reports') returns the app's handle, and reads the (default) documents through it.
pyric-admin getFirestore(app, databaseId)pyric-admin getFirestore takes no database id; a second argument is ignored and the handle reads and writes (default). The Admin SDK's getFirestore(app, databaseId) selects the named database.
packages/pyric-admin/test/firestore/named-database.test.ts writes through getFirestore(app, 'reports') and reads the document through getFirestore(app) and getFirestore(app, 'archive'). (Structured evidence: firestore-named-database-admin-mixing)
Rules `match /databases/{database}/documents`Rules evaluate the database path variable as (default) for every request, whatever database id the handle was created with. Production binds the named database's id.
packages/pyric/test/firestore/named-database.test.ts writes through a handle created for reports: a rule requiring database == '(default)' allows the write and a rule requiring database == 'reports' denies it. (Structured evidence: firestore-named-database-rules-api, firestore-named-database-cross-database)
getDocs(query)Query-proof scope remains conservative. Equality and finite scalar in filters can pin candidate fields; array-contains proves the corresponding membership fact, not the whole array. Helpers and positive OR branches reduce to sufficient, candidate-independent residuals. Every finite combination (up to 30) must pass auth, query limits, and any lookup whose path is pinned by the query. Unpinned fields, candidate identity, dynamic document-dependent collections, unbounded range guarantees, and unsupported syntax remain deny-only gaps. Queries are never authorized by filtering stored rows. A collection-group query is authorized only by a top-level list or read rule at match /{path=**}/<collectionId>/{id} or match /{document=**} whose condition reads no path binding; any other shape, including a match nested in match /{document=**}, denies the query. This expanded local support has unit evidence and upstream documented semantics, but no new hosted observation.
Local query support: unit:firestore/query-proof-application.test.ts covers finite membership, guardian array membership, pinned lookup paths, auth and limit controls, and adversarial array/lookup cases. Upstream semantics: firebase.google.com/docs/firestore/security/rules-query and firebase.google.com/docs/firestore/query-data/queries. Local diagnostic contract (#583): unit:firestore/query-proof-diagnostics.test.ts pins dynamic membership rejection, fallback attribution, constraint/residual distinctions, modular listener context, captured lifecycle errors, and immutable operation-summary proof metadata; this adds no production observation. unit:rules/simulator/query-proof.test.ts (function-inlining provable cases; full-accounting rejections for mixed equality + in/get/hasOnly/range/is shapes in inline and helper form; fail-closed classifier probes: bracket-access resource['data'], exists() keyed by resource.data through path-literal segments, slice access, resource.id, and an unrecognized node shape), unit:firestore/query-proof-enforcement.test.ts (seeded end-to-end denials of the demonstrated attacks: forbidden-field absence check in member and bracket form, banned-owner exists() lookup, slice conjunct, each returning zero documents). Collection-group scope: unit:firestore/collection-group-rules.test.ts authorizes getDocs(collectionGroup(db, 'items')) under match /{path=**}/items/{id}, proves a data-gated rule from the query's equality, and denies under a rule for another collection id, a rule that reads the recursive binding, and concrete collection rules; unit:firestore/sandbox/collection-group-rule-proof.test.ts pins the projection. Upstream semantics: firebase.google.com/docs/firestore/security/rules-query#secure_and_query_documents_based_on_collection_groups. No hosted collection-group query is captured; the production matcher verdicts for the same rule shape, from the Rules Test API, live in oracle:rules-firestore-hierarchical-match-cascade.
Query constructionIndex validation against firestore.indexes.json — sandbox uses LocalEnvironment's lint pass; prod has its own server-side validation
divergence: sandbox can mis-pass a query that prod would reject at the server with failed-precondition if no index exists
AggregatesAggregates count documents server-side without paying read cost per doc in prod; sandbox computes locally (no cost model)
divergence: cost behavior differs, observable shape identical. Oracle-locked: packages/conformance/observations/firestore/firestore-count-aggregate-shape.json — getCountFromServer().data() returns { count: <number> } (single key, no other fields). Empty query returns count: 0 (not null/undefined); seeded 3 docs returns count: 3; filtered query honors the where constraint (count: 2).
enableIndexedDbPersistenceResolves before Firestore starts and rejects with failed-precondition after any operation has started the service
Real Chromium: firestore-browser-lifecycle.json; replayed through the public modular API by oracle-conformance.test.ts and focused lifecycle coverage. Served planes: an accepted no-op that resolves after first use (FP-9). (Structured evidence: persistence-network.test.ts, firestore-served-surface.test.ts)
enableNetwork / disableNetworkDisabling network exposes local mutations with cache/pending-write metadata while holding write acknowledgement until network is re-enabled
Real Chromium: firestore-browser-lifecycle.json; replayed through the public modular API by oracle-conformance.test.ts and focused network coverage. Served planes: accepted no-ops, so an offline write commits at once (FP-9). (Structured evidence: persistence-network.test.ts, firestore-served-surface.test.ts)
terminateTerminates only the selected Firestore service instance: held refs reject with failed-precondition, owned listeners stop, and sibling Firestore or Auth services remain usable
Real Chromium: packages/conformance/observations/firestore/firestore-browser-lifecycle.json records failed-precondition on the terminated instance while Auth and a sibling Firestore instance continue. Replayed by oracle-conformance.test.ts; focused ownership coverage in terminate.test.ts. SharedWorker: a no-op, so held refs keep working (FP-9).
initializeFirestoreDelegates to sandbox getFirestore(app) and returns the same handle. Accepts the settings argument (so the explicit-init pattern doesn't crash at import) but no-ops the cache/network settings — persistence is always on
persistentLocalCache / memoryLocalCache / persistentSingleTabManager / persistentMultipleTabManager / memoryEagerGarbageCollector / memoryLruGarbageCollectorConfig token accepted, inert — each returns a small tagged object so identity/usage doesn't crash. Persistence is the sandbox default; there is no cache tier left to configure
getDocFromCache / getDocsFromCacheExplicit cache reads distinguish cold and warm state: cold document reads reject with unavailable, cold queries return empty, and server/default reads populate subsequent cache reads
Real Chromium: firestore-browser-lifecycle.json captures cold and warm document and query cache behavior; oracle-conformance.test.ts replays it through public APIs. Served planes: reads the store, so a cold read resolves (FP-9). (Structured evidence: tier1-cache-init-align.test.ts, firestore-served-surface.test.ts)
setLogLevelAccepted no-op. The sandbox has no modular-SDK-style logger to wire a level into. It uses host-level console logging directly, gated by pyric sandbox's own flags, not this call
Writes and reads in flight at a hosted connection drop (web hosted client)A Firestore write (setDoc, updateDoc, deleteDoc, a batch commit) or read (getDoc, getDocs) the web hosted client's socket had taken when it dropped fails once with unavailable and the message "The hosted sandbox connection was lost. Requests already sent may have completed; check state before retrying." It is not sent again. In production the Firestore Web SDK keeps a write in its mutation queue and sends it again on the next write stream until the backend acknowledges it, and answers a getDoc from its local cache, with fromCache, or fails it with unavailable when the document is not cached.
Production behavior read from @firebase/firestore 4.14.1, as recorded in ADR-0019 ("Reads and writes are treated alike, unlike production"). packages/cli/test/serve/worker/hosted-reconnect-hold.test.ts drops a real loopback socket with setDoc, getDoc and batchCommit in flight and asserts each fails once with that message and reaches the host once. The Realtime Database follows its SDK here instead (row rtdb-modular#HD1, #1088).
getFirestore(app) in a registered server processUnder a remote register activation on the Node host, firebase/firestore in a server process reads and writes the host's documents under its rules as the process's signed-in user. An open listener keeps the process up; a finished write releases it at once. A CommonJS require('firebase/firestore') resolves the same client. An app whose options differ from the host's gets each call rejected with app/multiple-configs-not-supported, and nothing throws past the call. When the host is not the Node host, every call fails with failed-precondition and a message naming the Node host (pyric sandbox --hosted or pyric({ hosted: true })); when no host is found, with the discovery error pyric-admin gets. No call falls back to an in-process sandbox.
App scenario test/apps/client-sdk-under-register runs the client SDKs under node --import @pyric/cli/register against a hosted Vite dev server, reads back with firebase-admin and a page, and asserts a write the page and firebase-admin read, a CommonJS require, an app with other options rejected per call, and that a listener holds the process while a finished write does not. On main (942cb175) it failed: the calls ran against a private in-process sandbox, so an upload returned a data: URL and firebase-admin read nothing they wrote. packages/cli/test/register/node-origin.test.ts runs the served surfaces under a Node origin whose host is not the Node host, or cannot be found, and asserts every call fails, useWorker stays true, the served app entry's placeholder sandbox stays empty, and a pyric/* mirror resolved from the app refuses. mapping.test.ts pins the mapping per activation value.. (Structured evidence: register-child.test.ts)
getFirestore(app) in a server-rendered module under vite devOn a hosted dev server, firebase/firestore in a server-rendered module reads and writes the host's documents under its rules as the SSR session's user: a write the rules deny for that user fails with permission-denied. ssrLoadModule, the environment runner and every ssr.noExternal setting share one app and one session. On a SharedWorker dev server every call fails with failed-precondition and a message naming pyric({ hosted: true }). No call reaches production or an in-process sandbox.
App scenario test/apps/vite-ssr-client-sdk writes and reads the SSR user's own document, is denied another user's, reads the writes back with firebase-admin in SSR and in a process on the host, with each externalization setting, and refuses on a SharedWorker dev server. On main (ba2c0bf0a) the scenario failed: SSR sign-in rejected with auth/network-request-failed from the network guard, and the RTDB, Firestore and Storage writes did not settle, because the imports loaded the real SDK. vite-module-swap.test.ts pins the routing per specifier, AI mode and environment (Vite 5's ssr option, a runnable environment, a non-runnable one), vite-ssr-activation.test.ts the host, the restart hand-over and the SharedWorker refusal, and vite-plugin-firestore.test.ts runs Vite with firebase installed, so it takes the externalized path. (Structured evidence: scenario.ts)
firebase-admin/firestore in a server-rendered module under vite devOn a hosted dev server, firebase-admin/firestore in a server-rendered module reads and writes the dev server host's documents as admin, past the rules, as a firebase-admin process on the host does. On a SharedWorker dev server its first call fails with failed-precondition and a message naming pyric({ hosted: true }).
App scenario test/apps/vite-ssr-client-sdk reads a document the rules let only the SSR user read with firebase-admin in SSR through both loaders and with each externalization setting. On main (ba2c0bf0a) firebase-admin in SSR was the real SDK. ambient-init.test.ts pins the ambient binding. (Structured evidence: scenario.ts)
getDocs / getAggregateFromServer on a shape that needs a composite indexProduction fails a query or multi-field aggregation that needs a missing composite index with failed-precondition. Pyric runs it by design; only the served dev chip signals it, and two-range, OR and aggregate shapes get no signal. FL-30.
oracle:firestore-query-composite-index-required (four shapes and two controls) and oracle:firestore-aggregate-field-semantics keys multi and nullField. Decided 2026-10-27: fix where production is clear; until then this row says they differ. (Structured evidence: firestore-query-composite-index-required.test.ts, firestore-aggregate-field-semantics.test.ts)

Bugs

Behavior that should match production Firebase but currently does not.

getAggregateFromServer(query, { n: count(), s: sum(field) })Production: when count() is paired with sum(y), count includes only the docs that have y (3 of 4). Pyric counts every doc in the query (4). FL-27.
sum(field) / average(field) over NaN or InfinityProduction: sum and average over a field holding NaN return NaN, and over Infinity return Infinity. Pyric skips the non-finite values (sum 3 and average 1.5; sum 1 and average 1). FL-28.
where(field, 'in' | 'not-in' | 'array-contains-any', values) / or(...)Production: getDocs fails with invalid-argument for in with 31 values, not-in with 11, array-contains-any with 31, or() with 31 branches, and 36 terms after normalization; 30 and 10 values succeed. Pyric runs every one. FL-29.
onSnapshot: per-doc metadata.hasPendingWrites on the local-write echoProduction: the echo of a local write reports hasPendingWrites true on the doc, for a doc listener and for the doc inside a query snapshot, and only on the written doc. Pyric reports false on the doc. FL-20.
QuerySnapshot.docChanges({ includeMetadataChanges: true }) on the ack snapshotProduction: the snapshot that acknowledges a local write lists the doc as modified with hasPendingWrites false. Pyric's list is empty. FL-21.
setDoc past the documented write limitsProduction fails with invalid-argument past its write limits (1 MiB docs, reserved or 1,501-byte ids and field names, 501 transforms, 26 nested maps); pyric stores them. FW-14.
runTransaction when the update function swallows a read-after-write errorProduction: runTransaction rejects invalid-argument and writes nothing, even when the update function catches the read-after-write error and returns. Pyric resolves with the returned value and commits the write. FW-6.
runTransaction error codesProduction fails read-after-write and update-after-missing-read with invalid-argument; pyric gives failed-precondition and not-found. FW-7.
oracle:firestore-transaction-client-checks keys readAfterWrite and updateAfterReadMissing. (Structured evidence: firestore-transaction-client-checks.test.ts)
serverTimestamp() read from the pending local echoProduction's pending serverTimestamp echo is pending and reads null, or the estimate or prior value by option; pyric reads a resolved Timestamp. FW-10; also #1355.
setDoc that the rules deny, made while the network is disabledProduction keeps a denied offline write pending with a local event, then rejects after reconnect; pyric rejects at once. FW-17.
NaN, Infinity, -Infinity and -0 on the served planesProduction keeps NaN, Infinity, -Infinity and -0 on a server read, and == NaN matches only the NaN doc. The in-page sandbox agrees. On the SharedWorker and Node host planes they read back as null and 0. FP-1.
QueryDocumentSnapshot.metadata.hasPendingWrites on the served planesProduction: only the doc with a pending write reports hasPendingWrites true. The served planes report each doc's own value from the in-page engine, which reports false on the written doc (FL-20), and they skip the first snapshot from the cache (#1355). FP-5 is fixed.

Reviewed public-runtime gaps

firestore.min-max-aggregatesThe maximum and minimum aggregates are new in firebase 12.19.0 and belong next to sum and average in the aggregate engine; implementing them is tracked in #1672.
maximum minimum
upstream:firebase/firestore@4.17.2