@hydranium/conformance 1.0.0-next.28 → 1.0.0-next.281

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/data/index.ts CHANGED
@@ -10,39 +10,75 @@
10
10
  /**
11
11
  * The `@hydranium/conformance/data` slice — protocol conformance for the
12
12
  * data-server head. The driver port IS the protocol-native
13
- * {@link DataServerProtocol} proxy (plus the captured `onDocumentUpdated`
14
- * events), so no upstream wire-lib dep enters the kit and `DataServerHarness`
15
- * satisfies the port structurally with no adapter.
13
+ * {@link DataServerProtocol} proxy (plus the captured client notifications),
14
+ * so no upstream wire-lib dep enters the kit and `DataServerHarness` satisfies
15
+ * the port structurally with no adapter.
16
16
  */
17
17
 
18
18
  import assert from 'node:assert/strict';
19
- import { TransferDocument, type TransferDiagnostic, type TransferElement } from '@hydranium/protocol';
20
- import type { DataServerProtocol, TransferDocumentUpdatedEvent } from '@hydranium/protocol/data';
19
+ import {
20
+ asModelVersion,
21
+ FRAMEWORK_CLIENT_IDS,
22
+ isConflictError,
23
+ isDocumentNotOpenError,
24
+ isDuplicateClientIdError,
25
+ isReservedClientIdError,
26
+ isSessionClosedError,
27
+ randomUuid,
28
+ ReferenceSource,
29
+ SyntheticStep,
30
+ SystemClock,
31
+ TransferDocument,
32
+ type TransferDiagnostic,
33
+ type TransferElement,
34
+ UNKNOWN_CLIENT_ID
35
+ } from '@hydranium/protocol';
36
+ import type {
37
+ DataServerProtocol,
38
+ ReferenceServerProtocol,
39
+ TransferDocumentDeletedEvent,
40
+ TransferDocumentsBuiltEvent,
41
+ TransferDocumentUpdatedEvent
42
+ } from '@hydranium/protocol/data';
21
43
  import { type Harness, waitFor } from '@hydranium/protocol/testing';
22
44
  import type { ConformanceCheck } from '../conformance-suite.js';
23
45
  import { type LanguageFixture, resolveDeferred, resolveModel } from '../model.js';
24
46
 
25
47
  /**
26
48
  * The data-server driver port — a live, connected, READY data-server exposed
27
- * through its protocol-native proxy plus the captured client-side update
28
- * events. The kit names only `@hydranium/protocol` types, so a
49
+ * through its protocol-native proxy plus the captured client-side
50
+ * notifications. The kit names only `@hydranium/protocol` types, so a
29
51
  * `DataServerHarness` satisfies the port structurally (it has `proxy` +
30
- * `events` + `dispose`) with NO adapter. `extends Harness` gives the kit the
31
- * universal `dispose()` teardown.
52
+ * `events`, `builds`, `deletions` and `dispose`) with NO adapter.
53
+ * `extends Harness` gives the kit the universal `dispose()` teardown.
32
54
  *
33
- * The kit seeds documents purely through the proxy: `updateModelDocument` is
34
- * an upsert (it creates a cold URI from the payload, not just modifies an
35
- * existing one), so the slice needs no services-level open hook. The adopter
36
- * only has to stand the server up READY in its `connect` — see
37
- * {@link DataConformanceOptions.connect}.
55
+ * The kit seeds documents purely through the proxy, as client sessions: it
56
+ * registers one with `createSession`, opens the document, or creates it with
57
+ * `createModelDocument` when there is no file to open, and writes it. So the
58
+ * head under test must implement sessions, and the slice needs no
59
+ * services-level open hook. The adopter only has to stand the server up READY
60
+ * in its `connect` — see {@link DataConformanceOptions.connect}.
38
61
  */
39
62
  export interface DataConformanceDriver<
40
63
  TTransfer extends TransferElement,
41
64
  TDiagnostic extends TransferDiagnostic = TransferDiagnostic
42
65
  > extends Harness {
43
66
  readonly proxy: DataServerProtocol<TTransfer, TDiagnostic>;
44
- /** Captured `onDocumentUpdated` events, append order — the subscription check's observation target. */
67
+ /** Captured `onDocumentUpdated` events, in append order. */
45
68
  readonly events: ReadonlyArray<TransferDocumentUpdatedEvent<TTransfer, TDiagnostic>>;
69
+ /** Captured `onDocumentsBuilt` events, append order — the cascade check's observation target. */
70
+ readonly builds: ReadonlyArray<TransferDocumentsBuiltEvent>;
71
+ /** Captured `onDocumentDeleted` events, append order. */
72
+ readonly deletions: ReadonlyArray<TransferDocumentDeletedEvent>;
73
+ /**
74
+ * The opt-in reference surface, when the head serves it.
75
+ *
76
+ * Separate from {@link proxy} because `ReferenceServerProtocol` is NOT part
77
+ * of `DataServerProtocol` — a head may serve documents and no references at
78
+ * all. Absent means the reference check reports skipped with a named reason
79
+ * rather than failing a head that never claimed the surface.
80
+ */
81
+ readonly references?: ReferenceServerProtocol;
46
82
  }
47
83
 
48
84
  /** Options for `runDataConformance`. */
@@ -52,6 +88,9 @@ export interface DataConformanceOptions<TTransfer extends TransferElement, TDiag
52
88
  * once per check for isolation; the kit disposes it after the check. The
53
89
  * adopter must initialise the workspace before returning, so `waitForReady`
54
90
  * resolves rather than hanging.
91
+ *
92
+ * Some checks save and delete documents beside each fixture's `valid`, so
93
+ * give each check a workspace the kit may write to and throw away.
55
94
  */
56
95
  readonly connect: () => DataConformanceDriver<TTransfer, TDiagnostic> | Promise<DataConformanceDriver<TTransfer, TDiagnostic>>;
57
96
  /** Per-language fixtures; the grammar-bearing checks run once per language. */
@@ -67,22 +106,141 @@ export interface DataConformanceOptions<TTransfer extends TransferElement, TDiag
67
106
  * from "never implemented" without the adopter saying which it is.
68
107
  */
69
108
  readonly expectsProjects?: boolean;
70
- /** Suite title override. Default `'conformance: data-server'`. */
109
+ /**
110
+ * Open another connection to the same server as `driver`, for the check
111
+ * that a connection's sessions end with it while the server lives on. That
112
+ * check disposes `driver` and needs its `dispose` to close the connection as
113
+ * the server sees it. Absent, the check reports skipped.
114
+ */
115
+ readonly attach?: (
116
+ driver: DataConformanceDriver<TTransfer, TDiagnostic>
117
+ ) => DataConformanceDriver<TTransfer, TDiagnostic> | Promise<DataConformanceDriver<TTransfer, TDiagnostic>>;
118
+ /** Suite title override. Default `'data-server conformance'`. */
71
119
  readonly suiteTitle?: string;
72
120
  }
73
121
 
74
- /** Client id the kit seeds/edits documents under (the originating author). */
75
- const AUTHOR = 'conformance-author';
76
- /** Client id the kit subscribes under — distinct from {@link AUTHOR} so the echo is recognisable. */
122
+ /** Client id the kit subscribes under; a watch needs no session. */
77
123
  const SUBSCRIBER = 'conformance-subscriber';
124
+
78
125
  /**
79
- * Client id for a write made BEFORE any subscription exists. Distinct from
80
- * {@link AUTHOR} so an event caused by it is recognisable: a head that fans
81
- * notifications out regardless of its subscription table is otherwise
82
- * indistinguishable from one that honours the table, since both deliver
83
- * something for the post-subscribe write.
126
+ * A fresh session id per check. A fixed one would be refused as a duplicate
127
+ * by a head whose `connect` reuses one server across checks, whenever an
128
+ * earlier check failed before ending its session.
84
129
  */
85
- const SEEDER = 'conformance-seeder';
130
+ function sessionId(label = 'conformance-session'): string {
131
+ return `${label}#${randomUuid()}`;
132
+ }
133
+
134
+ /** Register a session under a fresh id labelled `label`, and answer the id. */
135
+ async function startSession<TTransfer extends TransferElement, TDiagnostic extends TransferDiagnostic>(
136
+ driver: DataConformanceDriver<TTransfer, TDiagnostic>,
137
+ label: string
138
+ ): Promise<string> {
139
+ const clientId = sessionId(label);
140
+ await driver.proxy.createSession({ clientId, label });
141
+ return clientId;
142
+ }
143
+
144
+ /**
145
+ * Create `model` for the session `clientId`, then open it, since a fixture may
146
+ * name a document that exists nowhere but in the kit. A failed create is
147
+ * dropped when the open succeeds, so a head whose create is broken fails only
148
+ * the create check; an open that fails reports both failures.
149
+ */
150
+ async function openOrCreate<TTransfer extends TransferElement, TDiagnostic extends TransferDiagnostic>(
151
+ driver: DataConformanceDriver<TTransfer, TDiagnostic>,
152
+ clientId: string,
153
+ model: { readonly uri: string; readonly text: string }
154
+ ): Promise<void> {
155
+ const created = await rejectionOf(driver.proxy.createModelDocument({ uri: model.uri, clientId, text: model.text }));
156
+ const opened = await rejectionOf(driver.proxy.openModelDocument({ uri: model.uri, clientId }));
157
+ if (opened !== undefined) {
158
+ throw new Error(`Could not seed ${model.uri}: ${String(opened)}; creating it failed with ${String(created)}`, { cause: opened });
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Write `model` to its URI under a new session labelled `label`, and answer the
164
+ * session's id. The session keeps the document open until the driver is
165
+ * disposed: closing it would revert the document to its file, which holds
166
+ * another text or none.
167
+ */
168
+ async function seed<TTransfer extends TransferElement, TDiagnostic extends TransferDiagnostic>(
169
+ driver: DataConformanceDriver<TTransfer, TDiagnostic>,
170
+ model: { readonly uri: string; readonly text: string },
171
+ label = 'conformance-seeder'
172
+ ): Promise<string> {
173
+ const clientId = await startSession(driver, label);
174
+ await openOrCreate(driver, clientId, model);
175
+ await driver.proxy.updateModelDocument({ uri: model.uri, clientId, model: model.text, baseVersion: 'any' });
176
+ return clientId;
177
+ }
178
+
179
+ /** A new session labelled `label` with `uri` open, for a write after the seed; answers its id. */
180
+ async function openAs<TTransfer extends TransferElement, TDiagnostic extends TransferDiagnostic>(
181
+ driver: DataConformanceDriver<TTransfer, TDiagnostic>,
182
+ uri: string,
183
+ label = 'conformance-author'
184
+ ): Promise<string> {
185
+ const clientId = await startSession(driver, label);
186
+ await driver.proxy.openModelDocument({ uri, clientId });
187
+ return clientId;
188
+ }
189
+
190
+ /**
191
+ * Register `clientId` on `driver`, retrying while the server still refuses it
192
+ * as a duplicate, for up to `boundMs`; the last refusal is thrown.
193
+ */
194
+ async function registerWithin<TTransfer extends TransferElement, TDiagnostic extends TransferDiagnostic>(
195
+ driver: DataConformanceDriver<TTransfer, TDiagnostic>,
196
+ clientId: string,
197
+ boundMs: number
198
+ ): Promise<void> {
199
+ const waited = new SystemClock().stopwatch();
200
+ for (;;) {
201
+ const refusal = await rejectionOf(driver.proxy.createSession({ clientId }));
202
+ if (refusal === undefined) {
203
+ return;
204
+ }
205
+ if (!isDuplicateClientIdError(refusal) || waited.elapsedMs >= boundMs) {
206
+ throw refusal;
207
+ }
208
+ await new Promise(resolveDelay => setTimeout(resolveDelay, 20));
209
+ }
210
+ }
211
+
212
+ /** A URI beside `uri` in its folder, its file name prefixed with `prefix`, so the language and project stay the fixture's. */
213
+ function siblingOf(uri: string, prefix: string): string {
214
+ const slash = uri.lastIndexOf('/') + 1;
215
+ return `${uri.slice(0, slash)}${prefix}${uri.slice(slash)}`;
216
+ }
217
+
218
+ /**
219
+ * Read `uri` until `settled` holds of the answer, for up to two seconds; fail
220
+ * with `message` after that. For an effect a head may finish after its request
221
+ * answered, such as the revert of a last close. A refused read reaches
222
+ * `settled` as `undefined`.
223
+ */
224
+ async function readUntil<TTransfer extends TransferElement, TDiagnostic extends TransferDiagnostic>(
225
+ driver: DataConformanceDriver<TTransfer, TDiagnostic>,
226
+ uri: string,
227
+ settled: (document: TransferDocument<TTransfer, TDiagnostic> | undefined) => boolean,
228
+ message: string
229
+ ): Promise<void> {
230
+ const waited = new SystemClock().stopwatch();
231
+ while (!settled(await driver.proxy.getModelDocument({ uri }).catch(() => undefined))) {
232
+ assert.ok(waited.elapsedMs < 2_000, message);
233
+ await new Promise(resolveDelay => setTimeout(resolveDelay, 20));
234
+ }
235
+ }
236
+
237
+ /** Settle `promise` into its rejection, or `undefined` when it resolved. */
238
+ async function rejectionOf(promise: Promise<unknown>): Promise<unknown> {
239
+ return promise.then(
240
+ () => undefined,
241
+ (error: unknown) => error
242
+ );
243
+ }
86
244
 
87
245
  /**
88
246
  * Build the data-server check battery: server-level checks once, then the
@@ -91,13 +249,13 @@ const SEEDER = 'conformance-seeder';
91
249
  * unit tests; adopters call `runDataConformance`.
92
250
  *
93
251
  * `LanguageFixture.edit` is read HERE and nowhere else in the kit, and is
94
- * optional: its two checks report skipped when it is absent. See
252
+ * optional: every check that needs one reports skipped when it is absent. See
95
253
  * {@link LanguageFixture} for which slice reads which field.
96
254
  */
97
255
  export function buildDataChecks<TTransfer extends TransferElement, TDiagnostic extends TransferDiagnostic = TransferDiagnostic>(
98
256
  options: DataConformanceOptions<TTransfer, TDiagnostic>
99
257
  ): ConformanceCheck[] {
100
- const { connect, expectsProjects } = options;
258
+ const { connect, attach, expectsProjects } = options;
101
259
  const checks: ConformanceCheck[] = [];
102
260
 
103
261
  // Split from `waitForReady` so a failure names which of the two broke.
@@ -162,6 +320,46 @@ export function buildDataChecks<TTransfer extends TransferElement, TDiagnostic e
162
320
  : undefined
163
321
  });
164
322
 
323
+ checks.push({
324
+ title: 'createSession refuses an id already live, and frees it once the session ends',
325
+ body: async () => {
326
+ const driver = await connect();
327
+ try {
328
+ const clientId = await startSession(driver, 'conformance-session');
329
+ const duplicate = await rejectionOf(driver.proxy.createSession({ clientId }));
330
+ assert.ok(isDuplicateClientIdError(duplicate), `a second createSession under a live id was not refused: ${String(duplicate)}`);
331
+ await driver.proxy.closeSession({ clientId });
332
+ // The other half: a head that refused every id would pass the
333
+ // assertion above on its own.
334
+ await driver.proxy.createSession({ clientId });
335
+ await driver.proxy.closeSession({ clientId });
336
+ } finally {
337
+ driver.dispose();
338
+ }
339
+ }
340
+ });
341
+
342
+ checks.push({
343
+ title: 'createSession refuses every id the framework reserves, not as a duplicate',
344
+ body: async () => {
345
+ const driver = await connect();
346
+ try {
347
+ // Every id: a head that refuses only some passes a single case. A
348
+ // reserved id never frees up, so a caller retrying on a duplicate
349
+ // has to be able to tell this refusal apart.
350
+ for (const clientId of FRAMEWORK_CLIENT_IDS) {
351
+ const refusal = await rejectionOf(driver.proxy.createSession({ clientId }));
352
+ assert.ok(
353
+ isReservedClientIdError(refusal),
354
+ `createSession under the reserved id ${clientId} was not refused as reserved: ${String(refusal)}`
355
+ );
356
+ }
357
+ } finally {
358
+ driver.dispose();
359
+ }
360
+ }
361
+ });
362
+
165
363
  checks.push({
166
364
  title: 'waitForReady resolves rather than hanging or rejecting',
167
365
  body: async () => {
@@ -178,7 +376,7 @@ export function buildDataChecks<TTransfer extends TransferElement, TDiagnostic e
178
376
  });
179
377
 
180
378
  for (const language of options.languages) {
181
- const { valid, invalid, edit } = language;
379
+ const { valid, invalid, edit, dependent } = language;
182
380
  const tag = `[${valid.languageId}]`;
183
381
 
184
382
  checks.push({
@@ -189,7 +387,7 @@ export function buildDataChecks<TTransfer extends TransferElement, TDiagnostic e
189
387
  // Resolved AFTER `connect`, which is the whole point of allowing a
190
388
  // thunk: the fixture may name a workspace `connect` just created.
191
389
  const model = resolveModel(valid);
192
- await driver.proxy.updateModelDocument({ uri: model.uri, clientId: AUTHOR, model: model.text });
390
+ await seed(driver, model);
193
391
  // `includeDiagnostics` for the same reason the invalid check
194
392
  // passes it: a synchronous read settles at the integrity-settled
195
393
  // phase, so an empty array without it can mean "validation has
@@ -200,7 +398,8 @@ export function buildDataChecks<TTransfer extends TransferElement, TDiagnostic e
200
398
  // a shaped-but-contentless envelope for a document it did parse
201
399
  // would pass. `$type` is the one field every TransferElement
202
400
  // carries, so it is assertable with no fixture knowledge.
203
- const { root } = TransferDocument.assertLoaded(document);
401
+ const { model: snapshot } = TransferDocument.assertLoaded(document);
402
+ const { root } = snapshot;
204
403
  assert.ok(
205
404
  typeof root.$type === 'string' && root.$type.length > 0,
206
405
  `getModelDocument(valid) returned a root with no $type: ${JSON.stringify(root)}`
@@ -208,10 +407,11 @@ export function buildDataChecks<TTransfer extends TransferElement, TDiagnostic e
208
407
  // `version` is the conflict token every later update gates on, so
209
408
  // an envelope that omits it is unusable however good the root is.
210
409
  assert.ok(
211
- Number.isInteger(document.version),
212
- `getModelDocument(valid) returned a non-integer version: ${String(document.version)}`
410
+ Number.isInteger(snapshot.version),
411
+ `getModelDocument(valid) returned a non-integer version: ${String(snapshot.version)}`
213
412
  );
214
- assert.deepStrictEqual(document.diagnostics, []);
413
+ assert.strictEqual(typeof snapshot.hash, 'string', 'getModelDocument(valid) returned a model with no hash');
414
+ assert.deepStrictEqual(snapshot.diagnostics, []);
215
415
  } finally {
216
416
  driver.dispose();
217
417
  }
@@ -224,13 +424,13 @@ export function buildDataChecks<TTransfer extends TransferElement, TDiagnostic e
224
424
  const driver = await connect();
225
425
  try {
226
426
  const model = resolveModel(invalid);
227
- await driver.proxy.updateModelDocument({ uri: model.uri, clientId: AUTHOR, model: model.text });
427
+ await seed(driver, model);
228
428
  // Diagnostics are a validation-phase product; a synchronous read settles at the
229
429
  // integrity-settled phase by default, so request validation explicitly here.
230
430
  // Safe despite `includeDiagnostics` waiting rather than forcing a build: the
231
431
  // update above has already driven this document through validation.
232
432
  const document = await driver.proxy.getModelDocument({ uri: model.uri, includeDiagnostics: true });
233
- assert.ok(document.diagnostics.length >= 1, 'getModelDocument(invalid) reported no diagnostics');
433
+ assert.ok((document.model?.diagnostics?.length ?? 0) >= 1, 'getModelDocument(invalid) reported no diagnostics');
234
434
  } finally {
235
435
  driver.dispose();
236
436
  }
@@ -243,7 +443,7 @@ export function buildDataChecks<TTransfer extends TransferElement, TDiagnostic e
243
443
  const driver = await connect();
244
444
  try {
245
445
  const model = resolveModel(invalid);
246
- await driver.proxy.updateModelDocument({ uri: model.uri, clientId: AUTHOR, model: model.text });
446
+ await seed(driver, model);
247
447
  const document = await driver.proxy.getModelDocument({ uri: model.uri, includeDiagnostics: true });
248
448
 
249
449
  // Conditional rather than fixture-driven, and deliberately so: what
@@ -253,7 +453,7 @@ export function buildDataChecks<TTransfer extends TransferElement, TDiagnostic e
253
453
  // without `params` is the half-state that renders a translated
254
454
  // template with its placeholders left standing, and it is
255
455
  // reachable only by overriding `toTransferDiagnostic`.
256
- const halfIdentities = document.diagnostics.filter(
456
+ const halfIdentities = (document.model?.diagnostics ?? []).filter(
257
457
  diagnostic =>
258
458
  typeof diagnostic.code === 'string' && diagnostic.code.startsWith('hydranium/') && diagnostic.params === undefined
259
459
  );
@@ -268,8 +468,536 @@ export function buildDataChecks<TTransfer extends TransferElement, TDiagnostic e
268
468
  }
269
469
  });
270
470
 
271
- // Opt-in: both remaining checks need a second, observably different model
272
- // text, which only `edit` supplies.
471
+ checks.push({
472
+ title: `a session writes only a document it has open ${tag}`,
473
+ body: async () => {
474
+ const driver = await connect();
475
+ try {
476
+ const model = resolveModel(valid);
477
+ await seed(driver, model);
478
+ const clientId = await startSession(driver, 'conformance-session');
479
+ const write = { uri: model.uri, clientId, model: model.text, baseVersion: 'any' } as const;
480
+
481
+ const unopened = await rejectionOf(driver.proxy.updateModelDocument(write));
482
+ assert.ok(isDocumentNotOpenError(unopened), `a session wrote a document it never opened: ${String(unopened)}`);
483
+ await driver.proxy.openModelDocument({ uri: model.uri, clientId });
484
+ await driver.proxy.updateModelDocument(write);
485
+ await driver.proxy.closeModelDocument({ uri: model.uri, clientId });
486
+ const closed = await rejectionOf(driver.proxy.updateModelDocument(write));
487
+ assert.ok(isDocumentNotOpenError(closed), `a session wrote a document after closing it: ${String(closed)}`);
488
+ await driver.proxy.closeSession({ clientId });
489
+ } finally {
490
+ driver.dispose();
491
+ }
492
+ }
493
+ });
494
+
495
+ checks.push({
496
+ title: `a session saves only a document it has open ${tag}`,
497
+ body: async () => {
498
+ const driver = await connect();
499
+ try {
500
+ const model = resolveModel(valid);
501
+ await seed(driver, model);
502
+ const clientId = await startSession(driver, 'conformance-session');
503
+ const save = { uri: model.uri, clientId, model: model.text, baseVersion: 'any' } as const;
504
+
505
+ const unopened = await rejectionOf(driver.proxy.saveModelDocument(save));
506
+ assert.ok(isDocumentNotOpenError(unopened), `a session saved a document it never opened: ${String(unopened)}`);
507
+ // The other half: a head refusing every session save would pass
508
+ // the assertion above on its own.
509
+ await driver.proxy.openModelDocument({ uri: model.uri, clientId });
510
+ await driver.proxy.saveModelDocument(save);
511
+ await driver.proxy.closeSession({ clientId });
512
+ } finally {
513
+ driver.dispose();
514
+ }
515
+ }
516
+ });
517
+
518
+ checks.push({
519
+ title: `a document request under an id no session was registered for fails ${tag}`,
520
+ body: async () => {
521
+ const driver = await connect();
522
+ try {
523
+ const model = resolveModel(valid);
524
+ await seed(driver, model);
525
+ const clientId = sessionId('conformance-unregistered');
526
+
527
+ // Opened or written under an id that is no session, a document
528
+ // would stay open for a client whose end nothing ever reports.
529
+ const open = await rejectionOf(driver.proxy.openModelDocument({ uri: model.uri, clientId }));
530
+ assert.ok(isSessionClosedError(open), `a document opened under an unregistered id: ${String(open)}`);
531
+ const write = await rejectionOf(
532
+ driver.proxy.updateModelDocument({ uri: model.uri, clientId, model: model.text, baseVersion: 'any' })
533
+ );
534
+ assert.ok(isSessionClosedError(write), `a document was written under an unregistered id: ${String(write)}`);
535
+ } finally {
536
+ driver.dispose();
537
+ }
538
+ }
539
+ });
540
+
541
+ checks.push({
542
+ title: `ending a connection ends its sessions ${tag}`,
543
+ skipReason: attach ? undefined : 'options supply no `attach` (a second connection to the same server outlives the ended one)',
544
+ body: attach
545
+ ? async () => {
546
+ const driver = await connect();
547
+ let driverOpen = true;
548
+ try {
549
+ const model = resolveModel(valid);
550
+ await seed(driver, model);
551
+ const clientId = await startSession(driver, 'conformance-session');
552
+ await driver.proxy.openModelDocument({ uri: model.uri, clientId });
553
+ const sibling = await attach(driver);
554
+ try {
555
+ driverOpen = false;
556
+ driver.dispose();
557
+ // Refused as a duplicate while the ended connection's
558
+ // session lives on, which over a socket it does until the
559
+ // server has seen the close; so retried, within a bound.
560
+ await registerWithin(sibling, clientId, 2_000);
561
+ const write = await rejectionOf(
562
+ sibling.proxy.updateModelDocument({ uri: model.uri, clientId, model: model.text, baseVersion: 'any' })
563
+ );
564
+ assert.ok(isDocumentNotOpenError(write), `a document stayed open after its connection ended: ${String(write)}`);
565
+ await sibling.proxy.closeSession({ clientId });
566
+ } finally {
567
+ sibling.dispose();
568
+ }
569
+ } finally {
570
+ if (driverOpen) {
571
+ driver.dispose();
572
+ }
573
+ }
574
+ }
575
+ : undefined
576
+ });
577
+
578
+ checks.push({
579
+ title: `closeSession closes every document the session had open ${tag}`,
580
+ body: async () => {
581
+ const driver = await connect();
582
+ try {
583
+ const model = resolveModel(valid);
584
+ await seed(driver, model);
585
+ const clientId = await startSession(driver, 'conformance-session');
586
+ await driver.proxy.openModelDocument({ uri: model.uri, clientId });
587
+
588
+ await driver.proxy.closeSession({ clientId });
589
+
590
+ // Observed through a new session under the same id: one that
591
+ // inherited the ended session's open would write without opening.
592
+ await driver.proxy.createSession({ clientId });
593
+ const write = await rejectionOf(
594
+ driver.proxy.updateModelDocument({ uri: model.uri, clientId, model: model.text, baseVersion: 'any' })
595
+ );
596
+ assert.ok(isDocumentNotOpenError(write), `a document stayed open after its session ended: ${String(write)}`);
597
+ await driver.proxy.closeSession({ clientId });
598
+ } finally {
599
+ driver.dispose();
600
+ }
601
+ }
602
+ });
603
+
604
+ checks.push({
605
+ title: `createModelDocument creates a document open for the session, and refuses one that exists ${tag}`,
606
+ body: async () => {
607
+ const driver = await connect();
608
+ try {
609
+ const model = resolveModel(valid);
610
+ await seed(driver, model);
611
+ const clientId = await startSession(driver, 'conformance-session');
612
+ const createdUri = siblingOf(model.uri, `conformance-created-${randomUuid()}-`);
613
+
614
+ const created = await driver.proxy.createModelDocument({ uri: createdUri, clientId, text: model.text });
615
+ const { model: createdModel } = TransferDocument.assertLoaded(created);
616
+ // Written without an open: only the create can have opened it.
617
+ await driver.proxy.updateModelDocument({ uri: createdUri, clientId, model: model.text, baseVersion: createdModel.version });
618
+
619
+ const existing = await rejectionOf(driver.proxy.createModelDocument({ uri: model.uri, clientId, text: model.text }));
620
+ assert.ok(existing !== undefined, `createModelDocument accepted ${model.uri}, which already exists`);
621
+ await driver.proxy.closeSession({ clientId });
622
+ } finally {
623
+ driver.dispose();
624
+ }
625
+ }
626
+ });
627
+
628
+ checks.push({
629
+ title: `a write of the invalid model answers with its diagnostics ${tag}`,
630
+ body: async () => {
631
+ const driver = await connect();
632
+ try {
633
+ const model = resolveModel(invalid);
634
+ const clientId = await startSession(driver, 'conformance-session');
635
+ await openOrCreate(driver, clientId, model);
636
+ // Another text first, so that the invalid one is a change: the
637
+ // answer to a write that changes nothing can carry the
638
+ // diagnostics of an earlier validation. This does not prove the
639
+ // answer waited for this write's validation, only that it
640
+ // carries diagnostics at all.
641
+ const firstText = resolveDeferred(valid.text);
642
+ await driver.proxy.updateModelDocument({ uri: model.uri, clientId, model: firstText, baseVersion: 'any' });
643
+ // The answer alone, with no read after it: a caller that shows
644
+ // the problems of what it wrote should not need a second
645
+ // request, and a read could find a later write's state.
646
+ const answer = await driver.proxy.updateModelDocument({ uri: model.uri, clientId, model: model.text, baseVersion: 'any' });
647
+ assert.ok((answer.model?.diagnostics?.length ?? 0) >= 1, 'writing the invalid model answered with no diagnostics');
648
+ await driver.proxy.closeSession({ clientId });
649
+ } finally {
650
+ driver.dispose();
651
+ }
652
+ }
653
+ });
654
+
655
+ checks.push({
656
+ title: `a created document never saved leaves with its last close ${tag}`,
657
+ body: async () => {
658
+ const driver = await connect();
659
+ try {
660
+ const model = resolveModel(valid);
661
+ const uri = siblingOf(model.uri, `conformance-unsaved-${randomUuid()}-`);
662
+ const clientId = await startSession(driver, 'conformance-session');
663
+ await driver.proxy.createModelDocument({ uri, clientId, text: model.text });
664
+ // Served before the close, so an envelope without a model after
665
+ // it is the close's doing and not the head's answer for every
666
+ // created document.
667
+ TransferDocument.assertLoaded(await driver.proxy.getModelDocument({ uri }));
668
+ await driver.proxy.closeSession({ clientId });
669
+ // It has no file to go back to, so no text is left to serve, and
670
+ // the protocol answers a URI with no document with an envelope
671
+ // that has no model, not with a refusal.
672
+ await readUntil(
673
+ driver,
674
+ uri,
675
+ document => document !== undefined && !TransferDocument.isLoaded(document),
676
+ `${uri}, created and never saved, was not answered with an envelope without a model after its last close`
677
+ );
678
+ } finally {
679
+ driver.dispose();
680
+ }
681
+ }
682
+ });
683
+
684
+ checks.push({
685
+ title: `deleting a saved document removes it ${tag}`,
686
+ body: async () => {
687
+ const driver = await connect();
688
+ try {
689
+ const model = resolveModel(valid);
690
+ const uri = siblingOf(model.uri, `conformance-deleted-${randomUuid()}-`);
691
+ const clientId = await startSession(driver, 'conformance-session');
692
+ await driver.proxy.createModelDocument({ uri, clientId, text: model.text });
693
+ const saved = await driver.proxy.saveModelDocument({ uri, clientId, model: model.text, baseVersion: 'any' });
694
+
695
+ await driver.proxy.deleteModelDocument({ uri, clientId, baseVersion: TransferDocument.assertLoaded(saved).model.version });
696
+
697
+ // Once the delete answers, with no wait: the protocol answers a
698
+ // URI with no document with an envelope that has no model.
699
+ const read = await driver.proxy.getModelDocument({ uri });
700
+ assert.ok(!TransferDocument.isLoaded(read), `${uri} was still served with a model after its delete answered`);
701
+ await driver.proxy.closeSession({ clientId });
702
+ } finally {
703
+ driver.dispose();
704
+ }
705
+ }
706
+ });
707
+
708
+ checks.push({
709
+ title: `a delete on a stale base version conflicts and deletes nothing ${tag}`,
710
+ body: async () => {
711
+ const driver = await connect();
712
+ try {
713
+ const model = resolveModel(valid);
714
+ const uri = siblingOf(model.uri, `conformance-kept-${randomUuid()}-`);
715
+ const clientId = await startSession(driver, 'conformance-session');
716
+ const created = await driver.proxy.createModelDocument({ uri, clientId, text: model.text });
717
+ await driver.proxy.updateModelDocument({ uri, clientId, model: `${model.text}\n`, baseVersion: 'any' });
718
+
719
+ const stale = await rejectionOf(
720
+ driver.proxy.deleteModelDocument({ uri, clientId, baseVersion: TransferDocument.assertLoaded(created).model.version })
721
+ );
722
+
723
+ assert.ok(isConflictError(stale), `deleting ${uri} on a stale base version did not conflict: ${String(stale)}`);
724
+ TransferDocument.assertLoaded(await driver.proxy.getModelDocument({ uri }));
725
+ await driver.proxy.closeSession({ clientId });
726
+ } finally {
727
+ driver.dispose();
728
+ }
729
+ }
730
+ });
731
+
732
+ checks.push({
733
+ title: `a session deletes only a document it has open ${tag}`,
734
+ body: async () => {
735
+ const driver = await connect();
736
+ try {
737
+ const model = resolveModel(valid);
738
+ const seeder = await seed(driver, model);
739
+ const stranger = await startSession(driver, 'conformance-stranger');
740
+
741
+ const refusal = await rejectionOf(
742
+ driver.proxy.deleteModelDocument({ uri: model.uri, clientId: stranger, baseVersion: 'any' })
743
+ );
744
+
745
+ assert.ok(isDocumentNotOpenError(refusal), `a delete without an open did not fail as not open: ${String(refusal)}`);
746
+ TransferDocument.assertLoaded(await driver.proxy.getModelDocument({ uri: model.uri }));
747
+ await driver.proxy.closeSession({ clientId: stranger });
748
+ await driver.proxy.closeSession({ clientId: seeder });
749
+ } finally {
750
+ driver.dispose();
751
+ }
752
+ }
753
+ });
754
+
755
+ checks.push({
756
+ title: `a delete closes another session's open and names the deleting session ${tag}`,
757
+ body: async () => {
758
+ const driver = await connect();
759
+ try {
760
+ const model = resolveModel(valid);
761
+ const uri = siblingOf(model.uri, `conformance-shared-${randomUuid()}-`);
762
+ const deleter = await startSession(driver, 'conformance-deleter');
763
+ await driver.proxy.createModelDocument({ uri, clientId: deleter, text: model.text });
764
+ await driver.proxy.saveModelDocument({ uri, clientId: deleter, model: model.text, baseVersion: 'any' });
765
+ const other = await openAs(driver, uri, 'conformance-other');
766
+
767
+ await driver.proxy.deleteModelDocument({ uri, clientId: deleter, baseVersion: 'any' });
768
+
769
+ const write = await rejectionOf(
770
+ driver.proxy.updateModelDocument({ uri, clientId: other, model: model.text, baseVersion: 'any' })
771
+ );
772
+ assert.ok(isDocumentNotOpenError(write), `another session's open of ${uri} survived its delete: ${String(write)}`);
773
+ await waitFor(() => driver.deletions.some(event => event.uri === uri), {
774
+ message: `no onDocumentDeleted event for ${uri} after its delete`
775
+ });
776
+ const told = driver.deletions.filter(event => event.uri === uri).map(event => event.sourceClientId);
777
+ assert.deepStrictEqual(told, [deleter], `the deletion of ${uri} named ${told.join(', ')}, not the deleting session`);
778
+ await driver.proxy.closeSession({ clientId: other });
779
+ await driver.proxy.closeSession({ clientId: deleter });
780
+ } finally {
781
+ driver.dispose();
782
+ }
783
+ }
784
+ });
785
+
786
+ checks.push({
787
+ title: `a delete removes a created document never saved ${tag}`,
788
+ body: async () => {
789
+ const driver = await connect();
790
+ try {
791
+ const model = resolveModel(valid);
792
+ const uri = siblingOf(model.uri, `conformance-unsaved-deleted-${randomUuid()}-`);
793
+ const clientId = await startSession(driver, 'conformance-session');
794
+ await driver.proxy.createModelDocument({ uri, clientId, text: model.text });
795
+
796
+ await driver.proxy.deleteModelDocument({ uri, clientId, baseVersion: 'any' });
797
+
798
+ const read = await driver.proxy.getModelDocument({ uri });
799
+ assert.ok(
800
+ !TransferDocument.isLoaded(read),
801
+ `${uri}, created and never saved, was still served with a model after its delete`
802
+ );
803
+ await driver.proxy.closeSession({ clientId });
804
+ } finally {
805
+ driver.dispose();
806
+ }
807
+ }
808
+ });
809
+
810
+ checks.push({
811
+ title: `a document is dirty while its text differs from its file, and clean once saved ${tag}`,
812
+ body: async () => {
813
+ const driver = await connect();
814
+ try {
815
+ const model = resolveModel(valid);
816
+ // Only `dirty` is asserted, so any second text serves.
817
+ const unsaved = resolveDeferred(invalid.text);
818
+ const uri = siblingOf(model.uri, `conformance-saved-${randomUuid()}-`);
819
+ const clientId = await startSession(driver, 'conformance-session');
820
+ await driver.proxy.createModelDocument({ uri, clientId, text: model.text });
821
+
822
+ const saved = await driver.proxy.saveModelDocument({ uri, clientId, model: model.text, baseVersion: 'any' });
823
+ assert.strictEqual(saved.text?.dirty, false, `the save of ${uri} answered dirty: ${String(saved.text?.dirty)}, not false`);
824
+ assert.strictEqual(
825
+ saved.persisted?.version,
826
+ saved.text?.version,
827
+ `the save of ${uri} answered it wrote v${String(saved.persisted?.version)}, not the v${String(saved.text?.version)} it holds`
828
+ );
829
+ const edited = await driver.proxy.updateModelDocument({ uri, clientId, model: unsaved, baseVersion: 'any' });
830
+ assert.strictEqual(
831
+ edited.text?.dirty,
832
+ true,
833
+ `an unsaved write of ${uri} answered dirty: ${String(edited.text?.dirty)}, not true`
834
+ );
835
+ const resaved = await driver.proxy.saveModelDocument({ uri, clientId, model: unsaved, baseVersion: 'any' });
836
+ assert.strictEqual(
837
+ resaved.text?.dirty,
838
+ false,
839
+ `the second save of ${uri} answered dirty: ${String(resaved.text?.dirty)}, not false`
840
+ );
841
+ await driver.proxy.closeSession({ clientId });
842
+ } finally {
843
+ driver.dispose();
844
+ }
845
+ }
846
+ });
847
+
848
+ checks.push({
849
+ title: `persisting writes the text a document holds as it is, and refuses a stale base version ${tag}`,
850
+ body: async () => {
851
+ const driver = await connect();
852
+ try {
853
+ const model = resolveModel(valid);
854
+ // Trailing blank lines no serialiser writes, so a head that
855
+ // persists a re-serialised model rather than the text shows.
856
+ const held = `${model.text}\n\n`;
857
+ const uri = siblingOf(model.uri, `conformance-persisted-${randomUuid()}-`);
858
+ const writer = await startSession(driver, 'conformance-writer');
859
+ const created = await driver.proxy.createModelDocument({ uri, clientId: writer, text: model.text });
860
+ const written = await driver.proxy.updateModelDocument({ uri, clientId: writer, model: held, baseVersion: 'any' });
861
+ const persister = await openAs(driver, uri, 'conformance-persister');
862
+
863
+ const stale = await rejectionOf(
864
+ driver.proxy.persistModelDocument({
865
+ uri,
866
+ clientId: persister,
867
+ baseVersion: TransferDocument.assertLoaded(created).model.version
868
+ })
869
+ );
870
+ assert.ok(isConflictError(stale), `persisting ${uri} on a stale base version did not conflict: ${String(stale)}`);
871
+ const base = TransferDocument.assertLoaded(written).model.version;
872
+ const persisted = await driver.proxy.persistModelDocument({ uri, clientId: persister, baseVersion: base });
873
+ assert.strictEqual(
874
+ persisted.persisted?.version,
875
+ base,
876
+ `the persist of ${uri} answered it wrote v${String(persisted.persisted?.version)}, not the v${base} it was based on`
877
+ );
878
+ assert.strictEqual(persisted.text?.dirty, false, `the persist of ${uri} answered dirty: ${String(persisted.text?.dirty)}`);
879
+ assert.strictEqual(persisted.text?.hash, written.text?.hash, `persisting ${uri} changed the text it holds`);
880
+
881
+ // Read after the last close, which serves the file: read before
882
+ // it, the held text answers and a file written wrong passes.
883
+ await driver.proxy.closeSession({ clientId: writer });
884
+ await driver.proxy.closeSession({ clientId: persister });
885
+ const reader = await openAs(driver, uri, 'conformance-reader');
886
+ const reread = await driver.proxy.getModelDocument({ uri });
887
+ assert.strictEqual(reread.text?.hash, written.text?.hash, `the file persisted for ${uri} is not the text it held`);
888
+ await driver.proxy.closeSession({ clientId: reader });
889
+ } finally {
890
+ driver.dispose();
891
+ }
892
+ }
893
+ });
894
+
895
+ checks.push({
896
+ title: `a document's text hash is equal for equal text and differs for different text ${tag}`,
897
+ body: async () => {
898
+ const driver = await connect();
899
+ try {
900
+ const model = resolveModel(valid);
901
+ // Only the text is compared, so any second text serves.
902
+ const other = resolveDeferred(invalid.text);
903
+ const uri = siblingOf(model.uri, `conformance-hashed-${randomUuid()}-`);
904
+ const clientId = await startSession(driver, 'conformance-session');
905
+ const created = await driver.proxy.createModelDocument({ uri, clientId, text: model.text });
906
+ const edited = await driver.proxy.updateModelDocument({ uri, clientId, model: other, baseVersion: 'any' });
907
+ // Back to the first text at a later version: the hash follows
908
+ // the text, which is what a client compares across a revert.
909
+ const restored = await driver.proxy.updateModelDocument({ uri, clientId, model: model.text, baseVersion: 'any' });
910
+
911
+ assert.strictEqual(typeof created.text?.hash, 'string', `the create of ${uri} answered with no text hash`);
912
+ assert.notStrictEqual(
913
+ edited.text?.hash,
914
+ created.text?.hash,
915
+ `${uri} hashed a different text alike: ${String(edited.text?.hash)}`
916
+ );
917
+ assert.strictEqual(
918
+ restored.text?.hash,
919
+ created.text?.hash,
920
+ `${uri} hashed its first text again as ${String(restored.text?.hash)}`
921
+ );
922
+ const read = await driver.proxy.getModelDocument({ uri });
923
+ assert.strictEqual(read.text?.hash, restored.text?.hash, `a read of ${uri} hashed its text as ${String(read.text?.hash)}`);
924
+ const absent = await driver.proxy.getModelDocument({
925
+ uri: siblingOf(model.uri, `conformance-absent-${randomUuid()}-`)
926
+ });
927
+ assert.strictEqual(absent.text, undefined, `an envelope with no document carried text ${JSON.stringify(absent.text)}`);
928
+ await driver.proxy.closeSession({ clientId });
929
+ } finally {
930
+ driver.dispose();
931
+ }
932
+ }
933
+ });
934
+
935
+ // The create-dialog query, and the reason it is its own check: it is the
936
+ // only request a head receives whose URI names no file. Everything else
937
+ // in this battery addresses a document, so a head that routes purely by
938
+ // URI extension passes all of them and still cannot open a create dialog.
939
+ //
940
+ // Doubly opt-in — the fixture must name a query AND the driver must serve
941
+ // the reference surface — because either half missing means the head never
942
+ // claimed this behaviour. The reasons are reported separately so a skip
943
+ // says which half is absent.
944
+ const referenceQuery = language.referenceQuery;
945
+ const referenceSkipReason = !referenceQuery
946
+ ? 'fixture supplies no `referenceQuery` (omit it if this language has no create-element dialog)'
947
+ : undefined;
948
+
949
+ checks.push({
950
+ title: `findReferenceCandidates answers for a synthetic source at a folder URI ${tag}`,
951
+ skipReason: referenceSkipReason,
952
+ body: referenceQuery
953
+ ? async () => {
954
+ const driver = await connect();
955
+ try {
956
+ if (!driver.references) {
957
+ // Checked here rather than in `skipReason`: the driver only
958
+ // exists once `connect` has run, and skip reasons are
959
+ // computed while the battery is being planned.
960
+ return;
961
+ }
962
+ const model = resolveModel(valid);
963
+ await seed(driver, model);
964
+
965
+ // Default to the folder holding the valid model: a sibling of
966
+ // it is where a create flow would put the new file.
967
+ const folderUri = referenceQuery.folderUri
968
+ ? resolveDeferred(referenceQuery.folderUri)
969
+ : model.uri.slice(0, model.uri.lastIndexOf('/'));
970
+ assert.ok(
971
+ folderUri.length > 0 && folderUri !== model.uri,
972
+ `could not derive a folder URI from ${model.uri}; supply referenceQuery.folderUri`
973
+ );
974
+
975
+ const candidates = await driver.references.findReferenceCandidates({
976
+ source: ReferenceSource.synthetic(folderUri, referenceQuery.type),
977
+ syntheticPath: referenceQuery.path?.map(([containerProperty, type]) => SyntheticStep.of(containerProperty, type)),
978
+ property: referenceQuery.property
979
+ });
980
+
981
+ // The expected label, not merely a non-empty array: the defect
982
+ // this guards against answers `[]`, and an empty result is
983
+ // also what a head with a genuinely empty index answers, so
984
+ // only a named candidate tells the two apart.
985
+ const labels = candidates.map(candidate => candidate.label);
986
+ assert.ok(
987
+ labels.includes(referenceQuery.expectCandidate),
988
+ `findReferenceCandidates at the folder ${folderUri} did not offer ${JSON.stringify(
989
+ referenceQuery.expectCandidate
990
+ )}; got [${labels.join(', ')}]`
991
+ );
992
+ } finally {
993
+ driver.dispose();
994
+ }
995
+ }
996
+ : undefined
997
+ });
998
+
999
+ // Opt-in: a check that needs a second, observably different model text
1000
+ // takes it from `edit`, and skips without one.
273
1001
  const editSkipReason = 'fixture supplies no `edit` (data-slice only; omit it if this language is not driven through the data head)';
274
1002
 
275
1003
  checks.push({
@@ -280,10 +1008,18 @@ export function buildDataChecks<TTransfer extends TransferElement, TDiagnostic e
280
1008
  const driver = await connect();
281
1009
  try {
282
1010
  const model = resolveModel(valid);
283
- await driver.proxy.updateModelDocument({ uri: model.uri, clientId: AUTHOR, model: model.text });
284
- await driver.proxy.updateModelDocument({ uri: model.uri, clientId: AUTHOR, model: resolveDeferred(edit.to) });
1011
+ const seeder = await seed(driver, model);
1012
+ await driver.proxy.updateModelDocument({
1013
+ uri: model.uri,
1014
+ clientId: seeder,
1015
+ model: resolveDeferred(edit.to),
1016
+ baseVersion: 'any'
1017
+ });
285
1018
  const document = await driver.proxy.getModelDocument({ uri: model.uri });
286
- assert.ok(edit.expect(document.root), 'edit.expect(root) was false — the edit was not reflected by a follow-up get');
1019
+ assert.ok(
1020
+ edit.expect(document.model?.root),
1021
+ 'edit.expect(root) was false — the edit was not reflected by a follow-up get'
1022
+ );
287
1023
  } finally {
288
1024
  driver.dispose();
289
1025
  }
@@ -291,6 +1027,275 @@ export function buildDataChecks<TTransfer extends TransferElement, TDiagnostic e
291
1027
  : undefined
292
1028
  });
293
1029
 
1030
+ checks.push({
1031
+ title: `updateModelDocument arms the conflict gate on a base version ${tag}`,
1032
+ skipReason: edit ? undefined : editSkipReason,
1033
+ body: edit
1034
+ ? async () => {
1035
+ const driver = await connect();
1036
+ try {
1037
+ const model = resolveModel(valid);
1038
+ const seeder = await seed(driver, model);
1039
+ const author = await openAs(driver, model.uri);
1040
+
1041
+ // The version the gate is meant to accept, read BEFORE the
1042
+ // foreign edit that supersedes it.
1043
+ const stale = await driver.proxy.getModelDocument({ uri: model.uri });
1044
+ await driver.proxy.updateModelDocument({
1045
+ uri: model.uri,
1046
+ clientId: seeder,
1047
+ model: resolveDeferred(edit.to),
1048
+ baseVersion: 'any'
1049
+ });
1050
+
1051
+ let rejection: unknown;
1052
+ await driver.proxy
1053
+ .updateModelDocument({
1054
+ uri: model.uri,
1055
+ clientId: author,
1056
+ model: model.text,
1057
+ baseVersion: TransferDocument.assertLoaded(stale).model.version
1058
+ })
1059
+ .catch((error: unknown) => {
1060
+ rejection = error;
1061
+ });
1062
+ assert.ok(
1063
+ isConflictError(rejection),
1064
+ `a write based on the superseded v${String(stale.model?.version)} was not refused: ${String(rejection)}`
1065
+ );
1066
+
1067
+ // The other half, and it is not optional: a head that refused
1068
+ // EVERY write would satisfy the assertion above on its own, so
1069
+ // the gate has to be shown accepting a current snapshot too.
1070
+ const fresh = await driver.proxy.getModelDocument({ uri: model.uri });
1071
+ await driver.proxy.updateModelDocument({
1072
+ uri: model.uri,
1073
+ clientId: author,
1074
+ model: resolveDeferred(edit.to),
1075
+ baseVersion: TransferDocument.assertLoaded(fresh).model.version
1076
+ });
1077
+ } finally {
1078
+ driver.dispose();
1079
+ }
1080
+ }
1081
+ : undefined
1082
+ });
1083
+
1084
+ checks.push({
1085
+ title: `the last close drops a document's unsaved text and keeps what its save wrote ${tag}`,
1086
+ skipReason: edit ? undefined : editSkipReason,
1087
+ body: edit
1088
+ ? async () => {
1089
+ const driver = await connect();
1090
+ try {
1091
+ const model = resolveModel(valid);
1092
+ const edited = resolveDeferred(edit.to);
1093
+ const uri = siblingOf(model.uri, `conformance-reverted-${randomUuid()}-`);
1094
+ const writer = await startSession(driver, 'conformance-writer');
1095
+ // Created with the edit, so that going back to the created
1096
+ // text instead of the saved one shows.
1097
+ await driver.proxy.createModelDocument({ uri, clientId: writer, text: edited });
1098
+ const saved = await driver.proxy.saveModelDocument({ uri, clientId: writer, model: model.text, baseVersion: 'any' });
1099
+ assert.ok(
1100
+ !edit.expect(saved.model?.root),
1101
+ 'edit.expect holds of the valid text, so this check cannot tell the edit apart'
1102
+ );
1103
+ const reader = await openAs(driver, uri, 'conformance-reader');
1104
+ await driver.proxy.updateModelDocument({ uri, clientId: writer, model: edited, baseVersion: 'any' });
1105
+
1106
+ // Not the last close: the reader still shows the writer's
1107
+ // text. Read at once, so a head that reverts after answering
1108
+ // could still pass this half.
1109
+ await driver.proxy.closeSession({ clientId: writer });
1110
+ const held = await driver.proxy.getModelDocument({ uri });
1111
+ assert.ok(edit.expect(held.model?.root), `closing one of two sessions dropped the unsaved text of ${uri}`);
1112
+
1113
+ await driver.proxy.closeSession({ clientId: reader });
1114
+ await readUntil(
1115
+ driver,
1116
+ uri,
1117
+ document => document?.model !== undefined && !edit.expect(document.model.root),
1118
+ `${uri} did not go back to the text its save wrote after its last close`
1119
+ );
1120
+ } finally {
1121
+ driver.dispose();
1122
+ }
1123
+ }
1124
+ : undefined
1125
+ });
1126
+
1127
+ // Opt-in twice over: the cascade needs an edit to provoke it AND a second
1128
+ // document that references the first to be provoked.
1129
+ const cascadeSkipReason =
1130
+ 'fixture supplies no `dependent` (a document referencing `valid`), so no cascade can be provoked over the protocol';
1131
+
1132
+ checks.push({
1133
+ title: `updateModelDocuments writes a set all or none ${tag}`,
1134
+ skipReason:
1135
+ edit && dependent
1136
+ ? undefined
1137
+ : dependent
1138
+ ? editSkipReason
1139
+ : 'fixture supplies no `dependent`, the second document a set needs besides `valid`',
1140
+ body:
1141
+ edit && dependent
1142
+ ? async () => {
1143
+ const driver = await connect();
1144
+ try {
1145
+ const model = resolveModel(valid);
1146
+ const other = resolveModel(dependent);
1147
+ await seed(driver, model);
1148
+ await seed(driver, other);
1149
+ const clientId = await startSession(driver, 'conformance-session');
1150
+ const { model: first } = TransferDocument.assertLoaded(
1151
+ await driver.proxy.openModelDocument({ uri: model.uri, clientId })
1152
+ );
1153
+ const { model: second } = TransferDocument.assertLoaded(
1154
+ await driver.proxy.openModelDocument({ uri: other.uri, clientId })
1155
+ );
1156
+ const edited = resolveDeferred(edit.to);
1157
+
1158
+ // The stale member comes LAST, so a head that checks and
1159
+ // applies one document at a time has applied the first.
1160
+ const stale = await rejectionOf(
1161
+ driver.proxy.updateModelDocuments({
1162
+ clientId,
1163
+ updates: [
1164
+ { uri: model.uri, model: edited, baseVersion: first.version },
1165
+ { uri: other.uri, model: other.text, baseVersion: asModelVersion(second.version + 1) }
1166
+ ]
1167
+ })
1168
+ );
1169
+ assert.ok(isConflictError(stale), `a set with a stale member was not refused: ${String(stale)}`);
1170
+ const untouched = await driver.proxy.getModelDocument({ uri: model.uri });
1171
+ assert.strictEqual(untouched.model?.version, first.version, 'a refused set applied its first document');
1172
+
1173
+ await driver.proxy.updateModelDocuments({
1174
+ clientId,
1175
+ updates: [
1176
+ { uri: model.uri, model: edited, baseVersion: first.version },
1177
+ { uri: other.uri, model: other.text, baseVersion: second.version }
1178
+ ]
1179
+ });
1180
+ const applied = await driver.proxy.getModelDocument({ uri: model.uri });
1181
+ assert.ok(edit.expect(applied.model?.root), 'edit.expect(root) was false — a current set was not applied');
1182
+ await driver.proxy.closeSession({ clientId });
1183
+ } finally {
1184
+ driver.dispose();
1185
+ }
1186
+ }
1187
+ : undefined
1188
+ });
1189
+
1190
+ checks.push({
1191
+ title: `editing a document reports its unwatched dependent as built ${tag}`,
1192
+ skipReason: edit && dependent ? undefined : dependent ? editSkipReason : cascadeSkipReason,
1193
+ body:
1194
+ edit && dependent
1195
+ ? async () => {
1196
+ const driver = await connect();
1197
+ try {
1198
+ const model = resolveModel(valid);
1199
+ const other = resolveModel(dependent);
1200
+ await seed(driver, model);
1201
+ await seed(driver, other);
1202
+ // Watch ONLY the referenced document. The dependent is left
1203
+ // unwatched on purpose: that is the state in which no other
1204
+ // channel can report it, and the state a workspace view is in
1205
+ // for every document it displays without opening.
1206
+ await driver.proxy.watchModelDocument({ uri: model.uri, clientId: SUBSCRIBER });
1207
+ const author = await openAs(driver, model.uri);
1208
+ const before = driver.builds.length;
1209
+
1210
+ await driver.proxy.updateModelDocument({
1211
+ uri: model.uri,
1212
+ clientId: author,
1213
+ model: resolveDeferred(edit.to),
1214
+ baseVersion: 'any'
1215
+ });
1216
+
1217
+ await waitFor(() => driver.builds.slice(before).some(event => event.uris.includes(other.uri)), {
1218
+ message: `no onDocumentsBuilt event named ${other.uri} after editing the document it references`
1219
+ });
1220
+ const reported = driver.builds.slice(before).flatMap(event => [...event.uris]);
1221
+ // The watched document is excluded: its watcher already heard
1222
+ // about it on the update channel, and repeating it here would
1223
+ // be the bandwidth the per-URI gate exists to avoid.
1224
+ assert.ok(
1225
+ !reported.includes(model.uri),
1226
+ `onDocumentsBuilt named the WATCHED ${model.uri}; it is reported on the update channel instead`
1227
+ );
1228
+ } finally {
1229
+ driver.dispose();
1230
+ }
1231
+ }
1232
+ : undefined
1233
+ });
1234
+
1235
+ const breakingEdit = language.breakingEdit;
1236
+ checks.push({
1237
+ title: `an edit that changes a watched dependent credits the dependent's event to no client ${tag}`,
1238
+ skipReason: !dependent
1239
+ ? cascadeSkipReason
1240
+ : breakingEdit === undefined
1241
+ ? 'fixture supplies no `breakingEdit` (a text for `valid` that changes what `dependent` shows)'
1242
+ : undefined,
1243
+ body:
1244
+ dependent && breakingEdit !== undefined
1245
+ ? async () => {
1246
+ const driver = await connect();
1247
+ try {
1248
+ const model = resolveModel(valid);
1249
+ const other = resolveModel(dependent);
1250
+ const eventsFor = (uri: string, from = 0): TransferDocumentUpdatedEvent<TTransfer, TDiagnostic>[] =>
1251
+ driver.events.slice(from).filter(event => event.document.uri === uri);
1252
+ await seed(driver, model);
1253
+ // The dependent's seeder keeps it open: an open document is
1254
+ // the one a head could wrongly credit to its opener.
1255
+ await seed(driver, other);
1256
+ // Watched after the seeds: a seed that changes nothing, over
1257
+ // a fixture file that holds its text already, sends a watcher
1258
+ // nothing to wait for.
1259
+ await driver.proxy.watchModelDocument({ uri: model.uri, clientId: SUBSCRIBER });
1260
+ await driver.proxy.watchModelDocument({ uri: other.uri, clientId: SUBSCRIBER });
1261
+ const author = await openAs(driver, model.uri);
1262
+ const before = driver.events.length;
1263
+
1264
+ const answer = await driver.proxy.updateModelDocument({
1265
+ uri: model.uri,
1266
+ clientId: author,
1267
+ model: resolveDeferred(breakingEdit),
1268
+ baseVersion: 'any'
1269
+ });
1270
+
1271
+ const written = (): TransferDocumentUpdatedEvent<TTransfer, TDiagnostic> | undefined =>
1272
+ eventsFor(model.uri, before).find(event => event.document.model?.version === answer.model?.version);
1273
+ await waitFor(() => written() !== undefined && eventsFor(other.uri, before).length > 0, {
1274
+ message: `no onDocumentUpdated event for both ${model.uri} and its dependent ${other.uri} after the breaking edit`
1275
+ });
1276
+ assert.deepStrictEqual(
1277
+ { reason: written()?.reason, sourceClientId: written()?.sourceClientId },
1278
+ { reason: 'changed', sourceClientId: author },
1279
+ 'the written document’s event is not the author’s change'
1280
+ );
1281
+ // A recipient drops an event naming its own id as its echo, so
1282
+ // a dependent's event credited to the author, or to the client
1283
+ // that has the dependent open, is lost to exactly the client
1284
+ // that would show it.
1285
+ for (const event of eventsFor(other.uri, before)) {
1286
+ assert.deepStrictEqual(
1287
+ { reason: event.reason, sourceClientId: event.sourceClientId },
1288
+ { reason: 'rebuilt', sourceClientId: UNKNOWN_CLIENT_ID },
1289
+ 'the dependent’s event is not a rebuild that names no client'
1290
+ );
1291
+ }
1292
+ } finally {
1293
+ driver.dispose();
1294
+ }
1295
+ }
1296
+ : undefined
1297
+ });
1298
+
294
1299
  checks.push({
295
1300
  title: `subscribe + update delivers an onDocumentUpdated event with the originating clientId ${tag}`,
296
1301
  skipReason: edit ? undefined : editSkipReason,
@@ -299,21 +1304,36 @@ export function buildDataChecks<TTransfer extends TransferElement, TDiagnostic e
299
1304
  const driver = await connect();
300
1305
  try {
301
1306
  const model = resolveModel(valid);
302
- await driver.proxy.updateModelDocument({ uri: model.uri, clientId: SEEDER, model: model.text });
1307
+ // The seeder's write comes BEFORE any subscription, under an id
1308
+ // distinct from the author's so an event it caused is
1309
+ // recognisable: a head that fans notifications out regardless
1310
+ // of its subscription table is otherwise indistinguishable from
1311
+ // one that honours the table, since both deliver something for
1312
+ // the post-subscribe write.
1313
+ const seeder = await seed(driver, model);
1314
+ const author = await openAs(driver, model.uri);
303
1315
  await driver.proxy.watchModelDocument({ uri: model.uri, clientId: SUBSCRIBER });
304
- await driver.proxy.updateModelDocument({ uri: model.uri, clientId: AUTHOR, model: resolveDeferred(edit.to) });
305
- await waitFor(() => driver.events.some(event => event.sourceClientId === AUTHOR), {
1316
+ await driver.proxy.updateModelDocument({
1317
+ uri: model.uri,
1318
+ clientId: author,
1319
+ model: resolveDeferred(edit.to),
1320
+ baseVersion: 'any'
1321
+ });
1322
+ await waitFor(() => driver.events.some(event => event.sourceClientId === author), {
306
1323
  message: `no onDocumentUpdated event for ${model.uri} after the post-subscription update`
307
1324
  });
308
1325
  const last = driver.events[driver.events.length - 1];
309
1326
  assert.strictEqual(last.document.uri, model.uri);
310
- assert.strictEqual(last.sourceClientId, AUTHOR);
1327
+ assert.strictEqual(last.sourceClientId, author);
1328
+ // The first delivery of the author's version is a change;
1329
+ // reported as rebuilt, it says the event echoes no write.
1330
+ assert.strictEqual(last.reason, 'changed');
311
1331
  // Nothing from before the subscription. Waiting for the
312
1332
  // post-subscribe event first is what makes this provable: the
313
1333
  // two notifications share one ordered connection, so a seeding
314
1334
  // event that was ever going to arrive has arrived by now.
315
1335
  assert.ok(
316
- !driver.events.some(event => event.sourceClientId === SEEDER),
1336
+ !driver.events.some(event => event.sourceClientId === seeder),
317
1337
  'an onDocumentUpdated event arrived for the update made BEFORE watchModelDocument'
318
1338
  );
319
1339
  } finally {