@hydranium/data-server 1.0.0-next.4 → 1.0.0-next.400

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.
Files changed (35) hide show
  1. package/README.md +57 -73
  2. package/lib/browser/index.d.ts +10 -0
  3. package/lib/browser/index.d.ts.map +1 -0
  4. package/lib/browser/index.js +15 -0
  5. package/lib/browser/index.js.map +1 -0
  6. package/lib/browser/start-data-server-in-worker.d.ts +23 -0
  7. package/lib/browser/start-data-server-in-worker.d.ts.map +1 -0
  8. package/lib/browser/start-data-server-in-worker.js +29 -0
  9. package/lib/browser/start-data-server-in-worker.js.map +1 -0
  10. package/lib/data-server.d.ts +475 -290
  11. package/lib/data-server.d.ts.map +1 -1
  12. package/lib/data-server.js +813 -501
  13. package/lib/data-server.js.map +1 -1
  14. package/lib/messages/index.d.ts +18 -0
  15. package/lib/messages/index.d.ts.map +1 -0
  16. package/lib/messages/index.js +18 -0
  17. package/lib/messages/index.js.map +1 -0
  18. package/lib/node/node-diagnostics-provider.d.ts.map +1 -1
  19. package/lib/node/node-diagnostics-provider.js +3 -2
  20. package/lib/node/node-diagnostics-provider.js.map +1 -1
  21. package/lib/testing/data-server-harness.d.ts +31 -14
  22. package/lib/testing/data-server-harness.d.ts.map +1 -1
  23. package/lib/testing/data-server-harness.js +8 -3
  24. package/lib/testing/data-server-harness.js.map +1 -1
  25. package/lib/testing/index.d.ts +1 -0
  26. package/lib/testing/index.d.ts.map +1 -1
  27. package/lib/testing/index.js.map +1 -1
  28. package/package.json +39 -38
  29. package/src/browser/index.ts +15 -0
  30. package/src/browser/start-data-server-in-worker.ts +35 -0
  31. package/src/data-server.ts +994 -541
  32. package/src/messages/index.ts +26 -0
  33. package/src/node/node-diagnostics-provider.ts +3 -9
  34. package/src/testing/data-server-harness.ts +55 -26
  35. package/src/testing/index.ts +5 -2
@@ -8,13 +8,28 @@
8
8
  ********************************************************************************/
9
9
 
10
10
  import {
11
+ asModelVersion,
11
12
  createRpcProxy,
13
+ defineMessage,
14
+ describeErrorWithStack,
12
15
  DisposableCollection,
16
+ HYDRANIUM_ERROR_CODES,
13
17
  isDocumentSource,
14
18
  isElementSource,
19
+ isResponseError,
20
+ type BaseVersionGate,
21
+ ConflictError,
22
+ isModelVersion,
15
23
  isSyntheticSource,
24
+ messageData,
25
+ messageError,
16
26
  ReferenceSource,
27
+ SessionClosedError,
28
+ TIMED_OUT,
17
29
  type CloseModelArgs,
30
+ type HydraniumMessageData,
31
+ type HydraniumResponseError,
32
+ type CanonicalUri,
18
33
  type Disposable,
19
34
  type ElementSource,
20
35
  type FindNextNameArgs,
@@ -26,10 +41,21 @@ import {
26
41
  type ReferenceContext,
27
42
  type ReferenceRequest,
28
43
  type ReferenceTarget,
44
+ type TransferModelSnapshot,
45
+ type ModelVersion,
46
+ type TextState,
29
47
  type Tracer,
30
48
  type TransferDiagnostic,
31
- type TransferDocument,
32
- type TransferElement
49
+ TransferDocument,
50
+ type TransferCreatedDocument,
51
+ type TransferSavedDocument,
52
+ type TransferWatchedDocument,
53
+ type TransferWrittenDocument,
54
+ type TransferElement,
55
+ UNKNOWN_CLIENT_ID,
56
+ STALE_BASE_VERSION_SAVE,
57
+ STALE_BASE_VERSION_UPDATE,
58
+ textHash
33
59
  } from '@hydranium/protocol';
34
60
  import {
35
61
  DATA_SERVER_DIAGNOSTICS_METHODS,
@@ -42,29 +68,90 @@ import {
42
68
  type StartProfilingArgs,
43
69
  type StopProfilingArgs,
44
70
  type WriteServerHeapSnapshotArgs,
71
+ type CloseSessionArgs,
72
+ type CreatedSession,
73
+ type CreateModelDocumentArgs,
74
+ type CreateSessionArgs,
45
75
  type GetModelDocumentArgs,
46
76
  type GetProjectForUriArgs,
77
+ type ProjectChangeReason,
78
+ type TransferDeleteDocumentArgs,
79
+ type TransferPersistDocumentArgs,
47
80
  type TransferSaveDocumentArgs,
48
81
  type WatchModelDocumentArgs,
49
82
  type TransferDocumentSavedEvent,
50
83
  type TransferDocumentUpdatedEvent,
51
- type TransferUpdateDocumentArgs
84
+ type TransferUpdateDocumentArgs,
85
+ type TransferUpdateDocumentsArgs
52
86
  } from '@hydranium/protocol/data';
53
- import { REVERT_ON_CLOSE_CLIENT_ID, UNKNOWN_CLIENT_ID } from '@hydranium/core';
87
+ import { DOCUMENT_RELEASE_CLIENT_ID } from '@hydranium/core';
54
88
  import { defaultDataServerDiagnostics } from './default-diagnostics.js';
89
+
90
+ /**
91
+ * Raised when a profiling command arrives with no capture running.
92
+ *
93
+ * A `ResponseError` rather than a plain `Error` so the identity survives to the
94
+ * response boundary, which is where the message is rendered. An unwrapped throw
95
+ * reaches the client as a generic internal error instead: no code for a caller
96
+ * to switch on, and nothing for the boundary to render from.
97
+ */
98
+ export const NO_ACTIVE_PROFILE = defineMessage(
99
+ 'hydranium/data-server/no-active-profile',
100
+ 'No profiling capture is active; call startProfiling first.'
101
+ );
102
+
103
+ /**
104
+ * The JSON-RPC code, unrelated to the catalogue code above: this one is numeric,
105
+ * survives reconstruction and is what a caller switches on.
106
+ */
107
+ export const NO_ACTIVE_PROFILE_CODE = HYDRANIUM_ERROR_CODES.noActiveProfile;
108
+
109
+ export const noActiveProfileError = (): HydraniumResponseError => messageError(NO_ACTIVE_PROFILE_CODE, NO_ACTIVE_PROFILE);
110
+
111
+ /**
112
+ * Raised when a reference question's wait for the build exceeds
113
+ * {@link DataServerOptions.referenceSettleTimeoutMs}.
114
+ *
115
+ * A `ResponseError` because a class name does not cross RPC: without the code a
116
+ * wire client cannot tell a wedged build from a reference that resolves to
117
+ * nothing, which is the distinction the wait exists to keep.
118
+ */
119
+ export const REFERENCE_SETTLE_TIMEOUT = defineMessage(
120
+ 'hydranium/data-server/reference-settle-timeout',
121
+ 'The model is still being processed; try again in a moment.'
122
+ );
123
+
124
+ /** See {@link NO_ACTIVE_PROFILE_CODE} for why this is separate from the catalogue code. */
125
+ export const REFERENCE_SETTLE_TIMEOUT_CODE = HYDRANIUM_ERROR_CODES.referenceSettleTimeout;
126
+
127
+ /** The wait's length rides in `data` as `elapsedMs`, for the code that reacts rather than the reader. */
128
+ export const referenceSettleTimeoutError = (elapsedMs: number): ResponseError<HydraniumMessageData & { readonly elapsedMs: number }> =>
129
+ new ResponseError(REFERENCE_SETTLE_TIMEOUT_CODE, REFERENCE_SETTLE_TIMEOUT.format(), {
130
+ elapsedMs,
131
+ ...messageData(REFERENCE_SETTLE_TIMEOUT)
132
+ });
133
+
55
134
  import type { DataServerDiagnosticsProvider, DataServerProfileCapture } from './diagnostics-provider.js';
56
135
  import type {
57
- ClientTextDocumentChangeEvent,
136
+ ClientSession,
137
+ ClientSessionWriteArgs,
58
138
  HydraniumLanguageServices,
59
139
  LogNameOptions,
140
+ AstDiagnostic,
141
+ AstDocument,
142
+ AstDocumentSavedEvent,
143
+ EncodedTransferDocument,
144
+ ModelDeletedEvent,
145
+ ModelDirtyChangedEvent,
60
146
  ModelService,
147
+ ModelUpdatedEvent,
61
148
  ProjectChangeEvent,
62
149
  ServerSharedServices,
150
+ SessionEndCause,
63
151
  TransferEncoder
64
152
  } from '@hydranium/core';
65
- import type { TextDocument } from 'vscode-languageserver-textdocument';
66
- import { type AstNode, DocumentState, type LangiumDocument, UriUtils, type URI } from '@hydranium/langium';
67
- import type { CancellationToken, MessageConnection } from 'vscode-jsonrpc';
153
+ import { type AstNode, DocumentState, UriUtils, type URI } from '@hydranium/langium';
154
+ import { type MessageConnection, ResponseError } from 'vscode-jsonrpc';
68
155
 
69
156
  /**
70
157
  * Domain separator between text and diagnostics inputs of
@@ -75,34 +162,11 @@ import type { CancellationToken, MessageConnection } from 'vscode-jsonrpc';
75
162
  const FINGERPRINT_SEPARATOR = '\0';
76
163
 
77
164
  /**
78
- * Portable, non-cryptographic 64-bit fingerprint hash (cyrb53), returning a
79
- * 16-char hex digest.
80
- *
81
- * **A cryptographic hash via `node:crypto` is the wrong trade**: the
82
- * fingerprint only needs a stable signal that `(text, diagnostics)` changed
83
- * between emissions, and a `node:*` import would cost
84
- * `@hydranium/data-server` its browser-portability. Parts are fed
85
- * incrementally, char by char, so multi-MB document text is never
86
- * concatenated into one string.
165
+ * `LSPErrorCodes.ServerCancelled`, with which Langium's document wait rejects
166
+ * for a URI that has no document; `vscode-languageserver-protocol` is not a
167
+ * dependency of this package.
87
168
  */
88
- function fingerprintHash(parts: readonly string[]): string {
89
- let h1 = 0xdeadbeef;
90
- let h2 = 0x41c6ce57;
91
- for (const part of parts) {
92
- for (let i = 0; i < part.length; i++) {
93
- const ch = part.charCodeAt(i);
94
- h1 = Math.imul(h1 ^ ch, 2654435761);
95
- h2 = Math.imul(h2 ^ ch, 1597334677);
96
- }
97
- }
98
- h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);
99
- h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);
100
- h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);
101
- h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);
102
- const high = (h2 >>> 0).toString(16).padStart(8, '0');
103
- const low = (h1 >>> 0).toString(16).padStart(8, '0');
104
- return high + low;
105
- }
169
+ const SERVER_CANCELLED = -32802;
106
170
 
107
171
  /**
108
172
  * Which observable state {@link DataServer.computeDocumentFingerprint} hashes to
@@ -115,26 +179,32 @@ function fingerprintHash(parts: readonly string[]): string {
115
179
  * folded in on a cascade rebuild that leaves the document's own text
116
180
  * untouched. Safe for any adopter whose AST extensions fold derived state
117
181
  * into the transfer projection (the framework norm).
118
- * - `'text-diagnostics'` — the cheaper `getText()` + diagnostics hash. An
119
- * opt-DOWN for adopters that fold no derived state and want to avoid the
120
- * transfer-encode per phase event.
182
+ * - `'text-diagnostics'` — the cheaper parsed-text + diagnostics hash. An
183
+ * opt-DOWN for adopters that fold no derived state and want to avoid
184
+ * stringifying the transfer root per phase event.
121
185
  */
122
186
  export type FingerprintStrategy = 'transfer-document' | 'text-diagnostics';
123
187
 
124
- /** Hash a document's raw text + diagnostics — the `'text-diagnostics'` strategy. */
125
- function textDiagnosticsFingerprint(document: LangiumDocument): string {
126
- return fingerprintHash([document.textDocument.getText(), FINGERPRINT_SEPARATOR, JSON.stringify(document.diagnostics ?? [])]);
188
+ /**
189
+ * Hash `text`, the text the model was parsed from, + `model`'s diagnostics — the `'text-diagnostics'` strategy.
190
+ * The text comes from the root's ledger record or CST, as the document's own may have moved on,
191
+ * and a repair in place leaves the CST on the unrepaired text;
192
+ * a root built without a CST hashes as `'transfer-document'`.
193
+ * Absent diagnostics must hash apart from `[]`, as in {@link transferDocumentFingerprint}.
194
+ */
195
+ function textDiagnosticsFingerprint(text: string | undefined, model: EncodedTransferDocument<TransferElement, unknown>['model']): string {
196
+ return text === undefined
197
+ ? transferDocumentFingerprint(model)
198
+ : textHash([text, FINGERPRINT_SEPARATOR, JSON.stringify(model.diagnostics ?? null)]);
127
199
  }
128
200
 
129
- /** Hash an encoded transfer document's root + diagnostics — the `'transfer-document'` strategy. */
130
- function transferDocumentFingerprint(transferDocument: Pick<TransferDocument<TransferElement, unknown>, 'root' | 'diagnostics'>): string {
131
- // null, not undefined: `JSON.stringify(undefined)` yields undefined rather
132
- // than a string, putting a non-string into the hash inputs.
133
- return fingerprintHash([
134
- JSON.stringify(transferDocument.root ?? null),
135
- FINGERPRINT_SEPARATOR,
136
- JSON.stringify(transferDocument.diagnostics)
137
- ]);
201
+ /**
202
+ * Hash an encoded model's root + diagnostics — the `'transfer-document'` strategy.
203
+ * Absent diagnostics must hash apart from `[]`: a client skipping a render on an
204
+ * equal hash would otherwise miss a validation that found nothing.
205
+ */
206
+ function transferDocumentFingerprint(model: EncodedTransferDocument<TransferElement, unknown>['model']): string {
207
+ return textHash([JSON.stringify(model.root), FINGERPRINT_SEPARATOR, JSON.stringify(model.diagnostics ?? null)]);
138
208
  }
139
209
  /**
140
210
  * `logAfterMs` threshold passed to {@link Tracer.time} around
@@ -155,12 +225,14 @@ export interface DataServerOptions extends LogNameOptions {
155
225
  * (`DataClientProtocol.onDocumentUpdated`).
156
226
  *
157
227
  * **Subscription dispatch only** — distinct from the synchronous RPC
158
- * response phase. The lifecycle reads/writes (`getModelDocument` /
159
- * `updateModelDocument` / `saveModelDocument`) settle at the
160
- * integrity-settled landmark (`IntegrityService.SettledState`); a
161
- * read additionally upgrades to `Validated` per call when
162
- * {@link GetModelDocumentArgs.includeDiagnostics} is set. This option
163
- * controls only the async notification phase.
228
+ * response phase. A read (`getModelDocument`) settles at the
229
+ * integrity-settled landmark (`IntegrityService.SettledState`), or at
230
+ * `Validated` when {@link GetModelDocumentArgs.includeDiagnostics} is set.
231
+ * A write (`updateModelDocument` / `updateModelDocuments` /
232
+ * `saveModelDocument`) answers once its document is validated, as a
233
+ * session's write does, and then waits for
234
+ * `ModelService.settleLanguageClient`. This option controls only the async
235
+ * notification phase.
164
236
  *
165
237
  * Default: `DocumentState.Validated` — validation is the last builder
166
238
  * phase and produces the full diagnostic set, so subscription events fired
@@ -201,6 +273,22 @@ export interface DataServerOptions extends LogNameOptions {
201
273
  */
202
274
  readonly fingerprintStrategy?: FingerprintStrategy;
203
275
 
276
+ /**
277
+ * How long a reference question waits for the build to reach `Linked` before
278
+ * failing with {@link REFERENCE_SETTLE_TIMEOUT_CODE}. Bounded because the
279
+ * wait resolves off a build-phase notification, so a build cancelled below
280
+ * `Linked` with nothing after it leaves the request unanswered for the life
281
+ * of the server.
282
+ *
283
+ * Expiry rejects rather than reading the index anyway: the unsettled index
284
+ * is what the wait keeps the caller away from, so falling through to it on a
285
+ * slow build reinstates the fault — and on a name proposal persists it.
286
+ *
287
+ * Default {@link DataServer.DEFAULT_OPTIONS}, sized for a cold workspace
288
+ * still reaching `Linked` for the first time.
289
+ */
290
+ readonly referenceSettleTimeoutMs?: number;
291
+
204
292
  /**
205
293
  * Wire-method namespace for both inbound request handlers and the
206
294
  * outbound notification client proxy. Defaults to
@@ -258,15 +346,20 @@ export interface DataServerOptions extends LogNameOptions {
258
346
  * When supplied, every inbound data-server RPC is timed into this collector
259
347
  * (via the `createRpcProxy` binding) and exposed through
260
348
  * {@link DataServerDiagnosticsProtocol.getLatency}. A head that also runs an
261
- * LSP connection can pass the SAME collector to
262
- * `instrumentLspConnection(connection, latency)` so one report covers both
263
- * heads. Absent by default (no timing overhead).
349
+ * LSP connection can pass the SAME collector through `lspLatencyOptions` to
350
+ * that connection, so one report covers both heads. Absent by default (no
351
+ * timing overhead).
264
352
  */
265
353
  readonly latency?: LatencyCollector;
266
354
  }
267
355
 
268
- /** Fully-resolved variant — every field set, used internally after merging defaults. */
269
- interface ResolvedDataServerOptions {
356
+ /**
357
+ * Fully-resolved variant of {@link DataServerOptions} — every field set, after
358
+ * merging defaults. Returned by the `protected`
359
+ * {@link DataServer.resolveOptions} and held on {@link DataServer.options}, so
360
+ * an adopter changing how defaults resolve has to name it.
361
+ */
362
+ export interface ResolvedDataServerOptions {
270
363
  readonly subscriptionPhase: DocumentState;
271
364
  readonly fingerprintStrategy: FingerprintStrategy;
272
365
  readonly methodNamespace: string;
@@ -274,6 +367,41 @@ interface ResolvedDataServerOptions {
274
367
  readonly excludedMethods: readonly string[];
275
368
  /** Always resolved — to the caller's, or to the platform default. */
276
369
  readonly diagnostics: DataServerDiagnosticsProvider;
370
+ readonly referenceSettleTimeoutMs: number;
371
+ }
372
+
373
+ /**
374
+ * What a {@link DataServer} keeps per canonical URI, in the `protected`
375
+ * {@link DataServer.uriWatchRecords}. A record lives while it has a watcher
376
+ * or a release mark; {@link DataServer.pruneUriWatchRecord} enforces that on
377
+ * every path that removes either, so a record with no watcher has a release
378
+ * broadcast pending. Test the size of {@link DataServerUriWatchRecord.watchers}, not the
379
+ * record's presence, for "watched".
380
+ */
381
+ export interface DataServerUriWatchRecord {
382
+ /** The client ids watching the URI; save, dirty and phase events go out only while it is non-empty, a pending release mark aside. */
383
+ readonly watchers: Set<string>;
384
+ /** Digest of the last emitted state, or of the state a first watch found; see {@link DataServer.dispatchPhaseEvent} for why it de-duplicates, {@link DataServer.computeDocumentFingerprint} for its inputs. */
385
+ fingerprint?: string;
386
+ /**
387
+ * The version {@link DataServerUriWatchRecord.fingerprint} was taken at; an
388
+ * event goes out when either moves. Not {@link DataServerUriWatchRecord.sentVersion}:
389
+ * a first watch sets this and sends nothing, so the next event at its
390
+ * version still carries the manager's attribution.
391
+ */
392
+ fingerprintVersion?: ModelVersion;
393
+ /** Set by {@link DataServer.subscribeToModelReleases} once a release happened: its broadcast, the next phase event, goes out even without a watcher. */
394
+ releaseBroadcastPending?: boolean;
395
+ /**
396
+ * The version of an open document the last event sent was built at. The
397
+ * version sent again goes out as `'rebuilt'` from no client: the manager
398
+ * counts a version delivered only once its `Validated` listeners ran, so a
399
+ * build cancelled after the subscription phase would send it as a change
400
+ * twice. Only while the store has the document open: without it, a
401
+ * document can keep one version through changes of its file, so its events
402
+ * keep the manager's attribution.
403
+ */
404
+ sentVersion?: number;
277
405
  }
278
406
 
279
407
  /**
@@ -297,13 +425,19 @@ interface ResolvedDataServerOptions {
297
425
  * adopters subclass ONLY when they need to decorate wire returns or
298
426
  * notifications. The usual adoption path is DI rebinds alone.
299
427
  *
428
+ * **`TTransfer` is not checked.** It declares the union of the transfer roots
429
+ * the workspace's languages produce. Which root a document has is known only
430
+ * at runtime, from its language, so a `TTransfer` missing a language compiles.
431
+ *
300
432
  * Lifecycle: the constructor registers framework request handlers (plus
301
433
  * any names supplied via {@link DataServerOptions.additionalMethods}) and
302
434
  * builds the {@link DataClientProtocol} notification proxy on the same
303
435
  * connection in one {@link createRpcProxy} call (binding `this` as its
304
- * `localTarget`) under the configured namespace, and subscribes one
305
- * `DocumentBuilder.onDocumentPhase` listener per configured phase that
306
- * dispatches subscription events via `clientProxy.onDocumentUpdated`.
436
+ * `localTarget`) under the configured namespace, and follows documents
437
+ * through `ModelService`'s events: at the configured phase, `onModelUpdated`
438
+ * dispatches per-document `clientProxy.onDocumentUpdated` for watched URIs and
439
+ * `onModelsBuilt` a single `clientProxy.onDocumentsBuilt` naming the batch's
440
+ * unwatched documents.
307
441
  *
308
442
  * The data-server requires the full {@link ServerSharedServices}
309
443
  * shape — `HydraniumTextDocuments` for client-attributed updates,
@@ -331,87 +465,42 @@ export class DataServer<
331
465
  * Framework defaults, exposed so an adopter can spread them when
332
466
  * extending rather than restate a value the framework may change.
333
467
  */
334
- static readonly DEFAULT_OPTIONS: Required<Pick<DataServerOptions, 'subscriptionPhase'>> = {
335
- subscriptionPhase: DocumentState.Validated
468
+ static readonly DEFAULT_OPTIONS: Required<Pick<DataServerOptions, 'subscriptionPhase' | 'referenceSettleTimeoutMs'>> = {
469
+ subscriptionPhase: DocumentState.Validated,
470
+ referenceSettleTimeoutMs: 60_000
336
471
  };
337
472
 
338
473
  protected readonly options: ResolvedDataServerOptions;
339
- /** Subscription bookkeeping: URI → set of clientIds that subscribed for that URI. */
340
- protected readonly subscriptions = new Map<string, Set<string>>();
474
+ /** This connection's {@link DataServerUriWatchRecord} per canonical URI; see there for when a record lives. */
475
+ protected readonly uriWatchRecords = new Map<string, DataServerUriWatchRecord>();
341
476
  /**
342
- * Open-document bookkeeping: URI → set of clientIds that opened it over THIS
343
- * connection.
344
- *
345
- * Kept because the document store releases a client's hold only from an
346
- * explicit close, and a client that dies without closing would otherwise keep
347
- * the document open forever — resident, and with its last-close revert
348
- * suppressed. The store has no notion of which connection a clientId reached
349
- * it over, so the connection-scoped set has to live here; teaching it a client
350
- * identity is the more robust and much larger alternative.
477
+ * Per client id, the key each URI it watched resolved to when it watched.
478
+ * An unwatch looks the key up here: once a file is gone, a symlink to it
479
+ * no longer resolves to the key the watch is under.
351
480
  */
352
- protected readonly openedDocuments = new Map<string, Set<string>>();
353
- /** Typed client proxy — sends `data-server/on*` notifications back over the same wire. */
354
- protected readonly clientProxy: DataClientProtocol<TTransfer, TDiagnostic, TProject>;
355
- protected readonly disposables = new DisposableCollection();
481
+ protected readonly watchKeys = new Map<string, Map<string, string>>();
356
482
  /**
357
- * Snapshot of the most recent `DocumentBuilder.onUpdate` event. Drives
358
- * `reason` discrimination on outbound `onDocumentUpdated` notifications:
359
- * a URI in the `changed` list emits `'changed'`, in `deleted` emits
360
- * `'deleted'`, otherwise `'rebuilt'` (cascade rebuild from a dependent
361
- * URI's change). The same mechanism `AstDocumentManager.onUpdate` uses on
362
- * the LSP side, so reason fidelity stays consistent between heads.
483
+ * The position of the last update or deletion event sent, which each
484
+ * such event carries, and a watch's answer carries as of the moment it
485
+ * took whether its document exists: an event past it was sent after.
363
486
  */
364
- protected lastBuildUpdate?: { changed: readonly URI[]; deleted: readonly URI[] };
487
+ protected eventSequence = 0;
365
488
  /**
366
- * Per-URI hash of the last emitted (text + diagnostics) state,
367
- * used by {@link dispatchPhaseEvent} to suppress duplicate
368
- * `onDocumentUpdated` notifications for rebuilds that produce no
369
- * observable change since the last emit.
370
- *
371
- * Two scenarios routinely produce such rebuilds:
372
- * 1. **Refresh-triggered rebuilds.** When a second client attaches to a
373
- * document already open in another client,
374
- * `HydraniumTextDocuments.refreshContent` fires `onDidChangeContent`
375
- * purely to re-trigger the build pipeline — the text and diagnostics
376
- * are identical to the prior emit.
377
- * 2. **Cascade rebuilds with no diagnostic delta.** Langium rebuilds a
378
- * document when a dependency changes; if the rebuild produces the
379
- * same diagnostics, there is nothing new to communicate to subscribers.
380
- *
381
- * Without this filter, both scenarios reach subscribers as wire-side
382
- * `'changed'` events. A subscriber that interprets `'changed'` as
383
- * "another client wrote new content" and resets its in-memory root to
384
- * the server view then misreads the spurious event as a concurrent
385
- * third-party write and loses the user's edits.
386
- *
387
- * Initialised on {@link watchModelDocument} to the current
388
- * document fingerprint so the FIRST phase event after a fresh
389
- * subscription is also de-duplicated against the state subscribers
390
- * obtained via `getModelDocument` — they do not need a redundant phase
391
- * notification for the state they just fetched.
392
- *
393
- * Cleared in {@link unwatchModelDocument} when the last
394
- * subscriber for a URI leaves so memory does not accumulate.
395
- *
396
- * Stored as a cyrb53 hex digest (16 chars per URI) rather than the raw
397
- * text + diagnostics serialisation so the memory cost is constant in
398
- * document size. See {@link computeDocumentFingerprint} for the inputs.
489
+ * The live client sessions this connection registered, by client id. A
490
+ * document request carrying one of these ids acts as that session; one
491
+ * carrying any other id fails. A session leaves once it ends, so a
492
+ * connection that registers many over its life does not accumulate them.
399
493
  */
400
- protected readonly lastEmittedFingerprint = new Map<string, string>();
494
+ protected readonly clientSessions = new Map<string, ClientSession<AstNode, AstDiagnostic, TTransfer>>();
401
495
  /**
402
- * URIs whose LAST client just closed. The update handler rebuilds such a
403
- * document from its disk content (discarding unsaved in-session edits),
404
- * but {@link dispatchPhaseEvent} gates on the subscription map — and the
405
- * last close typically also removed the last watcher, so consumers that
406
- * only ever fetch via `getModelDocument` would keep showing the
407
- * discarded state forever. Marked on the last-close transition (see
408
- * {@link subscribeToTextDocumentCloses}) and consumed by
409
- * {@link dispatchPhaseEvent}, which broadcasts the following rebuild's
410
- * phase event even without a subscription — de-duplicated against
411
- * {@link lastEmittedFingerprint} where an entry survives, so a close
412
- * whose disk state equals the last emitted state stays silent.
496
+ * Typed client proxy — sends `data-server/on*` notifications back over the same wire.
497
+ * The proxy sends any `on[A-Z]*` name other than `onDidOpenConnection` and
498
+ * `onDidCloseConnection`, for which it returns its own events, so a subclass
499
+ * with notifications of its own narrows only the type:
500
+ * `declare protected readonly clientProxy: TheirClient`.
413
501
  */
414
- protected readonly pendingRevertBroadcasts = new Set<string>();
502
+ protected readonly clientProxy: DataClientProtocol<TTransfer, TDiagnostic, TProject>;
503
+ protected readonly disposables = new DisposableCollection();
415
504
  protected readonly tracer: Tracer;
416
505
  /** The in-flight interactive profile capture, held between {@link startProfiling} and {@link stopProfiling}. */
417
506
  protected activeProfile?: DataServerProfileCapture;
@@ -420,27 +509,23 @@ export class DataServer<
420
509
  /** Per-method RPC latency collector, when the head opted in via {@link DataServerOptions.latency}. */
421
510
  protected readonly latency?: LatencyCollector;
422
511
  /** Encoder pulled from DI. Adopters rebind `services.model.TransferEncoder` to a typed-overlay subclass. */
423
- protected readonly encoder: TransferEncoder<unknown, TDiagnostic>;
512
+ protected readonly encoder: TransferEncoder<TDiagnostic>;
424
513
  /**
425
514
  * In-process workspace facade — the lifecycle delegate `get` / `update` / `save` go through.
426
- * The facade's AstDocument diagnostic shape is intentionally typed `unknown` here: adopters
427
- * carry LSP-shape diagnostics in their AstDocument (e.g. an adopter's LSP-shape diagnostic type)
428
- * while the wire shape stays `TDiagnostic extends TransferDiagnostic`. The encoder's
429
- * `astDocumentToTransferDocument` accepts both shapes (wire-shape or LSP-shape) and projects
430
- * to wire shape on the return — see `TransferEncoder.astDocumentToTransferDocument`.
515
+ * Its documents carry the AST-layer {@link AstDiagnostic}, never the wire `TDiagnostic`:
516
+ * {@link encoder} converts one into the other on the way out.
431
517
  */
432
- protected readonly modelService: ModelService<AstNode, unknown, TTransfer>;
518
+ protected readonly modelService: ModelService<AstNode, AstDiagnostic, TTransfer>;
433
519
 
434
520
  constructor(
435
521
  protected readonly connection: MessageConnection,
436
- protected readonly services: ServerSharedServices<TProject>,
522
+ protected readonly services: ServerSharedServices<TProject, TDiagnostic>,
437
523
  options: DataServerOptions = {}
438
524
  ) {
439
525
  this.options = this.resolveOptions(options);
440
526
  this.tracer = this.services.Tracer.for(options.logName ?? 'DataServer').trace('instantiated');
441
527
  // DI-bound: adopters rebind `services.model.TransferEncoder` /
442
- // `services.model.ModelService` with their own subclasses. Slot types use the
443
- // framework upper bounds; the casts below narrow to this instance's generics.
528
+ // `services.model.ModelService` with their own subclasses.
444
529
  const { TransferEncoder: encoder, ModelService: modelService } = this.services.model;
445
530
  if (!encoder || !modelService) {
446
531
  throw new Error(
@@ -448,8 +533,8 @@ export class DataServer<
448
533
  'Did you compose `createServerSharedModule(ctx)` into your shared module?'
449
534
  );
450
535
  }
451
- this.encoder = encoder as TransferEncoder<unknown, TDiagnostic>;
452
- this.modelService = modelService as ModelService<AstNode, unknown, TTransfer>;
536
+ this.encoder = encoder;
537
+ this.modelService = modelService;
453
538
  const excluded = new Set<string>(this.options.excludedMethods);
454
539
  const registeredMethods = [
455
540
  ...DATA_SERVER_PROTOCOL_METHODS,
@@ -465,38 +550,43 @@ export class DataServer<
465
550
  methodNamespace: this.options.methodNamespace,
466
551
  localTarget: this,
467
552
  localMethods: registeredMethods as readonly (keyof this & string)[],
468
- latency: this.latency
553
+ latency: this.latency,
554
+ // Bound at the chokepoint rather than per handler, so an adopter's
555
+ // `additionalMethods` are rendered on the same terms as the
556
+ // framework's own rejections.
557
+ renderErrorMessage: error => this.services.MessageRenderer.renderError(error)
469
558
  });
470
- this.disposables.push(
471
- this.services.workspace.DocumentBuilder.onUpdate((changed, deleted) => {
472
- this.lastBuildUpdate = { changed, deleted };
473
- })
474
- );
475
- this.subscribeToDocumentBuilder();
559
+ this.disposables.push(this.modelService.onModelDeleted(event => this.dispatchDeleteEvent(event)));
560
+ this.subscribeToModelUpdates();
476
561
  this.subscribeToTextDocumentSaves();
477
- this.subscribeToTextDocumentCloses();
562
+ this.subscribeToDirtyChanges();
563
+ this.subscribeToModelReleases();
478
564
  this.subscribeToProjectManager();
479
565
  // Self-register teardown so an adopter that keeps no reference to the
480
566
  // server still releases per-connection state, with no lifecycle hook of
481
- // its own. See `dispose`.
482
- this.disposables.push(connection.onClose(() => this.dispose()));
567
+ // its own. The client did not close anything itself, so its sessions end
568
+ // as lost and each document it was the last to have open waits out the
569
+ // store's release grace. See `dispose`.
570
+ this.disposables.push(connection.onClose(() => this.dispose('lost')));
483
571
  }
484
572
 
485
573
  /**
486
574
  * Release everything the constructor wired up — the bound protocol
487
- * handlers and every listener — and clear the subscription map and the
488
- * per-URI emission-fingerprint cache, so a long-lived shared services
489
- * bundle does not retain per-connection memory after the connection
490
- * closes. Also closes every document still open over this connection (see
491
- * {@link closeOpenDocuments}), which is the SHARED store's state rather than
492
- * this server's and so outlives the connection unless released here.
575
+ * handlers and every listener — and clear {@link uriWatchRecords}, so a
576
+ * long-lived shared services bundle does not retain per-connection memory
577
+ * after the connection closes. Also ends every session this connection registered, which closes
578
+ * every document it has open: the SHARED store's state rather than this
579
+ * server's, which outlives the connection unless released here.
493
580
  *
494
- * Idempotent: subsequent calls are no-ops. Self-fires on
495
- * `connection.onClose` so adopters who don't hold a reference still
496
- * get per-connection cleanup; adopters that DO hold a reference may
497
- * call `dispose()` directly for early teardown.
581
+ * Idempotent: subsequent calls are no-ops. Runs by itself when the
582
+ * connection closes, so adopters who don't hold a reference still get
583
+ * per-connection cleanup; adopters that DO hold a reference may call
584
+ * `dispose()` directly for early teardown. The sessions end with `cause`:
585
+ * `'closed'` releases every document whose last open they close at once,
586
+ * and `'lost'`, the connection's own close, lets each wait out the release
587
+ * grace.
498
588
  */
499
- dispose(): void {
589
+ dispose(cause: SessionEndCause = 'closed'): void {
500
590
  this.disposed = true;
501
591
  // Release an in-flight interactive capture so the process-wide inspector
502
592
  // singleton is not left active after the connection closes.
@@ -505,102 +595,183 @@ export class DataServer<
505
595
  this.activeProfile = undefined;
506
596
  void capture.stop({}).catch(() => undefined);
507
597
  }
508
- // AFTER `disposables.dispose()`, deliberately: closing a document fires
509
- // `onDidClose`, and this server's own close listener would otherwise mark a
510
- // revert broadcast for a connection that is already gone.
598
+ // AFTER `disposables.dispose()`, deliberately: ending a session releases
599
+ // each document it was the last to hold, and this server's own
600
+ // `onModelReleased` subscription would otherwise mark a release broadcast
601
+ // for a connection that is already gone.
511
602
  this.disposables.dispose();
512
- this.closeOpenDocuments();
513
- this.subscriptions.clear();
514
- this.lastEmittedFingerprint.clear();
515
- this.pendingRevertBroadcasts.clear();
603
+ for (const [clientId, session] of this.clientSessions) {
604
+ this.endSession(clientId, session, cause);
605
+ }
606
+ this.uriWatchRecords.clear();
607
+ this.watchKeys.clear();
516
608
  }
517
609
 
518
610
  // ============================================================
519
- // DataServerProtocol implementation — delegates to ModelService.
611
+ // DataServerProtocol implementation
520
612
  // ============================================================
521
613
  //
522
- // The lifecycle methods (`get` / `update` / `save` / `ready`) forward
523
- // straight to `ModelService` and encode the returned `AstDocument` on
524
- // the wire boundary via `encoder.astDocumentToTransferDocument`.
525
- // Adopters customising lifecycle behaviour (normalisation, supersession,
526
- // settled-phase choice, etc.) override on the ModelService subclass —
527
- // no override on DataServer is needed.
528
-
529
- async openModelDocument(args: OpenModelArgs): Promise<TransferDocument<TTransfer, TDiagnostic>> {
530
- // Register the editor session (idempotent — `ModelService.open` refreshes
531
- // an already-open document rather than re-opening), then return the built
532
- // state at the configured target phase. The one-shot snapshot; subsequent
533
- // build-phase events arrive via `watchModelDocument`.
534
- await this.modelService.open(args);
535
- // Record the hold so `dispose` can release it for a client that never
536
- // closes. Keyed by the URI as given, because that is what `close` takes.
537
- let holders = this.openedDocuments.get(args.uri);
538
- if (!holders) {
539
- holders = new Set<string>();
540
- this.openedDocuments.set(args.uri, holders);
614
+ // Reads go to `ModelService`; a request that opens or writes a document
615
+ // goes to the session this connection registered under its `clientId`.
616
+ // Each answer is encoded on the wire boundary via
617
+ // `encoder.astDocumentToTransferDocument`. To change how documents are
618
+ // read, override on the ModelService subclass; to change how they are
619
+ // written, on the session class the bound `ClientSessionFactory` builds.
620
+
621
+ async createSession(args: CreateSessionArgs): Promise<CreatedSession> {
622
+ // After teardown nothing would ever end a session registered now, and its
623
+ // id would stay taken for the life of the process.
624
+ if (this.disposed) {
625
+ throw new SessionClosedError(args.clientId);
541
626
  }
542
- holders.add(args.clientId);
543
- const document = await this.getModelDocument({ uri: args.uri });
544
- // Project the authoritative client-facing version onto the open snapshot.
545
- // `getModelDocument` encodes the freshly-built AST snapshot, whose version
546
- // is the `LangiumDocument`'s own `textDocument.version`. That lags the
547
- // multi-client synced version whenever the open seeded the synced document
548
- // with a caller-supplied version id — and the synced version is what
549
- // `ModelService.update`'s optimistic-concurrency gate compares
550
- // `baseVersion` against, so reporting the snapshot's would make the
551
- // caller's first tagged write self-conflict. A genuine concurrent edit
552
- // still trips the gate and is reconciled by the caller's replay rather
553
- // than predicted here.
554
- return { ...document, version: this.services.workspace.TextDocuments.version(args.uri) };
627
+ const session = this.modelService.createSession(args.label, args.clientId, { resumeToken: args.resumeToken });
628
+ this.clientSessions.set(args.clientId, session);
629
+ // A session also ends without closeSession, as when a client registers
630
+ // again on another connection, and its watches and entry here would
631
+ // otherwise outlive it.
632
+ session.onDidDispose(cause => {
633
+ // A session class may report its end late, once a replacement holds
634
+ // the id here; the replacement's entry and watches stay.
635
+ if (this.clientSessions.get(args.clientId) !== session) {
636
+ return;
637
+ }
638
+ this.dropWatches(args.clientId);
639
+ this.clientSessions.delete(args.clientId);
640
+ this.tracer.debug(`Forget session ${args.clientId}: it ended as ${cause}`);
641
+ });
642
+ return { epoch: this.epoch };
555
643
  }
556
644
 
557
- async closeModelDocument(args: CloseModelArgs): Promise<void> {
558
- // Closing a session also releases its watch for (uri, clientId) — a
559
- // forgotten unwatch would otherwise leak phase-event dispatch until the
560
- // connection closes. Idempotent: a close without a prior watch is a no-op.
561
- await this.unwatchModelDocument({ uri: args.uri, clientId: args.clientId });
562
- this.forgetOpenDocument(args.uri, args.clientId);
563
- await this.modelService.close(args);
645
+ /**
646
+ * The epoch this server numbers versions in, which every registration and
647
+ * document names: the text store's, so every connection to the server
648
+ * answers the same one.
649
+ */
650
+ protected get epoch(): string {
651
+ return this.services.workspace.TextDocuments.epoch;
564
652
  }
565
653
 
566
654
  /**
567
- * Drop the recorded hold for `(uri, clientId)` so {@link dispose} does not
568
- * close it a second time. Idempotent.
655
+ * Refuse a write whose base version is numbered in another epoch, as a
656
+ * restarted server's predecessor numbered it. Versions start afresh with
657
+ * each epoch, so the session's gate would take the version for text the
658
+ * writer never saw. Checked once the session is found, before the open
659
+ * check and every other check of its documents.
569
660
  */
570
- protected forgetOpenDocument(uri: string, clientId: string): void {
571
- const holders = this.openedDocuments.get(uri);
572
- if (!holders) {
573
- return;
661
+ protected assertEpoch(
662
+ uri: string,
663
+ gate: BaseVersionGate,
664
+ message: typeof STALE_BASE_VERSION_UPDATE | typeof STALE_BASE_VERSION_SAVE = STALE_BASE_VERSION_UPDATE
665
+ ): void {
666
+ if (isModelVersion(gate.baseVersion) && gate.baseEpoch !== this.epoch) {
667
+ this.tracer.withUri(uri).debug(`Conflict: base v${gate.baseVersion} is numbered in epoch ${gate.baseEpoch}, not ${this.epoch}`);
668
+ throw new ConflictError(uri, gate.baseVersion, this.services.workspace.TextDocuments.version(uri), message);
574
669
  }
575
- holders.delete(clientId);
576
- if (holders.size === 0) {
577
- this.openedDocuments.delete(uri);
670
+ }
671
+
672
+ /** End a session this connection registered. */
673
+ async closeSession(args: CloseSessionArgs): Promise<void> {
674
+ const session = this.clientSessions.get(args.clientId);
675
+ if (session) {
676
+ this.endSession(args.clientId, session);
578
677
  }
579
678
  }
580
679
 
680
+ /** End `session`, registered here under `clientId`, with `cause`, and drop its watches on this connection. */
681
+ protected endSession(
682
+ clientId: string,
683
+ session: ClientSession<AstNode, AstDiagnostic, TTransfer>,
684
+ cause: SessionEndCause = 'closed'
685
+ ): void {
686
+ this.dropWatches(clientId);
687
+ session.dispose(cause);
688
+ }
689
+
690
+ protected dropWatches(clientId: string): void {
691
+ this.watchKeys.delete(clientId);
692
+ for (const [uri, record] of this.uriWatchRecords) {
693
+ if (record.watchers.delete(clientId)) {
694
+ this.pruneUriWatchRecord(uri);
695
+ }
696
+ }
697
+ }
698
+
699
+ async createModelDocument(args: CreateModelDocumentArgs): Promise<TransferCreatedDocument<TTransfer, TDiagnostic>> {
700
+ const session = this.requireSession(args.clientId);
701
+ const version = await session.create(args.uri, args.text);
702
+ const snapshot = await this.openedSnapshot(args.uri, () => session.close(args.uri));
703
+ return { ...snapshot, created: { version: asModelVersion(version) } };
704
+ }
705
+
706
+ async updateModelDocuments(args: TransferUpdateDocumentsArgs<TTransfer>): Promise<TransferWrittenDocument<TTransfer, TDiagnostic>[]> {
707
+ const session = this.requireSession(args.clientId);
708
+ // Every one before any applies, so a set stays all or none.
709
+ args.updates.forEach(update => this.assertEpoch(update.uri, update));
710
+ const astDocuments = await session.updateAll({
711
+ updates: args.updates.map(update => this.toSessionWrite(update)),
712
+ write: args.write
713
+ });
714
+ // A page that reads unsaved work from its editor sees the writes only once their text reaches it.
715
+ await Promise.all(args.updates.map(update => this.modelService.settleLanguageClient(update.uri)));
716
+ return astDocuments.map(astDocument => ({ ...this.encodeDocument(astDocument), written: astDocument.written }));
717
+ }
718
+
581
719
  /**
582
- * Close every document still open over this connection, for the clients that
583
- * opened it here.
584
- *
585
- * The document store releases a per-URI hold only from an explicit close, so
586
- * without this a client that dies mid-session keeps its documents open for the
587
- * lifetime of the process: `isOpenInAnyClient` stays true, the document stays
588
- * resident, and the last-close revert never runs. A long-lived multi-client
589
- * head is the configuration where a dead client is normal rather than
590
- * exceptional, so the leak accumulates there.
591
- *
592
- * Runs from {@link dispose}, which is synchronous, so each close is fired and
593
- * its failure swallowed — a teardown must not reject, and a URI whose close
594
- * fails is no worse off than it was before this drain existed.
720
+ * The session write a wire write request carries. Only the fields a session
721
+ * takes: a field an adopter adds to a request reaches the session only
722
+ * through an override of this.
595
723
  */
596
- protected closeOpenDocuments(): void {
597
- const held = [...this.openedDocuments];
598
- this.openedDocuments.clear();
599
- for (const [uri, clientIds] of held) {
600
- for (const clientId of clientIds) {
601
- void Promise.resolve(this.modelService.close({ uri, clientId })).catch(() => undefined);
602
- }
724
+ protected toSessionWrite(request: Omit<TransferUpdateDocumentArgs<TTransfer>, 'clientId'>): ClientSessionWriteArgs<TTransfer> {
725
+ return { uri: request.uri, model: request.model, baseVersion: request.baseVersion, restore: request.restore, write: request.write };
726
+ }
727
+
728
+ /**
729
+ * The session this connection registered under `clientId`, which every
730
+ * document request acts as. An id that is not one fails with the
731
+ * closed-session code: opening or writing under it would leave an open that
732
+ * no session end ever closes.
733
+ */
734
+ protected requireSession(clientId: string): ClientSession<AstNode, AstDiagnostic, TTransfer> {
735
+ const session = this.clientSessions.get(clientId);
736
+ if (!session) {
737
+ throw new SessionClosedError(clientId, 'The client session is not registered on this connection.');
603
738
  }
739
+ return session;
740
+ }
741
+
742
+ async openModelDocument(args: Pick<OpenModelArgs, 'uri' | 'clientId' | 'options'>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
743
+ const session = this.requireSession(args.clientId);
744
+ const wasOpen = this.services.workspace.TextDocuments.isOpenInClient(args.uri, args.clientId);
745
+ await session.open(args.uri, args.options);
746
+ // A repeat open keeps the earlier one, which is still in use.
747
+ return this.openedSnapshot(args.uri, wasOpen ? undefined : () => session.close(args.uri));
748
+ }
749
+
750
+ /**
751
+ * The snapshot a session's open or create answers with. When the read
752
+ * fails, `rollback` undoes the open this call made before the failure is
753
+ * rethrown: the caller sees no open, so nothing on its side would ever close
754
+ * it.
755
+ */
756
+ protected async openedSnapshot(uri: string, rollback?: () => Promise<void>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
757
+ try {
758
+ return await this.getModelDocument({ uri });
759
+ } catch (error: unknown) {
760
+ // The open's failure is the one the caller needs, not the cleanup's.
761
+ await rollback?.().catch(() => undefined);
762
+ throw error;
763
+ }
764
+ }
765
+
766
+ async closeModelDocument(args: CloseModelArgs): Promise<void> {
767
+ // Through the handle, so a close under an ended session fails as that
768
+ // session's calls do, and a session class's own close is honoured.
769
+ const session = this.requireSession(args.clientId);
770
+ // Closing also releases the watch for (uri, clientId) — a forgotten
771
+ // unwatch would otherwise leak phase-event dispatch until the connection
772
+ // closes. Idempotent: a close without a prior watch is a no-op.
773
+ await this.unwatchModelDocument({ uri: args.uri, clientId: args.clientId });
774
+ await session.close(args.uri);
604
775
  }
605
776
 
606
777
  async getModelDocument(args: GetModelDocumentArgs): Promise<TransferDocument<TTransfer, TDiagnostic>> {
@@ -615,77 +786,158 @@ export class DataServer<
615
786
  // unsubscribed caller that needs diagnostics inline passes
616
787
  // `includeDiagnostics: true` to settle at `Validated` instead.
617
788
  const state = args.includeDiagnostics ? DocumentState.Validated : undefined;
618
- const astDocument = await this.modelService.ensureDocumentState(args.uri, state);
619
- return this.encoder.astDocumentToTransferDocument(astDocument as never) as unknown as TransferDocument<TTransfer, TDiagnostic>;
789
+ try {
790
+ return this.encodeDocument(await this.modelService.ensureDocumentState(args.uri, state));
791
+ } catch (error: unknown) {
792
+ // The protocol answers a read of a URI with no document with an
793
+ // envelope that has no model.
794
+ if (this.isMissingDocument(error, args.uri)) {
795
+ return this.envelope(UriUtils.toUri(args.uri));
796
+ }
797
+ throw error;
798
+ }
799
+ }
800
+
801
+ async updateModelDocument(args: TransferUpdateDocumentArgs<TTransfer>): Promise<TransferWrittenDocument<TTransfer, TDiagnostic>> {
802
+ const session = this.requireSession(args.clientId);
803
+ this.assertEpoch(args.uri, args);
804
+ const astDocument = await session.update(this.toSessionWrite(args));
805
+ // A page that reads unsaved work from its editor sees the write only once the text reaches it.
806
+ await this.modelService.settleLanguageClient(args.uri);
807
+ return { ...this.encodeDocument(astDocument), written: astDocument.written };
620
808
  }
621
809
 
622
- async updateModelDocument(args: TransferUpdateDocumentArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
623
- const astDocument = await this.modelService.update(args);
624
- return this.encoder.astDocumentToTransferDocument(astDocument as never) as unknown as TransferDocument<TTransfer, TDiagnostic>;
810
+ async saveModelDocument(args: TransferSaveDocumentArgs<TTransfer>): Promise<TransferSavedDocument<TTransfer, TDiagnostic>> {
811
+ const session = this.requireSession(args.clientId);
812
+ this.assertEpoch(args.uri, args, STALE_BASE_VERSION_SAVE);
813
+ const astDocument = await session.save(this.toSessionWrite(args));
814
+ await this.modelService.settleLanguageClient(args.uri);
815
+ return { ...this.encodeDocument(astDocument), persisted: astDocument.persisted };
625
816
  }
626
817
 
627
- async saveModelDocument(args: TransferSaveDocumentArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
628
- const astDocument = await this.modelService.save(args);
629
- return this.encoder.astDocumentToTransferDocument(astDocument as never) as unknown as TransferDocument<TTransfer, TDiagnostic>;
818
+ async persistModelDocument(args: TransferPersistDocumentArgs): Promise<TransferSavedDocument<TTransfer, TDiagnostic>> {
819
+ const session = this.requireSession(args.clientId);
820
+ this.assertEpoch(args.uri, args, STALE_BASE_VERSION_SAVE);
821
+ const version = await session.persist({ uri: args.uri, baseVersion: args.baseVersion });
822
+ await this.modelService.settleLanguageClient(args.uri);
823
+ const astDocument = await this.modelService.ensureDocumentState(args.uri, this.services.workspace.DocumentBuilder.finalBuildState());
824
+ return { ...this.encodeDocument(astDocument), persisted: { version } };
825
+ }
826
+
827
+ /**
828
+ * Delete the document through the session, then release the session's
829
+ * watch of it, as {@link closeModelDocument} does. Released only after the
830
+ * delete: one that fails leaves the session its open and its watch. Other
831
+ * sessions' watches survive, as for any deletion.
832
+ */
833
+ async deleteModelDocument(args: TransferDeleteDocumentArgs): Promise<void> {
834
+ const session = this.requireSession(args.clientId);
835
+ this.assertEpoch(args.uri, args);
836
+ // Keyed before the delete: once the file is gone, a symlink to it no
837
+ // longer resolves to the key the watch is under.
838
+ const uri = this.canonicalKey(args.uri);
839
+ await session.delete({ uri: args.uri, baseVersion: args.baseVersion });
840
+ await this.unwatchModelDocument({ uri, clientId: args.clientId });
630
841
  }
631
842
 
632
843
  /**
633
- * Record a watch for `(uri, clientId)`. Subsequent phase events on `uri`
634
- * fan out to the wired `clientProxy.onDocumentUpdated`. The
635
- * bidirectional pattern means the event channel is the client
636
- * notification surface, not a returned handle — this method only
637
- * registers the URI in the dispatch table.
844
+ * Record a watch for `(uri, clientId)` in {@link uriWatchRecords}.
845
+ * Subsequent phase events on `uri` fan out to the wired
846
+ * `clientProxy.onDocumentUpdated`. The bidirectional pattern means the
847
+ * event channel is the client notification surface, not a returned
848
+ * handle.
638
849
  *
639
- * Also baselines the per-URI emission fingerprint (see
640
- * {@link lastEmittedFingerprint}) to the document's current state when
641
- * the first watcher for the URI registers. This guarantees that any
642
- * phase event firing immediately after the watch with no observable
643
- * change is suppressed — watchers obtain initial state via
644
- * `getModelDocument` (or {@link openModelDocument}) and do not need a
645
- * redundant phase notification for that same state.
850
+ * Also baselines the URI's emission fingerprint (see
851
+ * {@link dispatchPhaseEvent}) to the document's current state when the
852
+ * first watcher for the URI registers. This guarantees that any phase event firing immediately after
853
+ * the watch with no observable change is suppressed — watchers obtain
854
+ * initial state via `getModelDocument` (or {@link openModelDocument}) and
855
+ * do not need a redundant phase notification for that same state.
856
+ *
857
+ * Answers once the document is loaded as a read loads it, with the key
858
+ * events name it by and whether a document exists, taken after the watch
859
+ * is in place and the load, so an event sent while it loads is older.
646
860
  */
647
- async watchModelDocument(args: WatchModelDocumentArgs): Promise<void> {
861
+ async watchModelDocument(args: WatchModelDocumentArgs): Promise<TransferWatchedDocument> {
648
862
  const uri = this.canonicalKey(args.uri);
649
- let subscribers = this.subscriptions.get(uri);
650
- if (!subscribers) {
651
- subscribers = new Set();
652
- this.subscriptions.set(uri, subscribers);
653
- }
654
- subscribers.add(args.clientId);
655
- if (!this.lastEmittedFingerprint.has(uri)) {
656
- const document = this.services.workspace.LangiumDocuments.getDocument(UriUtils.toUri(uri));
657
- if (document) {
658
- this.lastEmittedFingerprint.set(uri, this.computeDocumentFingerprint(document));
863
+ const keys = this.watchKeys.get(args.clientId) ?? new Map<string, string>();
864
+ this.watchKeys.set(args.clientId, keys.set(args.uri, uri));
865
+ const record = this.uriWatchRecords.get(uri) ?? { watchers: new Set<string>() };
866
+ this.uriWatchRecords.set(uri, record);
867
+ record.watchers.add(args.clientId);
868
+ if (record.fingerprint === undefined) {
869
+ const document = this.modelService.getDocument(args.uri);
870
+ if (document && !this.services.workspace.ModelLedger.isPlaceholder(document.parseResult.value)) {
871
+ record.fingerprint = this.computeDocumentFingerprint(document.parseResult.value, this.encoder.toTransferDocument(document));
872
+ record.fingerprintVersion = this.services.workspace.ModelLedger.versionOf(document.parseResult.value);
659
873
  }
660
874
  }
875
+ // As for a read, only a missing document counts as none. A file briefly
876
+ // unreadable leaves the builder's placeholder, and is there all the same.
877
+ // Whether it exists, the text held and the position of the last event
878
+ // sent are read in one synchronous run, so an event sent after is past
879
+ // the position and moves the text past the state answered.
880
+ const answer = (exists: boolean): TransferWatchedDocument => {
881
+ const text = exists ? this.serverTextState(args.uri) : undefined;
882
+ return { uri, epoch: this.epoch, exists, sequence: this.eventSequence, ...(text ? { text } : {}) };
883
+ };
884
+ return this.modelService.ensureDocumentState(args.uri).then(
885
+ () => answer(this.modelService.getDocument(args.uri) !== undefined),
886
+ (error: unknown) => answer(!this.isMissingDocument(error, args.uri))
887
+ );
661
888
  }
662
889
 
663
890
  /**
664
891
  * Remove a watch for `(uri, clientId)` previously created by
665
892
  * {@link watchModelDocument}. Idempotent — unwatching twice is a no-op.
666
- * Dispatch for `uri` stops once no watchers remain, at which point the
667
- * per-URI emission fingerprint is also cleared so the next first-watch
668
- * re-baselines against the then-current document state rather than a
669
- * stale snapshot from the previous watch.
893
+ * Dispatch for `uri` stops once no watchers remain, and the emission
894
+ * fingerprint goes with the last watcher (see {@link pruneUriWatchRecord}).
895
+ *
896
+ * A URI the client watched is unwatched under the key it resolved to then,
897
+ * from {@link watchKeys}, which still holds once its file is gone.
670
898
  */
671
899
  async unwatchModelDocument(args: WatchModelDocumentArgs): Promise<void> {
672
- const uri = this.canonicalKey(args.uri);
673
- const subscribers = this.subscriptions.get(uri);
674
- if (!subscribers) {
900
+ const keys = this.watchKeys.get(args.clientId);
901
+ const uri = keys?.get(args.uri) ?? this.canonicalKey(args.uri);
902
+ // Every spelling the client watched it under was this one watch.
903
+ keys?.forEach((key, spelling) => {
904
+ if (key === uri) {
905
+ keys.delete(spelling);
906
+ }
907
+ });
908
+ if (keys?.size === 0) {
909
+ this.watchKeys.delete(args.clientId);
910
+ }
911
+ if (this.uriWatchRecords.get(uri)?.watchers.delete(args.clientId)) {
912
+ this.pruneUriWatchRecord(uri);
913
+ }
914
+ }
915
+
916
+ /**
917
+ * Drop what `uri` no longer needs: the
918
+ * {@link DataServerUriWatchRecord.fingerprint} once no client watches it,
919
+ * and the whole record once it holds no
920
+ * {@link DataServerUriWatchRecord.releaseBroadcastPending} mark either.
921
+ * Every path that removes a watcher or consumes a mark ends here.
922
+ */
923
+ protected pruneUriWatchRecord(uri: string): void {
924
+ const record = this.uriWatchRecords.get(uri);
925
+ if (!record || record.watchers.size > 0) {
675
926
  return;
676
927
  }
677
- subscribers.delete(args.clientId);
678
- if (subscribers.size === 0) {
679
- this.subscriptions.delete(uri);
680
- this.lastEmittedFingerprint.delete(uri);
928
+ if (record.releaseBroadcastPending) {
929
+ record.fingerprint = undefined;
930
+ record.fingerprintVersion = undefined;
931
+ } else {
932
+ this.uriWatchRecords.delete(uri);
681
933
  }
682
934
  }
683
935
 
684
936
  /**
685
- * Canonicalise a URI string for use as a subscription / fingerprint
686
- * map key, via the shared `DocumentUriPolicy`. Callers may send
687
- * non-canonical URIs (drive-letter casing, percent-encoding differences,
688
- * or a symlink path) over the wire; the dispatch side keys by
937
+ * Canonicalise a URI string for use as a {@link uriWatchRecords} key, via the
938
+ * shared `DocumentUriPolicy`. Callers may send non-canonical URIs
939
+ * (drive-letter casing, percent-encoding differences, or a symlink path)
940
+ * over the wire; the dispatch side keys by
689
941
  * `document.uri.toString()` from `LangiumDocuments`, so writer keys must
690
942
  * canonicalise to the same form or events silently fail to deliver.
691
943
  * Routing through the seam (rather than a bare `UriUtils.normalize`)
@@ -695,26 +947,24 @@ export class DataServer<
695
947
  * LSP head resolves.
696
948
  *
697
949
  * Adopters can still override for head-specific URI policy by subclassing.
950
+ * The result keys watches only; a document is looked up by its own URI.
698
951
  */
699
952
  protected canonicalKey(uri: string): string {
700
953
  return this.services.workspace.DocumentUriPolicy.canonicalUri(uri);
701
954
  }
702
955
 
703
956
  async getProjects(): Promise<readonly TProject[]> {
704
- // Pass-through: `ProjectManager<TProject>` already produces `TProject`
705
- // (the shared services are parameterised over the same generic).
706
957
  // The framework reads `id` for registry identity and `dependencies`
707
958
  // for the visibility closure; every other field rides on the
708
959
  // JSON-RPC envelope as adopter-defined wire metadata.
709
- return this.services.workspace.ProjectManager.getProjects();
960
+ return this.services.workspace.ProjectManager.getProjects().map(project => this.encodeProject(project));
710
961
  }
711
962
 
712
963
  async getProjectForUri(args: GetProjectForUriArgs): Promise<TProject | undefined> {
713
- // Pass-through: `ProjectManager.getProject(uri)` already returns the
714
- // adopter's `TProject` shape. Membership logic belongs to the adopter's
715
- // `ProjectManager`; the data-server forwards the URI without
716
- // interpretation.
717
- return this.services.workspace.ProjectManager.getProject(UriUtils.toUri(args.uri));
964
+ // Membership logic belongs to the adopter's `ProjectManager`; the
965
+ // data-server forwards the URI without interpretation.
966
+ const project = this.services.workspace.ProjectManager.getProject(UriUtils.toUri(args.uri));
967
+ return project && this.encodeProject(project);
718
968
  }
719
969
 
720
970
  /**
@@ -734,27 +984,60 @@ export class DataServer<
734
984
  // (see resolveReferenceServices) and delegate.
735
985
  // ============================================================
736
986
 
737
- async findReferenceCandidates(ctx: ReferenceContext): Promise<ReferenceCandidate[]> {
738
- // Candidates are derived from resolved cross-references, so the relevant document(s) must
739
- // have finished the Linked phase — otherwise a query issued right after a model update races
740
- // the asynchronous rebuild and returns stale candidates. Wait the source document
741
- // specifically, but ONLY when a document is actually loaded at that URI: a synthetic source
742
- // can address a URI with no document (a directory URI, typically), and a per-URI `waitUntil`
743
- // there throws "No document found". Fall back to a global Linked settle, matching the
744
- // id-based ElementSource (no URI) path.
745
- const uri = isDocumentSource(ctx.source) || isSyntheticSource(ctx.source) ? UriUtils.toUri(ctx.source.uri) : undefined;
987
+ /**
988
+ * Settle the build before a reference question is answered from the index.
989
+ *
990
+ * A query issued right after a model update otherwise races the rebuild and
991
+ * reads an index missing the symbols it asks about. The cost is not confined
992
+ * to this call: a scope built inside that window is cached, and the build's
993
+ * remaining documents link against it.
994
+ *
995
+ * Waits the source document specifically, but ONLY when one is loaded at
996
+ * that URI: a synthetic source can address a URI with no document (a
997
+ * directory URI, typically), where a per-URI `waitUntil` throws "No document
998
+ * found". Falls back to a global settle, matching the id-based
999
+ * `ElementSource` path.
1000
+ *
1001
+ * Bounded by {@link DataServerOptions.referenceSettleTimeoutMs}.
1002
+ */
1003
+ protected async awaitReferencesLinked(source: ReferenceSource): Promise<void> {
1004
+ const uri = isDocumentSource(source) || isSyntheticSource(source) ? UriUtils.toUri(source.uri) : undefined;
746
1005
  const waitUri = uri && this.services.workspace.LangiumDocuments.hasDocument(uri) ? uri : undefined;
747
- await this.services.workspace.DocumentBuilder.waitUntil(DocumentState.Linked, waitUri);
1006
+ const stopwatch = this.services.Clock.stopwatch();
1007
+ const linked = this.services.workspace.DocumentBuilder.waitUntil(DocumentState.Linked, waitUri);
1008
+ if ((await this.services.Clock.raceTimer(linked, this.options.referenceSettleTimeoutMs)) !== TIMED_OUT) {
1009
+ return;
1010
+ }
1011
+ const elapsedMs = Math.round(stopwatch.elapsedMs);
1012
+ // A per-URI wait resolves off a document-phase notification, so a
1013
+ // missed one strands a wait on a document that HAS reached the
1014
+ // phase. Re-read before failing; the workspace-wide wait has no
1015
+ // equivalent reading and can only reject.
1016
+ const document = waitUri ? this.services.workspace.LangiumDocuments.getDocument(waitUri) : undefined;
1017
+ if (waitUri && document && document.state >= DocumentState.Linked) {
1018
+ this.tracer
1019
+ .withUri(waitUri.toString())
1020
+ .warn(`Missed the 'Linked' notification after ${elapsedMs}ms; the document already reached it`);
1021
+ return;
1022
+ }
1023
+ throw referenceSettleTimeoutError(elapsedMs);
1024
+ }
1025
+
1026
+ async findReferenceCandidates(ctx: ReferenceContext): Promise<ReferenceCandidate[]> {
1027
+ await this.awaitReferencesLinked(ctx.source);
748
1028
  return this.resolveReferenceServices(ctx.source).CandidateProvider.find(ctx);
749
1029
  }
750
1030
 
751
- async resolveReference(ref: ReferenceRequest): Promise<ReferenceTarget<TTransfer> | undefined> {
1031
+ async resolveReference<TElement extends TransferElement = TransferElement>(
1032
+ ref: ReferenceRequest
1033
+ ): Promise<ReferenceTarget<TElement> | undefined> {
1034
+ await this.awaitReferencesLinked(ref.source);
752
1035
  const resolved = this.resolveReferenceServices(ref.source).CandidateProvider.resolveCandidate(ref);
753
1036
  if (!resolved) {
754
1037
  return undefined;
755
1038
  }
756
- const element = this.encoder.toTransfer(resolved.node) as unknown as TTransfer;
757
- return { ...resolved.candidate, element };
1039
+ // `TElement` is the caller's claim about the target's type; nothing checks it.
1040
+ return { ...resolved.candidate, element: this.encoder.toTransfer(resolved.node) as TElement };
758
1041
  }
759
1042
 
760
1043
  async findNextName(args: FindNextNameArgs): Promise<string> {
@@ -764,15 +1047,31 @@ export class DataServer<
764
1047
  // synthetic source — and the create-element flow driving this method is
765
1048
  // the one that produces directory URIs, on which a bare
766
1049
  // `getServices(uri)` throws while `findReferenceCandidates` succeeds.
767
- const nameProvider = this.resolveReferenceServices(ReferenceSource.synthetic(args.uri, args.type)).NameProvider;
1050
+ const source = ReferenceSource.synthetic(args.uri, args.type, args.language);
1051
+ // Mid-rebuild the names of documents not yet re-indexed are absent from
1052
+ // the taken set, and the caller PERSISTS what it is handed. Nothing
1053
+ // reserves the answer either, so a name is free of the collisions the
1054
+ // index knows about and of nothing else — two callers racing get the same
1055
+ // proposal, which only uniqueness at the write can catch.
1056
+ await this.awaitReferencesLinked(source);
1057
+ const nameProvider = this.resolveReferenceServices(source).NameProvider;
768
1058
  const tier = args.tier ?? 'project';
769
1059
  if (tier === 'public') {
770
1060
  return nameProvider.findNextProjectQualifiedName(args.type, args.proposal);
771
1061
  }
772
1062
  if (tier === 'local') {
773
- // Document-scoped uniqueness: the document root is the container.
774
- const document = await this.modelService.ensureDocumentState(args.uri);
775
- return document.root ? nameProvider.findNextName(args.type, args.proposal, document.root as AstNode) : args.proposal;
1063
+ // Document-scoped uniqueness: the document root is the container. A
1064
+ // URI with no document has nothing to collide with, like a document
1065
+ // with no root.
1066
+ try {
1067
+ const document = await this.modelService.ensureDocumentState(args.uri);
1068
+ return document.root ? nameProvider.findNextName(args.type, args.proposal, document.root) : args.proposal;
1069
+ } catch (error: unknown) {
1070
+ if (this.isMissingDocument(error, args.uri)) {
1071
+ return args.proposal;
1072
+ }
1073
+ throw error;
1074
+ }
776
1075
  }
777
1076
  const project = this.services.workspace.ProjectManager.getProject(uri);
778
1077
  if (!project) {
@@ -809,67 +1108,32 @@ export class DataServer<
809
1108
  }
810
1109
 
811
1110
  /**
812
- * Pick the language that owns a reference source, in order:
1111
+ * Pick the language that owns a reference source: the registry's
1112
+ * `getLanguageFor` over the source's declared language, URI and AST type,
1113
+ * with an {@link isElementSource} routed by the document that holds the
1114
+ * element (see {@link findElementDocumentUri}) before its type, and
1115
+ * {@link fallbackReferenceLanguage}, adopter policy, last.
813
1116
  *
814
- * 1. A URI-bearing source ({@link isDocumentSource}/{@link isSyntheticSource})
815
- * whose URI resolves to a registered language routes by URI.
816
- * 2. A single-language workspace always routes to that one language — so
817
- * single-language adopters never reach the steps below, and never pay
818
- * for them.
819
- * 3. An {@link isElementSource} source carries no URI, so in a
820
- * multi-language workspace it is routed via the document that holds the
821
- * element (see {@link findElementDocumentUri}).
822
- * 4. A source carrying an AST type is routed by that type when exactly one
823
- * registered grammar can produce it (see
824
- * {@link resolveReferenceLanguageByType}, over the registry's own type
825
- * index). This is what resolves a create-element flow's synthetic source
826
- * on a bare directory URI without asking the adopter.
827
- * 5. Anything still unresolved falls to {@link fallbackReferenceLanguage},
828
- * which is adopter policy.
1117
+ * An unregistered declared language falls through rather than failing: the
1118
+ * id crosses the wire, so a client built against a head with one more
1119
+ * grammar would otherwise lose queries the other signals answer.
829
1120
  */
830
1121
  protected resolveReferenceLanguage(source: ReferenceSource): HydraniumLanguageServices | undefined {
831
1122
  const registry = this.services.ServiceRegistry;
832
- // `getServicesFor` (non-throwing, one ladder walk) gates the URI lookup:
833
- // an extensionless / unregistered URI falls through to the steps below
834
- // rather than throwing "no services for the extension ''".
835
- const uri = isDocumentSource(source) || isSyntheticSource(source) ? UriUtils.toUri(source.uri) : undefined;
836
- const byUri = uri && registry.getServicesFor(uri);
837
- if (byUri) {
838
- return byUri;
839
- }
840
- const all = registry.all;
841
- if (all.length === 1) {
842
- return all[0] as HydraniumLanguageServices;
843
- }
844
1123
  if (isElementSource(source)) {
845
- const documentUri = this.findElementDocumentUri(source);
846
- const byDocument = documentUri && registry.getServicesFor(documentUri);
847
- if (byDocument) {
848
- return byDocument;
849
- }
1124
+ // The index lookup runs only once the cheaper signals abstained.
1125
+ return (
1126
+ registry.getLanguageFor({}) ??
1127
+ registry.getLanguageFor({ target: this.findElementDocumentUri(source), type: source.type }) ??
1128
+ this.fallbackReferenceLanguage(source)
1129
+ );
850
1130
  }
851
- const byType = this.resolveReferenceLanguageByType(source);
852
- return byType ?? this.fallbackReferenceLanguage(source);
853
- }
854
-
855
- /**
856
- * Route a reference source by the AST type it carries — a
857
- * {@link isSyntheticSource}'s `type` (the transient node being created) or an
858
- * {@link isElementSource}'s optional narrowing `type`.
859
- *
860
- * Answers only when EXACTLY ONE registered grammar can produce the type.
861
- * Several can when the type comes from a grammar both import, and then the
862
- * type genuinely does not identify a language — that is a fall-through to
863
- * adopter policy, not a coin toss. Note this asks which grammar can *produce*
864
- * the type, not which mentions it: a grammar that merely cross-references a
865
- * type can never hold a node of it.
866
- */
867
- protected resolveReferenceLanguageByType(source: ReferenceSource): HydraniumLanguageServices | undefined {
868
- const type = isSyntheticSource(source) ? source.type : isElementSource(source) ? source.type : undefined;
869
- // The registry owns the type index — it is the one place that knows when
870
- // the registered set changed, so unlike a private memo here it cannot go
871
- // stale on a language registered after the first lookup.
872
- return type ? this.services.ServiceRegistry.soleServicesByType(type) : undefined;
1131
+ const hint = isSyntheticSource(source)
1132
+ ? { languageId: source.language, target: source.uri, type: source.type }
1133
+ : isDocumentSource(source)
1134
+ ? { target: source.uri }
1135
+ : {};
1136
+ return registry.getLanguageFor(hint) ?? this.fallbackReferenceLanguage(source);
873
1137
  }
874
1138
 
875
1139
  /**
@@ -879,15 +1143,14 @@ export class DataServer<
879
1143
  * disambiguates names that repeat across types (honouring grammar
880
1144
  * subtyping through `AstReflection.isSubtype`).
881
1145
  *
882
- * Only reached on the multi-language, name-based path (step 3 of
883
- * {@link resolveReferenceLanguage}); single-language adopters return at
884
- * step 2.
1146
+ * Only reached in a multi-language workspace, once the declared language
1147
+ * and the URI have abstained.
885
1148
  *
886
1149
  * Abstains when the name matches elements in more than one DOCUMENT — the
887
1150
  * index spans every language and is filled in build order, so "the
888
- * first match" would be file-watch order rather than an answer. Step 3
889
- * then falls through to the type-based step 4, which abstains on ties
890
- * in the same way, and finally to adopter policy.
1151
+ * first match" would be file-watch order rather than an answer. Routing
1152
+ * then falls through to the element's type, which abstains on ties in the
1153
+ * same way, and finally to adopter policy.
891
1154
  */
892
1155
  protected findElementDocumentUri(source: ElementSource): URI | undefined {
893
1156
  const matches = this.services.workspace.IndexManager.getElementsByName(source.name, source.type);
@@ -922,61 +1185,179 @@ export class DataServer<
922
1185
  // Internal plumbing
923
1186
  // ============================================================
924
1187
 
1188
+ /**
1189
+ * Whether `error`, from waiting on `uri`'s document, means that `uri` has
1190
+ * no document: a URI with neither a file nor text builds nothing, and
1191
+ * Langium's wait after the build rejects for want of one, with a
1192
+ * `ServerCancelled` response error. Any other failure, such as a read
1193
+ * that fails before a document is registered, a cancelled wait or a
1194
+ * `ReentrantWriteLockError`, is the caller's to see.
1195
+ */
1196
+ protected isMissingDocument(error: unknown, uri: string): boolean {
1197
+ return isResponseError(error) && error.code === SERVER_CANCELLED && this.modelService.getDocument(uri) === undefined;
1198
+ }
1199
+
925
1200
  /**
926
1201
  * Build a {@link TransferDocument} envelope from the current document state,
927
1202
  * delegating root + diagnostic encoding to {@link encoder} (see
928
- * `TransferEncoder.toTransferDocument` for the walk).
929
- *
930
- * The encoder field's generic-map binding is widened to
931
- * `Record<string, TransferElement>` at the framework-default level, and an
932
- * adopter supplying a typed-overlay encoder narrows the runtime shape to
933
- * its wire types. The cast on the return is where that invariant — the
934
- * adopter's `TTransfer` matches its encoder's overlay — is asserted, at a
935
- * single boundary point rather than spread across the callers.
1203
+ * `TransferEncoder.toTransferDocument` for the walk). `fingerprint` is the
1204
+ * caller's {@link computeDocumentFingerprint} of that same state, which
1205
+ * spares hashing it twice.
936
1206
  */
937
- protected envelope(uri: URI): TransferDocument<TTransfer, TDiagnostic> {
1207
+ protected envelope(uri: URI, fingerprint?: string): TransferDocument<TTransfer, TDiagnostic> {
938
1208
  // Resolve through the model service's canonicalizing gateway rather than
939
1209
  // reaching into `LangiumDocuments` directly, so a divergent (symlink) URI
940
1210
  // still finds the document the build keys by its real path — and so the
941
1211
  // data-server never has to remember to canonicalize this lookup itself.
942
1212
  const document = this.modelService.getDocument(uri.toString());
943
- if (!document) {
1213
+ if (!document || this.services.workspace.ModelLedger.isPlaceholder(document.parseResult.value)) {
944
1214
  // No document — a shaped envelope rather than a throw, so the caller
945
- // decides policy at its own layer; `root` is optional on the envelope
1215
+ // decides policy at its own layer; `model` is optional on the envelope
946
1216
  // so the compiler forces that decision. Adopters preferring to throw
947
- // override `envelope`.
948
- return {
949
- uri: uri.toString(),
950
- version: 0,
951
- root: undefined,
952
- diagnostics: [] as TDiagnostic[]
953
- };
1217
+ // override `envelope`. The builder's unparsed placeholder is no
1218
+ // document either: its root parses no text.
1219
+ return TransferDocument.absent<TTransfer, TDiagnostic>(uri.toString(), this.epoch);
954
1220
  }
955
- return this.encoder.toTransferDocument<AstNode>(document) as unknown as TransferDocument<TTransfer, TDiagnostic>;
1221
+ const encoded = this.encoder.toTransferDocument(document);
1222
+ return this.withServerState(encoded, fingerprint ?? this.computeDocumentFingerprint(document.parseResult.value, encoded));
956
1223
  }
957
1224
 
958
1225
  /**
959
- * Subscribe one listener at the configured {@link DataServerOptions.subscriptionPhase}.
960
- * The listener dispatches subscription events for every matching URI. A
961
- * single listener (rather than one per subscription) keeps the cost flat
962
- * regardless of subscriber count.
1226
+ * The transfer document a request answers with for `astDocument`, its model
1227
+ * hashed and the text stamped on it by {@link withServerState}. Every
1228
+ * document a request answers with goes through here, so none goes out
1229
+ * without them.
963
1230
  */
964
- protected subscribeToDocumentBuilder(): void {
965
- this.disposables.push(
966
- this.services.workspace.DocumentBuilder.onDocumentPhase(this.options.subscriptionPhase, (document, cancelToken) =>
967
- this.dispatchPhaseEvent(document, cancelToken)
968
- )
969
- );
1231
+ protected encodeDocument(astDocument: AstDocument<AstNode, AstDiagnostic>): TransferDocument<TTransfer, TDiagnostic> {
1232
+ const encoded = this.encoder.astDocumentToTransferDocument(astDocument);
1233
+ return this.withServerState(encoded, this.computeDocumentFingerprint(astDocument.root, encoded));
1234
+ }
1235
+
1236
+ /**
1237
+ * The project a client receives for `project`, unchanged by default. Every
1238
+ * project a request answers with or a change notification carries goes
1239
+ * through here, so a field derived for clients cannot miss one path. The
1240
+ * result crosses as JSON, so a value a client reads goes in a data field,
1241
+ * not a getter.
1242
+ */
1243
+ protected encodeProject(project: TProject): TProject {
1244
+ return project;
1245
+ }
1246
+
1247
+ /**
1248
+ * `encoded` with `hash` on its model and the text the server holds for it:
1249
+ * the store's while it holds the document, the build's otherwise. The text
1250
+ * is read when the document is sent rather than kept with the build: a save
1251
+ * changes `text.dirty` without a rebuild, and the store's text moves on before
1252
+ * the build that follows it.
1253
+ */
1254
+ protected withServerState(
1255
+ encoded: EncodedTransferDocument<TransferElement, TDiagnostic>,
1256
+ hash: string
1257
+ ): TransferDocument<TTransfer, TDiagnostic> {
1258
+ const text = this.serverTextState(encoded.uri);
1259
+ if (text && text.version > encoded.model.version) {
1260
+ this.tracer.withUri(encoded.uri).debug(`Send a model behind its text: model v${encoded.model.version} / text v${text.version}`);
1261
+ }
1262
+ return {
1263
+ uri: encoded.uri,
1264
+ epoch: this.epoch,
1265
+ heldWrites: this.heldWrites(encoded.uri, encoded.model.version),
1266
+ // The encoder returns the structural base; `TTransfer` is the adopter's
1267
+ // declaration of the roots its languages produce, and nothing checks it.
1268
+ model: { ...encoded.model, hash } as TransferModelSnapshot<TTransfer, TDiagnostic>,
1269
+ ...(text ? { text } : {})
1270
+ };
1271
+ }
1272
+
1273
+ /** Per session registered on this connection, the highest of its numbered writes of `uri` that `version` holds. */
1274
+ protected heldWrites(uri: string, version: number): Record<string, number> {
1275
+ const held: [string, number][] = [];
1276
+ for (const [clientId, session] of this.clientSessions) {
1277
+ const write = session.heldWrite(uri, version);
1278
+ if (write !== undefined) {
1279
+ held.push([clientId, write]);
1280
+ }
1281
+ }
1282
+ // Built from entries, so a session named `__proto__` is kept as a key.
1283
+ return Object.fromEntries(held);
1284
+ }
1285
+
1286
+ /**
1287
+ * The text the server holds for `uri`, as every envelope and a watch's
1288
+ * answer carry it: the store's while it holds the document, the build's
1289
+ * otherwise, and none for a document it has neither of.
1290
+ */
1291
+ protected serverTextState(uri: string): TextState | undefined {
1292
+ return this.services.workspace.TextDocuments.textState(uri) ?? this.builtTextState(uri);
1293
+ }
1294
+
1295
+ /**
1296
+ * The text a build read for a document the store never held, which is
1297
+ * clean: the store holds every text a client gave it.
1298
+ */
1299
+ protected builtTextState(uri: string): TextState | undefined {
1300
+ const textDocument = this.modelService.getDocument(uri)?.textDocument;
1301
+ return textDocument && { version: textDocument.version, hash: textHash(textDocument.getText()), dirty: false };
1302
+ }
1303
+
1304
+ /**
1305
+ * Follow every document at the configured
1306
+ * {@link DataServerOptions.subscriptionPhase}, once per connection rather
1307
+ * than once per watch, so the cost stays flat in the number of watches.
1308
+ */
1309
+ protected subscribeToModelUpdates(): void {
1310
+ const phase = this.options.subscriptionPhase;
1311
+ this.disposables.push(this.modelService.onModelUpdated(event => this.dispatchPhaseEvent(event), { phase }));
1312
+ // One message per build rather than one per document.
1313
+ this.disposables.push(this.modelService.onModelsBuilt(event => this.dispatchBuiltEvent(event.uris), { phase }));
1314
+ }
1315
+
1316
+ /**
1317
+ * Report the documents that reached {@link DataServerOptions.subscriptionPhase}
1318
+ * and that NOBODY on this
1319
+ * connection is watching — the ones a client was not told about through
1320
+ * {@link dispatchPhaseEvent}, which is gated per URI.
1321
+ *
1322
+ * **The gap this closes is the one no other source can observe.** A document
1323
+ * the client watches, it hears about already. A file changed on disk, the
1324
+ * host's own filesystem watcher reports — and on a browser host, where the
1325
+ * workspace lives behind this head, an external change cannot happen at all.
1326
+ * What is left, and what nothing outside the server can see, is a document
1327
+ * rebuilt because something it DEPENDS ON changed: its file never changed, so
1328
+ * a filesystem watcher is silent by construction, and it has no subscriber, so
1329
+ * the update channel is silent by design. A consumer displaying data derived
1330
+ * from that document — a tree label, a decorator — otherwise goes stale with
1331
+ * no signal from any source, and repairs itself the moment someone opens the
1332
+ * file to investigate, which is what makes it expensive to diagnose later.
1333
+ *
1334
+ * Payload-free on purpose: URIs only, so a client re-reads what it displays
1335
+ * rather than being handed transfer documents it did not ask for. That is the
1336
+ * property the watcher gate protects, and it is preserved here by
1337
+ * carrying no document rather than by gating the message.
1338
+ *
1339
+ * Quiet in the common case. Editing a document that an editor has open leaves
1340
+ * that URI watched and therefore out of this set, so a build with no
1341
+ * dependents produces nothing at all, and workspace initialisation produces
1342
+ * nothing because it does not build to this phase. The ceiling is a
1343
+ * whole-workspace rebuild at the subscription phase: one message, URIs only.
1344
+ */
1345
+ protected dispatchBuiltEvent(built: readonly CanonicalUri[]): void {
1346
+ const uris = built.map(uri => this.canonicalKey(uri)).filter(uri => !this.uriWatchRecords.get(uri)?.watchers.size);
1347
+ if (uris.length === 0) {
1348
+ return;
1349
+ }
1350
+ this.tracer.debug(`Emit onDocumentsBuilt: ${uris.length} unwatched document(s)`);
1351
+ this.clientProxy.onDocumentsBuilt({ uris });
970
1352
  }
971
1353
 
972
1354
  /**
973
- * Subscribe to the universal save event on `HydraniumTextDocuments` so a
974
- * single `onDocumentSaved` wire notification fires for ANY save of a
975
- * subscribed URI — regardless of whether the save originated from the
976
- * data-server's RPC `saveModelDocument`, the LSP head's text-editor save,
977
- * or any other client writing through `notifyDidSaveTextDocument`.
1355
+ * Follow every save so a single `onDocumentSaved` wire notification fires
1356
+ * for ANY save of a subscribed URI — regardless of whether the save
1357
+ * originated from the data-server's RPC `saveModelDocument`, the LSP head's
1358
+ * text-editor save, or any other client.
978
1359
  *
979
- * Architectural symmetry with {@link subscribeToDocumentBuilder}: every
1360
+ * Architectural symmetry with {@link subscribeToModelUpdates}: every
980
1361
  * subscribed client sees every state change to documents they care about,
981
1362
  * regardless of which client triggered it. Firing `onDocumentSaved` only
982
1363
  * from the data-server's own RPC path is a bug, not an optimisation: an
@@ -984,41 +1365,115 @@ export class DataServer<
984
1365
  * clients, which never clear their dirty state.
985
1366
  */
986
1367
  protected subscribeToTextDocumentSaves(): void {
987
- this.disposables.push(this.services.workspace.TextDocuments.onDidSave(event => this.dispatchSaveEvent(event)));
1368
+ this.disposables.push(this.modelService.onModelSaved(event => this.dispatchSaveEvent(event)));
1369
+ }
1370
+
1371
+ /** Relay each change of a document's dirty state; see {@link dispatchDirtyEvent}. */
1372
+ protected subscribeToDirtyChanges(): void {
1373
+ this.disposables.push(this.modelService.onDirtyChanged(event => this.dispatchDirtyEvent(event)));
1374
+ }
1375
+
1376
+ /**
1377
+ * Send a dirty flip to the connection, gated on the URI's watchers as
1378
+ * {@link dispatchSaveEvent} is: the answer at any one moment travels on
1379
+ * every document sent, so a client that watches nothing reads it there.
1380
+ */
1381
+ protected dispatchDirtyEvent(event: ModelDirtyChangedEvent): void {
1382
+ const uri = this.canonicalKey(event.uri);
1383
+ if (this.uriWatchRecords.get(uri)?.watchers.size) {
1384
+ this.clientProxy.onDocumentDirtyChanged({ uri, text: event.text });
1385
+ }
988
1386
  }
989
1387
 
990
1388
  /**
991
- * Mark the last-close transition per URI (see
992
- * {@link pendingRevertBroadcasts}). The listener consults
993
- * `isOpenInAnyClient` AFTER the store decremented the closing client's
994
- * hold, so a `false` answer means this close was the last one.
1389
+ * Mark each document the store releases, so {@link dispatchPhaseEvent}
1390
+ * broadcasts the build that follows even without a watcher. By default
1391
+ * that build reverts the document to its disk content, discarding unsaved
1392
+ * in-session edits, and the last close typically also
1393
+ * removed the last watcher: without the broadcast, a consumer that only
1394
+ * ever fetches via `getModelDocument` keeps showing the discarded state.
1395
+ * The broadcast is de-duplicated against the fingerprint while a watcher
1396
+ * holds one, so a close whose disk state equals the last emitted state
1397
+ * stays silent; with no watcher there is no fingerprint, and every release
1398
+ * build is sent. The first build after the release consumes the mark, and
1399
+ * goes out as the release unless it is stamped past the version a client
1400
+ * opened the document at again: a client's write or an integrity repair
1401
+ * that rides it keeps its author.
1402
+ *
1403
+ * A release, not the close itself: a document whose last client lost its
1404
+ * connection is released only once the release grace runs out, or when
1405
+ * another client opens it meanwhile, and not at all when a client lost
1406
+ * from it opens it again within its own grace.
995
1407
  */
996
- protected subscribeToTextDocumentCloses(): void {
997
- const textDocuments = this.services.workspace.TextDocuments;
1408
+ protected subscribeToModelReleases(): void {
998
1409
  this.disposables.push(
999
- textDocuments.onDidClose(event => {
1000
- if (!textDocuments.isOpenInAnyClient(event.document.uri)) {
1001
- this.pendingRevertBroadcasts.add(this.canonicalKey(event.document.uri));
1002
- }
1410
+ this.modelService.onModelReleased(event => {
1411
+ const uri = this.canonicalKey(event.uri);
1412
+ const record = this.uriWatchRecords.get(uri) ?? { watchers: new Set<string>() };
1413
+ record.releaseBroadcastPending = true;
1414
+ this.uriWatchRecords.set(uri, record);
1415
+ this.tracer.withUri(uri).debug('Release marked: the first build after it is broadcast, watched or not');
1003
1416
  })
1004
1417
  );
1005
1418
  }
1006
1419
 
1007
- /** Fan out a save event for the document's URI, gated by the subscription map. */
1008
- protected dispatchSaveEvent(event: ClientTextDocumentChangeEvent<TextDocument>): void {
1009
- // The save event arrives under the CLIENT URI the text store keys by (e.g. a
1010
- // symlink path S); the subscription map and `dispatchPhaseEvent` key by the
1011
- // CANONICAL identity R. Canonicalize before both the gate and the envelope so
1012
- // a save of a symlinked file isn't silently dropped (and the envelope resolves
1013
- // the R-keyed document rather than missing into an empty one).
1420
+ /**
1421
+ * Fan out a deletion for each removed URI, to EVERY client on the connection
1422
+ * rather than only to the ones watching that URI.
1423
+ *
1424
+ * **Deliberately ungated, where {@link dispatchPhaseEvent} and
1425
+ * {@link dispatchSaveEvent} are gated.** Those two carry a built document and
1426
+ * fire on every build, so the watcher gate is what keeps bandwidth
1427
+ * proportional to what a client asked for. A deletion is neither: it is one
1428
+ * URI, it is rare, and it reports the workspace's STRUCTURE rather than a
1429
+ * document's content. Gating it forces any consumer that displays the
1430
+ * workspace — a model tree, a file decorator — to learn about disappearances
1431
+ * from a filesystem watcher instead, which a client hosted in a browser has
1432
+ * no way to run: its workspace lives behind the head. A client that does not
1433
+ * care filters on the URI, which costs it a comparison.
1434
+ *
1435
+ * The precedent is the release broadcast (see
1436
+ * {@link subscribeToModelReleases}), where the same judgement was already made
1437
+ * in the other direction: a transition that matters enough is delivered
1438
+ * without a subscription.
1439
+ *
1440
+ * A deletion is announced before the build that follows it, so this goes
1441
+ * out ahead of the `'rebuilt'` events for the dependents whose references
1442
+ * the deletion just broke.
1443
+ *
1444
+ * The URI's fingerprint and release mark are dropped: they describe a
1445
+ * document that no longer exists. A kept fingerprint is adopted as the
1446
+ * baseline and suppresses the first emit after the file returns with its
1447
+ * previous content.
1448
+ *
1449
+ * The watchers SURVIVE: a recreated file resumes delivering to them with no
1450
+ * re-subscription, and a client that answers the deletion by closing
1451
+ * releases the watch through `closeModelDocument` anyway. A session that
1452
+ * deleted the document has its own released by {@link deleteModelDocument}.
1453
+ */
1454
+ protected dispatchDeleteEvent(event: ModelDeletedEvent): void {
1455
+ const uri = this.canonicalKey(event.uri);
1456
+ const record = this.uriWatchRecords.get(uri);
1457
+ if (record) {
1458
+ record.fingerprint = undefined;
1459
+ record.fingerprintVersion = undefined;
1460
+ record.releaseBroadcastPending = undefined;
1461
+ record.sentVersion = undefined;
1462
+ this.pruneUriWatchRecord(uri);
1463
+ }
1464
+ this.clientProxy.onDocumentDeleted({ uri, sourceClientId: event.sourceClientId, sequence: ++this.eventSequence });
1465
+ }
1466
+
1467
+ /** Fan out a save event for the document's URI, gated on the URI's watchers. */
1468
+ protected dispatchSaveEvent(event: AstDocumentSavedEvent<AstNode>): void {
1014
1469
  const uri = this.canonicalKey(event.document.uri);
1015
- if (!this.subscriptions.has(uri)) {
1470
+ if (!this.uriWatchRecords.get(uri)?.watchers.size) {
1016
1471
  return;
1017
1472
  }
1018
- const response = this.envelope(UriUtils.toUri(uri));
1473
+ const response = this.envelope(UriUtils.toUri(event.document.uri));
1019
1474
  const wireEvent: TransferDocumentSavedEvent<TTransfer, TDiagnostic> = {
1020
1475
  document: response,
1021
- sourceClientId: event.clientId
1476
+ sourceClientId: event.sourceClientId
1022
1477
  };
1023
1478
  this.clientProxy.onDocumentSaved(wireEvent);
1024
1479
  }
@@ -1032,116 +1487,115 @@ export class DataServer<
1032
1487
  * out to multiple local subscribers with an `Emitter<T>` — the
1033
1488
  * framework deliberately does NOT promise multi-listener semantics.
1034
1489
  *
1035
- * The dispatch is guarded by two filters:
1036
- * 1. **Subscription map**: events for URIs no subscriber registered for
1037
- * are NOT sent over the wire (bandwidth scales with subscribed URIs,
1038
- * not phase events).
1039
- * 2. **Emission fingerprint**: events for rebuilds that produce no
1040
- * observable change since the last emit are suppressed. See
1041
- * {@link lastEmittedFingerprint} for the rationale.
1490
+ * An event for a URI no client watches is NOT sent over the wire, so
1491
+ * bandwidth scales with watched URIs rather than with phase events; a
1492
+ * pending release mark is the exception (see
1493
+ * {@link subscribeToModelReleases}).
1494
+ *
1495
+ * An event for a rebuild with no observable change since the last emit is
1496
+ * suppressed against the URI's fingerprint and the version it was taken at;
1497
+ * a new version with the same fingerprint goes out with the same
1498
+ * `model.hash`, so a watcher still learns the version. Such rebuilds are routine: a
1499
+ * second client attaching to an open document makes
1500
+ * `HydraniumTextDocuments.refreshContent` fire `onDidChangeContent` purely
1501
+ * to re-trigger the build, and Langium rebuilds a document when a
1502
+ * dependency changes even if its diagnostics come out the same. Sent at a
1503
+ * version this head has not sent, they reach watchers as `'changed'`, and a
1504
+ * watcher that reads `'changed'` as another client's write and resets its
1505
+ * root to the server view loses the user's edits. The first {@link watchModelDocument} baselines the
1506
+ * fingerprint, so the first event after a watch is de-duplicated against
1507
+ * the state the watcher just fetched; it goes with the last watcher, so the
1508
+ * next first watch re-baselines rather than adopting a stale digest. A
1509
+ * digest keeps its memory constant in document size; see
1510
+ * {@link computeDocumentFingerprint} for the inputs.
1042
1511
  */
1043
- protected dispatchPhaseEvent(document: LangiumDocument, cancelToken: CancellationToken): void {
1044
- if (cancelToken.isCancellationRequested) {
1045
- // Build preempted by a concurrent write lock (or other cancel source) —
1046
- // the subscription event is stale by the time it would fire. Skip
1047
- // emission so RPC subscribers don't surface intermediate states.
1048
- // A pending revert mark is deliberately NOT consumed here: the
1049
- // follow-up build re-fires this phase and broadcasts then.
1512
+ protected dispatchPhaseEvent(event: ModelUpdatedEvent<AstNode>): void {
1513
+ const uri = this.canonicalKey(event.document.uri);
1514
+ const record = this.uriWatchRecords.get(uri);
1515
+ const afterRelease = record?.releaseBroadcastPending === true;
1516
+ if (!record || (record.watchers.size === 0 && !afterRelease)) {
1050
1517
  return;
1051
1518
  }
1052
- const uri = document.uri.toString();
1053
- // Consume the last-close mark even when subscriptions exist — the
1054
- // regular dispatch below serves those watchers, and the mark's author
1055
- // attribution is more precise than the post-close `UNKNOWN_CLIENT_ID`
1056
- // the author lookup would yield.
1057
- const revertedOnClose = this.pendingRevertBroadcasts.delete(uri);
1058
- if (!this.subscriptions.has(uri) && !revertedOnClose) {
1519
+ if (afterRelease) {
1520
+ // Consumed even when watchers exist — the regular dispatch below
1521
+ // serves them, and the mark's attribution is more precise than the
1522
+ // post-close unknown client the manager's attribution would yield.
1523
+ // With no watcher the record goes now, so the fingerprint written
1524
+ // below lands on a detached record and the next first watch
1525
+ // re-baselines instead of adopting it.
1526
+ record.releaseBroadcastPending = undefined;
1527
+ this.pruneUriWatchRecord(uri);
1528
+ }
1529
+ // The encoder reads the built document, which the event's holds for this
1530
+ // synchronous run.
1531
+ const document = this.modelService.getDocument(event.document.uri);
1532
+ if (!document) {
1059
1533
  return;
1060
1534
  }
1061
- const fingerprint = this.computeDocumentFingerprint(document);
1062
- if (this.lastEmittedFingerprint.get(uri) === fingerprint) {
1535
+ const fingerprint = this.computeDocumentFingerprint(document.parseResult.value, this.encoder.toTransferDocument(document));
1536
+ const stamped = this.services.workspace.ModelLedger.versionOf(document.parseResult.value);
1537
+ if (record.fingerprint === fingerprint && record.fingerprintVersion === stamped) {
1063
1538
  // A rebuild that produced no observable change since the last emit —
1064
1539
  // suppressed so RPC subscribers don't see a no-op broadcast. Logged at
1065
1540
  // debug so a *needed* re-broadcast wrongly suppressed by this dedup
1066
1541
  // (the failure mode the fingerprint strategy must avoid) is visible.
1067
- this.tracer.withUri(uri).debug(`Suppress onDocumentUpdated v${document.textDocument.version}: fingerprint unchanged`);
1542
+ this.tracer.withUri(uri).debug(`Suppress onDocumentUpdated v${stamped}: fingerprint and version unchanged`);
1068
1543
  return;
1069
1544
  }
1070
- this.lastEmittedFingerprint.set(uri, fingerprint);
1071
- const event: TransferDocumentUpdatedEvent<TTransfer, TDiagnostic> = {
1072
- document: this.envelope(document.uri),
1073
- sourceClientId: revertedOnClose ? REVERT_ON_CLOSE_CLIENT_ID : this.resolveSourceClientId(document),
1074
- reason: this.resolveUpdateReason(document.uri)
1545
+ record.fingerprint = fingerprint;
1546
+ record.fingerprintVersion = stamped;
1547
+ // The event's attribution, so this head names the same client as the
1548
+ // in-process heads do for one build, except for a version this head
1549
+ // already sent; see `DataServerUriWatchRecord.sentVersion`.
1550
+ const version = this.modelService.isOpen(event.document.uri) ? document.textDocument.version : undefined;
1551
+ const { reason, sourceClientId } =
1552
+ version !== undefined && record.sentVersion === version
1553
+ ? { reason: 'rebuilt' as const, sourceClientId: UNKNOWN_CLIENT_ID }
1554
+ : event;
1555
+ record.sentVersion = version;
1556
+ // The stamp, not the live version: a write after the build's parse moves
1557
+ // only the latter. At the opened version too, which a reopen with the
1558
+ // released text keeps.
1559
+ const openedVersion = afterRelease ? this.modelService.openedVersion(event.document.uri) : undefined;
1560
+ const releaseBuild = afterRelease && (openedVersion === undefined || stamped <= openedVersion);
1561
+ const wireEvent: TransferDocumentUpdatedEvent<TTransfer, TDiagnostic> = {
1562
+ document: this.envelope(document.uri, fingerprint),
1563
+ sourceClientId: releaseBuild ? DOCUMENT_RELEASE_CLIENT_ID : sourceClientId,
1564
+ reason,
1565
+ sequence: ++this.eventSequence
1075
1566
  };
1567
+ const mark = afterRelease ? `, release mark: opened v${openedVersion ?? '-'}, attributed ${sourceClientId}` : '';
1076
1568
  this.tracer
1077
1569
  .withUri(uri)
1078
- .debug(`Emit onDocumentUpdated v${event.document.version} (reason=${event.reason}, sourceClientId=${event.sourceClientId})`);
1079
- this.clientProxy.onDocumentUpdated(event);
1570
+ .debug(`Emit onDocumentUpdated v${stamped} (reason=${wireEvent.reason}, sourceClientId=${wireEvent.sourceClientId}${mark})`);
1571
+ this.clientProxy.onDocumentUpdated(wireEvent);
1080
1572
  }
1081
1573
 
1082
1574
  /**
1083
- * Fingerprint of the document's observable state, used to de-dup
1084
- * `onDocumentUpdated` emissions. The {@link FingerprintStrategy} option
1085
- * selects what is hashed (default `'transfer-document'` — see the type), and
1086
- * {@link additionalFingerprintInputs} folds in any extra adopter signal.
1575
+ * Fingerprint of the snapshot `root` and its encoding `encoded`, used to
1576
+ * de-dup `onDocumentUpdated` emissions and sent as every document's
1577
+ * `model.hash`, so it must not depend on the version or on live state. The
1578
+ * {@link FingerprintStrategy} option selects what is hashed (default
1579
+ * `'transfer-document'` — see the type).
1087
1580
  *
1088
- * The default `'transfer-document'` strategy goes through the encoder's
1089
- * {@link TransferEncoder.toTransferDocument}, which is cached per build —
1090
- * so within one phase event the fingerprint and the subsequently-emitted
1091
- * `envelope` share a single encode walk.
1581
+ * {@link TransferEncoder.toTransferDocument} is cached per build, so within
1582
+ * one phase event the fingerprint and the subsequently-emitted `envelope`
1583
+ * share a single encode walk.
1092
1584
  *
1093
1585
  * Wrapped in {@link Tracer.time} against {@link FINGERPRINT_LOG_AFTER_MS}.
1094
1586
  */
1095
- protected computeDocumentFingerprint(document: LangiumDocument): string {
1096
- return this.tracer.withUri(document.uri.toString()).time(
1097
- 'Compute fingerprint',
1098
- () => {
1099
- const base =
1587
+ protected computeDocumentFingerprint(root: AstNode, encoded: EncodedTransferDocument<TransferElement, TDiagnostic>): string {
1588
+ return this.tracer
1589
+ .withUri(encoded.uri)
1590
+ .time(
1591
+ 'Compute fingerprint',
1592
+ () =>
1100
1593
  this.options.fingerprintStrategy === 'text-diagnostics'
1101
- ? textDiagnosticsFingerprint(document)
1102
- : transferDocumentFingerprint(this.encoder.toTransferDocument(document));
1103
- const extra = this.additionalFingerprintInputs(document);
1104
- return extra.length === 0 ? base : fingerprintHash([base, FINGERPRINT_SEPARATOR, ...extra.map(value => JSON.stringify(value))]);
1105
- },
1106
- 'debug',
1107
- { logAfterMs: FINGERPRINT_LOG_AFTER_MS }
1108
- );
1109
- }
1110
-
1111
- /**
1112
- * Extra inputs folded into {@link computeDocumentFingerprint} alongside the
1113
- * chosen {@link FingerprintStrategy}. Default: none. Override to contribute a
1114
- * signal that lives outside the document's text / root / diagnostics — each
1115
- * entry need only be stable across equivalent emissions and
1116
- * JSON-serialisable.
1117
- */
1118
- protected additionalFingerprintInputs(_document: LangiumDocument): readonly unknown[] {
1119
- return [];
1120
- }
1121
-
1122
- /**
1123
- * Discriminate the reason for a phase-event-driven update notification.
1124
- * Uses the most recent `DocumentBuilder.onUpdate` snapshot:
1125
- * - URI in the `deleted` list → `'deleted'`
1126
- * - URI in the `changed` list → `'changed'` (the URI was passed to
1127
- * `documentBuilder.update(changed, deleted)`, which spans `didChange`
1128
- * text-document events and programmatic `update([uri], [])` calls).
1129
- * - Otherwise → `'rebuilt'` (cascade re-derivation: this URI was rebuilt
1130
- * because something it depends on changed; its own text wasn't flagged).
1131
- *
1132
- * `'saved'` is NOT emitted from this code path — saves take the dedicated
1133
- * `DataClientProtocol.onDocumentSaved` channel; adopters that want a
1134
- * unified update stream synthesise `'saved'` in their bridge layer.
1135
- */
1136
- protected resolveUpdateReason(uri: URI): TransferDocumentUpdatedEvent<TTransfer, TDiagnostic>['reason'] {
1137
- const last = this.lastBuildUpdate;
1138
- if (last?.deleted.some(deleted => UriUtils.equals(deleted, uri))) {
1139
- return 'deleted';
1140
- }
1141
- if (last?.changed.some(changed => UriUtils.equals(changed, uri))) {
1142
- return 'changed';
1143
- }
1144
- return 'rebuilt';
1594
+ ? textDiagnosticsFingerprint(this.services.workspace.ModelLedger.textOf(root), encoded.model)
1595
+ : transferDocumentFingerprint(encoded.model),
1596
+ 'debug',
1597
+ { logAfterMs: FINGERPRINT_LOG_AFTER_MS }
1598
+ );
1145
1599
  }
1146
1600
 
1147
1601
  /**
@@ -1167,40 +1621,38 @@ export class DataServer<
1167
1621
  /**
1168
1622
  * Fan one internal {@link ProjectChangeEvent} out to per-project wire
1169
1623
  * notifications. Each `removed` entry pairs the id with the pre-removal
1170
- * snapshot needed for the `'removed'` wire payload.
1624
+ * snapshot needed for the `'removed'` wire payload. A project whose
1625
+ * {@link encodeProject} throws is logged and skipped, so the rest of the
1626
+ * batch still reaches the client.
1171
1627
  */
1172
1628
  protected dispatchProjectChangeEvent(event: ProjectChangeEvent<TProject>): void {
1629
+ const send = (project: TProject, reason: ProjectChangeReason): void => {
1630
+ let encoded: TProject;
1631
+ try {
1632
+ encoded = this.encodeProject(project);
1633
+ } catch (error: unknown) {
1634
+ this.tracer.error(`Project ${project.id} not sent as ${reason}: encodeProject threw: ${describeErrorWithStack(error)}`);
1635
+ return;
1636
+ }
1637
+ this.clientProxy.onProjectsChanged({ project: encoded, reason });
1638
+ };
1173
1639
  for (const id of event.added) {
1174
1640
  const project = this.services.workspace.ProjectManager.getProjectById(id);
1175
1641
  if (project) {
1176
- this.clientProxy.onProjectsChanged({ project, reason: 'added' });
1642
+ send(project, 'added');
1177
1643
  }
1178
1644
  }
1179
1645
  for (const id of event.updated) {
1180
1646
  const project = this.services.workspace.ProjectManager.getProjectById(id);
1181
1647
  if (project) {
1182
- this.clientProxy.onProjectsChanged({ project, reason: 'updated' });
1648
+ send(project, 'updated');
1183
1649
  }
1184
1650
  }
1185
1651
  for (const entry of event.removed) {
1186
- this.clientProxy.onProjectsChanged({ project: entry.snapshot, reason: 'removed' });
1652
+ send(entry.snapshot, 'removed');
1187
1653
  }
1188
1654
  }
1189
1655
 
1190
- /**
1191
- * Resolve the wire-level `sourceClientId` for `document`'s events — the client
1192
- * that authored its current version, from the version-author history on
1193
- * `HydraniumTextDocuments`. The protocol-level counterpart of the internal
1194
- * `AstDocumentManager.getAuthor`: a framework-internal rebuild has no author,
1195
- * so this surfaces the {@link UNKNOWN_CLIENT_ID} presentation default. Adopters
1196
- * that rebuild through non-text-document channels override to derive a
1197
- * source id of their own.
1198
- */
1199
- protected resolveSourceClientId(document: LangiumDocument): string {
1200
- const author = this.services.workspace.TextDocuments.getAuthor(document.textDocument.uri, document.textDocument.version);
1201
- return author ?? UNKNOWN_CLIENT_ID;
1202
- }
1203
-
1204
1656
  // --- Diagnostics (DataServerDiagnosticsProtocol) ---------------------------
1205
1657
  // Computed in THIS process: the data-server child holds the model store, so
1206
1658
  // these snapshots reflect the heap that actually carries the workspace
@@ -1243,7 +1695,7 @@ export class DataServer<
1243
1695
 
1244
1696
  async stopProfiling(args: StopProfilingArgs): Promise<string> {
1245
1697
  if (!this.activeProfile) {
1246
- throw new Error('No profiling capture is active; call startProfiling first.');
1698
+ throw noActiveProfileError();
1247
1699
  }
1248
1700
  const capture = this.activeProfile;
1249
1701
  this.activeProfile = undefined;
@@ -1262,11 +1714,11 @@ export class DataServer<
1262
1714
  /** Resolve a partial options object into a fully-defaulted form. */
1263
1715
  protected resolveOptions(partial: DataServerOptions): ResolvedDataServerOptions {
1264
1716
  const additionalMethods = partial.additionalMethods ?? [];
1265
- const builtIn = [...DATA_SERVER_PROTOCOL_METHODS, ...DATA_SERVER_DIAGNOSTICS_METHODS] as readonly string[];
1717
+ const builtIn: readonly string[] = [...DATA_SERVER_PROTOCOL_METHODS, ...DATA_SERVER_DIAGNOSTICS_METHODS];
1266
1718
  const overlap = additionalMethods.filter(name => builtIn.includes(name));
1267
1719
  if (overlap.length > 0) {
1268
1720
  throw new Error(
1269
- `DataServer.additionalMethods overlaps with built-in data-server methods: ${overlap.join(', ')}. ` +
1721
+ `DataServerOptions.additionalMethods overlaps with built-in data-server methods: ${overlap.join(', ')}. ` +
1270
1722
  'Adopter protocols must not redeclare framework method names; rename the adopter method or remove it from additionalMethods.'
1271
1723
  );
1272
1724
  }
@@ -1276,7 +1728,8 @@ export class DataServer<
1276
1728
  methodNamespace: partial.methodNamespace ?? DATA_SERVER_WIRE_PREFIX,
1277
1729
  additionalMethods,
1278
1730
  excludedMethods: partial.excludedMethods ?? [],
1279
- diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics()
1731
+ diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics(),
1732
+ referenceSettleTimeoutMs: partial.referenceSettleTimeoutMs ?? DataServer.DEFAULT_OPTIONS.referenceSettleTimeoutMs
1280
1733
  };
1281
1734
  }
1282
1735
  }