Skip to content

Commit dd14e51

Browse files
ampagenttmm
andcommitted
zero-swift: port upstream's aggregate client tests, and rebase only for mutations from before a launch
Ports zero-client's aggregate-read-your-writes, group-read-your-writes, crud-impl, custom, context, ivm-branch, keys and zero-poke-handler tests of synced aggregates as JS-generated client scenarios (and an `aggregate-row-key` vector), so Swift replays what JS does: read-your-writes in both the optimistic and the rebase run, a distinct's new and removed values, groupBy sum and avg creating a group, an orderBy-reordered group key, an edit inside a group the client lacks, JSON path sums, null correlations, row counts, junction aggregates, and source release. Three scenarios showed Swift moving a synced group JS doesn't: the rebase Swift runs when an aggregate first registers (standing in for the writes JS persists for a pending mutation across a relaunch) also ran for mutations made since launch, after the server dropped the query, or when a mutator's read was the only reader. It now runs only while a mutation replayed at launch is pending. Co-authored-by: tmm <tmm@tmm.dev> Amp-Thread-ID: https://ampcode.com/threads/T-01a19a37-5aa9-7256-bff5-cdc47c01a1fe
1 parent 1c93766 commit dd14e51

11 files changed

Lines changed: 2602 additions & 43 deletions

File tree

‎.changeset/swift-synced-aggregates.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22
'zero-swift': patch
33
---
44

5-
Aggregates, `distinct()` and `groupBy()` sync from zero-cache: a named query's view reads the rows the server computes, stored under `a/`, instead of dropping them from pokes. Until the server answers, a view computes nothing and shows the empty value (`0` for a count). A local mutation moves a synced relationship aggregate or grouped count at once, as the JS client's optimistic deltas do, and the server's rows replace them when it confirms. A mutator's `tx.run` reads the synced rows for a query the server has answered, and computes them otherwise. Pending mutations are rebased when a synced aggregate's query first materializes after launch, so a relaunched client keeps their moves.
5+
Aggregates, `distinct()` and `groupBy()` sync from zero-cache: a named query's view reads the rows the server computes, stored under `a/`, instead of dropping them from pokes. Until the server answers, a view computes nothing and shows the empty value (`0` for a count). A local mutation moves a synced relationship aggregate or grouped count at once, as the JS client's optimistic deltas do, and the server's rows replace them when it confirms. A mutator's `tx.run` reads the synced rows for a query the server has answered, and computes them otherwise. While mutations made before a relaunch are pending, they are rebased when a synced aggregate's query first materializes, so the relaunched client keeps their moves.

‎packages/zero-conformance/src/client/app.ts‎

Lines changed: 107 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,66 @@ export const queries = defineQueries({
8383
timeByAuthor: defineQuery(() =>
8484
zql.comment.groupBy('authorId').sum('createdAt'),
8585
),
86+
// From zero-client's aggregate-read-your-writes, group-read-your-writes,
87+
// context, crud-impl and custom tests.
88+
issueWithCommentCount: defineQuery(({args}: {args: string}) =>
89+
zql.issue
90+
.where('id', args)
91+
.related('comments', q => q.count())
92+
.one(),
93+
),
94+
openByState: defineQuery(() =>
95+
zql.issue.where('closed', false).groupBy('closed').count(),
96+
),
97+
issueStates: defineQuery(() => zql.issue.distinct('closed')),
98+
issueStateCount: defineQuery(() => zql.issue.distinct('closed').count()),
99+
countByState: defineQuery(() => zql.issue.groupBy('closed').count()),
100+
timeByState: defineQuery(() =>
101+
zql.issue.groupBy('closed').sum('createdAt'),
102+
),
103+
avgTimeByState: defineQuery(() =>
104+
zql.issue.groupBy('closed').avg('createdAt'),
105+
),
106+
issuesByOwner: defineQuery(() =>
107+
zql.issue.groupBy('closed', 'ownerId').count().orderBy('ownerId', 'desc'),
108+
),
109+
latestIssueTime: defineQuery(() => zql.issue.max('createdAt')),
110+
commentAndLabelCounts: defineQuery(() =>
111+
zql.issue
112+
.related('comments', q => q.count())
113+
.related('labels', q => q.count())
114+
.orderBy('id', 'asc'),
115+
),
116+
commentTimeSums: defineQuery(() =>
117+
zql.issue
118+
.related('comments', q => q.sum('createdAt'))
119+
.orderBy('id', 'asc'),
120+
),
121+
userIssueCounts: defineQuery(() =>
122+
zql.user.related('issues', q => q.count()).orderBy('id', 'asc'),
123+
),
124+
// `points` isn't in the metadata's declared type, which only the
125+
// builder's types check.
126+
pointsByName: defineQuery(() =>
127+
zql.user
128+
.groupBy('name')
129+
// oxlint-disable-next-line @typescript-eslint/no-explicit-any
130+
.sum(({json}) => (json as any)('metadata', 'points')),
131+
),
132+
avgPointsByName: defineQuery(() =>
133+
zql.user
134+
.groupBy('name')
135+
// oxlint-disable-next-line @typescript-eslint/no-explicit-any
136+
.avg(({json}) => (json as any)('metadata', 'points')),
137+
),
138+
labelMax: defineQuery(() =>
139+
zql.issue.related('labels', q => q.max('name')).orderBy('id', 'asc'),
140+
),
141+
bugLabelCounts: defineQuery(() =>
142+
zql.issue
143+
.related('labels', q => q.where('name', 'bug').count())
144+
.orderBy('id', 'asc'),
145+
),
86146
},
87147
// A table with a compound primary key.
88148
issueLabels: {
@@ -201,33 +261,59 @@ const harden = {
201261
}),
202262
};
203263

204-
/**
205-
* Runs `ops` (CRUD operations, as `harden.ops` does), then each of the named
206-
* `queries` through the transaction, and returns what they read: a query the
207-
* server has answered reads its synced aggregates, any other computes them.
208-
*/
264+
type QueryRef = {name: string; args?: ReadonlyJSONValue};
265+
266+
/** What each of `refs` reads through `tx`, as JSON. */
267+
async function readAll(tx: Tx, refs: QueryRef[]): Promise<ReadonlyJSONValue[]> {
268+
const out: ReadonlyJSONValue[] = [];
269+
for (const {name, args: queryArgs} of refs) {
270+
let v: unknown = queries;
271+
for (const part of name.split('.')) {
272+
v = (v as Record<string, unknown>)[part];
273+
}
274+
const request = (v as (...a: unknown[]) => unknown)(
275+
...(queryArgs === undefined ? [] : [queryArgs]),
276+
);
277+
// oxlint-disable-next-line @typescript-eslint/no-explicit-any
278+
const result = await tx.run(addContextToQuery(request as any, undefined));
279+
out.push(JSON.parse(JSON.stringify(result ?? null)));
280+
}
281+
return out;
282+
}
283+
209284
const aggregates = {
285+
/**
286+
* Runs `ops` (CRUD operations, as `harden.ops` does), then each of the named
287+
* `queries` through the transaction, and returns what they read: a query the
288+
* server has answered reads its synced aggregates, any other computes them.
289+
*/
210290
read: defineMutator(async ({tx, args}: {tx: Tx; args: JSONObject}) => {
211291
for (const o of (args['ops'] ?? []) as CRUDOp[]) {
212292
await tx.mutate[o.table][o.op](o.value);
213293
}
214-
const out: ReadonlyJSONValue[] = [];
215-
for (const {name, args: queryArgs} of (args['queries'] ?? []) as {
216-
name: string;
217-
args?: ReadonlyJSONValue;
218-
}[]) {
219-
let v: unknown = queries;
220-
for (const part of name.split('.')) {
221-
v = (v as Record<string, unknown>)[part];
222-
}
223-
const request = (v as (...a: unknown[]) => unknown)(
224-
...(queryArgs === undefined ? [] : [queryArgs]),
225-
);
226-
// oxlint-disable-next-line @typescript-eslint/no-explicit-any
227-
const result = await tx.run(addContextToQuery(request as any, undefined));
228-
out.push(JSON.parse(JSON.stringify(result ?? null)));
294+
return readAll(tx, (args['queries'] ?? []) as QueryRef[]);
295+
}),
296+
/**
297+
* Reads the `queries`, runs `ops`, and reads them again; returns both
298+
* reads. With `record`, it also upserts the user `record` with the
299+
* transaction's reason as its name and the reads as its metadata, so a
300+
* view of the users shows what the latest run, a rebase too, read.
301+
*/
302+
record: defineMutator(async ({tx, args}: {tx: Tx; args: JSONObject}) => {
303+
const refs = (args['queries'] ?? []) as QueryRef[];
304+
const before = await readAll(tx, refs);
305+
for (const o of (args['ops'] ?? []) as CRUDOp[]) {
306+
await tx.mutate[o.table][o.op](o.value);
307+
}
308+
const after = await readAll(tx, refs);
309+
if (typeof args['record'] === 'string') {
310+
await tx.mutate.user.upsert({
311+
id: args['record'],
312+
name: tx.reason,
313+
metadata: {before, after},
314+
});
229315
}
230-
return out;
316+
return {before, after};
231317
}),
232318
};
233319

‎packages/zero-conformance/src/client/scenarios.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import type {Scenario} from './harness.ts';
2-
import {aggregateScenarios} from './scenarios/aggregates.ts';
2+
import {
3+
aggregateScenarios,
4+
upstreamAggregateScenarios,
5+
} from './scenarios/aggregates.ts';
36
import {connectionScenarios} from './scenarios/connection.ts';
47
import {errorScenarios} from './scenarios/errors.ts';
58
import {mutationScenarios} from './scenarios/mutations.ts';
@@ -14,6 +17,7 @@ export const scenarios: Scenario[] = [
1417
...pokeScenarios,
1518
...queryScenarios,
1619
...aggregateScenarios,
20+
...upstreamAggregateScenarios,
1721
...mutationScenarios,
1822
...persistenceScenarios,
1923
...visibilityScenarios,

0 commit comments

Comments
 (0)