diff --git a/sdk/typescript/src/client.test.ts b/sdk/typescript/src/client.test.ts index dc894439..f1189128 100644 --- a/sdk/typescript/src/client.test.ts +++ b/sdk/typescript/src/client.test.ts @@ -338,7 +338,7 @@ describe("ZyncBaseClient", () => { ); const handle = await pendingListen; await new Promise((r) => setTimeout(r, 0)); - expect(values).toEqual([]); + expect(values).toEqual([null]); // A namespace switch re-runs the replay path without dropping the socket. const switching = client.setStoreNamespace("other"); @@ -375,6 +375,7 @@ describe("ZyncBaseClient", () => { // The remapped document listen receives its snapshot again. expect(values).toEqual([ + null, { id: userId, namespace_id: 1, @@ -442,8 +443,9 @@ describe("ZyncBaseClient", () => { ], }), ); - await waitFor(() => values.length === 1); - expect(values[0]).toMatchObject({ name: "Ada" }); + await waitFor(() => values.length === 2); + expect(values[0]).toBeNull(); + expect(values[1]).toMatchObject({ name: "Ada" }); client.disconnect(); restoreWebSocket(); diff --git a/sdk/typescript/src/filter_eval.test.ts b/sdk/typescript/src/filter_eval.test.ts new file mode 100644 index 00000000..d0fcd427 --- /dev/null +++ b/sdk/typescript/src/filter_eval.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, test } from "bun:test"; +import { compileWhere } from "./filter_eval.js"; +import { + FILTER_VECTOR_DOC_ID_FIELDS, + FILTER_VECTOR_RECORDS, + FILTER_VECTORS, +} from "./filter_eval.vectors.js"; +import { encodeQueryOptions } from "./store_wire.js"; + +const isDocIdField = (field: string) => FILTER_VECTOR_DOC_ID_FIELDS.has(field); + +describe("compileWhere", () => { + for (const vector of FILTER_VECTORS) { + test(vector.name, () => { + const matches = compileWhere( + encodeQueryOptions({ where: vector.where }), + isDocIdField, + ); + const ids = FILTER_VECTOR_RECORDS.filter(matches).map((r) => r.id); + expect(ids.sort()).toEqual([...vector.expected].sort()); + }); + } + + test("a missing field reads as null", () => { + const matches = compileWhere( + encodeQueryOptions({ where: { score: { isNull: true } } }), + isDocIdField, + ); + expect(matches({ id: "x" })).toBe(true); + expect(matches({ id: "x", score: 1 })).toBe(false); + }); + + test("array equality ignores order and duplicates on the record side", () => { + const matches = compileWhere( + encodeQueryOptions({ where: { tags: ["a", "b"] } }), + isDocIdField, + ); + expect(matches({ tags: ["b", "a", "b"] })).toBe(true); + }); + + test("binary operands are snapshotted when the predicate is compiled", () => { + const bytes = new Uint8Array([1, 2, 3]); + const eq = compileWhere( + encodeQueryOptions({ where: { coordinates: bytes } }), + isDocIdField, + ); + const ne = compileWhere( + encodeQueryOptions({ where: { coordinates: { ne: bytes } } }), + isDocIdField, + ); + + bytes[0] = 9; + + expect(eq({ coordinates: new Uint8Array([1, 2, 3]) })).toBe(true); + expect(eq({ coordinates: new Uint8Array([9, 2, 3]) })).toBe(false); + expect(ne({ coordinates: new Uint8Array([1, 2, 3]) })).toBe(false); + expect(ne({ coordinates: new Uint8Array([9, 2, 3]) })).toBe(true); + }); +}); diff --git a/sdk/typescript/src/filter_eval.ts b/sdk/typescript/src/filter_eval.ts new file mode 100644 index 00000000..34fa3d17 --- /dev/null +++ b/sdk/typescript/src/filter_eval.ts @@ -0,0 +1,156 @@ +import { getDeepProperty, splitFieldPath } from "./path.js"; +import { OP_CODES, type WireCondition } from "./store_wire.js"; +import type { JsonValue } from "./types.js"; +import { compareScalars, scalarsEqual, sortedSet } from "./value_order.js"; + +/** Whether a record belongs in a view; the server's delta matching, client side. */ +export type RecordMatcher = (record: JsonValue) => boolean; + +type Condition = WireCondition | [string, number, JsonValue?]; + +/** A wire `where`, as `encodeQueryOptions` builds it. */ +export interface WireWhere { + conditions?: readonly Condition[]; + orConditions?: readonly Condition[]; +} + +type ValueTest = (value: JsonValue) => boolean; + +const ORDERINGS: Record boolean> = { + [OP_CODES.gt]: (order) => order > 0, + [OP_CODES.lt]: (order) => order < 0, + [OP_CODES.gte]: (order) => order >= 0, + [OP_CODES.lte]: (order) => order <= 0, +}; + +/** + * Compiles a wire `where` into a matcher: every condition holds, and when + * `orConditions` is present at least one of them holds. `isDocIdField` + * reports whether a flat field name holds document ids. + */ +export function compileWhere( + where: WireWhere, + isDocIdField: (field: string) => boolean, +): RecordMatcher { + const all = (where.conditions ?? []).map((c) => + compileCondition(c, isDocIdField), + ); + const any = (where.orConditions ?? []).map((c) => + compileCondition(c, isDocIdField), + ); + return (record) => + all.every((matches) => matches(record)) && + (any.length === 0 || any.some((matches) => matches(record))); +} + +function compileCondition( + [field, op, operand = null]: Condition, + isDocIdField: (field: string) => boolean, +): RecordMatcher { + const parts = splitFieldPath(field); + const test = compileTest(op, operand, isDocIdField(field)); + return (record) => test(getDeepProperty(record, parts) ?? null); +} + +function compileTest( + op: number, + operand: JsonValue, + docId: boolean, +): ValueTest { + switch (op) { + case OP_CODES.isNull: + return (value) => value === null; + case OP_CODES.isNotNull: + return (value) => value !== null; + case OP_CODES.eq: + return compileEquality(operand, docId, false); + case OP_CODES.ne: + return compileEquality(operand, docId, true); + case OP_CODES.in: + return compileMembership(operand as JsonValue[], false); + case OP_CODES.notIn: + return compileMembership(operand as JsonValue[], true); + case OP_CODES.contains: + return compileContains(operand); + case OP_CODES.startsWith: + return compileText(operand, (value, needle) => value.startsWith(needle)); + case OP_CODES.endsWith: + return compileText(operand, (value, needle) => value.endsWith(needle)); + default: + return compileOrdering(ORDERINGS[op], operand, docId); + } +} + +/** Null fails both `eq` and `ne`; arrays compare as sorted sets. */ +function compileEquality( + operand: JsonValue, + docId: boolean, + negate: boolean, +): ValueTest { + const expected = snapshotBinary(operand); + const equals: ValueTest = Array.isArray(expected) + ? setEquals(sortedSet(expected, docId), docId) + : (value) => scalarsEqual(value, expected); + return (value) => value !== null && equals(value) !== negate; +} + +/** Snapshot bytes so later caller mutations cannot change a compiled predicate. */ +function snapshotBinary(value: JsonValue): JsonValue { + if (value instanceof Uint8Array) return value.slice(); + if (Array.isArray(value)) return value.map(snapshotBinary); + return value; +} + +function setEquals(expected: JsonValue[], docId: boolean): ValueTest { + return (value) => { + if (!Array.isArray(value)) return false; + const actual = sortedSet(value, docId); + return ( + actual.length === expected.length && + actual.every((item, i) => scalarsEqual(item, expected[i])) + ); + }; +} + +/** `in []` matches nothing and `notIn []` everything, null included; otherwise null fails both. */ +function compileMembership(members: JsonValue[], negate: boolean): ValueTest { + if (members.length === 0) return () => negate; + const set = new Set(members); + return (value) => value !== null && set.has(value) !== negate; +} + +/** Exact element membership on arrays; ASCII case-insensitive substring on text. */ +function compileContains(operand: JsonValue): ValueTest { + const text = compileText(operand, (value, needle) => value.includes(needle)); + return (value) => + Array.isArray(value) + ? value.some((item) => scalarsEqual(item, operand)) + : text(value); +} + +function compileText( + operand: JsonValue, + matches: (value: string, needle: string) => boolean, +): ValueTest { + const needle = typeof operand === "string" ? foldAscii(operand) : null; + return (value) => + typeof value === "string" && + needle !== null && + matches(foldAscii(value), needle); +} + +function compileOrdering( + accepts: (order: number) => boolean, + operand: JsonValue, + docId: boolean, +): ValueTest { + return (value) => + value !== null && + typeof value === typeof operand && + accepts(compareScalars(value, operand, docId)); +} + +/** Lowercases A-Z only, like the server's ASCII case-insensitive matching. */ +function foldAscii(value: string): string { + return value.replace(/[A-Z]/g, (char) => char.toLowerCase()); +} diff --git a/sdk/typescript/src/filter_eval.vectors.ts b/sdk/typescript/src/filter_eval.vectors.ts new file mode 100644 index 00000000..6c20e24c --- /dev/null +++ b/sdk/typescript/src/filter_eval.vectors.ts @@ -0,0 +1,211 @@ +// Filter matching vectors shared by the evaluator unit test and the e2e +// conformance suite, which runs them against a live server. + +import type { JsonValue, QueryOptions } from "./types.js"; + +export interface FilterVector { + name: string; + where: NonNullable; + /** Matching record ids, in any order. */ + expected: string[]; +} + +/** The doc-id field of the vector collection; everything else is a plain value. */ +export const FILTER_VECTOR_DOC_ID_FIELDS: ReadonlySet = new Set(["id"]); + +const UUID = "01936b2e-1e85-7000-8000-000000000005"; +const ALL = ["r1", "r2", "r3", "r4", UUID]; + +export const FILTER_VECTOR_RECORDS: Array< + { id: string } & Record +> = [ + { + id: "r1", + name: "Alpha", + label: "\uff21", + score: 10, + ratio: 1.5, + active: true, + tags: ["a", "b"], + meta: { rank: 1 }, + }, + { + id: "r2", + name: "alphabet", + label: "\u{1f600}", + score: 5, + ratio: -2, + active: false, + tags: ["b"], + meta: { rank: null }, + }, + { + id: "r3", + name: "Ärger", + label: null, + score: null, + ratio: null, + active: null, + tags: null, + meta: { rank: 3 }, + }, + { + id: "r4", + name: null, + label: null, + score: 0, + ratio: 0, + active: true, + tags: [], + meta: { rank: 2 }, + }, + { + id: UUID, + name: "beta_%", + label: "a", + score: 7, + ratio: 0.5, + active: false, + tags: ["c"], + meta: { rank: null }, + }, +]; + +export const FILTER_VECTORS: FilterVector[] = [ + { + name: "eq on text is case-sensitive", + where: { name: "alpha" }, + expected: [], + }, + { name: "eq on text", where: { name: "Alpha" }, expected: ["r1"] }, + { + name: "ne skips null", + where: { score: { ne: 5 } }, + expected: ["r1", "r4", UUID], + }, + { + name: "lt skips null", + where: { score: { lt: 6 } }, + expected: ["r2", "r4"], + }, + { + name: "gte on a real field", + where: { ratio: { gte: 0 } }, + expected: ["r1", "r4", UUID], + }, + { name: "isNull", where: { score: { isNull: true } }, expected: ["r3"] }, + { + name: "isNotNull", + where: { name: { isNotNull: true } }, + expected: ["r1", "r2", "r3", UUID], + }, + { + name: "startsWith folds ASCII case", + where: { name: { startsWith: "ALPHA" } }, + expected: ["r1", "r2"], + }, + { + name: "startsWith does not fold non-ASCII case", + where: { name: { startsWith: "ä" } }, + expected: [], + }, + { + name: "startsWith matches non-ASCII exactly", + where: { name: { startsWith: "Är" } }, + expected: ["r3"], + }, + { + name: "endsWith folds ASCII case", + where: { name: { endsWith: "BET" } }, + expected: ["r2"], + }, + { + name: "contains treats % and _ literally", + where: { name: { contains: "a_" } }, + expected: [UUID], + }, + { + name: "an empty needle matches every non-null text", + where: { name: { startsWith: "" } }, + expected: ["r1", "r2", "r3", UUID], + }, + { + name: "contains on an array is exact membership", + where: { tags: { contains: "a" } }, + expected: ["r1"], + }, + { + name: "contains on an array is case-sensitive", + where: { tags: { contains: "A" } }, + expected: [], + }, + { + name: "eq on an array compares sets", + where: { tags: ["b", "a"] }, + expected: ["r1"], + }, + { name: "eq on an empty array", where: { tags: [] }, expected: ["r4"] }, + { + name: "ne on an array skips null", + where: { tags: { ne: ["b"] } }, + expected: ["r1", "r4", UUID], + }, + { name: "in", where: { score: { in: [5, 0] } }, expected: ["r2", "r4"] }, + { + name: "notIn skips null", + where: { score: { notIn: [5] } }, + expected: ["r1", "r4", UUID], + }, + { name: "in [] matches nothing", where: { score: { in: [] } }, expected: [] }, + { + name: "notIn [] matches everything, null included", + where: { score: { notIn: [] } }, + expected: ALL, + }, + { name: "eq on a boolean", where: { active: false }, expected: ["r2", UUID] }, + { + name: "gt on a boolean", + where: { active: { gt: false } }, + expected: ["r1", "r4"], + }, + { + name: "nested field", + where: { meta: { rank: { gte: 2 } } }, + expected: ["r3", "r4"], + }, + { + name: "text orders by UTF-8 bytes", + where: { label: { gt: "\uff21" } }, + expected: ["r2"], + }, + { + name: "doc ids order short ids before UUIDs", + where: { id: { gt: "r4" } }, + expected: [UUID], + }, + { + name: "doc ids order short ids by their characters", + where: { id: { lt: "r2" } }, + expected: ["r1"], + }, + { + name: "or", + where: { or: [{ score: 10 }, { name: { isNull: true } }] }, + expected: ["r1", "r4"], + }, + { + name: "and with or", + where: { active: true, or: [{ score: 0 }, { tags: { contains: "a" } }] }, + expected: ["r1", "r4"], + }, + { + name: "an or branch with notIn [] always holds", + where: { or: [{ score: 99 }, { score: { notIn: [] } }] }, + expected: ALL, + }, + { + name: "an or of only in [] matches nothing", + where: { or: [{ score: { in: [] } }] }, + expected: [], + }, +]; diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts index 3d59d1c8..196176b6 100644 --- a/sdk/typescript/src/index.ts +++ b/sdk/typescript/src/index.ts @@ -35,6 +35,7 @@ export type { JsonValue, LifecycleEvent, ListenHandle, + ListenMeta, Path, Presence, PresenceEntry, @@ -47,10 +48,12 @@ export type { StatusDetail, Store, SubscriptionHandle, + SubscriptionMeta, TicketResponse, TypedOrderClause, TypedQueryOptions, TypedWhere, WhereOperators, + WriteOptions, } from "./types.js"; export { generateUUIDv7 } from "./uuid.js"; diff --git a/sdk/typescript/src/optimistic.test.ts b/sdk/typescript/src/optimistic.test.ts new file mode 100644 index 00000000..baebee9d --- /dev/null +++ b/sdk/typescript/src/optimistic.test.ts @@ -0,0 +1,399 @@ +import { describe, expect, test } from "bun:test"; +import { + type OverlayContext, + type OverlayOp, + overlayOps, + PendingWrites, +} from "./optimistic.js"; +import { SchemaDictionary } from "./schema_dictionary.js"; + +const TODO_FIELDS = [ + "id", + "namespace_id", + "owner_id", + "title", + "count", + "tags", + "refs", + "data", + "address__city", + "address__zip", + "created_at", + "updated_at", +]; + +async function makeContext(time = 100): Promise { + const schema = new SchemaDictionary(); + await schema.processSchemaSync({ + version: "1.0.0", + tables: ["todos", "users"], + fields: [ + TODO_FIELDS, + ["id", "namespace_id", "owner_id", "name", "created_at", "updated_at"], + ], + fieldFlags: [ + [0b11, 0b01, 0b11, 0, 0, 0, 0b10, 0, 0, 0, 0b01, 0b01], + [0b11, 0b01, 0b11, 0, 0b01, 0b01], + ], + }); + return { schema, userId: "me", time }; +} + +const BASE = { + id: "t1", + title: "old", + count: 1, + address: { city: "Oslo", zip: "0150" }, + updated_at: 5, +}; + +function set( + id: string, + patch: Record, +): OverlayOp { + return { kind: "set", collection: "todos", id, patch }; +} + +describe("PendingWrites.apply", () => { + test("set merges into the server record", () => { + const pending = new PendingWrites(); + pending.add([set("t1", { title: "new" })]); + expect(pending.apply("todos", "t1", BASE)).toEqual({ + ...BASE, + title: "new", + }); + }); + + test("set on an unknown document shows nothing", () => { + const pending = new PendingWrites(); + pending.add([set("t1", { title: "new" })]); + expect(pending.apply("todos", "t1", null)).toBeNull(); + }); + + test("a set after a pending create applies to the created row", () => { + const pending = new PendingWrites(); + pending.add([ + { + kind: "create", + collection: "todos", + id: "t1", + record: { id: "t1", title: "a" }, + }, + ]); + pending.add([set("t1", { title: "b" })]); + expect(pending.apply("todos", "t1", null)).toEqual({ + id: "t1", + title: "b", + }); + }); + + test("remove hides the document", () => { + const pending = new PendingWrites(); + pending.add([{ kind: "remove", collection: "todos", id: "t1" }]); + expect(pending.apply("todos", "t1", BASE)).toBeNull(); + }); + + test("increment applies only to a number", () => { + const pending = new PendingWrites(); + const op: OverlayOp = { + kind: "increment", + collection: "todos", + id: "t1", + field: "count", + by: 2, + time: 9, + }; + pending.add([op, { ...op, field: "title" }]); + expect(pending.apply("todos", "t1", BASE)).toEqual({ + ...BASE, + count: 3, + updated_at: 9, + }); + expect(pending.apply("todos", "t1", { ...BASE, count: null })).toEqual({ + ...BASE, + count: null, + }); + }); + + test("increment reconciliation survives records without a revision", () => { + const pending = new PendingWrites(); + const increment = (by: number): OverlayOp => ({ + kind: "increment", + collection: "todos", + id: "t1", + field: "count", + by, + time: 9, + }); + const base = { id: "t1", count: 0 }; + const first = pending.add([increment(1)]); + pending.add([increment(1)]); + + expect(pending.apply("todos", "t1", base)).toMatchObject({ count: 2 }); + const committed = { ...base, count: 2 }; + expect(pending.apply("todos", "t1", committed)).toMatchObject({ + count: 2, + }); + + pending.commit(first); + expect(pending.apply("todos", "t1", committed)).toMatchObject({ + count: 2, + }); + expect(pending.apply("todos", "t1", base)).toMatchObject({ count: 1 }); + }); + + test("an unchanged base does not mark a zero-sum prefix reflected", () => { + const pending = new PendingWrites(); + const increment = (by: number): OverlayOp => ({ + kind: "increment", + collection: "todos", + id: "t1", + field: "count", + by, + time: 9, + }); + pending.add([increment(1)]); + pending.add([increment(-1)]); + + expect(pending.apply("todos", "t1", { ...BASE, count: 0 })).toMatchObject({ + count: 0, + }); + expect( + pending.apply("todos", "t1", { + ...BASE, + count: 1, + updated_at: 6, + }), + ).toMatchObject({ count: 0 }); + }); + + test("an older base does not reset a newer reconciliation", () => { + const pending = new PendingWrites(); + const increment = (): OverlayOp => ({ + kind: "increment", + collection: "todos", + id: "t1", + field: "count", + by: 1, + time: 9, + }); + pending.add([increment()]); + pending.add([increment()]); + pending.add([increment()]); + + const base = { ...BASE, count: 0, updated_at: 0 }; + expect(pending.apply("todos", "t1", base)).toMatchObject({ count: 3 }); + expect( + pending.apply("todos", "t1", { ...BASE, count: 2, updated_at: 2 }), + ).toMatchObject({ count: 3 }); + expect(pending.apply("todos", "t1", base)).toMatchObject({ count: 3 }); + expect( + pending.apply("todos", "t1", { ...BASE, count: 3, updated_at: 3 }), + ).toMatchObject({ count: 3 }); + }); + + test("writes apply in send order", () => { + const pending = new PendingWrites(); + pending.add([set("t1", { title: "first" })]); + pending.add([set("t1", { title: "second" })]); + expect(pending.apply("todos", "t1", BASE)).toMatchObject({ + title: "second", + }); + }); +}); + +describe("PendingWrites settlement", () => { + test("a commit settles every earlier write on the same documents", () => { + const pending = new PendingWrites(); + pending.add([set("t1", { title: "a" }), set("t2", { title: "a" })]); + const second = pending.add([set("t1", { title: "b" })]); + const keys = pending.commit(second); + expect(keys).toEqual(new Map([["todos", new Set(["t1"])]])); + expect(pending.has("todos", "t1")).toBe(false); + expect(pending.has("todos", "t2")).toBe(true); + }); + + test("a commit leaves later writes pending", () => { + const pending = new PendingWrites(); + const first = pending.add([set("t1", { title: "a" })]); + pending.add([set("t1", { title: "b" })]); + pending.commit(first); + expect(pending.apply("todos", "t1", BASE)).toMatchObject({ title: "b" }); + }); + + test("a failure settles only that write", () => { + const pending = new PendingWrites(); + pending.add([set("t1", { title: "a" })]); + const second = pending.add([set("t1", { title: "b" })]); + pending.fail(second); + expect(pending.apply("todos", "t1", BASE)).toMatchObject({ title: "a" }); + }); + + test("settling a cleared write is a no-op", () => { + const pending = new PendingWrites(); + const entry = pending.add([set("t1", { title: "a" })]); + expect(pending.clear()).toEqual(new Map([["todos", new Set(["t1"])]])); + pending.commit(entry); + expect(pending.has("todos", "t1")).toBe(false); + }); +}); + +describe("overlayOps", () => { + test("conditional writes are never optimistic", async () => { + const context = await makeContext(); + const ifWire = { + conditions: [["title", 0, "x"]] as [string, number, string][], + }; + expect( + overlayOps( + { type: "StoreSet", path: ["todos", "t1"], value: {}, if: ifWire }, + false, + context, + ), + ).toBeNull(); + expect( + overlayOps( + { type: "StoreRemove", path: ["todos", "t1"], if: ifWire }, + false, + context, + ), + ).toBeNull(); + expect( + overlayOps( + { + type: "StoreBatch", + ops: [ + ["r", ["todos", "t1"]], + ["i", ["todos", "t2"], "count", 1, ifWire], + ], + }, + false, + context, + ), + ).toBeNull(); + }); + + test("a set expands null namespaces, sorts arrays and bumps updated_at", async () => { + const context = await makeContext(42); + const ops = overlayOps( + { + type: "StoreSet", + path: ["todos", "t1"], + value: { + address: null, + address__zip: "1", + tags: ["b", "a", "b"], + refs: ["u2", "u10"], + }, + }, + false, + context, + ); + expect(ops).toEqual([ + { + kind: "set", + collection: "todos", + id: "t1", + patch: { + address__city: null, + address__zip: "1", + tags: ["a", "b"], + refs: ["u10", "u2"], + updated_at: 42, + }, + }, + ]); + }); + + test("a set copies byte buffers into the pending patch", async () => { + const context = await makeContext(42); + const bytes = new Uint8Array([1, 2, 3]); + const [op] = + overlayOps( + { type: "StoreSet", path: ["todos", "t1"], value: { data: bytes } }, + false, + context, + ) ?? []; + + bytes[0] = 9; + + expect(op?.kind === "set" ? op.patch.data : null).toEqual( + new Uint8Array([1, 2, 3]), + ); + expect(op?.kind === "set" ? op.patch.data : null).not.toBe(bytes); + }); + + test("a create shapes a complete row with provisional system fields", async () => { + const context = await makeContext(42); + const [op] = + overlayOps( + { type: "StoreSet", path: ["todos", "t1"], value: { title: "a" } }, + true, + context, + ) ?? []; + expect(op).toEqual({ + kind: "create", + collection: "todos", + id: "t1", + record: { + id: "t1", + namespace_id: null, + owner_id: "me", + title: "a", + count: null, + tags: null, + refs: null, + data: null, + address__city: null, + address__zip: null, + created_at: 42, + updated_at: 42, + }, + }); + }); + + test("a created user owns itself", async () => { + const context = await makeContext(); + const [op] = + overlayOps( + { type: "StoreSet", path: ["users", "u1"], value: { name: "a" } }, + true, + context, + ) ?? []; + expect(op?.kind === "create" && op.record.owner_id).toBe("u1"); + }); + + test("a batch becomes one op per write", async () => { + const context = await makeContext(7); + expect( + overlayOps( + { + type: "StoreBatch", + ops: [ + ["s", ["todos", "t1"], { title: "a" }], + ["r", ["todos", "t2"]], + ["i", ["todos", "t3"], "count", 2], + ], + }, + false, + context, + ), + ).toEqual([ + { + kind: "set", + collection: "todos", + id: "t1", + patch: { title: "a", updated_at: 7 }, + }, + { kind: "remove", collection: "todos", id: "t2" }, + { + kind: "increment", + collection: "todos", + id: "t3", + field: "count", + by: 2, + time: 7, + }, + ]); + }); +}); diff --git a/sdk/typescript/src/optimistic.ts b/sdk/typescript/src/optimistic.ts new file mode 100644 index 00000000..7cdcf73e --- /dev/null +++ b/sdk/typescript/src/optimistic.ts @@ -0,0 +1,543 @@ +// Pending local writes, applied over server records until they settle. + +import type { OutboundRequest } from "./connection_wire.js"; +import { flatten, unflatten } from "./path.js"; +import type { SchemaDictionary } from "./schema_dictionary.js"; +import type { JsonValue } from "./types.js"; +import { sortedSet } from "./value_order.js"; + +type Flat = Record; + +/** One document change of a write, in the flat `__` field form. */ +export type OverlayOp = + | { kind: "create"; collection: string; id: string; record: Flat } + | { kind: "set"; collection: string; id: string; patch: Flat } + | { kind: "remove"; collection: string; id: string } + | { + kind: "increment"; + collection: string; + id: string; + field: string; + by: number; + time: number; + }; + +/** Documents touched by writes: collection → ids. */ +export type OverlayKeys = Map>; + +/** A write's handle in `PendingWrites`. */ +export interface PendingEntry { + readonly seq: number; + readonly keys: OverlayKeys; +} + +interface KeyOps { + seq: number; + ops: OverlayOp[]; +} + +type IncrementOp = Extract; + +/** Where a pending increment sits relative to the committed record. */ +interface IncrementState { + /** Committed field value from which this increment is not yet reflected. */ + base?: number; + /** Latest server revision (`updated_at`) used for reconciliation. */ + observedAt?: number; + /** Server revision (`updated_at`) that already includes the increment. */ + reflectedAt?: number; + /** Committed field value that included it, when no revision is available. */ + reflectedValue?: number; +} + +/** + * Pending writes per document, in send order. The server applies writes in + * send order and never retries one, so a commit also settles every earlier + * write's changes to the same documents: they are applied or failed already. + */ +export class PendingWrites { + private readonly docs = new Map>(); + private readonly incrementStates = new WeakMap(); + private seq = 0; + + add(ops: readonly OverlayOp[]): PendingEntry { + const seq = ++this.seq; + const keys: OverlayKeys = new Map(); + for (const op of ops) { + const ids = keys.get(op.collection) ?? new Set(); + keys.set(op.collection, ids.add(op.id)); + const byId = this.docs.get(op.collection) ?? new Map(); + this.docs.set(op.collection, byId); + const list = byId.get(op.id) ?? []; + byId.set(op.id, list); + const last = list[list.length - 1]; + if (last?.seq === seq) last.ops.push(op); + else list.push({ seq, ops: [op] }); + } + return { seq, keys }; + } + + /** The write committed: drop it and every earlier write on its documents. */ + commit(entry: PendingEntry): OverlayKeys { + return this.drop(entry, (ops) => ops.seq <= entry.seq, true); + } + + /** The write failed: drop only it. */ + fail(entry: PendingEntry): OverlayKeys { + return this.drop(entry, (ops) => ops.seq === entry.seq, false); + } + + /** Drop every pending write; returns the documents they touched. */ + clear(): OverlayKeys { + const keys: OverlayKeys = new Map(); + for (const [collection, byId] of this.docs) { + keys.set(collection, new Set(byId.keys())); + } + this.docs.clear(); + return keys; + } + + has(collection: string, id: string): boolean { + return this.docs.get(collection)?.has(id) ?? false; + } + + /** Whether any document in `collection` has a pending write. */ + touches(collection: string): boolean { + return this.docs.has(collection); + } + + /** Ids in `collection` with pending writes. */ + ids(collection: string): Iterable { + return this.docs.get(collection)?.keys() ?? []; + } + + /** + * Applies the document's pending writes, in send order, to `base` (the + * server record, or null when unknown or absent). Returns null when the + * result is no document. + */ + apply( + collection: string, + id: string, + base: JsonValue | null, + ): JsonValue | null { + let value = isRecord(base) ? flatten(base) : null; + const entries = this.docs.get(collection)?.get(id) ?? []; + const skip = + value === null || !hasIncrement(entries) + ? undefined + : this.reconcile(collection, id, value); + for (const { ops } of entries) { + for (const op of ops) { + if (skip?.has(op)) continue; + value = applyOp(value, op); + } + } + return value === null ? null : unflatten(value); + } + + /** + * Marks pending increments the committed record already includes. A delta + * can carry one or several pending increments; those form a prefix whose + * cumulative `by` matches the committed field value. + */ + private reconcile( + collection: string, + id: string, + base: Flat, + ): ReadonlySet { + const skip = new Set(); + const revision = + typeof base.updated_at === "number" ? base.updated_at : undefined; + for (const [field, ops] of this.incrementsByField(collection, id)) { + const baseValue = base[field]; + if (typeof baseValue === "number") { + this.reconcileField(skip, ops, baseValue, revision); + } + } + return skip; + } + + private incrementsByField( + collection: string, + id: string, + ): Map { + const byField = new Map(); + for (const { ops } of this.docs.get(collection)?.get(id) ?? []) { + for (const op of ops) { + if (op.kind !== "increment") continue; + const list = byField.get(op.field) ?? []; + byField.set(op.field, list); + list.push(op); + } + } + return byField; + } + + private reconcileField( + skip: Set, + ops: IncrementOp[], + baseValue: number, + revision: number | undefined, + ): void { + const candidates: IncrementOp[] = []; + let stale = false; + for (const op of ops) { + const state = this.incrementState(op); + if (this.isReflected(state, revision, baseValue)) { + skip.add(op); + continue; + } + if (this.isStaleObservation(state, revision)) { + stale = true; + continue; + } + if (state.base === undefined) state.base = baseValue; + candidates.push(op); + } + // An older record is still projected, but it must not learn over a + // newer observation. + if (stale || candidates.length === 0) return; + const matched = this.matchIncrementPrefix(candidates, baseValue); + if (matched < 0) { + this.rebaseIncrements(candidates, 0, baseValue, revision); + return; + } + this.markReflected(skip, candidates, matched, baseValue, revision); + this.rebaseIncrements(candidates, matched + 1, baseValue, revision); + } + + private isStaleObservation( + state: IncrementState, + revision: number | undefined, + ): boolean { + return ( + revision !== undefined && + state.observedAt !== undefined && + revision < state.observedAt + ); + } + + private isReflected( + state: IncrementState, + revision: number | undefined, + baseValue: number, + ): boolean { + if (revision !== undefined && state.reflectedAt !== undefined) { + return revision >= state.reflectedAt; + } + return ( + state.reflectedValue !== undefined && state.reflectedValue === baseValue + ); + } + + private matchIncrementPrefix(ops: IncrementOp[], baseValue: number): number { + const start = this.incrementState(ops[0]).base ?? baseValue; + // An unchanged base cannot prove that a zero-sum run was applied. + if (baseValue === start) return -1; + let cumulative = start; + let matched = -1; + for (let i = 0; i < ops.length; i += 1) { + cumulative += ops[i].by; + if (baseValue === cumulative) matched = i; + } + return matched; + } + + private markReflected( + skip: Set, + ops: IncrementOp[], + matched: number, + baseValue: number, + revision: number | undefined, + ): void { + for (let i = 0; i <= matched; i += 1) { + const op = ops[i]; + const state = this.incrementState(op); + if (this.isStaleObservation(state, revision)) continue; + state.base = baseValue; + if (revision !== undefined) { + state.observedAt = revision; + state.reflectedAt = revision; + } + state.reflectedValue = baseValue; + skip.add(op); + } + } + + private rebaseIncrements( + ops: IncrementOp[], + from: number, + baseValue: number, + revision: number | undefined, + ): void { + for (let i = from; i < ops.length; i += 1) { + const state = this.incrementState(ops[i]); + if (this.isStaleObservation(state, revision)) continue; + state.base = baseValue; + if (revision !== undefined) state.observedAt = revision; + } + } + + private incrementState(op: IncrementOp): IncrementState { + let state = this.incrementStates.get(op); + if (state === undefined) { + state = {}; + this.incrementStates.set(op, state); + } + return state; + } + + private drop( + entry: PendingEntry, + settled: (ops: KeyOps) => boolean, + advanceRemaining: boolean, + ): OverlayKeys { + for (const [collection, ids] of entry.keys) { + const byId = this.docs.get(collection); + if (byId === undefined) continue; + for (const id of ids) { + this.dropDocument(byId, id, settled, advanceRemaining); + } + if (byId.size === 0) this.docs.delete(collection); + } + return entry.keys; + } + + private dropDocument( + byId: Map, + id: string, + settled: (ops: KeyOps) => boolean, + advanceRemaining: boolean, + ): void { + const remaining: KeyOps[] = []; + const settledIncrements: IncrementOp[] = []; + for (const ops of byId.get(id) ?? []) { + if (!settled(ops)) remaining.push(ops); + else if (advanceRemaining) collectIncrements(ops, settledIncrements); + } + if (advanceRemaining) { + this.advanceBaselines(remaining, settledIncrements); + } + if (remaining.length) byId.set(id, remaining); + else byId.delete(id); + } + + /** + * A commit makes an earlier increment part of committed state even while + * its delta is still batched. Move later pending increments' baseline past + * it so that delta reconciles instead of adding the increment twice. + */ + private advanceBaselines(remaining: KeyOps[], settled: IncrementOp[]): void { + for (const { ops } of remaining) { + for (const op of ops) { + if (op.kind === "increment") this.advanceBaseline(op, settled); + } + } + } + + private advanceBaseline(op: IncrementOp, settled: IncrementOp[]): void { + const state = this.incrementState(op); + for (const dropped of settled) { + if (dropped.field !== op.field) continue; + const droppedState = this.incrementState(dropped); + if ( + droppedState.reflectedAt !== undefined || + droppedState.reflectedValue !== undefined + ) { + continue; + } + if (state.base !== undefined) state.base += dropped.by; + } + } +} + +function hasIncrement(entries: readonly KeyOps[]): boolean { + for (const { ops } of entries) { + for (const op of ops) { + if (op.kind === "increment") return true; + } + } + return false; +} + +function collectIncrements(ops: KeyOps, out: IncrementOp[]): void { + for (const op of ops.ops) { + if (op.kind === "increment") out.push(op); + } +} + +/** `set` and `increment` need a known document; only `create` makes one. */ +function applyOp(value: Flat | null, op: OverlayOp): Flat | null { + switch (op.kind) { + case "create": + return { ...op.record }; + case "remove": + return null; + case "set": + return value && { ...value, ...op.patch }; + case "increment": { + const current = value?.[op.field]; + if (value === null || typeof current !== "number") return value; + return { ...value, [op.field]: current + op.by, updated_at: op.time }; + } + } +} + +function isRecord(value: JsonValue | null): value is Flat { + return ( + value !== null && + typeof value === "object" && + !Array.isArray(value) && + !(value instanceof Uint8Array) + ); +} + +/** Context for shaping a write's overlay like the server shapes its rows. */ +export interface OverlayContext { + schema: SchemaDictionary; + /** The connection's internal user id; the owner of rows it creates. */ + userId: string | null; + /** Provisional `created_at` / `updated_at`, in microseconds. */ + time: number; +} + +/** + * Builds the overlay ops of a store write message, or null when the write + * must not be shown before it commits (any `if`). `create` marks a + * `StoreSet` from `store.create`, which makes a new document. + */ +export function overlayOps( + message: OutboundRequest, + create: boolean, + context: OverlayContext, +): OverlayOp[] | null { + switch (message.type) { + case "StoreSet": + if (message.if !== undefined || !isRecord(message.value)) return null; + return [ + create + ? createOp(message.path, message.value, context) + : setOp(message.path, message.value, context), + ]; + case "StoreRemove": + if (message.if !== undefined) return null; + return [ + { kind: "remove", collection: message.path[0], id: message.path[1] }, + ]; + case "StoreBatch": + return batchOps(message.ops, context); + default: + return null; + } +} + +type BatchTuple = Extract< + OutboundRequest, + { type: "StoreBatch" } +>["ops"][number]; + +function batchOps( + tuples: BatchTuple[], + context: OverlayContext, +): OverlayOp[] | null { + const ops: OverlayOp[] = []; + for (const tuple of tuples) { + const op = batchOp(tuple, context); + if (op === null) return null; + ops.push(op); + } + return ops; +} + +function batchOp(tuple: BatchTuple, context: OverlayContext): OverlayOp | null { + const [collection, id] = tuple[1]; + switch (tuple[0]) { + case "s": + return tuple[3] === undefined && isRecord(tuple[2]) + ? setOp(tuple[1], tuple[2], context) + : null; + case "r": + return tuple[2] === undefined ? { kind: "remove", collection, id } : null; + case "i": + return tuple[4] === undefined + ? { + kind: "increment", + collection, + id, + field: tuple[2], + by: tuple[3], + time: context.time, + } + : null; + } +} + +function setOp( + path: string[], + value: Flat, + context: OverlayContext, +): OverlayOp { + const [collection, id] = path; + const patch = shapePatch(collection, value, context.schema); + return { + kind: "set", + collection, + id, + patch: { ...patch, updated_at: context.time }, + }; +} + +/** A new row: every schema field present, unset ones null, system fields provisional. */ +function createOp( + path: string[], + value: Flat, + context: OverlayContext, +): OverlayOp { + const [collection, id] = path; + const schema = context.schema; + const record: Flat = {}; + for (const field of schema.getFields(schema.getTableIndex(collection))) { + record[field] = null; + } + Object.assign(record, shapePatch(collection, value, schema)); + const system: Flat = { + id, + namespace_id: null, + owner_id: collection === "users" ? id : context.userId, + created_at: context.time, + updated_at: context.time, + }; + for (const [field, fieldValue] of Object.entries(system)) { + if (Object.hasOwn(record, field)) record[field] = fieldValue; + } + return { kind: "create", collection, id, record }; +} + +/** Expands null namespaces and stores arrays in the server's sorted-set form. */ +function shapePatch( + collection: string, + value: Flat, + schema: SchemaDictionary, +): Flat { + const tableIndex = schema.getTableIndex(collection); + const patch = { ...schema.expandNullNamespaces(tableIndex, value) }; + for (const [field, fieldValue] of Object.entries(patch)) { + if (!Array.isArray(fieldValue)) { + patch[field] = copyBinary(fieldValue); + continue; + } + const docId = schema.isDocIdField( + tableIndex, + schema.getFieldIndex(tableIndex, field), + ); + patch[field] = sortedSet(fieldValue, docId).map(copyBinary); + } + return patch; +} + +/** Copy a leaf buffer so later caller mutations cannot alter the pending patch. */ +function copyBinary(value: JsonValue): JsonValue { + if (value instanceof Uint8Array) return value.slice(); + return value; +} diff --git a/sdk/typescript/src/react/hooks.test.ts b/sdk/typescript/src/react/hooks.test.ts index 8e9e3893..0016f565 100644 --- a/sdk/typescript/src/react/hooks.test.ts +++ b/sdk/typescript/src/react/hooks.test.ts @@ -28,33 +28,43 @@ afterEach(() => { // ─── Mocks ────────────────────────────────────────────────────────────────── +type QueryCallback = ( + rows: unknown[], + meta: { pending: ReadonlySet }, +) => void; +type ListenCallback = (value: unknown, meta: { pending: boolean }) => void; + class FakeSubscription { unsubscribed = 0; snapshot: unknown[] = []; + pendingIds: ReadonlySet = new Set(); loadMore = async () => {}; hasMore = false; - constructor(private readonly callback: (rows: unknown[]) => void) {} + constructor(private readonly callback: QueryCallback) {} getSnapshot = () => this.snapshot; unsubscribe = async () => { this.unsubscribed += 1; }; - push(rows: unknown[]) { + push(rows: unknown[], pending: ReadonlySet = new Set()) { this.snapshot = rows; - this.callback(rows); + this.pendingIds = pending; + this.callback(rows, { pending }); } } class FakeListener { unlistened = 0; snapshot: unknown = undefined; - constructor(private readonly callback: (value: unknown) => void) {} + isPending = false; + constructor(private readonly callback: ListenCallback) {} getSnapshot = () => this.snapshot; unlisten = async () => { this.unlistened += 1; }; - push(value: unknown) { + push(value: unknown, pending = false) { this.snapshot = value; - this.callback(value); + this.isPending = pending; + this.callback(value, { pending }); } } @@ -82,13 +92,13 @@ function makeClient() { subscribe: async ( _collection: string, _options: unknown, - callback: (rows: unknown[]) => void, + callback: QueryCallback, ) => { const subscription = new FakeSubscription(callback); querySubs.push(subscription); return subscription; }, - listen: async (path: string, callback: (value: unknown) => void) => { + listen: async (path: string, callback: ListenCallback) => { const listener = new FakeListener(callback); listenSubs.push({ path, listener }); return listener; @@ -207,12 +217,31 @@ describe("useQuery", () => { expect(result.current).toEqual({ data: [], + pending: new Set(), isLoading: false, error: null, }); expect(querySubs.length).toBe(0); }); + test("pending follows the delivered rows", async () => { + const { client, querySubs } = makeClient(); + const { result } = renderHook(() => useQuery("tasks", {}), { + wrapper: wrapperFor(client), + }); + await waitFor(() => expect(querySubs.length).toBe(1)); + + act(() => { + querySubs[0].push([{ id: "a", title: "local" }], new Set(["a"])); + }); + expect([...result.current.pending]).toEqual(["a"]); + + act(() => { + querySubs[0].push([{ id: "a", title: "local" }]); + }); + expect(result.current.pending.size).toBe(0); + }); + test("inline option literals do not re-subscribe", async () => { const { client, querySubs } = makeClient(); const { rerender } = renderHook( @@ -336,6 +365,24 @@ describe("useListen", () => { expect(result.current.isLoading).toBe(false); }); + test("isPending follows the delivered value", async () => { + const { client, listenSubs } = makeClient(); + const { result } = renderHook(() => useListen("users.alice.status"), { + wrapper: wrapperFor(client), + }); + await waitFor(() => expect(listenSubs.length).toBe(1)); + + act(() => { + listenSubs[0].listener.push("away", true); + }); + expect(result.current).toMatchObject({ value: "away", isPending: true }); + + act(() => { + listenSubs[0].listener.push("away"); + }); + expect(result.current.isPending).toBe(false); + }); + test("path change re-binds and ignores late deliveries", async () => { const { client, listenSubs } = makeClient(); const { result, rerender } = renderHook( diff --git a/sdk/typescript/src/react/index.ts b/sdk/typescript/src/react/index.ts index 85986862..cd4c0384 100644 --- a/sdk/typescript/src/react/index.ts +++ b/sdk/typescript/src/react/index.ts @@ -36,16 +36,20 @@ import type { // ─── Public types ──────────────────────────────────────────────────────────── -/** Triad returned by `useQuery`. */ +/** State returned by `useQuery`. */ export interface QueryState { data: R; + /** Ids of rows in `data` that show a write not yet committed. */ + pending: ReadonlySet; isLoading: boolean; error: ZyncBaseError | null; } -/** Triad returned by `useListen`. */ +/** State returned by `useListen`. */ export interface ListenState { value: V; + /** Whether `value` shows a write not yet committed. */ + isPending: boolean; isLoading: boolean; error: ZyncBaseError | null; } @@ -80,6 +84,7 @@ type SubscribeOptions< type PresenceData

= Parameters["set"]>[0]; const EMPTY_ROWS: never[] = []; +const NO_PENDING: ReadonlySet = new Set(); // ─── Canonical option keying ───────────────────────────────────────────────── @@ -159,6 +164,7 @@ export function createZyncBaseReact< client: Client; key: string; data: QueryRows; + pending: ReadonlySet; isLoading: boolean; error: ZyncBaseError | null; } | null>(null); @@ -170,10 +176,21 @@ export function createZyncBaseReact< let disposed = false; let handle: SubscriptionHandle | null = null; client.store - .subscribe(collection, options as SubscribeOptions, (rows) => { - if (disposed) return; - setState({ client, key, data: rows, isLoading: false, error: null }); - }) + .subscribe( + collection, + options as SubscribeOptions, + (rows, { pending }) => { + if (disposed) return; + setState({ + client, + key, + data: rows, + pending, + isLoading: false, + error: null, + }); + }, + ) .then((resolved) => { if (disposed) { void resolved.unsubscribe().catch(() => {}); @@ -182,12 +199,20 @@ export function createZyncBaseReact< handle = resolved; const seed = resolved.getSnapshot(); if (seed.length > 0) { + const pending = resolved.pendingIds; setState((prev) => prev === null || prev.client !== client || prev.key !== key || prev.isLoading - ? { client, key, data: seed, isLoading: false, error: null } + ? { + client, + key, + data: seed, + pending, + isLoading: false, + error: null, + } : prev, ); } @@ -198,6 +223,7 @@ export function createZyncBaseReact< client, key, data: empty, + pending: NO_PENDING, isLoading: false, error: error as ZyncBaseError, }); @@ -212,16 +238,22 @@ export function createZyncBaseReact< }, [client, key]); if (key === null) { - return { data: empty, isLoading: false, error: null }; + return { + data: empty, + pending: NO_PENDING, + isLoading: false, + error: null, + }; } if (state !== null && state.client === client && state.key === key) { return { data: state.data, + pending: state.pending, isLoading: state.isLoading, error: state.error, }; } - return { data: empty, isLoading: true, error: null }; + return { data: empty, pending: NO_PENDING, isLoading: true, error: null }; } function useListen["listen"]>[0]>( @@ -233,6 +265,7 @@ export function createZyncBaseReact< client: Client; key: string; value: ListenValue; + isPending: boolean; isLoading: boolean; error: ZyncBaseError | null; } | null>(null); @@ -242,9 +275,16 @@ export function createZyncBaseReact< let disposed = false; let handle: ListenHandle | null = null; client.store - .listen(path, (value) => { + .listen(path, (value, { pending }) => { if (disposed) return; - setState({ client, key, value, isLoading: false, error: null }); + setState({ + client, + key, + value, + isPending: pending, + isLoading: false, + error: null, + }); }) .then((resolved) => { if (disposed) { @@ -254,12 +294,20 @@ export function createZyncBaseReact< handle = resolved; const seed = resolved.getSnapshot(); if (seed !== undefined) { + const isPending = resolved.isPending; setState((prev) => prev === null || prev.client !== client || prev.key !== key || prev.isLoading - ? { client, key, value: seed, isLoading: false, error: null } + ? { + client, + key, + value: seed, + isPending, + isLoading: false, + error: null, + } : prev, ); } @@ -270,6 +318,7 @@ export function createZyncBaseReact< client, key, value: undefined as ListenValue, + isPending: false, isLoading: false, error: error as ZyncBaseError, }); @@ -286,12 +335,14 @@ export function createZyncBaseReact< if (state !== null && state.client === client && state.key === key) { return { value: state.value, + isPending: state.isPending, isLoading: state.isLoading, error: state.error, }; } return { value: undefined as ListenValue, + isPending: false, isLoading: true, error: null, }; diff --git a/sdk/typescript/src/schema_dictionary.ts b/sdk/typescript/src/schema_dictionary.ts index e63dc636..c49ba1d5 100644 --- a/sdk/typescript/src/schema_dictionary.ts +++ b/sdk/typescript/src/schema_dictionary.ts @@ -472,72 +472,49 @@ export class SchemaDictionary { ); } - const entries = Object.entries(value); - - // Fast path: no namespace clear, so preserve insertion order and avoid - // the Map/sort allocation on ordinary writes. - const needsExpansion = entries.some( - ([key, val]) => val === null && !fieldMap.has(key), - ); - if (!needsExpansion) { - const result: SparseFieldArray = []; - for (const [key, val] of entries) { - const fieldIndex = fieldMap.get(key); - if (fieldIndex === undefined) { - throw this.unknownFieldError(tableIndex, key); - } - result.push( - fieldIndex, - this.encodeFieldValue(tableIndex, fieldIndex, val), - ); + const result: SparseFieldArray = []; + const expanded = this.expandNullNamespaces(tableIndex, value); + for (const [key, val] of Object.entries(expanded)) { + const fieldIndex = fieldMap.get(key); + if (fieldIndex === undefined) { + throw this.unknownFieldError(tableIndex, key); } - return result; + result.push( + fieldIndex, + this.encodeFieldValue(tableIndex, fieldIndex, val), + ); } - - const encoded = new Map(); - this.expandNullNamespaces(tableIndex, value, fieldMap, encoded); - this.applyDirectFields(tableIndex, value, fieldMap, encoded); - return this.toSparseArray(encoded); + return result; } - /** Expands a null namespace key to every leaf beneath it. */ - private expandNullNamespaces( + /** + * Replaces each null key that names an object namespace with a null for + * every leaf beneath it. Explicit leaves win regardless of key order; + * other keys, known or not, pass through. Returns `value` itself when + * there is nothing to expand. + */ + expandNullNamespaces( tableIndex: number, - value: Record, - fieldMap: Map, - encoded: Map, - ): void { + value: Record, + ): Record { + const fieldMap = this.fieldToIndex.get(tableIndex); + if (fieldMap === undefined) return value; + const expanded: Record = {}; + const namespaces = new Set(); for (const [key, val] of Object.entries(value)) { - if (fieldMap.has(key) || val !== null) continue; + if (val !== null || fieldMap.has(key)) continue; const prefix = `${key}__`; - let matched = false; - for (const [name, index] of fieldMap) { + for (const name of fieldMap.keys()) { if (!name.startsWith(prefix)) continue; - encoded.set(index, null); - matched = true; + expanded[name] = null; + namespaces.add(key); } - if (!matched) throw this.unknownFieldError(tableIndex, key); } - } - - /** Applies direct leaf keys after namespace clears so they always win. */ - private applyDirectFields( - tableIndex: number, - value: Record, - fieldMap: Map, - encoded: Map, - ): void { + if (namespaces.size === 0) return value; for (const [key, val] of Object.entries(value)) { - const fieldIndex = fieldMap.get(key); - if (fieldIndex === undefined) { - if (val === null) continue; - throw this.unknownFieldError(tableIndex, key); - } - encoded.set( - fieldIndex, - this.encodeFieldValue(tableIndex, fieldIndex, val), - ); + if (!namespaces.has(key)) expanded[key] = val; } + return expanded; } private unknownFieldError(tableIndex: number, key: string): SchemaError { @@ -547,16 +524,6 @@ export class SchemaDictionary { ); } - private toSparseArray(encoded: Map): SparseFieldArray { - const result: SparseFieldArray = []; - for (const [index, val] of [...encoded.entries()].sort( - ([a], [b]) => a - b, - )) { - result.push(index, val); - } - return result; - } - /** Decode a complete positional record into its final nested SDK shape. */ decodeRecord( tableIndex: number, diff --git a/sdk/typescript/src/store.ts b/sdk/typescript/src/store.ts index 9e17ca19..be3a8f5c 100644 --- a/sdk/typescript/src/store.ts +++ b/sdk/typescript/src/store.ts @@ -1,8 +1,9 @@ // Store API import type { OutboundRequest } from "./connection_wire.js"; -import { compareDocIds } from "./doc_id.js"; import { ErrorCodes, toZyncError, ZyncBaseError } from "./errors.js"; +import { compileWhere } from "./filter_eval.js"; +import { overlayOps, type PendingEntry } from "./optimistic.js"; import { flatten, getDeepProperty, splitFieldPath } from "./path.js"; import type { SchemaDictionary } from "./schema_dictionary.js"; import { @@ -22,6 +23,8 @@ import { import { createCreatedAtComparator, createListenProjection, + type DeliveryCallback, + NO_PENDING, type SubscriptionEntry, type SubscriptionTracker, } from "./subscriptions.js"; @@ -37,8 +40,10 @@ import type { QueryOptions, StoreSubscribe, SubscriptionHandle, + WriteOptions, } from "./types.js"; import { generateUUIDv7 } from "./uuid.js"; +import { compareScalars } from "./value_order.js"; /** How long a keyed subscription outlives its last consumer before teardown. */ const GRACE_TEARDOWN_MS = 300; @@ -66,6 +71,8 @@ export interface StoreConnection { dispatchWrite(msg: OutboundRequest): Promise; on(event: LifecycleEvent, handler: (...args: unknown[]) => void): void; readonly schemaDictionary: SchemaDictionary; + /** The connection's internal user id; owner of the rows it creates. */ + readonly userId: string | null; } /** @@ -93,7 +100,7 @@ interface RegistrationKey { /** Query options for the comparator (subscribe only). */ options: QueryOptions | null; /** Shared consumer callbacks — the tracker entry holds this same array. */ - callbacks: Array<(value: JsonValue) => void>; + callbacks: DeliveryCallback[]; /** Server subId once accepted; null while queued or establishing. */ subId: number | null; /** Establishment promise; null once settled (accepted or dropped). */ @@ -110,7 +117,7 @@ interface RegistrationKey { /** A registration whose promise has not settled yet. */ interface PendingConsumer { state: RegistrationKey; - callback: (value: JsonValue) => void; + callback: DeliveryCallback; settled: boolean; reject: (err: unknown) => void; } @@ -150,6 +157,7 @@ export class StoreImpl { return this.write( () => buildSet(path, value, options).message, "Set failed", + options, ); } @@ -157,6 +165,7 @@ export class StoreImpl { return this.write( () => buildRemove(path, options).message, "Remove failed", + options, ); } @@ -172,15 +181,25 @@ export class StoreImpl { }, ]), "Increment failed", + options, ); } - create(collection: string, value: JsonValue): Promise { + create( + collection: string, + value: JsonValue, + options?: WriteOptions, + ): Promise { const id = generateUUIDv7(); - const result = this.write(() => { - this.validateRequiredFields(collection, value); - return buildCreate(collection, value, id).message; - }, "Create failed").then(() => id); + const result = this.write( + () => { + this.validateRequiredFields(collection, value); + return buildCreate(collection, value, id).message; + }, + "Create failed", + options, + true, + ).then(() => id); result.catch(() => {}); // see write() return result; } @@ -208,13 +227,13 @@ export class StoreImpl { } } - batch(operations: BatchOperation[]): Promise { - return this.write(() => buildBatch(operations), "Batch failed"); + batch(operations: BatchOperation[], options?: WriteOptions): Promise { + return this.write(() => buildBatch(operations), "Batch failed", options); } listen( path: Path, - callback: (value: JsonValue) => void, + callback: (value: JsonValue, meta: { pending: boolean }) => void, ): Promise { const command = buildListen(path); const state = this.acquireKey(`l:${JSON.stringify(command.segments)}`, { @@ -224,15 +243,20 @@ export class StoreImpl { collection: null, options: null, }); - return this.attach(state, callback, () => { + const deliver = callback as DeliveryCallback; + const pending = () => this.pendingOf(state); + return this.attach(state, deliver, () => { let released = false; return { unlisten: () => { if (released) return Promise.resolve(); released = true; - return this.release(state, callback); + return this.release(state, deliver); }, getSnapshot: () => this.snapshotOf(state), + get isPending() { + return pending() === true; + }, }; }); } @@ -240,7 +264,10 @@ export class StoreImpl { subscribe( collection: string, options: QueryOptions, - callback: (results: JsonValue[]) => void, + callback: ( + results: JsonValue[], + meta: { pending: ReadonlySet }, + ) => void, ): Promise { const command = buildSubscribe(collection, options); const state = this.acquireKey(`s:${JSON.stringify(command.message)}`, { @@ -253,7 +280,9 @@ export class StoreImpl { // (which throws `DataCloneError` on non-cloneable user values). options: { orderBy: options.orderBy?.map((clause) => ({ ...clause })) }, }); - return this.attach(state, callback as (value: JsonValue) => void, () => { + const deliver = callback as DeliveryCallback; + const pending = () => this.pendingOf(state); + return this.attach(state, deliver, () => { let released = false; return { get hasMore() { @@ -263,11 +292,15 @@ export class StoreImpl { unsubscribe: () => { if (released) return Promise.resolve(); released = true; - return this.release(state, callback as (value: JsonValue) => void); + return this.release(state, deliver); }, // A subscribe key's materialized view always snapshots to rows. getSnapshot: () => (this.snapshotOf(state) as JsonValue[] | undefined) ?? [], + get pendingIds() { + const ids = pending(); + return ids instanceof Set ? ids : NO_PENDING; + }, }; }); } @@ -317,7 +350,7 @@ export class StoreImpl { */ private attach( state: RegistrationKey, - callback: (value: JsonValue) => void, + callback: DeliveryCallback, makeHandle: () => H, ): Promise { const request = new Promise((resolve, reject) => { @@ -343,13 +376,16 @@ export class StoreImpl { resolve(makeHandle()); if (entry.deliveredValue === undefined) return; const value = entry.deliveredValue; + const pending = + entry.deliveredPending ?? + (state.kind === "listen" ? false : NO_PENDING); // Fire on a microtask: a caller's synchronous tail // (storing the handle) must run first, or a delivery // guard keyed on that store drops the snapshot. queueMicrotask(() => { if (!state.callbacks.includes(callback)) return; try { - callback(value); + callback(value, { pending }); } catch (err) { console.error("[SDK] Subscription callback threw:", err); } @@ -497,26 +533,42 @@ export class StoreImpl { } private entryFor(state: RegistrationKey): SubscriptionEntry { + const onRemap = (newId: number): void => { + state.subId = newId; + }; + if (state.kind === "listen") { + const segments = state.segments as string[]; + return { + params: state.message, + collection: segments[0], + docId: segments[1], + callbacks: state.callbacks, + projection: createListenProjection(segments), + onRemap, + }; + } + const collection = state.collection as string; + const schema = this.conn.schemaDictionary; return { params: state.message, + collection, callbacks: state.callbacks, - projection: - state.kind === "listen" - ? createListenProjection(state.segments as string[]) - : null, - materializedView: - state.kind === "subscribe" - ? { - records: new Map(), - comparator: this.buildCollectionComparator( - state.collection as string, - state.options as QueryOptions, - ), - } - : undefined, - onRemap: (newId) => { - state.subId = newId; + projection: null, + materializedView: { + records: new Map(), + comparator: this.buildCollectionComparator( + collection, + state.options as QueryOptions, + ), + matches: compileWhere(state.message, (field) => { + const tableIndex = schema.getTableIndex(collection); + return schema.isDocIdField( + tableIndex, + schema.getFieldIndex(tableIndex, field), + ); + }), }, + onRemap, }; } @@ -535,7 +587,7 @@ export class StoreImpl { */ private release( state: RegistrationKey, - callback: (value: JsonValue) => void, + callback: DeliveryCallback, ): Promise { const index = state.callbacks.indexOf(callback); if (index !== -1) state.callbacks.splice(index, 1); @@ -605,6 +657,13 @@ export class StoreImpl { return this.tracker.get(state.subId)?.deliveredValue; } + private pendingOf( + state: RegistrationKey, + ): ReadonlySet | boolean | undefined { + if (state.subId === null) return undefined; + return this.tracker.get(state.subId)?.deliveredPending; + } + /** * Internal: the client calls this once the session (schema + replay) is * ready — it wakes queued establishments and waits for their acks. @@ -623,6 +682,7 @@ export class StoreImpl { markNotReady(): void { this.sessionReady = false; this.scopeGen++; + this.tracker.refresh(this.tracker.pending.clear()); } /** Internal: a namespace switch is in flight — pause new establishments. */ @@ -725,29 +785,86 @@ export class StoreImpl { /** * Build and send a write synchronously, so writes and reads issued - * back-to-back reach the server in call order. The server sends a write's - * deltas before its outcome, so subscriptions are flushed before the - * promise resolves. Failures emit on('error'); the returned promise is - * marked handled so un-awaited writes do not raise unhandled rejections. + * back-to-back reach the server in call order. Unless opted out, the + * write then shows in subscriptions and listens before this returns. The + * server sends a write's deltas before its outcome, so subscriptions are + * flushed before the promise resolves. Failures revert the local write + * and emit on('error'); the returned promise is marked handled so + * un-awaited writes do not raise unhandled rejections. */ private write( build: () => OutboundRequest, fallbackMessage: string, + options: WriteOptions | undefined, + create = false, ): Promise { + let message: OutboundRequest | null = null; let sent: Promise; try { - sent = this.conn.dispatchWrite(build()); + message = build(); + sent = this.conn.dispatchWrite(message); } catch (err) { sent = Promise.reject(err); } + const entry = + message !== null && options?.optimistic !== false + ? this.showLocally(message, create) + : null; const result = sent.then( - () => this.tracker.flushNow(), - (err: unknown) => this.emitAndThrow(err, fallbackMessage), + () => this.settle(entry, true), + (err: unknown) => { + this.settle(entry, false); + this.emitAndThrow(err, fallbackMessage); + }, ); result.catch(() => {}); return result; } + /** + * Adds a sent write to the overlay and delivers it. Skipped while the + * session is not ready (the write fails fast) or a namespace switch is + * in flight, and for writes the overlay cannot shape: those fail on the + * server, which rejects what the schema cannot describe. + */ + private showLocally( + message: OutboundRequest, + create: boolean, + ): PendingEntry | null { + if (!this.sessionReady || this.switchPending > 0) return null; + let ops: ReturnType; + try { + ops = overlayOps(message, create, { + schema: this.conn.schemaDictionary, + userId: this.conn.userId, + time: this.tracker.provisionalTime(), + }); + } catch { + return null; + } + if (ops === null) return null; + const entry = this.tracker.pending.add(ops); + this.tracker.refresh(entry.keys); + return entry; + } + + /** + * Drops a settled write from the overlay. A commit's deltas arrive before + * it, so they are flushed after the drop and before the refresh: one + * delivery, with no frame showing the old server value. + */ + private settle(entry: PendingEntry | null, committed: boolean): void { + const pending = this.tracker.pending; + const keys = + entry === null + ? null + : committed + ? pending.commit(entry) + : pending.fail(entry); + if (committed) this.tracker.flushNow(); + if (keys !== null) this.tracker.refresh(keys); + } + private async dispatchVoid( message: OutboundRequest, fallbackMessage: string, @@ -845,58 +962,6 @@ function compareSortEntry( if (va == null) return vb == null ? 0 : 1; if (vb == null) return -1; - const result = - entry.docId && typeof va === "string" && typeof vb === "string" - ? compareDocIds(va, vb) - : compareNonNullValues(va, vb); + const result = compareScalars(va, vb, entry.docId); return entry.desc ? -result : result; } - -function compareNonNullValues(a: JsonValue, b: JsonValue): number { - if (typeof a !== typeof b) return 0; - switch (typeof a) { - case "number": - return compareAsc(a, b as number); - case "boolean": - return compareBooleans(a, b as boolean); - case "string": - return compareUtf8(a, b as string); - default: - return 0; - } -} - -function compareAsc(a: T, b: T): number { - return a < b ? -1 : a > b ? 1 : 0; -} - -function compareBooleans(a: boolean, b: boolean): number { - return a === b ? 0 : a ? 1 : -1; -} - -const textEncoder = new TextEncoder(); - -/** Compares strings by the exact UTF-8 bytes used by SQLite BINARY ordering. */ -function compareUtf8(a: string, b: string): number { - if (isUtf8LexicalFastPath(a) && isUtf8LexicalFastPath(b)) { - return compareAsc(a, b); - } - return compareUtf8Bytes(a, b); -} - -function compareUtf8Bytes(a: string, b: string): number { - const ba = textEncoder.encode(a); - const bb = textEncoder.encode(b); - const length = Math.min(ba.length, bb.length); - for (let i = 0; i < length; i++) { - if (ba[i] !== bb[i]) return ba[i] < bb[i] ? -1 : 1; - } - return ba.length < bb.length ? -1 : ba.length > bb.length ? 1 : 0; -} - -function isUtf8LexicalFastPath(value: string): boolean { - for (let i = 0; i < value.length; i += 1) { - if (value.charCodeAt(i) >= 0x800) return false; - } - return true; -} diff --git a/sdk/typescript/src/store_optimistic.test.ts b/sdk/typescript/src/store_optimistic.test.ts new file mode 100644 index 00000000..1e0dbb2b --- /dev/null +++ b/sdk/typescript/src/store_optimistic.test.ts @@ -0,0 +1,435 @@ +import { describe, expect, test } from "bun:test"; +import type { OutboundRequest } from "./connection_wire.js"; +import { SchemaDictionary } from "./schema_dictionary.js"; +import { type StoreConnection, StoreImpl } from "./store.js"; +import { SubscriptionTracker } from "./subscriptions.js"; +import type { JsonValue, OkResponse, QueryOptions } from "./types.js"; + +type Row = Record; + +interface Delivery { + rows: Row[]; + pending: ReadonlySet; +} + +interface Write { + message: OutboundRequest; + commit: () => void; + fail: (err: unknown) => void; +} + +const FIELDS = [ + "id", + "namespace_id", + "owner_id", + "title", + "status", + "rank", + "tags", + "address__city", + "address__zip", + "created_at", + "updated_at", +]; + +function row(id: string, fields: Row & { created_at: number }): Row { + return { + id, + namespace_id: 1, + owner_id: "me", + title: null, + status: null, + rank: null, + tags: null, + address: { city: null, zip: null }, + updated_at: fields.created_at, + ...fields, + }; +} + +const T1 = row("t1", { title: "one", status: "open", rank: 1, created_at: 10 }); +const T2 = row("t2", { title: "two", status: "done", rank: 2, created_at: 20 }); + +async function makeStore() { + const schema = new SchemaDictionary(); + await schema.processSchemaSync({ + version: "1.0.0", + tables: ["todos"], + fields: [FIELDS], + fieldFlags: [[0b11, 0b01, 0b11, 0, 0, 0, 0, 0, 0, 0b01, 0b01]], + }); + const writes: Write[] = []; + const acks: OkResponse[] = []; + const errors: unknown[] = []; + const conn: StoreConnection = { + dispatch: async () => acks.shift() ?? { type: "ok", id: 0 }, + dispatchWrite: (message) => + new Promise((resolve, reject) => { + writes.push({ message, commit: resolve, fail: reject }); + }), + on: () => {}, + schemaDictionary: schema, + userId: "me", + }; + const tracker = new SubscriptionTracker(); + const store = new StoreImpl(conn, tracker, (err) => errors.push(err)); + await store.markSessionReady(); + + let nextSubId = 1; + const subscribe = async ( + options: QueryOptions, + records: Row[] = [T1, T2], + ) => { + const subId = nextSubId++; + acks.push({ type: "ok", id: 0, subId, value: records }); + const deliveries: Delivery[] = []; + const handle = await store.subscribe("todos", options, (rows, meta) => { + deliveries.push({ rows: rows as Row[], pending: meta.pending }); + }); + await tick(); + return { subId, handle, deliveries }; + }; + const delta = (subId: number, record: Row) => + tracker.dispatch({ + type: "StoreDelta", + subId, + ops: [{ op: "set", path: ["todos", record.id as string], value: record }], + }); + + return { store, tracker, writes, acks, errors, subscribe, delta }; +} + +function tick(): Promise { + return new Promise((resolve) => setTimeout(resolve, 0)); +} + +function ids(delivery: Delivery | undefined): string[] { + return (delivery?.rows ?? []).map((r) => r.id as string); +} + +describe("optimistic writes", () => { + test("a set shows synchronously, marked pending", async () => { + const { store, subscribe } = await makeStore(); + const { handle, deliveries } = await subscribe({}); + + void store.set("todos.t1", { title: "edited" }); + + const last = deliveries.at(-1); + expect(last?.rows[0]).toMatchObject({ + id: "t1", + title: "edited", + status: "open", + }); + expect([...(last?.pending ?? [])]).toEqual(["t1"]); + expect([...handle.pendingIds]).toEqual(["t1"]); + }); + + test("a commit whose delta is still batched delivers once, with the server row", async () => { + const { store, writes, subscribe, delta } = await makeStore(); + const { subId, handle, deliveries } = await subscribe({}); + const done = store.set("todos.t1", { title: "edited" }); + expect(handle.pendingIds.has("t1")).toBe(true); + const before = deliveries.length; + + delta(subId, { ...T1, title: "edited", updated_at: 11 }); + writes[0].commit(); + await done; + + expect(deliveries.length).toBe(before + 1); + expect(deliveries.at(-1)?.rows[0]).toMatchObject({ + title: "edited", + updated_at: 11, + }); + expect(deliveries.at(-1)?.pending.size).toBe(0); + expect(handle.pendingIds.size).toBe(0); + }); + + test("a failed write reverts and rejects", async () => { + const { store, writes, errors, subscribe } = await makeStore(); + const { deliveries } = await subscribe({}); + const done = store.set("todos.t1", { title: "edited" }); + expect(deliveries.at(-1)?.rows[0]).toMatchObject({ title: "edited" }); + + writes[0].fail(new Error("unique violation")); + + await expect(done).rejects.toMatchObject({ message: "unique violation" }); + expect(deliveries.at(-1)?.rows[0]).toBe(T1); + expect(deliveries.at(-1)?.pending.size).toBe(0); + expect(errors).toHaveLength(1); + }); + + test("a later write committing first settles the earlier one too", async () => { + const { store, writes, subscribe, delta } = await makeStore(); + const { subId, deliveries } = await subscribe({}); + const first = store.set("todos.t1", { title: "first" }); + const second = store.set("todos.t1", { title: "second" }); + expect(deliveries.at(-1)?.rows[0]).toMatchObject({ title: "second" }); + expect(deliveries.at(-1)?.pending.has("t1")).toBe(true); + + delta(subId, { ...T1, title: "first", updated_at: 11 }); + delta(subId, { ...T1, title: "second", updated_at: 12 }); + writes[1].commit(); + await second; + const settled = deliveries.length; + expect(deliveries.at(-1)?.rows[0]).toMatchObject({ title: "second" }); + expect(deliveries.at(-1)?.pending.size).toBe(0); + + writes[0].commit(); + await first; + expect(deliveries.length).toBe(settled); + }); + + test("optimistic: false and conditional writes wait for the server", async () => { + const { store, subscribe } = await makeStore(); + const { deliveries } = await subscribe({}); + const before = deliveries.length; + + void store.set("todos.t1", { title: "a" }, { optimistic: false }); + void store.set("todos.t1", { title: "b" }, { if: { status: "open" } }); + void store.batch([{ op: "remove", path: "todos.t2" }], { + optimistic: false, + }); + + expect(deliveries.length).toBe(before); + }); + + test("a write while the session is not ready is not shown", async () => { + const { store, subscribe } = await makeStore(); + const { deliveries } = await subscribe({}); + const before = deliveries.length; + + store.markNotReady(); + void store.set("todos.t1", { title: "a" }); + + expect(deliveries.length).toBe(before); + }); + + test("losing the session drops pending writes", async () => { + const { store, subscribe } = await makeStore(); + const { deliveries } = await subscribe({}); + void store.set("todos.t1", { title: "a" }); + expect(deliveries.at(-1)?.rows[0]).toMatchObject({ title: "a" }); + + store.markNotReady(); + + expect(deliveries.at(-1)?.rows[0]).toBe(T1); + expect(deliveries.at(-1)?.pending.size).toBe(0); + }); + + test("a pending edit moves a row out of a filtered view, and back on failure", async () => { + const { store, writes, subscribe } = await makeStore(); + const { deliveries } = await subscribe({ where: { status: "open" } }, [T1]); + void store.set("todos.t1", { status: "done" }).catch(() => {}); + + expect(ids(deliveries.at(-1))).toEqual([]); + + writes[0].fail(new Error("denied")); + await tick(); + expect(ids(deliveries.at(-1))).toEqual(["t1"]); + }); + + test("a pending edit moves a row into a view that did not hold it", async () => { + const { store, subscribe } = await makeStore(); + await subscribe({}); + const open = await subscribe({ where: { status: "open" } }, [T1]); + + void store.set("todos.t2", { status: "open" }); + + expect(ids(open.deliveries.at(-1))).toEqual(["t1", "t2"]); + expect([...(open.deliveries.at(-1)?.pending ?? [])]).toEqual(["t2"]); + }); + + test("a create appears last, in matching views only", async () => { + const { store, subscribe } = await makeStore(); + const open = await subscribe({ where: { status: "open" } }, [T1]); + const done = await subscribe({ where: { status: "done" } }, [T2]); + const doneCount = done.deliveries.length; + + void store.create("todos", { title: "new", status: "open" }); + + const created = open.deliveries.at(-1)?.rows[1]; + expect(created).toMatchObject({ + title: "new", + status: "open", + owner_id: "me", + rank: null, + }); + expect(open.deliveries.at(-1)?.pending.has(created?.id as string)).toBe( + true, + ); + expect(done.deliveries.length).toBe(doneCount); + }); + + test("an OR view takes a row that matches one branch", async () => { + const { store, subscribe } = await makeStore(); + await subscribe({}); + const view = await subscribe( + { where: { or: [{ status: "open" }, { rank: { gt: 5 } }] } }, + [T1], + ); + + void store.set("todos.t2", { rank: 9 }); + + expect(ids(view.deliveries.at(-1))).toEqual(["t1", "t2"]); + }); + + test("a pending edit re-sorts the row by the view's order", async () => { + const { store, subscribe } = await makeStore(); + const { deliveries } = await subscribe({ orderBy: [{ rank: "asc" }] }); + + void store.set("todos.t1", { rank: 3 }); + + expect(ids(deliveries.at(-1))).toEqual(["t2", "t1"]); + }); + + test("a commit that changes no value still clears the pending mark", async () => { + const { store, writes, subscribe } = await makeStore(); + const { deliveries } = await subscribe({}); + const done = store.set("todos.t1", { + title: "one", + updated_at: T1.updated_at, + }); + expect(deliveries.at(-1)?.pending.has("t1")).toBe(true); + const before = deliveries.length; + + writes[0].commit(); + await done; + + expect(deliveries.length).toBe(before + 1); + expect(deliveries.at(-1)?.pending.size).toBe(0); + }); + + test("arrays show as sorted sets and a null object clears its fields", async () => { + const { store, subscribe } = await makeStore(); + const { deliveries } = await subscribe({}, [ + row("t1", { + tags: ["x"], + address: { city: "Oslo", zip: "0150" }, + created_at: 10, + }), + ]); + + void store.set("todos.t1", { tags: ["b", "a", "b"], address: null }); + + expect(deliveries.at(-1)?.rows[0]).toMatchObject({ + tags: ["a", "b"], + address: { city: null, zip: null }, + }); + }); + + test("an increment applies to the shown number", async () => { + const { store, subscribe } = await makeStore(); + const { deliveries } = await subscribe({}); + + void store.increment("todos.t2.rank", 5); + + expect(deliveries.at(-1)?.rows[1]).toMatchObject({ id: "t2", rank: 7 }); + }); + + test("a listen delivers its first null value", async () => { + const { store, acks } = await makeStore(); + acks.push({ type: "ok", id: 0, subId: 9, value: [] }); + const values: JsonValue[] = []; + const handle = await store.listen("todos.missing", (value) => + values.push(value), + ); + + expect(values).toEqual([null]); + expect(handle.getSnapshot()).toBeNull(); + }); + + test("a listen does not apply an increment its delta already includes", async () => { + const { store, writes, acks, tracker } = await makeStore(); + acks.push({ type: "ok", id: 0, subId: 9, value: [T2] }); + const values: Array<[JsonValue, boolean]> = []; + await store.listen("todos.t2.rank", (value, meta) => { + values.push([value, meta.pending]); + }); + + const done = store.increment("todos.t2.rank", 5); + expect(values.at(-1)).toEqual([7, true]); + + tracker.dispatch({ + type: "StoreDelta", + subId: 9, + ops: [{ op: "set", path: ["todos", "t2"], value: { ...T2, rank: 7 } }], + }); + expect(values.at(-1)).toEqual([7, true]); + + writes[0].commit(); + await done; + expect(values.at(-1)).toEqual([7, false]); + }); + + test("a coalesced increment delta is not counted again by an earlier commit", async () => { + const { store, writes, subscribe, delta, tracker } = await makeStore(); + const { subId, deliveries } = await subscribe({}); + + const first = store.increment("todos.t2.rank", 1); + const second = store.increment("todos.t2.rank", 1); + expect(deliveries.at(-1)?.rows[1]).toMatchObject({ rank: 4 }); + + delta(subId, { ...T2, rank: 4, updated_at: 21 }); + tracker.flushNow(); + expect(deliveries.at(-1)?.rows[1]).toMatchObject({ rank: 4 }); + + writes[0].commit(); + await first; + expect(deliveries.at(-1)?.rows[1]).toMatchObject({ rank: 4 }); + + writes[1].commit(); + await second; + expect(deliveries.at(-1)?.rows[1]).toMatchObject({ rank: 4 }); + }); + + test("a pending increment still applies to a base that predates it", async () => { + const { store, subscribe, delta, tracker } = await makeStore(); + const { subId, deliveries } = await subscribe({}); + + void store.increment("todos.t2.rank", 5); + expect(deliveries.at(-1)?.rows[1]).toMatchObject({ rank: 7 }); + + delta(subId, { ...T2, updated_at: 21 }); + tracker.flushNow(); + expect(deliveries.at(-1)?.rows[1]).toMatchObject({ rank: 7 }); + }); + + test("a listen shows a pending field write and clears its mark on commit", async () => { + const { store, writes, acks, tracker } = await makeStore(); + acks.push({ type: "ok", id: 0, subId: 9, value: [T1] }); + const values: Array<[JsonValue, boolean]> = []; + const handle = await store.listen("todos.t1.title", (value, meta) => { + values.push([value, meta.pending]); + }); + + const done = store.set("todos.t1.title", "edited"); + expect(values.at(-1)).toEqual(["edited", true]); + expect(handle.isPending).toBe(true); + + tracker.dispatch({ + type: "StoreDelta", + subId: 9, + ops: [ + { op: "set", path: ["todos", "t1"], value: { ...T1, title: "edited" } }, + ], + }); + writes[0].commit(); + await done; + expect(values.at(-1)).toEqual(["edited", false]); + expect(handle.isPending).toBe(false); + }); + + test("a listen shows a pending remove as null", async () => { + const { store, writes, acks } = await makeStore(); + acks.push({ type: "ok", id: 0, subId: 9, value: [T1] }); + const values: JsonValue[] = []; + await store.listen("todos.t1", (value) => values.push(value)); + + void store.remove("todos.t1").catch(() => {}); + expect(values.at(-1)).toBeNull(); + + writes[0].fail(new Error("denied")); + await tick(); + expect(values.at(-1)).toEqual(T1); + }); +}); diff --git a/sdk/typescript/src/store_wire.ts b/sdk/typescript/src/store_wire.ts index e1235f8a..9fd1a434 100644 --- a/sdk/typescript/src/store_wire.ts +++ b/sdk/typescript/src/store_wire.ts @@ -31,7 +31,7 @@ export interface StoreCommand { export type WireCondition = [string, number] | [string, number, JsonValue]; -const OP_CODES: Record = { +export const OP_CODES: Record = { eq: 0, ne: 1, gt: 2, diff --git a/sdk/typescript/src/subscriptions.perf.test.ts b/sdk/typescript/src/subscriptions.perf.test.ts index 28dd3ee4..d5640a20 100644 --- a/sdk/typescript/src/subscriptions.perf.test.ts +++ b/sdk/typescript/src/subscriptions.perf.test.ts @@ -1,17 +1,21 @@ import { describe, expect, test } from "bun:test"; +import { SchemaDictionary } from "./schema_dictionary"; +import { type StoreConnection, StoreImpl } from "./store"; import { createCreatedAtComparator, SubscriptionTracker, } from "./subscriptions"; -import type { StoreDelta, StoreSubscribe } from "./types"; +import type { JsonValue, StoreDelta, StoreSubscribe } from "./types"; + +const tick = () => new Promise((resolve) => setTimeout(resolve, 0)); /** * Pure unit benchmark for the materialized-view delta path — no network, no * schema, no client. Exercises the hot loop that was O(records) per delta: - * 2000-record view, 20000 deltas, one flush. + * 10000-record view with 100 pending local writes, 20000 deltas, one flush. */ describe("SubscriptionTracker delta fan-in performance", () => { - test("20000 deltas on a 2000-record view batch into per-tick callbacks", async () => { + test("20000 deltas on a 10000-record view with pending writes batch into per-tick callbacks", async () => { const tracker = new SubscriptionTracker(); let callbackCount = 0; @@ -23,6 +27,7 @@ describe("SubscriptionTracker delta fan-in performance", () => { }; tracker.register(101, { params, + collection: "items", callbacks: [ (value) => { callbackCount++; @@ -33,43 +38,145 @@ describe("SubscriptionTracker delta fan-in performance", () => { materializedView: { records: new Map(), comparator: createCreatedAtComparator(), + matches: () => true, }, }); - const seedOps: StoreDelta["ops"] = Array.from({ length: 2000 }, (_, i) => ({ - op: "set" as const, - path: ["items", `doc-${i}`], - value: { id: `doc-${i}`, n: i }, - })); + const seedOps: StoreDelta["ops"] = Array.from( + { length: 10000 }, + (_, i) => ({ + op: "set" as const, + path: ["items", `doc-${i}`], + value: { id: `doc-${i}`, n: i, created_at: i }, + }), + ); tracker.dispatch({ type: "StoreDelta", subId: 101, ops: seedOps }); - await new Promise((resolve) => setTimeout(resolve, 0)); + await tick(); + for (let i = 0; i < 100; i++) { + tracker.pending.add([ + { + kind: "set", + collection: "items", + id: `doc-${i * 100}`, + patch: { local: true }, + }, + ]); + } const t0 = performance.now(); for (let i = 0; i < 20000; i++) { - const doc = `doc-${i % 2000}`; + const doc = `doc-${i % 10000}`; tracker.dispatch({ type: "StoreDelta", subId: 101, - ops: [{ op: "set", path: ["items", doc], value: { id: doc, n: i } }], + ops: [ + { + op: "set", + path: ["items", doc], + value: { id: doc, n: i, created_at: i % 10000 }, + }, + ], }); } - await new Promise((resolve) => setTimeout(resolve, 0)); + await tick(); const elapsedMs = performance.now() - t0; console.log( - `Fan-in (2000 records / 20000 deltas) [ms]: ${elapsedMs.toFixed(2)} callbacks=${callbackCount}`, + `Fan-in (10000 records / 100 pending / 20000 deltas) [ms]: ${elapsedMs.toFixed(2)} callbacks=${callbackCount}`, ); // Contract: exactly two flushes — seed dispatch, then the single-tick // 20000-delta burst. A per-delta callback (or an extra flush) fails here. expect(callbackCount).toBe(2); - // Final state: all records present, last write wins per doc. - expect(Array.isArray(lastSnapshot)).toBe(true); - const snapshot = lastSnapshot as Array<{ id: string; n: number }>; - expect(snapshot.length).toBe(2000); - const doc5 = snapshot.find((r) => r.id === "doc-5"); - expect(doc5?.n).toBe(18005); + // Final state: all records present, last write wins per doc, pending + // writes applied over it. + const snapshot = lastSnapshot as Array<{ + id: string; + n: number; + local?: boolean; + }>; + expect(snapshot.length).toBe(10000); + expect(snapshot[5]).toMatchObject({ id: "doc-5", n: 10005 }); + expect(snapshot[100]).toMatchObject({ + id: "doc-100", + n: 10100, + local: true, + }); // Loose threshold — headroom for CI variance. expect(elapsedMs).toBeLessThan(1000); }); }); + +/** + * Mirrors the e2e filtered-subscription stress shape: many in-process + * clients, each with a large filtered view, each issuing a burst of local + * writes. Local delivery is incremental, so the burst costs no re-sorts. + */ +describe("optimistic local delivery performance", () => { + test("400 stores with 800-row views take 8 local writes each", async () => { + const schema = new SchemaDictionary(); + await schema.processSchemaSync({ + version: "1.0.0", + tables: ["items"], + fields: [ + [ + "id", + "namespace_id", + "owner_id", + "priority", + "active", + "created_at", + "updated_at", + ], + ], + fieldFlags: [[0b11, 0b01, 0b11, 0, 0, 0b01, 0b01]], + }); + const rows: JsonValue[] = Array.from({ length: 800 }, (_, i) => ({ + id: `item-${i}`, + namespace_id: 1, + owner_id: "me", + priority: i % 10, + active: true, + created_at: i + 1, + updated_at: i + 1, + })); + + const stores: StoreImpl[] = []; + let deliveries = 0; + for (let s = 0; s < 400; s++) { + const conn: StoreConnection = { + dispatch: async () => ({ type: "ok", id: 0, subId: 1, value: rows }), + dispatchWrite: () => new Promise(() => {}), + on: () => {}, + schemaDictionary: schema, + userId: "me", + }; + const store = new StoreImpl(conn, new SubscriptionTracker()); + await store.markSessionReady(); + await store.subscribe( + "items", + { where: { priority: { gte: 0 }, active: true } }, + () => { + deliveries++; + }, + ); + stores.push(store); + } + await tick(); + deliveries = 0; + + const t0 = performance.now(); + for (const store of stores) { + for (let w = 0; w < 8; w++) { + void store.set(["items", `item-${w * 97}`], { priority: 9 - w }); + } + } + const elapsedMs = performance.now() - t0; + + console.log( + `Local burst (400 stores x 800 rows x 8 writes) [ms]: ${elapsedMs.toFixed(2)}`, + ); + expect(deliveries).toBe(400 * 8); + expect(elapsedMs).toBeLessThan(100); + }); +}); diff --git a/sdk/typescript/src/subscriptions.test.ts b/sdk/typescript/src/subscriptions.test.ts index 978136f2..c4041a1d 100644 --- a/sdk/typescript/src/subscriptions.test.ts +++ b/sdk/typescript/src/subscriptions.test.ts @@ -17,11 +17,13 @@ function registerView( ): void { tracker.register(subId, { params, + collection: String(params.table_index), callbacks: [callback], projection: null, materializedView: { records: new Map(), comparator: createCreatedAtComparator(), + matches: () => true, }, }); } @@ -31,7 +33,7 @@ function registerView( * Validates: Requirements 3.6, 8.2 */ describe("SubscriptionTracker", () => { - test("Property 9: dispatching a StoreDelta invokes the registered callback exactly once with the delta ops", () => { + test("Property 9: dispatching a StoreDelta invokes the registered callback exactly once with the record", () => { fc.assert( fc.property(fc.integer({ min: 1, max: 100000 }), (subId) => { const tracker = new SubscriptionTracker(); @@ -46,20 +48,20 @@ describe("SubscriptionTracker", () => { tracker.register(subId, { params, + collection: "users", + docId: "u1", callbacks: [callback], - projection: null, // store.subscribe style + projection: createListenProjection(["users", "u1"]), }); - const delta: StoreDelta = { + const record = { id: "u1", name: "Alice" }; + tracker.dispatch({ type: "StoreDelta", subId, - ops: [{ op: "set", path: ["name"], value: "Alice" }], - }; - - tracker.dispatch(delta); + ops: [{ op: "set", path: ["users", "u1"], value: record }], + }); - // Callback invoked exactly once with the delta's ops - return received.length === 1 && received[0] === delta.ops; + return received.length === 1 && received[0] === record; }), { numRuns: 100 }, ); @@ -436,6 +438,53 @@ describe("SubscriptionTracker - field projection delivery", () => { expect(seen[1]).toEqual(new Uint8Array([9, 2, 3])); }); + test("a nested delivery stops the superseded outer callback loop", () => { + const tracker = new SubscriptionTracker(); + const first: JsonValue[] = []; + const second: JsonValue[] = []; + let nested = false; + + tracker.register(308, { + params: { type: "StoreSubscribe", table_index: "users" }, + docId: "u1", + callbacks: [ + (value) => { + first.push(value); + if (nested) return; + nested = true; + tracker.dispatch({ + type: "StoreDelta", + subId: 308, + ops: [ + { + op: "set", + path: ["users", "u1"], + value: { id: "u1", name: "second", updated_at: 2 }, + }, + ], + }); + }, + (value) => second.push(value), + ], + projection: createListenProjection(["users", "u1", "name"]), + }); + + tracker.dispatch({ + type: "StoreDelta", + subId: 308, + ops: [ + { + op: "set", + path: ["users", "u1"], + value: { id: "u1", name: "first", updated_at: 1 }, + }, + ], + }); + + expect(first).toEqual(["first", "second"]); + expect(second).toEqual(["second"]); + }); + test("own __proto__ keys survive the suppression baseline clone", () => { const tracker = new SubscriptionTracker(); const values: JsonValue[] = []; diff --git a/sdk/typescript/src/subscriptions.ts b/sdk/typescript/src/subscriptions.ts index f7670cf3..9a534211 100644 --- a/sdk/typescript/src/subscriptions.ts +++ b/sdk/typescript/src/subscriptions.ts @@ -1,3 +1,5 @@ +import type { RecordMatcher } from "./filter_eval.js"; +import { type OverlayKeys, PendingWrites } from "./optimistic.js"; import { fieldPathToFlat, getDeepProperty, unflatten } from "./path.js"; import type { JsonValue, StoreDelta, StoreSubscribe } from "./types.js"; @@ -11,33 +13,57 @@ export interface ListenProjection { /** Client-side materialized view for store.subscribe() registrations. */ export interface MaterializedView { - /** Current records keyed by document id. Values are unflattened. */ + /** Server records keyed by document id. Values are unflattened. */ records: Map; /** Total-order comparator applied to every snapshot. Never null. */ comparator: (a: JsonValue, b: JsonValue) => number; + /** The view's `where`; decides membership of locally overlaid records. */ + matches: RecordMatcher; } +/** Second argument of every subscription and listen callback. */ +export interface DeliveryMeta { + /** Views: ids of delivered rows with a pending local write. Listens: whether the document has one. */ + pending: ReadonlySet | boolean; +} + +export type DeliveryCallback = (value: JsonValue, meta: DeliveryMeta) => void; + /** A single registered subscription entry. */ export interface SubscriptionEntry { /** Original StoreSubscribe params — used for replay on reconnect. */ params: Omit; + /** Collection the entry reads. */ + collection: string; /** Registered callbacks to invoke when a delta arrives. */ - callbacks: Array<(value: JsonValue) => void>; + callbacks: DeliveryCallback[]; /** Projection info; null for store.subscribe (collection-level) registrations. */ projection: ListenProjection | null; /** Optional materialized view for collection-level subscriptions. */ materializedView?: MaterializedView; + /** Listen only: the watched document id. */ + docId?: string; + /** Listen only: the latest server record; null when the document is absent. */ + serverRecord?: JsonValue; /** Updates the caller's handle when a reconnect remaps the server subId. */ onRemap?: (newSubId: number) => void; /** Private suppression baseline: an isolated copy of the last value. */ lastValue?: JsonValue; /** Last value delivered to callbacks — what `getSnapshot()` returns. */ deliveredValue?: JsonValue; + /** Pending marker delivered with `deliveredValue`. */ + deliveredPending?: ReadonlySet | boolean; + /** Bumped by each delivery so a nested one supersedes an outer loop. */ + deliveryRevision?: number; } +export const NO_PENDING: ReadonlySet = new Set(); + // ─── SubscriptionTracker ───────────────────────────────────────────────────── export class SubscriptionTracker { + /** Local writes shown before they commit. */ + readonly pending = new PendingWrites(); private readonly subscriptions = new Map(); private readonly deltaQueue: StoreDelta[] = []; private pendingDeltas: StoreDelta[] = []; @@ -48,6 +74,8 @@ export class SubscriptionTracker { private flushScheduled = false; private connected = true; private debug = false; + /** Latest `updated_at` seen or issued, in microseconds. */ + private clock = 0; setDebug(debug: boolean): void { this.debug = debug; @@ -95,6 +123,15 @@ export class SubscriptionTracker { this.connected = false; } + /** + * A timestamp for a local write: after every server timestamp seen, so a + * local create sorts last in the default order, as it will on the server. + */ + provisionalTime(): number { + this.clock = Math.max(Date.now() * 1000, this.clock + 1); + return this.clock; + } + /** * Dispatch a StoreDelta to the appropriate subscription callbacks. * If disconnected, the delta is queued for later delivery. @@ -169,6 +206,23 @@ export class SubscriptionTracker { this._flushPending(); } + /** + * Re-deliver the views and listens that show any of `keys` after a local + * write is added or settles. Views update incrementally: only the + * changed rows move, by binary insertion. + */ + refresh(keys: OverlayKeys): void { + for (const entry of this.subscriptions.values()) { + const ids = keys.get(entry.collection); + if (ids === undefined) continue; + if (entry.materializedView) { + this._refreshView(entry, ids); + } else if (entry.docId !== undefined && ids.has(entry.docId)) { + this._refreshListen(entry); + } + } + } + /** * Apply all pending deltas (per subscription, in arrival order) and * invoke each subscription's callbacks once with the current snapshot. @@ -210,17 +264,7 @@ export class SubscriptionTracker { changed = this._applyOpsToView(entry.materializedView, delta.ops) || changed; } - if (!changed) return; - const value = this._snapshotView(entry.materializedView); - entry.lastValue = value; - entry.deliveredValue = value; - for (const cb of entry.callbacks) { - try { - cb(value); - } catch (err) { - console.error("[SDK] Subscription callback threw:", err); - } - } + if (changed) this._deliverSnapshot(entry); } dispatchInitialSnapshot( @@ -233,25 +277,19 @@ export class SubscriptionTracker { this.dispatch(delta); return; } - // An acknowledged empty collection (value: []) produces no ops. Deliver - // the empty snapshot so subscribers leave their loading state; the - // deliveredValue guard keeps an empty loadMore page from re-delivering - // an existing view. Listen entries keep their no-initial-delivery path: - // their ack value is a records array, not the projected value. const entry = this.subscriptions.get(subId); - if (!entry?.materializedView || entry.deliveredValue !== undefined) { + if (entry === undefined) return; + if (!entry.materializedView) { + // The listened document does not exist; a local create can still show. + entry.serverRecord = null; + this._refreshListen(entry); return; } - const snapshot = this._snapshotView(entry.materializedView); - entry.lastValue = snapshot; - entry.deliveredValue = snapshot; - for (const cb of entry.callbacks) { - try { - cb(snapshot); - } catch (err) { - console.error("[SDK] Subscription callback threw:", err); - } - } + // An acknowledged empty collection (value: []) produces no ops. Deliver + // the empty snapshot so subscribers leave their loading state; the + // deliveredValue guard keeps an empty loadMore page from re-delivering + // an existing view. + if (entry.deliveredValue === undefined) this._deliverSnapshot(entry); } /** @@ -331,12 +369,14 @@ export class SubscriptionTracker { // suppressed like a duplicate empty loadMore page. entry.lastValue = undefined; entry.deliveredValue = undefined; + entry.deliveredPending = undefined; } } } // ─── Private helpers ──────────────────────────────────────────────────────── + /** Listen deltas: the latest server record, with local writes applied. */ private _dispatchDelta(delta: StoreDelta): void { const entry = this.subscriptions.get(delta.subId); if (!entry) { @@ -344,14 +384,10 @@ export class SubscriptionTracker { return; } - let value: JsonValue; - - if (entry.materializedView) { - this._applyOpsToView(entry.materializedView, delta.ops); - value = this._snapshotView(entry.materializedView); - } else { - value = this._project(delta, entry.projection); - } + entry.serverRecord = this._reconstructRecord(delta.ops); + this._observeTime(entry.serverRecord); + const pending = this._listenPending(entry); + const value = this._listenValue(entry, pending); // Field projections extract one value out of each whole pushed record; // sibling or system-field writes must not re-fire them. Scalars compare @@ -360,6 +396,7 @@ export class SubscriptionTracker { if ( entry.projection?.field != null && entry.lastValue !== undefined && + pending === entry.deliveredPending && valuesEqual(value, entry.lastValue) ) { return; @@ -371,45 +408,67 @@ export class SubscriptionTracker { JSON.stringify(value), ); } + this._deliver(entry, value, pending); + } + + private _refreshListen(entry: SubscriptionEntry): void { + if (entry.serverRecord === undefined) return; + const pending = this._listenPending(entry); + const value = this._listenValue(entry, pending); + const unchanged = + entry.deliveredValue !== undefined && + pending === entry.deliveredPending && + valuesEqual(value, entry.lastValue as JsonValue); + if (!unchanged) this._deliver(entry, value, pending); + } + + private _listenPending(entry: SubscriptionEntry): boolean { + return ( + entry.docId !== undefined && + this.pending.has(entry.collection, entry.docId) + ); + } + + private _listenValue(entry: SubscriptionEntry, pending: boolean): JsonValue { + const server = entry.serverRecord ?? null; + const record = pending + ? this.pending.apply(entry.collection, entry.docId as string, server) + : server; + const field = entry.projection?.field; + if (field == null) return record; + return getDeepProperty(record, field.split(".")) ?? null; + } + private _deliverSnapshot(entry: SubscriptionEntry): void { + const { rows, pending } = this._snapshotView(entry); + this._deliver(entry, rows, pending); + } + + /** Deliver `value` with its pending marker to every callback of `entry`. */ + private _deliver( + entry: SubscriptionEntry, + value: JsonValue, + pending: ReadonlySet | boolean, + ): void { // Suppression compares against lastValue; keep an isolated copy so a // callback mutating the delivered value cannot corrupt the baseline. + const revision = (entry.deliveryRevision ?? 0) + 1; + entry.deliveryRevision = revision; entry.lastValue = entry.projection?.field != null ? cloneValue(value) : value; entry.deliveredValue = value; + entry.deliveredPending = pending; + const meta: DeliveryMeta = { pending }; for (const cb of entry.callbacks) { try { - cb(value); + cb(value, meta); } catch (err) { console.error("[SDK] Subscription callback threw:", err); } + if (entry.deliveryRevision !== revision) return; } } - /** - * Apply SDK-side field projection for store.listen registrations. - */ - private _project( - delta: StoreDelta, - projection: ListenProjection | null, - ): JsonValue { - if (projection === null) { - // Fallback — should not normally be reached with materialized view in place - return delta.ops; - } - - const record = this._reconstructRecord(delta.ops); - - if (projection.field === null) { - // Document-level listen — return the unflattened record - return record; - } - - // Depth 3+ — extract the specific nested field - const field = getDeepProperty(record, projection.field.split(".")); - return field !== undefined ? field : null; - } - private _applyRecordOp( flat: Record, op: StoreDelta["ops"][number], @@ -447,6 +506,7 @@ export class SubscriptionTracker { const id = op.path[1] as string; if (op.op === "set") { view.records.set(id, op.value); + this._observeTime(op.value); changed = true; } else if (view.records.delete(id)) { changed = true; @@ -455,14 +515,157 @@ export class SubscriptionTracker { return changed; } + private _observeTime(record: JsonValue | undefined): void { + const time = isPlainRecord(record) ? record.updated_at : undefined; + if (typeof time === "number" && time > this.clock) this.clock = time; + } + + /** + * Every row of the view, local writes applied, sorted by its comparator, + * with the ids of rows that have a pending local write. + */ + private _snapshotView(entry: SubscriptionEntry): { + rows: JsonValue[]; + pending: ReadonlySet; + } { + const view = entry.materializedView as MaterializedView; + if (!this.pending.touches(entry.collection)) { + const rows = Array.from(view.records.values()); + rows.sort(view.comparator); + return { rows, pending: NO_PENDING }; + } + const rows: JsonValue[] = []; + const pending = new Set(); + const add = (id: string, row: JsonValue | null): void => { + if (row === null) return; + rows.push(row); + if (this.pending.has(entry.collection, id)) pending.add(id); + }; + for (const [id, record] of view.records) { + add( + id, + this.pending.has(entry.collection, id) + ? this._viewRow(entry, id) + : record, + ); + } + for (const id of this.pending.ids(entry.collection)) { + if (!view.records.has(id)) add(id, this._viewRow(entry, id)); + } + rows.sort(view.comparator); + return { rows, pending: pending.size === 0 ? NO_PENDING : pending }; + } + + /** Incremental local update: move only the rows of `ids`. */ + private _refreshView( + entry: SubscriptionEntry, + ids: ReadonlySet, + ): void { + const view = entry.materializedView as MaterializedView; + const current = entry.deliveredValue as JsonValue[] | undefined; + if (current === undefined) return; + const before = (entry.deliveredPending ?? + NO_PENDING) as ReadonlySet; + let rows: JsonValue[] | null = null; + let pending: Set | null = null; + for (const id of ids) { + const next = this._viewRow(entry, id); + rows = withRow(current, rows, view.comparator, id, next); + const isPending = next !== null && this.pending.has(entry.collection, id); + if (isPending !== before.has(id)) { + pending = toggle(pending ?? new Set(before), id, isPending); + } + } + if (rows !== null || pending !== null) { + this._deliver(entry, rows ?? current, pending ?? before); + } + } + /** - * Snapshot array from the view; always sorted by the view's comparator. + * The row `id` shows in a view, or null when it shows none: the server + * record, or with pending local writes the overlaid record if it still + * matches the view's `where`. */ - private _snapshotView(view: MaterializedView): JsonValue[] { - const records = Array.from(view.records.values()); - records.sort(view.comparator); - return records; + private _viewRow(entry: SubscriptionEntry, id: string): JsonValue | null { + const view = entry.materializedView as MaterializedView; + const record = view.records.get(id); + if (!this.pending.has(entry.collection, id)) return record ?? null; + const base = record ?? this._serverRecord(entry.collection, id); + const value = this.pending.apply(entry.collection, id, base); + return value !== null && view.matches(value) ? value : null; + } + + /** The server record of a document any view or listen holds, else null. */ + private _serverRecord(collection: string, id: string): JsonValue | null { + for (const entry of this.subscriptions.values()) { + if (entry.collection !== collection) continue; + const record = entry.materializedView + ? entry.materializedView.records.get(id) + : entry.docId === id + ? entry.serverRecord + : undefined; + if (record != null) return record; + } + return null; + } +} + +/** + * The delivered rows with the row of `id` set to `next` (null: none). The + * first change copies `current`, which consumers already hold; `rows` is + * that copy, or null while nothing changed. + */ +function withRow( + current: JsonValue[], + rows: JsonValue[] | null, + comparator: (a: JsonValue, b: JsonValue) => number, + id: string, + next: JsonValue | null, +): JsonValue[] | null { + const list = rows ?? current; + const at = indexOfId(list, id); + if ((at === -1 ? null : list[at]) === next) return rows; + const copy = rows ?? current.slice(); + placeRow(copy, comparator, at, next); + return copy; +} + +function indexOfId(rows: JsonValue[], id: string): number { + for (let i = 0; i < rows.length; i += 1) { + if ((rows[i] as Record).id === id) return i; + } + return -1; +} + +/** Replace, remove or binary-insert the row at `at` (-1: none) in sorted `rows`. */ +function placeRow( + rows: JsonValue[], + comparator: (a: JsonValue, b: JsonValue) => number, + at: number, + next: JsonValue | null, +): void { + if (at !== -1) { + if (next !== null && comparator(rows[at], next) === 0) { + rows[at] = next; + return; + } + rows.splice(at, 1); } + if (next === null) return; + let low = 0; + let high = rows.length; + while (low < high) { + const mid = (low + high) >>> 1; + if (comparator(rows[mid], next) > 0) high = mid; + else low = mid + 1; + } + rows.splice(low, 0, next); +} + +function toggle(set: Set, id: string, on: boolean): Set { + if (on) set.add(id); + else set.delete(id); + return set; } /** Deep equality where arrays and bytes are whole values. */ diff --git a/sdk/typescript/src/types.ts b/sdk/typescript/src/types.ts index f09e0564..525a2151 100644 --- a/sdk/typescript/src/types.ts +++ b/sdk/typescript/src/types.ts @@ -337,15 +337,31 @@ type CollectionOfPath = P extends readonly [ ? C : CollectionsOf; +/** Options every store write accepts. */ +export type WriteOptions = { + /** + * Show the write in subscriptions and listens before it commits, marked + * pending, and revert it if it fails. Default true; writes with `if` are + * never shown early. + */ + optimistic?: boolean; +}; + /** Options for conditional writes; `if` is checked against the stored row at commit. */ -export type ConditionalWriteOptions = { +export type ConditionalWriteOptions< + S extends object = SchemaLike, + P = Path, +> = WriteOptions & { if?: IsLooseSchema extends true ? QueryOptions["where"] : TypedWhere, keyof S & string>>; }; /** Options for atomic increments. */ -export type IncrementOptions = { +export type IncrementOptions< + S extends object = SchemaLike, + P = Path, +> = WriteOptions & { if?: IsLooseSchema extends true ? QueryOptions["where"] : TypedWhere, keyof S & string>>; @@ -390,6 +406,8 @@ export interface SubscriptionHandle< hasMore: boolean; /** Current sorted results; empty before the first delivery. */ getSnapshot: () => RowsOf; + /** Ids of rows in the current results that show a write not yet committed. */ + readonly pendingIds: ReadonlySet; } /** Handle returned by `store.listen`. */ @@ -398,6 +416,20 @@ export interface ListenHandle { unlisten: () => Promise; /** Last value delivered to callbacks for this path; `undefined` before the first. */ getSnapshot: () => GetValue; + /** Whether the current value shows a write not yet committed. */ + readonly isPending: boolean; +} + +/** Second callback argument of `store.subscribe`. */ +export interface SubscriptionMeta { + /** Ids of delivered rows that show a write not yet committed. */ + pending: ReadonlySet; +} + +/** Second callback argument of `store.listen`. */ +export interface ListenMeta { + /** Whether the delivered value shows a write not yet committed. */ + pending: boolean; } // ─── Store interface ────────────────────────────────────────────────────────── @@ -427,22 +459,24 @@ export interface Store { create>( collection: C, value: CreateValue, + options?: WriteOptions, ): Promise; - /** Get current value(s) in a one-off read. */ + /** Get the committed value(s) in a one-off read; local pending writes are not applied. */ get>(path: P): Promise>; /** Listen for changes at a path; resolves with a handle once the registration settles. */ listen>( path: P, - callback: (value: GetValue) => void, + callback: (value: GetValue, meta: ListenMeta) => void, ): Promise>; /** Subscribe to a collection with complex queries; resolves with its handle after server acknowledgement. */ subscribe>( collection: C, options: QueryOptionsFor, - callback: (results: RowsOf) => void, + callback: (results: RowsOf, meta: SubscriptionMeta) => void, ): Promise>; /** Apply operations atomically. Resolves when the batch commits. */ - batch(operations: BatchOperation[]): Promise; + batch(operations: BatchOperation[], options?: WriteOptions): Promise; + /** Query the committed rows once; local pending writes are not applied. */ query>( collection: C, options?: QueryOptionsFor, diff --git a/sdk/typescript/src/value_order.ts b/sdk/typescript/src/value_order.ts new file mode 100644 index 00000000..bcc287f5 --- /dev/null +++ b/sdk/typescript/src/value_order.ts @@ -0,0 +1,80 @@ +import { compareDocIds } from "./doc_id.js"; +import type { JsonValue } from "./types.js"; + +const textEncoder = new TextEncoder(); + +/** + * Orders two non-null scalars as the server does: numbers numerically, + * strings by UTF-8 bytes (packed order when `docId`), booleans + * false < true. Values of different types compare equal. + */ +export function compareScalars( + a: JsonValue, + b: JsonValue, + docId: boolean, +): number { + if (typeof a !== typeof b) return 0; + switch (typeof a) { + case "number": + return compareAsc(a, b as number); + case "boolean": + return a === b ? 0 : a ? 1 : -1; + case "string": + return docId + ? compareDocIds(a, b as string) + : compareUtf8(a, b as string); + default: + return 0; + } +} + +/** Exact scalar equality: numbers by value (0 equals -0), bytes by content. */ +export function scalarsEqual(a: JsonValue, b: JsonValue): boolean { + if (a === b) return true; + if (!(a instanceof Uint8Array) || !(b instanceof Uint8Array)) return false; + if (a.length !== b.length) return false; + for (let i = 0; i < a.length; i += 1) { + if (a[i] !== b[i]) return false; + } + return true; +} + +/** The server's array form: sorted by `compareScalars`, exact duplicates removed. */ +export function sortedSet( + items: readonly JsonValue[], + docId: boolean, +): JsonValue[] { + const sorted = [...items].sort((a, b) => compareScalars(a, b, docId)); + return sorted.filter( + (item, i) => i === 0 || !scalarsEqual(item, sorted[i - 1]), + ); +} + +/** Compares strings by the exact UTF-8 bytes used by SQLite BINARY ordering. */ +export function compareUtf8(a: string, b: string): number { + if (isUtf8LexicalFastPath(a) && isUtf8LexicalFastPath(b)) { + return compareAsc(a, b); + } + return compareUtf8Bytes(a, b); +} + +function compareAsc(a: T, b: T): number { + return a < b ? -1 : a > b ? 1 : 0; +} + +function compareUtf8Bytes(a: string, b: string): number { + const ba = textEncoder.encode(a); + const bb = textEncoder.encode(b); + const length = Math.min(ba.length, bb.length); + for (let i = 0; i < length; i++) { + if (ba[i] !== bb[i]) return ba[i] < bb[i] ? -1 : 1; + } + return ba.length < bb.length ? -1 : ba.length > bb.length ? 1 : 0; +} + +function isUtf8LexicalFastPath(value: string): boolean { + for (let i = 0; i < value.length; i += 1) { + if (value.charCodeAt(i) >= 0x800) return false; + } + return true; +} diff --git a/sdk/typescript/tsconfig.json b/sdk/typescript/tsconfig.json index 6c876d12..72157a6a 100644 --- a/sdk/typescript/tsconfig.json +++ b/sdk/typescript/tsconfig.json @@ -13,5 +13,11 @@ "skipLibCheck": true }, "include": ["src/**/*"], - "exclude": ["node_modules", "dist", "src/**/*.test.ts", "src/test-helpers.ts"] + "exclude": [ + "node_modules", + "dist", + "src/**/*.test.ts", + "src/test-helpers.ts", + "src/filter_eval.vectors.ts" + ] } diff --git a/specs/api-design/error-handling.md b/specs/api-design/error-handling.md index 6adf0582..e52736fd 100644 --- a/specs/api-design/error-handling.md +++ b/specs/api-design/error-handling.md @@ -86,9 +86,9 @@ client.on('error', (error: ZyncBaseError) => { ### 3. WriteError messages -Writer failures arrive as `WriteError`s, not rollback NACKs. They carry the write's request id, and the SDK rejects that write's promise with them. +Writer failures arrive as `WriteError`s. They carry the write's request id, and the SDK rejects that write's promise with them. -`WriteError` is used for user feedback and diagnostics. It does not imply local rollback because the SDK does not apply speculative local subscription updates. +A write the SDK showed optimistically reverts when it fails, whatever the failure: an accept-phase `error`, a `WriteError`, a timeout, or a disconnect. The SDK removes only that write's overlay, then recomputes the displayed value from committed state plus any remaining pending writes; earlier or later pending writes to the same document stay visible. The value returns to committed state only when no pending write remains. Subscriptions and listens deliver the recomputed value again before the promise rejects. `WriteError` is used for user feedback and diagnostics. ### 4. Framework hooks @@ -111,7 +111,7 @@ ZyncBase separates state delivery from write outcome reporting: 4. `PRECONDITION_FAILED` means the write did not apply: a conditional `if` did not hold, the row was missing, or an increment was NULL, out of range, or would overflow. No subscription delta is emitted. The application may retry after re-reading; the SDK never auto-retries a write. 5. Increments are not idempotent. A manual retry after an ambiguous connection failure or timeout may apply twice; there is no write dedupe. -A write that gets no outcome within `writeTimeoutMs` (default 30 s) rejects with `TIMEOUT`. A timeout or a disconnect does not imply the write was aborted or failed to commit. After reconnect, subscriptions remain the source of truth for final state. +A write that gets no outcome within `writeTimeoutMs` (default 30 s) rejects with `TIMEOUT`. A timeout or a disconnect does not imply the write was aborted or failed to commit: its optimistic value reverts, and if it committed, the delta brings it back. After reconnect, subscriptions remain the source of truth for final state. --- diff --git a/specs/api-design/react-api.md b/specs/api-design/react-api.md index 1e2f053d..81eb6571 100644 --- a/specs/api-design/react-api.md +++ b/specs/api-design/react-api.md @@ -34,11 +34,11 @@ Locked during competitive research (session 2026-11-10), with receipts. Cite the | :--- | :--- | :--- | | Package layout | Same package, `/react` subpath (not a second package) | Convex (`convex/react`), Zero (`@rocicorp/zero/react`). At 0.x protocol churn, a second package doubles version choreography; splitting later is easy, merging is not. | | React target | `^19.0.0` peer dependency, **optional** so non-React consumers are unaffected | React 19 covers the audience; `peerDependenciesMeta.optional` keeps Node/bun CLI users of the core package clean. | -| Query hook return | `{ data, isLoading, error }` triad (not a tuple, not `undefined`-punning) | InstantDB, PowerSync (`+isFetching`), Liveblocks all use the triad. Majority of the cohort; friendlier than Convex's `undefined`-while-loading. | +| Query hook return | `{ data, isLoading, error }` triad plus the `pending` marker (not a tuple, not `undefined`-punning) | InstantDB, PowerSync (`+isFetching`), Liveblocks all use the triad. Majority of the cohort; friendlier than Convex's `undefined`-while-loading. | | Conditional queries | `"skip"` sentinel argument (not `enabled: false`) | Convex's documented pattern; one-line semantics, no config object growth. | | Presence hook shape | `{ mine, peers, publish }` with merge-on-publish | InstantDB `db.rooms.usePresence`. Almost identical to our `Presence` client primitive (`localUserId`, unordered `PresenceEntry[]`, `set`). | | Status hook shape | `{ status, synced }` over `ConnectionStatus` + lifecycle events | Liveblocks' richer `lost/restored/failed` vocabulary requires client-side lost-detection the client does not expose yet; keep the hook mapped to existing primitives. | -| Optimistic writes | Out of scope; subscription-first propagation stays (ADR-018) | Local echo is a client-store product decision, not a hooks concern. Mentioned here so it is not rediscovered. | +| Optimistic writes | Applied by the client store (ADR-018); hooks surface `pending` (`useQuery`) and `isPending` (`useListen`) | Local echo is a client-store concern, so every consumer sees the same overlay; hooks only expose which rows are not committed yet. | | Suspense variant | Deferred to a future dual export | Liveblocks ships root + `/suspense`; Zero builds suspense-first. Both validate that this can be added without renaming anything. | ## Package & Exports @@ -77,25 +77,26 @@ import { ZyncBaseProvider } from "@zyncbase/client/react"; ## Hooks -Six hooks, in dependency-free order. All return-triad members are stable between deliveries. +Six hooks, in dependency-free order. All returned fields are stable between deliveries. ### `useQuery(collection, options | "skip")` Reactive collection query over `store.subscribe`. ```typescript -const { data, isLoading, error } = useQuery("tasks", { +const { data, pending, isLoading, error } = useQuery("tasks", { where: { done: false }, orderBy: [{ createdAt: "desc" }], }); const nothing = useQuery("tasks", "skip"); ``` -- `data: RowsOf` — current rows, synchronously available from the first server delivery; `[]` before it and while skipped. +- `data: RowsOf` — current rows, synchronously available from the first server delivery; `[]` before it and while skipped. The client's own writes show here before they commit (ADR-018). +- `pending: ReadonlySet` — ids of rows in `data` that show a write not committed yet; empty before the first delivery and while skipped. - `isLoading` — `true` until **any** snapshot has been delivered since the hook's subscription began; `false` thereafter, also when skipped. - `error: ZyncBaseError | null` — subscription-registration failures land here; render never throws. - Subscribes on mount, `unsubscribe()` on unmount. Re-subscription happens only when the canonical query changes: options are key-serialized (sorted-key canonical form), so callers may pass inline object literals safely. -- `"skip"` registers nothing and resets the triad — the Convex conditional-query idiom for hooks under early returns. +- `"skip"` registers nothing and resets every field — the Convex conditional-query idiom for hooks under early returns. - Pagination (`handle.loadMore`, `hasMore`) is **not** exposed by this hook yet; see [Deliberately Not Included](#deliberately-not-included). ### `useListen(path)` @@ -103,11 +104,12 @@ const nothing = useQuery("tasks", "skip"); Reactive single-path value over `store.listen`. ```typescript -const { value, isLoading, error } = useListen("users.alice.status"); +const { value, isPending, isLoading, error } = useListen("users.alice.status"); ``` - `value: GetValue` — last value, or `undefined` before the first delivery (matches `ListenHandle.getSnapshot` semantics exactly). -- Same triad, subscribe/unmount, and canonical-keying rules as `useQuery`. +- `isPending: boolean` — whether `value` shows a write not committed yet. +- Same `isLoading` / `error`, subscribe/unmount, and canonical-keying rules as `useQuery`. - Changing `path` between renders unlistens the old path and listens the new one; the hook must tolerate the async `unlisten` rejection race by ignoring late deliveries from a detached handle. ### `useAction(name, options?)` @@ -196,7 +198,7 @@ This section binds what the React layer must and must not do: - **Reconnection:** the client restores all active subscriptions and emits `synced`/`reconnected`. Hooks must not unsubscribe/resubscribe on connection events. If a hook re-subscribes on anything, it is wrong. - **Schema change:** the client invalidates active subscriptions and re-registers them itself; hooks again do nothing. Any new data arrives through the same callback. - **Strict Mode:** double mount/unmount must leak neither wires subscriptions nor callbacks. Handles are disposable; late async acks after unmount are ignored, not unawaited garbage. -- **Never read-and-throw:** registration methods whose promise rejects mid-render windows resolve in effect scope, not render scope. The triad fields are the only render-visible effect. +- **Never read-and-throw:** registration methods whose promise rejects mid-render windows resolve in effect scope, not render scope. The returned fields are the only render-visible effect. ## Deliberately Not Included @@ -205,7 +207,6 @@ Named so absence is a decision, not an omission. Each is a cheap follow-up in ve - **`/react/suspense` dual export** — Liveblocks-style; hooks get suspense twins sharing semantics with these names. - **Infinite query hook** — `SubscriptionHandle.loadMore`/`hasMore` exist client-side; a hook will come with cursor UX rather than wrapping them ad hoc. - **Selector + shallow rerender control** (`useOthers(selector, shallow)`, `rowComparator`) — mirror Liveblocks/PowerSync if real apps show over-render pain our snapshot diffing does not already cure. -- **`useMutation`-style write hooks and optimistic local echo** — blocked on an ADR-level product decision in the store, not React. - **TanStack Query adapter** — InstantDB ships one after their React SDK hardened (`start-tanstack` guide), a good precedent for when to add one. - **React Native** — the client library is runtime-agnostic, but hooks stay browser/worker-targeted until someone asks. - **Devtools** — not a spec artifact until the API stabilizes. @@ -215,10 +216,14 @@ Named so absence is a decision, not an omission. Each is a cheap follow-up in ve Creation of `@zyncbase/client/react` is complete; these remain its acceptance criteria. Hook tests run under `@testing-library/react` with happy-dom via Bun; per repo convention, no production code is added to accommodate tests: 1. Provider missing → every hook throws a descriptive dev error. -2. `useQuery` triad transitions: `isLoading` true → false on first delivery; skip sentinel registers nothing; inline option literals do not re-subscribe. -3. `useListen` path change re-binds; late detached deliveries ignored. +2. `useQuery` transitions: `isLoading` true → false on first delivery; `pending` follows each delivery; skip sentinel registers nothing; inline option literals do not re-subscribe. +3. `useListen` path change re-binds; late detached deliveries ignored; `isPending` follows each delivery. 4. `useAction` returns a stable identity; rejects propagate. 5. `usePresence`: `publish` reaches `presence.set`; peers exclude self; two consumers share one wire subscription (registry asserted); last unmount unsubscribes. 6. `useSyncStatus`: maps `statusChange` and `synced`/`reconnected` exactly; correct SSR defaults. 7. Unmount/Strict-Mode double-invoke leaks nothing (mock handles count calls). -8. **One live e2e** against a running server: provider + `useQuery` + `useListen` + real `store.set` round-trip, verifying the hook's `data` matches the plain client's `getSnapshot()` for the same query (existing e2e harness). Protocol changes (if any) re-run `bun run test:e2e` per repo convention. +8. **Live e2e** against a running server (existing e2e harness): + - provider + `useQuery` + `useListen` + real `store.set` round-trip, verifying the hook's `data` matches the plain client's `getSnapshot()` for the same query + - an optimistic write renders, marked pending, before the server round trip; a unique violation renders, then reverts; two clients' concurrent edits converge + + Protocol changes (if any) re-run `bun run test:e2e` per repo convention. diff --git a/specs/api-design/store-api.md b/specs/api-design/store-api.md index a7f551d7..071cd0f9 100644 --- a/specs/api-design/store-api.md +++ b/specs/api-design/store-api.md @@ -4,15 +4,16 @@ The Store API handles durable, synchronized data. Everything in this namespace i Store methods require a ready store scope. `client.connect()` and `client.setStoreNamespace(namespace)` resolve only after the server has resolved the namespace and internal `users.id`. Data operations (`get`, `set`, `remove`, `increment`, `create`, `query`, `batch`) issued before that point fail with `SESSION_NOT_READY`. Subscription registrations (`listen`, `subscribe`) are the exception: they are queued and dispatched when the session becomes ready — see [Subscription Lifecycle](#subscription-lifecycle). -Mutating methods (`set`, `remove`, `increment`, `create`, `batch`) resolve when the writer commits the write and reject on any failure (ADR-018). A read issued after a write resolves observes that write only if no later write to the same field has superseded it; when another client has committed a superseding write, the read returns the newer value ([ADR-010](../architecture/adrs.md#adr-010-conflict-resolution--last-write-wins)). Mutations do not optimistically update local subscription state; subscription callbacks are the authoritative source of committed observable state. +Mutating methods (`set`, `remove`, `increment`, `create`, `batch`) resolve when the writer commits the write and reject on any failure (ADR-018). A read issued after a write resolves observes that write only if no later write to the same field has superseded it; when another client has committed a superseding write, the read returns the newer value ([ADR-010](../architecture/adrs.md#adr-010-conflict-resolution--last-write-wins)). Unless a write opts out, the client shows it in its own subscriptions and listens before it commits, marked pending, and reverts it if it fails ([Optimistic Writes](#optimistic-writes)). Subscription callbacks are the authoritative source of committed observable state. ## Table of Contents 1. [Direct Path Access](#direct-path-access-crud) 2. [Query API (Path Filtering)](#query-api-path-filtering) 3. [Batch Operations](#batch-operations) -4. [Subscription Lifecycle](#subscription-lifecycle) -5. [Path Syntax](#path-syntax-strings-vs-arrays) +4. [Optimistic Writes](#optimistic-writes) +5. [Subscription Lifecycle](#subscription-lifecycle) +6. [Path Syntax](#path-syntax-strings-vs-arrays) --- @@ -28,7 +29,7 @@ There are strict rules on what you can write based on the depth of the path: | **Document** (`'users.u1'`) | `2` | `get`, `set`, `remove`, `listen` | **Full CRUD**. `set` upserts the document, `remove` deletes it. | | **Field** (`'users.u1.name'`) | `3` | `get`, `set`, `listen` | **Updates only**. To clear a field, `set` it to `null`. `remove` is forbidden. | -### `store.create(collection, value)` +### `store.create(collection, value, options?)` Creates a new document within a collection. The SDK generates a canonical lowercase UUIDv7 string and calls `set` under the hood. ```typescript @@ -42,7 +43,7 @@ const id = await client.store.create('elements', { type: 'rect', x: 10 }) Custom document IDs are also supported when supplied in the path directly, but they must match the strict short-ID grammar: `[a-z0-9_-]{1,24}`. ### `store.get(path)` -Read a value from the state tree. +Read a committed value from the state tree; the client's pending writes are not applied. ```typescript const element = client.store.get('elements.rect-1') ``` @@ -90,7 +91,7 @@ await client.store.set('accounts.a1.balance', 900, { **Outcome**: Resolves when the writer commits the write, including a no-op. Rejects with `ZyncBaseError` when the server refuses the write (`details.phase: "accept"`) or the writer rejects it (`details.phase: "write"`). If no outcome arrives within `writeTimeoutMs` (default 30 s), it rejects with `TIMEOUT`; the write may still commit. -**State Propagation**: Local subscription data changes only when the server emits subscription updates. A resolved write promise is not a substitute for subscription state. +**State Propagation**: The write shows in the client's own subscriptions and listens synchronously, marked pending, unless it has `if` or `optimistic: false` ([Optimistic Writes](#optimistic-writes)). Committed state arrives through subscription updates; once the promise resolves, the client's subscriptions show the committed value. **Error Handling**: Every failure rejects the promise and is also emitted on `client.on('error')`; an un-awaited write does not raise an unhandled rejection. Writes are never retried automatically. See [Error Handling](./error-handling.md#error-propagation). A failed `if` rejects with `PRECONDITION_FAILED` (`state`, non-retryable); the application may retry after re-reading. @@ -140,8 +141,8 @@ await client.store.increment('accounts.a1.coins', -100, { ### `store.listen(path, callback)` Listen to real-time updates at a specific path. ```typescript -const { unlisten, getSnapshot } = await client.store.listen('elements.rect-1', (element) => { - render(element) +const { unlisten, getSnapshot } = await client.store.listen('elements.rect-1', (element, { pending }) => { + render(element, pending) }) // Synchronous read of the current value — no round trip @@ -153,10 +154,13 @@ const current = getSnapshot() - **Object** when listening to a document - **Scalar** when listening to a field +The second argument is `{ pending: boolean }`: whether the value shows a write not committed yet ([Optimistic Writes](#optimistic-writes)). + **Returns**: `Promise`: - `unlisten(): Promise` — detaches this consumer; its callback stops firing immediately ([teardown contract](#teardown-and-the-grace-window)). - `getSnapshot(): JsonValue | undefined` — last value delivered to callbacks for this path ([snapshot contract](#snapshots)). +- `isPending: boolean` — whether that value shows a write not committed yet. The callback delivers the initial value and each change to the observed value. For a field path, a delta that leaves the projected value deep-equal — for example a write to a sibling field of the listened document — is not delivered. Document-level listens deliver each updated record. @@ -172,7 +176,7 @@ For filtering, sorting, and searching through data collections. - Filtered real-time subscriptions ### `store.query(collection, options)` -Execute a one-off query (non-real-time). +Execute a one-off query (non-real-time). Like `get`, it returns committed state only; the client's pending writes are not applied. ```typescript const users = await client.store.query('users', { @@ -209,8 +213,8 @@ Subscribe to filtered query results (real-time). const { unsubscribe, loadMore, hasMore } = await client.store.subscribe('tasks', { where: { status: { eq: 'active' } }, limit: 50 -}, (tasks) => { - renderTaskList(tasks) +}, (tasks, { pending }) => { + renderTaskList(tasks, pending) }) // Load older history into the live view @@ -220,7 +224,7 @@ if (hasMore) await loadMore() **Parameters:** - `collection` (string) - Name of the collection to query - `options` (object) - Query options (same as `query()`) -- `callback` (function) - Called when results change +- `callback` (function) - Called when results change, with `{ pending }`: the ids of delivered rows that show a write not committed yet ([Optimistic Writes](#optimistic-writes)) **Returns**: `Promise`: @@ -228,6 +232,7 @@ if (hasMore) await loadMore() - `loadMore(): Promise` — appends the next page ([shared per key](#keyed-sharing)). - `hasMore: boolean` — whether more pages exist ([shared per key](#keyed-sharing)). - `getSnapshot(): JsonValue[]` — current sorted results ([snapshot contract](#snapshots)). +- `pendingIds: ReadonlySet` — ids of rows in those results that show a write not committed yet. Initial and subsequent results are delivered through the callback. @@ -239,7 +244,7 @@ Initial and subsequent results are delivered through the callback. Perform multiple write operations (`set`, `remove`, and `increment`) atomically. -### `store.batch(operations)` +### `store.batch(operations, options?)` Performs all operations atomically. ```typescript await client.store.batch([ @@ -274,6 +279,32 @@ If the first operation's precondition fails, the whole batch rolls back and reje --- +## Optimistic Writes + +A write shows in the issuing client's subscriptions and listens before it commits ([ADR-018](../architecture/adrs.md#adr-018-mutation-outcomes-and-optimistic-local-state)). The callbacks fire synchronously inside the write call, so a controlled input sees its own value in the same handler. + +```typescript +await client.store.subscribe('tasks', { where: { done: false } }, (tasks, { pending }) => { + render(tasks, pending) // pending: ids of rows that show an uncommitted write +}) + +void client.store.set('tasks.t1.done', true) // t1 leaves the view now, not on commit +``` + +`set`, `remove`, `increment`, `create`, and `batch` accept `optimistic?: boolean` (default `true`). + +- **Pending marker**: subscription callbacks receive `{ pending }`, the ids of delivered rows that show an uncommitted write; listen callbacks receive `{ pending: boolean }`. Handles expose the same as `pendingIds` and `isPending`. A change to the marker alone is also delivered. +- **Commit**: the row shows the committed value and leaves the pending set in one delivery. +- **Failure**: any failure (accept phase, write phase, timeout, disconnect) removes only the failed write's overlay before the promise rejects, then recomputes the row from committed state plus any remaining pending writes. The row returns to its committed value only when no pending write remains. A batch removes its whole overlay. +- **Membership**: a pending row is in a filtered view exactly when its local value matches the view's `where` under the server's [matching rules](./query-language.md), at its sorted position. A `create` appears in every matching view. `limit` does not bound pending rows, just as it does not bound live deltas. +- **Shown only when known**: a `set` or `increment` on a document no subscription or listen of this client holds waits for the server, because the document's other fields are unknown. +- **Never shown early**: writes with `if` and batches containing one, writes with `optimistic: false`, and writes issued while the session is not ready or a namespace switch is in flight. +- **Scope**: a disconnect or a store namespace switch drops every pending write. +- **Read rules** run on the server only. A local create that a view's read rule hides shows until it commits, then disappears. +- `get` and `query` return committed state only. + +--- + ## Subscription Lifecycle `store.listen` and `store.subscribe` share one registration lifecycle: readiness queueing, keyed sharing, reference-counted teardown, and synchronous snapshots. diff --git a/specs/architecture/adrs.md b/specs/architecture/adrs.md index 289d2d3f..cf1fae31 100644 --- a/specs/architecture/adrs.md +++ b/specs/architecture/adrs.md @@ -632,11 +632,11 @@ ADR-022 adds `client.actions.*` / `server.actions.*` as a third, independent sur --- -## ADR-018: Mutation Outcomes +## ADR-018: Mutation Outcomes and Optimistic Local State -Client-visible state in a real-time system is observed through subscriptions, but the client that issued a write needs its own definite outcome: to report a failed save, and to read its own write once it resolves. +Client-visible state in a real-time system is observed through subscriptions, but the client that issued a write needs its own definite outcome: to report a failed save, and to read its own write once it resolves. Its UI should also show the write without waiting a round trip. -**Decision**: Every store write (`store.set`, `store.remove`, `store.increment`, `store.create`, `store.batch`) is tracked. Its promise resolves when the writer commits the write and rejects on any failure. Subscriptions deliver committed state to every observer; the write promise reports the outcome to the client that issued it. There is no optimistic local state and no local rollback. +**Decision**: Every store write (`store.set`, `store.remove`, `store.increment`, `store.create`, `store.batch`) is tracked. Its promise resolves when the writer commits the write and rejects on any failure. Subscriptions deliver committed state to every observer; the write promise reports the outcome to the client that issued it. The issuing client also shows the write in its own subscriptions and listens as soon as it sends it: a pending overlay on top of committed state, dropped when the write settles. ### Outcome Reporting @@ -658,10 +658,39 @@ For a covered write while the subscription tracker is synced, when its promise r The server holds a transaction's outcomes until each subscription worker has finished the transaction's changes. When the writer's active-subscription check saw zero subscriptions, outcomes go out as soon as the transaction ends. +### Optimistic Local State + +The SDK keeps committed records exactly as subscriptions deliver them. Pending writes are kept apart, per document, in send order. Each delivered value combines committed state with only the pending writes that committed state does not already reflect; the overlay never changes a committed record. + +1. **Apply.** A document's pending writes apply in send order to its committed record, taken from any subscription or listen that holds it. + - `set` merges into a known document. + - `create` makes a row with every schema field (unset ones null), `owner_id` set to the connection's user id (a `users` row owns itself), and provisional `created_at` / `updated_at` after every server timestamp the client has seen, so it sorts last in the default order. + - `remove` hides the document. + - `increment` adds to a number it can see, unless the committed record already includes it. + - A `set` or `increment` on a document the client holds no record of is not shown. + - Array fields show in the server's sorted-set form; a null object clears every field beneath it. +2. **Revision-bounded prefix reconciliation.** A delta carries committed state, not write identities, so the SDK reconciles pending increments against each observed committed record without treating a value match as authoritative write attribution. Each pending increment remembers the committed value from which it is not yet reflected and the latest observation revision. A delta can carry one pending increment, several coalesced increments, or none. A prefix is considered reflected only when the observed value has changed from that baseline and equals the cumulative `by` through the prefix: an unchanged value never marks a zero-sum run. The covered prefix is marked with the observation's `updated_at` and value, and only the remaining suffix applies. A later committed record at or after that revision skips it; a base that predates it still applies it. An older observation is still projected, but never replaces a baseline or marker learned from a newer one. This is display reconciliation only: another client writing the same value can look like a covered increment until the write outcome or a later delta resolves it. Outcomes remain authoritative. The same rule serves listens and materialized views. +3. **Commit.** A commit drops the write and every earlier pending write's changes to the same documents. The server applies a connection's writes in send order and never retries one, so those writes are already applied or failed. For subscriptions covered by the delivery-ordering guarantee ([Ordering](#ordering)), their deltas arrived before this outcome. A subscription whose response was still in flight when the write was sent is outside that guarantee: the outcome may arrive before its delta. The client has not delivered the optimistic projection to that subscription, so there is no frame to revert; it retains the subscription's committed snapshot and any buffered delta for its `subId`, replays buffered deltas after the initial snapshot, and does not synthesize a post-commit projection. If the snapshot predates the commit and its delta has not arrived, the first callback may observe that committed snapshot until the delta catches it up. Dropping an overlay never changes the committed base; later pending increments already covered by an earlier delta stay marked reflected, so an outcome arriving after a coalesced delta does not make them count twice. +4. **Failure.** Any failure (accept phase, write phase, timeout, disconnect) drops only that write. The displayed value is recomputed from committed state plus remaining pending writes; it returns to committed state only when no pending write remains. The promise rejects and `on('error')` fires. +5. **Scope.** Losing the session or switching the store namespace drops every pending write; subscriptions show committed state, and the snapshot after reconnect is authoritative. +6. **Exclusions.** These writes are never shown early: + - writes with `if`, and batches containing one: compare-and-set depends on server state + - writes with `{ optimistic: false }` + - writes made while the session is not ready (they fail fast) or a namespace switch is in flight +7. **Membership.** A document with pending writes belongs in a view exactly when the overlaid record matches the view's `where` under the server's matching semantics ([Query Engine](../implementation/query-engine.md#client-evaluation)). Its position follows the view's order. `limit` does not apply, as for deltas. + +Delivery: +- A local write is delivered synchronously, inside the write call and after its message is sent, to every affected subscription and listen. Only the changed rows move, by binary insertion; nothing is re-sorted. +- Each delivery carries the ids of rows that show a pending write. A delivery also happens when only that set changes. +- On commit, for subscriptions covered by the delivery-ordering guarantee, the SDK drops the settled overlays, keeps the committed base, and delivers once: no frame shows the previous committed value, and remaining pending increments already covered by the committed record are not applied again. A subscription whose response is still in flight has no prior delivered frame; its first snapshot may predate the commit until the corresponding delta arrives, as described under Commit. +- Read authorization stays on the server. A local create that a view's read rule hides shows until it commits, then leaves with the next snapshot or delta. +- One-shot `get` and `query` return committed state only. + ### Terminology - **committed** — the writer transaction containing the write committed, or the write was a no-op. -- **WriteError** — the name for writer failure messages. Not "NACK" — there is no speculative local state to roll back. +- **pending** — sent and shown locally, outcome not received. +- **WriteError** — the name for writer failure messages. ### Error Phases @@ -679,7 +708,7 @@ Failed batch operations include `batchIndex` when the failing operation is ident Outside an explicit batch, the writer groups queued writes into opportunistic flush transactions. In a flush, guard, precondition, and constraint rejections fail only their own write; storage-level failures (I/O, disk full, allocation, commit) fail every write in the flush. -Subscription observation is transaction-endpoint based. Explicit batches and opportunistic writer flush transactions may coalesce repeated changes to one record into one final delta without changing per-write outcomes. Subscriptions are state replication, not a mutation event log. +Subscription observation is transaction-endpoint based. Explicit batches and opportunistic writer flush transactions may coalesce repeated changes to one record into one final delta without changing per-write outcomes. A coalesced delta covering several pending increments marks the whole covered run as reflected; outcomes that arrive later drop only their own overlays. Subscriptions are state replication, not a mutation event log. ### Retries and Timeouts @@ -703,7 +732,7 @@ Ownership rules such as `{ "$doc.owner_id": { "eq": "$session.userId" } }` natur ### Connection Failures -Write promises are scoped to the originating live connection. On disconnect, the SDK rejects pending write promises with a connection error. The write may still commit. After reconnect, subscriptions are the source of truth for final state. +Write promises are scoped to the originating live connection. On disconnect, the SDK drops pending writes from the overlay and rejects their promises with a connection error. The write may still commit. After reconnect, subscriptions are the source of truth for final state. **Rejected alternatives**: - **Acknowledge writes on acceptance by default** — rejected; write-phase failures (constraint violations, precondition failures, post-read authorization, storage errors) would be invisible to the caller, and a resolved write would not guarantee that a following read sees it. @@ -713,15 +742,17 @@ Write promises are scoped to the originating live connection. On disconnect, the - **Sequence outcomes behind deltas on the event loop** — rejected; the event loop does not know which deltas a transaction produces, only the subscription workers do. - **A marker job per change-queue shard** — rejected; every transaction would cost one job per shard, including shards it never touched. - **No writer failure reporting** — rejected; ambiguous missing deltas cannot support user-facing save-failure feedback. -- **Optimistic local writes** — rejected; requires rollback machinery, conflict handling, and speculative materialized-view logic that the subscription-first model avoids entirely. -- **NACK messages as rollback commands** — rejected; there is no speculative local state to roll back. +- **Show only committed state** — rejected; every UI update would wait a round trip plus the writer's batch window, and a controlled input that waits for its own value loses its caret position. +- **Snapshot and rollback per write** — rejected; restoring a snapshot on failure discards remote changes and later local writes that arrived after it. +- **Attributing deltas by value alone** — rejected; a delta's content cannot prove which write it covers when other clients write the same values, and a coalesced transaction merges several writes into one delta. Value matching is used only for the revision-bounded display reconciliation above, never to settle a write. +- **Optimistic conditional writes** — rejected; an `if` is checked against server state the client may not have. **Consequences**: - A resolved write is durable, a read issued after it resolves observes it, and the issuing client's subscriptions already show it. -- With subscriptions active, write latency includes delta fan-out for the write's transaction. +- With subscriptions active, write latency includes delta fan-out for the write's transaction; the overlay hides it from the issuing client's UI. - Write latency includes the writer's batch window and commit. -- Every write failure reaches the caller; un-awaited writes surface failures on `on('error')`. -- The SDK never speculatively mutates local state; subscriptions are the single source of truth. +- Every write failure reaches the caller; un-awaited writes surface failures on `on('error')`. A failed write shows for up to one round trip plus the writer's batch window, then reverts. +- Committed state comes only from subscriptions; the overlay is a pending, revertible projection on top of it. **Principles**: P-RTF, P-SAT, P-TSF, P-SOT diff --git a/specs/architecture/core-principles.md b/specs/architecture/core-principles.md index ae1276d5..5a73f1fe 100644 --- a/specs/architecture/core-principles.md +++ b/specs/architecture/core-principles.md @@ -40,7 +40,7 @@ ZyncBase is built on thirteen core principles that guide every architectural dec 12. **P-SOT — SQLite as the Source of Truth**: All persistent state lives in SQLite. In-memory structures (subscription engine, lock-free cache, namespace maps) are performance derivatives, never independent sources of truth. On restart, SQLite alone must be sufficient to reconstruct all application state. -13. **P-SAT — Subscriptions as Authority for Client State**: Client-visible committed state is observed through subscriptions, not through write outcomes. A write outcome reports whether that write committed; it does not deliver state. The SDK must not mutate local subscription state speculatively — subscriptions are the source of truth for what the server has committed. +13. **P-SAT — Subscriptions as Authority for Client State**: Client-visible committed state is observed through subscriptions, not through write outcomes. A write outcome reports whether that write committed; it does not deliver state. The SDK may show the client's own pending writes as an overlay, but never changes committed records with them: the overlay is a pending, revertible projection on top of what subscriptions deliver (ADR-018). --- diff --git a/specs/implementation/message-handler.md b/specs/implementation/message-handler.md index 6bcffa74..336aa040 100644 --- a/specs/implementation/message-handler.md +++ b/specs/implementation/message-handler.md @@ -1,6 +1,6 @@ # Message Handler -**Drivers**: [Wire Protocol](./wire-protocol.md), [Threading](./threading.md), [Memory Strategy](./memory-strategy.md), [Error Taxonomy](./error-taxonomy.md), [ADR-015](../architecture/adrs.md#adr-015-scoped-session-management), [ADR-018](../architecture/adrs.md#adr-018-mutation-outcomes) +**Drivers**: [Wire Protocol](./wire-protocol.md), [Threading](./threading.md), [Memory Strategy](./memory-strategy.md), [Error Taxonomy](./error-taxonomy.md), [ADR-015](../architecture/adrs.md#adr-015-scoped-session-management), [ADR-018](../architecture/adrs.md#adr-018-mutation-outcomes-and-optimistic-local-state) `MessageHandler` is the WebSocket request router. It decodes the envelope, enforces connection-local limits, gates operations on scoped session readiness, dispatches to store/presence/subscription/auth services, and encodes either an immediate response or an error. diff --git a/specs/implementation/query-engine.md b/specs/implementation/query-engine.md index ebe8cdfb..fe94d17a 100644 --- a/specs/implementation/query-engine.md +++ b/specs/implementation/query-engine.md @@ -60,6 +60,22 @@ SQL lowering (`filter_sql.zig`) and in-memory evaluation (`eval.zig`) implement - **NULL fields.** A field that is NULL (or absent from the record) matches only `isNull`. Every other operator, `ne` and non-empty `notIn` included, evaluates to false — SQL's three-valued comparison, where `NULL != x` is not true. An empty `notIn` list is the exception: normalization removes `notIn([])` as trivially true, so the resulting filter includes rows with NULL fields. - **NULL operands.** The parser rejects a `null` operand (`NullOperandUnsupported`); `isNull` / `isNotNull` are the only way to test for NULL. +- **Array equality.** Arrays are stored as JSONB in sorted-set form, and an array `eq` / `ne` operand is parsed into the same form and bound through `jsonb(?)`, so SQL compares like for like. + +### Client Evaluation + +The SDK evaluates the same rules for its optimistic overlay (ADR-018): `sdk/typescript/src/filter_eval.ts` decides whether a locally changed record belongs in a view. A filter matches when every `conditions` entry holds and, when `orConditions` is present, at least one of them holds. + +| Operator | Holds when the field is non-null and… | +|---|---| +| `eq` / `ne` | equal / not equal, exactly: text is case-sensitive, numbers compare by value (`0` equals `-0`), arrays compare as sorted sets | +| `gt` / `gte` / `lt` / `lte` | ordered: numbers numerically, text by UTF-8 bytes, booleans `false < true`, document ids in packed order (short ids before UUIDv7) | +| `startsWith` / `endsWith` / `contains` on text | the substring test holds after folding ASCII `A`–`Z` only; other letters compare exactly; an empty operand matches | +| `contains` on an array | the array has an element exactly equal to the operand | +| `in` / `notIn` | the value is / is not a member; `in []` holds for no row and `notIn []` for every row, NULL included | +| `isNull` / `isNotNull` | the field is / is not NULL or absent (no non-null requirement) | + +The vectors in `sdk/typescript/src/filter_eval.vectors.ts` are the conformance suite: `filter_eval.test.ts` runs them against the evaluator, and the e2e suite `tests/e2e/src/test-filter-conformance.ts` runs them against a live server's snapshot (SQL) and delta (in-memory) paths. ## Invariants diff --git a/specs/implementation/storage.md b/specs/implementation/storage.md index 6a843dc7..684d96d4 100644 --- a/specs/implementation/storage.md +++ b/specs/implementation/storage.md @@ -1,6 +1,6 @@ # Storage -**Drivers**: [ADR-005](../architecture/adrs.md#adr-005-sqlite-as-the-storage-engine), [ADR-010](../architecture/adrs.md#adr-010-conflict-resolution--last-write-wins), [ADR-018](../architecture/adrs.md#adr-018-mutation-outcomes), [Threading](./threading.md), [Query Engine](./query-engine.md) +**Drivers**: [ADR-005](../architecture/adrs.md#adr-005-sqlite-as-the-storage-engine), [ADR-010](../architecture/adrs.md#adr-010-conflict-resolution--last-write-wins), [ADR-018](../architecture/adrs.md#adr-018-mutation-outcomes-and-optimistic-local-state), [Threading](./threading.md), [Query Engine](./query-engine.md) The storage layer persists store data in SQLite with WAL mode. It owns schema-to-DDL generation, reader/writer connection roles, typed value encoding, write serialization, query execution, and committed change production. Migration execution runs on the storage engine's setup connection. Its contract lives in [Schema Migrations](./schema-migrations.md). diff --git a/specs/implementation/threading.md b/specs/implementation/threading.md index ecdabe81..63109f56 100644 --- a/specs/implementation/threading.md +++ b/specs/implementation/threading.md @@ -1,6 +1,6 @@ # Threading -**Drivers**: [Threading Model Architecture](../architecture/threading-model.md), [ADR-006](../architecture/adrs.md#adr-006-deterministic-thread-budget-architecture), [ADR-014](../architecture/adrs.md#adr-014-unified-subscription-engine), [ADR-018](../architecture/adrs.md#adr-018-mutation-outcomes) +**Drivers**: [Threading Model Architecture](../architecture/threading-model.md), [ADR-006](../architecture/adrs.md#adr-006-deterministic-thread-budget-architecture), [ADR-014](../architecture/adrs.md#adr-014-unified-subscription-engine), [ADR-018](../architecture/adrs.md#adr-018-mutation-outcomes-and-optimistic-local-state) ZyncBase uses a deterministic thread budget architecture with six thread domains computed from CPU core count. Thread counts are hardcoded via formula — no configuration overrides. The server refuses to start on machines with fewer than 2 CPU cores. diff --git a/specs/implementation/typescript-sdk.md b/specs/implementation/typescript-sdk.md index 6b78b625..e4d181ca 100644 --- a/specs/implementation/typescript-sdk.md +++ b/specs/implementation/typescript-sdk.md @@ -1,6 +1,6 @@ # TypeScript SDK -**Drivers**: [Wire Protocol](./wire-protocol.md), [Error Taxonomy](./error-taxonomy.md), [ADR-017](../architecture/adrs.md#adr-017-strict-sdk-api-surface--store-vs-presence), [ADR-018](../architecture/adrs.md#adr-018-mutation-outcomes) +**Drivers**: [Wire Protocol](./wire-protocol.md), [Error Taxonomy](./error-taxonomy.md), [ADR-017](../architecture/adrs.md#adr-017-strict-sdk-api-surface--store-vs-presence), [ADR-018](../architecture/adrs.md#adr-018-mutation-outcomes-and-optimistic-local-state) The TypeScript SDK owns the browser/application API surface, connection lifecycle, wire translation, local subscription materialization, presence API, retry behavior, and client-side validation before requests reach the server. @@ -14,7 +14,10 @@ The TypeScript SDK owns the browser/application API surface, connection lifecycl | `sdk/typescript/src/pending_requests.ts` | Pending request registry, timeout handling, and write-outcome correlation. | | `sdk/typescript/src/store.ts` | Public store API, subscription registry (keyed sharing, readiness queue, grace teardown), and namespace-aware store connection wrapper. | | `sdk/typescript/src/store_wire.ts` | Store command construction for set/remove/create/get/query/batch/listen/subscribe/loadMore. | -| `sdk/typescript/src/subscriptions.ts` | Local materialized views, listen projections, sorting, pagination, and delta application. | +| `sdk/typescript/src/subscriptions.ts` | Local materialized views, listen projections, sorting, pagination, delta application, and overlay delivery. | +| `sdk/typescript/src/optimistic.ts` | Pending local writes (`PendingWrites`): overlay ops built from sent write messages, apply and settle rules. | +| `sdk/typescript/src/filter_eval.ts` | Client filter evaluator deciding overlay membership in views; vectors in `filter_eval.vectors.ts`. | +| `sdk/typescript/src/value_order.ts` | Server value order: UTF-8 text, packed doc ids, sorted-set arrays. | | `sdk/typescript/src/presence.ts` | Public presence API, user/shared subscriptions, and presence event delivery. | | `sdk/typescript/src/schema_dictionary.ts` | `SchemaSync` dictionary decoding and integer table/field lookup. | | `sdk/typescript/src/errors.ts` | SDK `ErrorCodes`, `ZyncBaseError`, category derivation, and retryability. | @@ -36,7 +39,8 @@ The TypeScript SDK owns the browser/application API surface, connection lifecycl | `PendingRequests` | timers, request ids | Resolves/rejects request promises, including store writes by request id, and enforces the write timeout. | | `StoreImpl` | `StoreCommand`, subscriptions, connection | Implements store reads, writes, batches, listens, load-more behavior, and the keyed subscription registry. The registry shares one server subscription per key across consumers and sits above `SubscriptionTracker` (which remains the subId→entry layer). | | `PresenceImpl` | connection, schema dictionary | Implements user and shared presence APIs. | -| `SubscriptionTracker` | materialized view, comparator, cursor state | Tracks local subscription state and applies `StoreDelta` pushes. | +| `SubscriptionTracker` | materialized view, comparator, cursor state, `PendingWrites` | Tracks local subscription state, applies `StoreDelta` pushes, and delivers committed state with pending writes applied. | +| `PendingWrites` | overlay ops | Pending writes per document in send order; applies them over committed records and settles them. | | `SchemaDictionary` | `SchemaSync` payload | Maps names to integer table/field ids and decodes server records. | | `ZyncBaseError` | `ErrorCodes` | Stable SDK error object and retry metadata. | @@ -65,7 +69,7 @@ The TypeScript SDK owns the browser/application API surface, connection lifecycl 1. Public store/presence method validates SDK inputs and builds a semantic command. 2. `ConnectionManager` ensures the connection and required namespace scope are ready. 3. `ConnectionWireCodec` encodes the command using current schema dictionaries and replaces the logical `type` name with its numeric wire ID from the shared registry (`WireMessageType`); `decodeMessage` maps numeric IDs back to the logical `InboundMessage` type names, so the rest of the SDK never sees numeric wire IDs. -4. `PendingRequests` records the request id; store writes also get the `writeTimeoutMs` timer. +4. `PendingRequests` records the request id; store writes also get the `writeTimeoutMs` timer. Once a write is sent, `StoreImpl` adds it to the overlay and delivers it ([Optimistic Overlay](#optimistic-overlay)). 5. An `ok` or `error` response resolves/rejects the request. A store write gets no `ok`: `WriteCommitted` resolves it, `WriteError` or `error` rejects it, and writes are never retried. 6. Server pushes update subscription and presence listeners. While the subscription tracker is synced, a write's deltas arrive before `WriteCommitted` for subscriptions registered before the writer checks the active subscription count for that write; subscriptions registered after that check are not guaranteed delta-before-`WriteCommitted`. The SDK delivers pending subscription snapshots before the `StoreImpl.write` promise resolves for the deltas that were produced and delivered; a write that produces no delta fires no callback. A write made while the tracker is disconnected can resolve before its queued deltas are delivered on reconnect; `reconnect()` drains and applies them. `flushNow()` flushes only pending batched snapshots, not the disconnected queue. @@ -84,9 +88,22 @@ Recovery orchestration lives in `client.ts` (resolve-at-`synced`, emit `synced`/ - `StoreImpl` and `SubscriptionTracker` receive final nested records. They must not reinterpret positional rows or unflatten complete records. - A malformed correlated record rejects its pending request. A malformed delta push is dropped without preventing later complete messages in the same frame from being processed. +## Optimistic Overlay + +Contract: [ADR-018 → Optimistic Local State](../architecture/adrs.md#optimistic-local-state) and [Store API → Optimistic Writes](../api-design/store-api.md#optimistic-writes). + +- `StoreImpl.write` sends the message first, then `showLocally` builds overlay ops from that sent message (`overlayOps`), so the overlay sees exactly the field paths and values the server does. Delivering after the send keeps a callback that writes from reordering writes on the wire. +- Shaping goes through `SchemaDictionary`: `expandNullNamespaces`, shared with `encodeValue`, clears object namespaces; arrays take the server's sorted-set form; a create gets every schema field plus provisional system fields from `tracker.provisionalTime()`, which stays above the largest `updated_at` the tracker has seen. +- `PendingWrites` holds each entry's ops per document in send order; `apply` replays them over the flattened committed record. Committed records stay untouched in `MaterializedView.records` and `SubscriptionEntry.serverRecord`. +- A document's committed base comes from the entry itself, else from any view or listen of the collection that holds it. Without one, only a pending create produces a row. +- A view admits an overlaid row when `MaterializedView.matches` holds; `compileWhere` builds it once per entry from the subscribe message. +- `refresh(keys)` updates delivered arrays incrementally: copy, find the row by id, replace it in place when the comparator ranks old and new equal, else remove it and binary-insert. Full sorts happen only for server delta flushes and initial snapshots, which apply the overlay too. +- `settle` drops the entry (`commit` or `fail`), calls `flushNow()` on commit, then `refresh`. `markNotReady` (disconnect, namespace commit) clears the overlay and refreshes. +- Each delivery stores `deliveredPending` (views: id set; listens: boolean) next to `deliveredValue`; callbacks receive it as `meta.pending` and handles read it through `pendingIds` / `isPending`. + ## Subscription Delivery Contract -- `store.subscribe` callbacks receive the current full snapshot of matching records and fire **at most once per event-loop tick** while deltas arrive. Deltas within a tick are applied to the local materialized view in arrival order, then one snapshot is delivered. A tick whose ops applied nothing (e.g. removes of absent records) fires no callback. The view state read inside a callback is always current; only the callback timing is batched (≈1 tick, sub-ms to a few ms under load). Unchanged records keep their object reference across snapshots. +- `store.subscribe` callbacks receive the current full snapshot of matching records and fire **at most once per event-loop tick** while deltas arrive. Local writes add a synchronous delivery from the write call (and one when they settle). Deltas within a tick are applied to the local materialized view in arrival order, then one snapshot is delivered. A tick whose ops applied nothing (e.g. removes of absent records) fires no callback. The view state read inside a callback is always current; only the callback timing is batched (≈1 tick, sub-ms to a few ms under load). Unchanged records keep their object reference across snapshots. - `store.listen` callbacks are synchronous per emitted committed delta within the message handling task (single-record projection, O(1) per delta). A field-path delta whose projected value is deep-equal to the last delivered value is not delivered; document-level listens deliver each updated record. A delta represents one record's transaction endpoints, not one write: repeated writes to a record in one writer transaction may yield one callback, and create-then-delete may yield none. - Both preserve per-subscription arrival order; there is no cross-subscription ordering contract. - Delivery is per server subscription, not per consumer: all consumers of a shared key observe the same snapshots at the same times — no per-consumer buffering or divergence. @@ -97,7 +114,7 @@ Recovery orchestration lives in `client.ts` (resolve-at-`synced`, emit `synced`/ - **Keyed sharing.** One server subscription per key (key definition: [Store API → Keyed sharing](../api-design/store-api.md#keyed-sharing)). `StoreImpl`'s keyed registry owns key→subId, refcounts, per-key pagination state (`nextCursor`, `hasMore`), and grace timers. Establishment races use the presence generation-guard pattern (`presence.ts` establish loop): detach-during-establishment re-checks the refcount when the wire response lands and unsubscribes immediately if it is zero. - **Deltas before the ack.** The server registers a subscription before it reads the snapshot, so deltas can arrive before the `ok` that reveals their subId, and the snapshot may predate them. While any subscribe is in flight, `SubscriptionTracker` holds deltas for unknown subIds. `acceptAck` registers the entry, delivers the snapshot, then replays that subId's held deltas in arrival order into the same flush. When no subscribe is in flight the held deltas are discarded; deltas for unknown subIds are then dropped with a warning. - **Grace teardown.** Last-consumer detach schedules the wire unsubscribe after the contract's grace window via a single `setTimeout` per key, cancelled on re-attach. -- **Snapshots.** Collection entries read the sorted `materializedView.records`; listen entries retain a `lastValue` field (projection dispatch stores what it delivers — new field on `SubscriptionEntry`), which `getSnapshot()` returns. +- **Snapshots.** `getSnapshot()` returns the entry's `deliveredValue`: for collections the sorted `materializedView.records` with the overlay applied, for listens the last projected value. - **Namespace switch.** `setStoreNamespace` flushes every live store key against the new namespace through the registry before resolving; registry refcounts are preserved across re-dispatch. Presence and action replay is scoped to `setPresenceNamespace`. ## Error And Retry Rules diff --git a/specs/implementation/wire-protocol.md b/specs/implementation/wire-protocol.md index 6088cf0d..c6c9326e 100644 --- a/specs/implementation/wire-protocol.md +++ b/specs/implementation/wire-protocol.md @@ -1,6 +1,6 @@ # Wire Protocol -**Drivers**: [ADR-008](../architecture/adrs.md#adr-008-wire-encoding), [ADR-009](../architecture/adrs.md#adr-009-integer-routing-architecture), [ADR-014](../architecture/adrs.md#adr-014-unified-subscription-engine), [ADR-018](../architecture/adrs.md#adr-018-mutation-outcomes), [ADR-020](../architecture/adrs.md#adr-020-typed-two-tier-presence-system) +**Drivers**: [ADR-008](../architecture/adrs.md#adr-008-wire-encoding), [ADR-009](../architecture/adrs.md#adr-009-integer-routing-architecture), [ADR-014](../architecture/adrs.md#adr-014-unified-subscription-engine), [ADR-018](../architecture/adrs.md#adr-018-mutation-outcomes-and-optimistic-local-state), [ADR-020](../architecture/adrs.md#adr-020-typed-two-tier-presence-system) This document is the canonical implementation contract for ZyncBase's WebSocket messages. It names the message types, stable fields, source files, and routing rules. Detailed query operators, schema dictionaries, and public error codes live in their owner specs. @@ -181,7 +181,7 @@ Every `StoreSet`, `StoreRemove`, and `StoreBatch` receives exactly one of these | `WriteCommitted` | The writer committed the write, including a no-op. An empty `StoreBatch` commits nothing and receives `WriteCommitted` immediately. | | `WriteError` | The writer rejected the write (`phase: "write"`). | -Store subscription state is updated by committed `StoreDelta` pushes, not by optimistic mutation responses. +Committed store state reaches subscriptions only through `StoreDelta` pushes; write outcomes carry no state. ## Conditional Writes and Atomic Increments diff --git a/src/json/write.zig b/src/json/write.zig index 372122e2..8c85c20f 100644 --- a/src/json/write.zig +++ b/src/json/write.zig @@ -65,6 +65,12 @@ pub const Writer = struct { } fn appendFloat(self: *Writer, value: anytype) !void { + // JSONB keeps the number text, so normalize signed zero: -0.0 and 0.0 + // must serialize identically for array equality. + if (value == 0) { + try self.buf.appendSlice(self.allocator, "0.0"); + return; + } var buf: [64]u8 = undefined; const s = std.fmt.bufPrint(&buf, "{d}", .{value}) catch return error.WriteFailed; if (std.mem.indexOfAny(u8, s, ".eE") == null) { diff --git a/src/query/parser_test.zig b/src/query/parser_test.zig index 80cb3330..b7924cc0 100644 --- a/src/query/parser_test.zig +++ b/src/query/parser_test.zig @@ -347,6 +347,27 @@ test "contains on array field parses using element type" { try testing.expectEqualStrings("urgent", filter.predicate.conditions.?[0].value.?.scalar.text); } +test "eq on array field rejects scalar operand" { + const allocator = std.testing.allocator; + + var schema = try schema_helpers.createTestSchema(allocator, &[_]schema_helpers.TableDef{.{ + .name = "items", + .fields = &[_][]const u8{"tags"}, + .types = &[_]schema_types.FieldType{.array}, + }}); + defer schema.deinit(); + + const tbl = schema.table("items") orelse return error.TestExpectedValue; + const root = try qth.createQueryFilterPayload(allocator, tbl, .{ + .conditions = .{ + .{ "tags", 0, "urgent" }, // eq + }, + }); + defer root.free(allocator); + + try testing.expectError(error.TypeMismatch, query_parser.parseQueryFilter(allocator, &schema, tbl.index, root)); +} + test "contains on text rejects non-string operand" { const allocator = std.testing.allocator; diff --git a/src/storage_engine/filter_sql.zig b/src/storage_engine/filter_sql.zig index 59dbbee7..e4e0e873 100644 --- a/src/storage_engine/filter_sql.zig +++ b/src/storage_engine/filter_sql.zig @@ -121,6 +121,7 @@ pub fn appendConditionSql( .eq, .ne, .gt, .lt, .gte, .lte => { const val = try requireValue(cond); try buf.appendSlice(allocator, cmpOpSql(cond.op)); + if (cond.field_type == .array) try buf.appendSlice(allocator, "jsonb(?)") else try buf.append(allocator, '?'); try appendClonedValue(allocator, values, val); }, .contains => { @@ -157,12 +158,12 @@ fn requireValue(cond: *const query_ast.Condition) !Value { fn cmpOpSql(op: query_ast.Operator) []const u8 { return switch (op) { - .eq => " = ?", - .ne => " != ?", - .gt => " > ?", - .lt => " < ?", - .gte => " >= ?", - .lte => " <= ?", + .eq => " = ", + .ne => " != ", + .gt => " > ", + .lt => " < ", + .gte => " >= ", + .lte => " <= ", else => unreachable, }; } diff --git a/src/subscription/consistency_test.zig b/src/subscription/consistency_test.zig index 22768614..e16c8887 100644 --- a/src/subscription/consistency_test.zig +++ b/src/subscription/consistency_test.zig @@ -117,7 +117,7 @@ test "Subscription Consistency: delta matching agrees with SQL snapshots on NULL var members = [_]typed.ScalarValue{.{ .integer = 5 }}; const ops = [_]query_ast.Operator{ .eq, .ne, .gt, .lt, .gte, .lte, .in, .notIn, .isNull, .isNotNull }; - for (ops, 0..) |op, sub_id| { + for (ops) |op| { const operand: ?typed.Value = switch (op) { .isNull, .isNotNull => null, .in, .notIn => .{ .array = &members }, @@ -125,37 +125,83 @@ test "Subscription Consistency: delta matching agrees with SQL snapshots on NULL }; var filter = try qth.makeFilterWithConditions(allocator, &.{.{ .field_index = score_index, .op = op, .value = operand, .field_type = .integer, .items_type = null }}); defer filter.deinit(allocator); + _ = try expectDeltasAgreeWithSnapshot(allocator, &ctx, items, &stored, &filter, op); + } +} + +test "Subscription Consistency: delta matching agrees with SQL snapshots on array equality" { + const allocator = std.heap.smp_allocator; + + var fields_arr = [_]sth.Field{ + schema_helpers.makeField("name", .text), + schema_helpers.makeField("tags", .array), + }; + var ctx: sth.EngineTestContext = undefined; + try sth.setupEngine(&ctx, allocator, "array-eq-consistency", schema_helpers.makeTable("items", &fields_arr)); + defer ctx.deinit(); + + const items = try ctx.tableMetadata("items"); + const tags_index = items.fieldIndex("tags") orelse return error.UnknownField; + var both = [_]typed.ScalarValue{ .{ .text = "a" }, .{ .text = "b" } }; + var only_a = [_]typed.ScalarValue{.{ .text = "a" }}; + try ctx.insertField("items", 1, 1, "tags", .{ .array = &both }); + try ctx.insertField("items", 2, 1, "tags", .{ .array = &only_a }); + try ctx.insertText("items", 3, 1, "name", "no tags"); + try ctx.engine.flushPendingWrites(); + + var stored: [3]typed.Record = undefined; + for (&stored, 1..) |*record, id| { + record.* = (try sth.readDoc(allocator, &ctx.engine, items.index, @intCast(id), 1)) orelse return error.TestExpectedValue; + } + defer for (stored) |record| record.deinit(allocator); + + for ([_]query_ast.Operator{ .eq, .ne }) |op| { + var filter = try qth.makeFilterWithConditions(allocator, &.{.{ .field_index = tags_index, .op = op, .value = .{ .array = &both }, .field_type = .array, .items_type = .text }}); + defer filter.deinit(allocator); + const matched = try expectDeltasAgreeWithSnapshot(allocator, &ctx, items, &stored, &filter, op); + try testing.expectEqual(@as(usize, 1), matched); + } +} + +/// Asserts that each stored record produces a delta exactly when the SQL +/// snapshot for `filter` contains it. Returns the snapshot size. +fn expectDeltasAgreeWithSnapshot( + allocator: std.mem.Allocator, + ctx: *sth.EngineTestContext, + items: *const sth.TableMetadata, + stored: []const typed.Record, + filter: *const query_ast.QueryFilter, + op: query_ast.Operator, +) !usize { + const snapshot = try sth.queryDocs(allocator, &ctx.engine, items.index, 1, filter); + defer snapshot.deinit(allocator); + + var snapshot_ids = std.AutoHashMap(typed_doc_id.DocId, void).init(allocator); + defer snapshot_ids.deinit(); + for (snapshot.records) |record| { + const id = sth.getFieldDocIdOrNull(record, items, "id") orelse return error.TestExpectedValue; + try snapshot_ids.put(id, {}); + } - const snapshot = try sth.queryDocs(allocator, &ctx.engine, items.index, 1, &filter); - defer snapshot.deinit(allocator); - - var snapshot_ids = std.AutoHashMap(typed_doc_id.DocId, void).init(allocator); - defer snapshot_ids.deinit(); - for (snapshot.records) |record| { - const id = sth.getFieldDocIdOrNull(record, items, "id") orelse return error.TestExpectedValue; - try snapshot_ids.put(id, {}); - } - - var sub_engine = SubscriptionEngine.init(testing.io, allocator); - defer sub_engine.deinit(); - try sub_engine.subscribe(1, items.index, filter, 42, sub_id); - - // A row the snapshot excludes must not produce a delta, and vice versa. - for (stored) |record| { - const matches = try sub_engine.handleRecordChange(.{ - .namespace_id = 1, - .table_index = items.index, - .operation = .insert, - .new_record = record, - .old_record = null, - }, allocator); - defer allocator.free(matches); - const id = sth.getFieldDocIdOrNull(record, items, "id") orelse return error.TestExpectedValue; - const in_snapshot = snapshot_ids.contains(id); - testing.expectEqual(in_snapshot, matches.len > 0) catch |err| { - std.debug.print("operator {s}: record {d} in SQL snapshot: {}, deltas matched: {d}\n", .{ @tagName(op), id, in_snapshot, matches.len }); - return err; - }; - } + var sub_engine = SubscriptionEngine.init(testing.io, allocator); + defer sub_engine.deinit(); + try sub_engine.subscribe(1, items.index, filter.*, 42, 1); + + for (stored) |record| { + const matches = try sub_engine.handleRecordChange(.{ + .namespace_id = 1, + .table_index = items.index, + .operation = .insert, + .new_record = record, + .old_record = null, + }, allocator); + defer allocator.free(matches); + const id = sth.getFieldDocIdOrNull(record, items, "id") orelse return error.TestExpectedValue; + const in_snapshot = snapshot_ids.contains(id); + testing.expectEqual(in_snapshot, matches.len > 0) catch |err| { + std.debug.print("operator {s}: record {d} in SQL snapshot: {}, deltas matched: {d}\n", .{ @tagName(op), id, in_snapshot, matches.len }); + return err; + }; } + return snapshot.records.len; } diff --git a/src/typed/codec.zig b/src/typed/codec.zig index 772ccd13..1f1f9a1a 100644 --- a/src/typed/codec.zig +++ b/src/typed/codec.zig @@ -122,6 +122,7 @@ pub fn fromPayload(allocator: Allocator, ft: schema_types.FieldType, items_type: if (value == .nil) return .nil; return switch (ft) { .array => { + if (value != .arr) return error.TypeMismatch; const it = items_type orelse return error.TypeMismatch; return buildArrayValue(allocator, msgpack.Payload, value.arr, it, scalarFromPayload, struct { fn f(v: msgpack.Payload) bool { diff --git a/src/typed/codec_test.zig b/src/typed/codec_test.zig index 49a316c6..5d8ee18e 100644 --- a/src/typed/codec_test.zig +++ b/src/typed/codec_test.zig @@ -91,6 +91,21 @@ test "writeJsonToBuf: arrays" { } } +test "writeJsonToBuf: negative zero serializes as zero" { + var arena = std.heap.ArenaAllocator.init(std.heap.smp_allocator); + defer arena.deinit(); + const allocator = arena.allocator(); + + var arr = [_]msgpack.Payload{.{ .float = -0.0 }}; + const tv = try typed.fromPayload(allocator, .array, .real, .{ .arr = arr[0..] }); + + var buf: std.ArrayListUnmanaged(u8) = .empty; + defer buf.deinit(allocator); + try typed.writeJsonToBuf(&buf, allocator, tv); + + try testing.expectEqualStrings("[0.0]", buf.items); +} + test "writeJsonToBuf: scalars and nil" { var arena = std.heap.ArenaAllocator.init(std.heap.smp_allocator); defer arena.deinit(); diff --git a/tests/e2e/schema-filter-conformance.json b/tests/e2e/schema-filter-conformance.json new file mode 100644 index 00000000..54778fa1 --- /dev/null +++ b/tests/e2e/schema-filter-conformance.json @@ -0,0 +1,36 @@ +{ + "version": "0.0.1", + "store": { + "vectors": { + "fields": { + "name": { + "type": "string" + }, + "label": { + "type": "string" + }, + "score": { + "type": "integer" + }, + "ratio": { + "type": "number" + }, + "active": { + "type": "boolean" + }, + "tags": { + "type": "array", + "items": "string" + }, + "meta": { + "type": "object", + "fields": { + "rank": { + "type": "integer" + } + } + } + } + } + } +} diff --git a/tests/e2e/src/e2e.test.ts b/tests/e2e/src/e2e.test.ts index 31d74e5b..89e53fb8 100644 --- a/tests/e2e/src/e2e.test.ts +++ b/tests/e2e/src/e2e.test.ts @@ -20,6 +20,7 @@ import { run as runComboStress } from "./test-combo-stress"; import { run as runConditional } from "./test-conditional"; import { run as runCrash } from "./test-crash"; import { run as runErrors } from "./test-errors"; +import { run as runFilterConformance } from "./test-filter-conformance"; import { run as runFilters } from "./test-filters"; import { run as runMigrations } from "./test-migrations"; import { run as runObservability } from "./test-observability"; @@ -139,6 +140,22 @@ describe("ZyncBase E2E", () => { }); }); + test("server filter matching agrees with the SDK evaluator", async () => { + await runE2ETest("Filter conformance", async (ctx) => { + await withServer( + ctx, + { + schemaPath: ctx.schemaPath("schema-filter-conformance.json"), + dataDir: ctx.dataPath("filter-conformance"), + configName: "zyncbase-config-filter-conformance.json", + }, + async ({ port }) => { + await runFilterConformance(port); + }, + ); + }); + }); + test("presence: user state, shared state, merge, throttle, namespace switch", async () => { await runE2ETest("Presence", async (ctx) => { await withServer( diff --git a/tests/e2e/src/react-e2e.test.ts b/tests/e2e/src/react-e2e.test.ts index d02c3ca3..873c34ce 100644 --- a/tests/e2e/src/react-e2e.test.ts +++ b/tests/e2e/src/react-e2e.test.ts @@ -166,4 +166,121 @@ describe("React hooks E2E", () => { ); }); }); + + test("optimistic writes render before the round trip, revert on failure, and converge", async () => { + await runE2ETest("React optimistic writes", async (ctx) => { + await withServer( + ctx, + { + schemaPath: ctx.schemaPath("schema-sync.json"), + dataDir: ctx.dataPath("react-optimistic"), + configName: "zyncbase-config-react-optimistic.json", + authPath: ctx.schemaPath("auth-allow-all.json"), + }, + async ({ port }) => { + const url = `ws://127.0.0.1:${port}`; + const client = createClient({ url, auth: { anonymous: true } }); + const peer = createClient({ url, auth: { anonymous: true } }); + + const renders: OverlayRender[] = []; + function Probe() { + const query = useQuery("unique_projects", {}); + renders.push({ + isLoading: query.isLoading, + slugs: Object.fromEntries( + query.data.map((row) => { + const { id, slug } = row as { id?: unknown; slug?: unknown }; + return [String(id), String(slug)]; + }), + ), + pending: [...query.pending], + }); + return null; + } + const last = () => renders[renders.length - 1]; + + const tree = render( + createElement(ZyncBaseProvider, { client }, createElement(Probe)), + ); + try { + await act(async () => { + await client.connect(); + await peer.connect(); + }); + await waitFor(() => expect(last()?.isLoading).toBe(false), { + timeout: 10_000, + }); + await act(async () => { + await client.store.set("unique_projects.p1", { + slug: "taken", + provider: "gh", + externalId: "1", + }); + await client.store.set("unique_projects.p2", { + slug: "free", + provider: "gh", + externalId: "2", + }); + }); + expect(last()?.slugs).toEqual({ p1: "taken", p2: "free" }); + + // A synchronous act renders before any server reply can be read. + let edit: Promise = Promise.resolve(); + act(() => { + edit = client.store.set("unique_projects.p2.slug", "renamed"); + }); + expect(last()?.slugs.p2).toBe("renamed"); + expect(last()?.pending).toEqual(["p2"]); + await act(async () => { + await edit; + }); + expect(last()?.slugs.p2).toBe("renamed"); + expect(last()?.pending).toEqual([]); + + // A unique violation shows until the server rejects it. + let duplicate: Promise = Promise.resolve(); + act(() => { + duplicate = client.store.set("unique_projects.p2.slug", "taken"); + }); + expect(last()?.slugs.p2).toBe("taken"); + let code: string | undefined; + await act(async () => { + await duplicate.catch((err: { code?: string }) => { + code = err.code; + }); + }); + expect(code).toBe("UNIQUE_CONSTRAINT_VIOLATED"); + expect(last()?.slugs).toEqual({ p1: "taken", p2: "renamed" }); + expect(last()?.pending).toEqual([]); + + // Concurrent edits converge on the server's apply order. + await act(async () => { + await Promise.all([ + client.store.set("unique_projects.p1.slug", "mine"), + peer.store.set("unique_projects.p1.slug", "theirs"), + ]); + }); + const committed = await peer.store.get("unique_projects.p1.slug"); + await waitFor( + () => expect(last()?.slugs.p1).toBe(String(committed)), + { + timeout: 10_000, + }, + ); + expect(last()?.pending).toEqual([]); + } finally { + tree.unmount(); + client.disconnect(); + peer.disconnect(); + } + }, + ); + }); + }); }); + +interface OverlayRender { + isLoading: boolean; + slugs: Record; + pending: string[]; +} diff --git a/tests/e2e/src/test-filter-conformance.ts b/tests/e2e/src/test-filter-conformance.ts new file mode 100644 index 00000000..f297d3a8 --- /dev/null +++ b/tests/e2e/src/test-filter-conformance.ts @@ -0,0 +1,73 @@ +import type { JsonValue, SubscriptionHandle } from "@zyncbase/client"; +import { + FILTER_VECTOR_RECORDS, + FILTER_VECTORS, +} from "../../../sdk/typescript/src/filter_eval.vectors"; +import { ZyncBaseClient } from "./client"; + +const COLLECTION = "vectors"; + +function sortedIds(rows: JsonValue[]): string[] { + return (rows as Record[]) + .map((row) => row.id as string) + .sort(); +} + +function mismatch( + label: string, + actual: string[], + expected: string[], +): string | null { + const want = [...expected].sort(); + return JSON.stringify(actual) === JSON.stringify(want) + ? null + : `${label}: expected [${want.join(", ")}], got [${actual.join(", ")}]`; +} + +/** + * Runs the SDK filter vectors against the server's two matching paths: + * deltas (in-memory) for views subscribed before the writes, and snapshots + * (SQL) for queries issued after them. + */ +export async function run(port: number): Promise { + const client = new ZyncBaseClient(`ws://127.0.0.1:${port}`); + const handles: SubscriptionHandle[] = []; + try { + await client.connect(); + for (const vector of FILTER_VECTORS) { + handles.push( + await client.store.subscribe( + COLLECTION, + { where: vector.where }, + () => {}, + ), + ); + } + for (const { id, ...value } of FILTER_VECTOR_RECORDS) { + await client.store.set([COLLECTION, id], value, { optimistic: false }); + } + + const failures: string[] = []; + for (const [i, vector] of FILTER_VECTORS.entries()) { + const deltas = sortedIds(handles[i].getSnapshot()); + const snapshot = sortedIds( + await client.store.query(COLLECTION, { where: vector.where }), + ); + for (const failure of [ + mismatch(`${vector.name} (deltas)`, deltas, vector.expected), + mismatch(`${vector.name} (snapshot)`, snapshot, vector.expected), + ]) { + if (failure) failures.push(failure); + } + } + if (failures.length > 0) { + throw new Error(`Filter conformance failed:\n${failures.join("\n")}`); + } + console.log( + `E2E filter conformance passed (${FILTER_VECTORS.length} vectors).`, + ); + } finally { + await Promise.all(handles.map((handle) => handle.unsubscribe())); + client.close(); + } +}