@elaraai/e3-api-server 1.0.97 → 1.0.99

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 (88) hide show
  1. package/README.md +77 -5
  2. package/dist/src/errors.d.ts.map +1 -1
  3. package/dist/src/errors.js +8 -1
  4. package/dist/src/errors.js.map +1 -1
  5. package/dist/src/handlers/dataflow.d.ts +9 -1
  6. package/dist/src/handlers/dataflow.d.ts.map +1 -1
  7. package/dist/src/handlers/dataflow.js +22 -62
  8. package/dist/src/handlers/dataflow.js.map +1 -1
  9. package/dist/src/handlers/dataflow.spec.js +1 -1
  10. package/dist/src/handlers/dataflow.spec.js.map +1 -1
  11. package/dist/src/handlers/dataset-batches.d.ts +203 -0
  12. package/dist/src/handlers/dataset-batches.d.ts.map +1 -0
  13. package/dist/src/handlers/dataset-batches.js +442 -0
  14. package/dist/src/handlers/dataset-batches.js.map +1 -0
  15. package/dist/src/handlers/dataset-place.d.ts +104 -0
  16. package/dist/src/handlers/dataset-place.d.ts.map +1 -0
  17. package/dist/src/handlers/dataset-place.js +282 -0
  18. package/dist/src/handlers/dataset-place.js.map +1 -0
  19. package/dist/src/handlers/dataset-reads.d.ts +205 -0
  20. package/dist/src/handlers/dataset-reads.d.ts.map +1 -0
  21. package/dist/src/handlers/dataset-reads.js +350 -0
  22. package/dist/src/handlers/dataset-reads.js.map +1 -0
  23. package/dist/src/handlers/datasets.d.ts +19 -30
  24. package/dist/src/handlers/datasets.d.ts.map +1 -1
  25. package/dist/src/handlers/datasets.js +84 -549
  26. package/dist/src/handlers/datasets.js.map +1 -1
  27. package/dist/src/handlers/datasets.spec.js +970 -16
  28. package/dist/src/handlers/datasets.spec.js.map +1 -1
  29. package/dist/src/handlers/functions.spec.js +26 -20
  30. package/dist/src/handlers/functions.spec.js.map +1 -1
  31. package/dist/src/handlers/index.d.ts +5 -1
  32. package/dist/src/handlers/index.d.ts.map +1 -1
  33. package/dist/src/handlers/index.js +4 -1
  34. package/dist/src/handlers/index.js.map +1 -1
  35. package/dist/src/handlers/key-search.d.ts +102 -0
  36. package/dist/src/handlers/key-search.d.ts.map +1 -0
  37. package/dist/src/handlers/key-search.js +351 -0
  38. package/dist/src/handlers/key-search.js.map +1 -0
  39. package/dist/src/handlers/records.spec.js.map +1 -1
  40. package/dist/src/handlers/segments.d.ts +124 -0
  41. package/dist/src/handlers/segments.d.ts.map +1 -0
  42. package/dist/src/handlers/segments.js +278 -0
  43. package/dist/src/handlers/segments.js.map +1 -0
  44. package/dist/src/handlers/tasks.js +9 -9
  45. package/dist/src/handlers/tasks.js.map +1 -1
  46. package/dist/src/handlers/workspaces.d.ts.map +1 -1
  47. package/dist/src/handlers/workspaces.js +8 -11
  48. package/dist/src/handlers/workspaces.js.map +1 -1
  49. package/dist/src/handlers/workspaces.spec.js +1 -0
  50. package/dist/src/handlers/workspaces.spec.js.map +1 -1
  51. package/dist/src/portable.d.ts +1 -0
  52. package/dist/src/portable.d.ts.map +1 -1
  53. package/dist/src/portable.js +2 -0
  54. package/dist/src/portable.js.map +1 -1
  55. package/dist/src/portable.spec.js +3 -2
  56. package/dist/src/portable.spec.js.map +1 -1
  57. package/dist/src/routes/bundles.d.ts +27 -0
  58. package/dist/src/routes/bundles.d.ts.map +1 -0
  59. package/dist/src/routes/bundles.js +93 -0
  60. package/dist/src/routes/bundles.js.map +1 -0
  61. package/dist/src/routes/dataset-path.d.ts +16 -0
  62. package/dist/src/routes/dataset-path.d.ts.map +1 -1
  63. package/dist/src/routes/dataset-path.js +18 -0
  64. package/dist/src/routes/dataset-path.js.map +1 -1
  65. package/dist/src/routes/datasets.d.ts.map +1 -1
  66. package/dist/src/routes/datasets.js +228 -2
  67. package/dist/src/routes/datasets.js.map +1 -1
  68. package/dist/src/routes/executions.js +1 -1
  69. package/dist/src/routes/executions.js.map +1 -1
  70. package/dist/src/routes/index.d.ts +1 -0
  71. package/dist/src/routes/index.d.ts.map +1 -1
  72. package/dist/src/routes/index.js +1 -0
  73. package/dist/src/routes/index.js.map +1 -1
  74. package/dist/src/routes/transfer.d.ts.map +1 -1
  75. package/dist/src/routes/transfer.js +11 -5
  76. package/dist/src/routes/transfer.js.map +1 -1
  77. package/dist/src/server.d.ts.map +1 -1
  78. package/dist/src/server.js +2 -0
  79. package/dist/src/server.js.map +1 -1
  80. package/dist/src/stopping-run.d.ts +24 -3
  81. package/dist/src/stopping-run.d.ts.map +1 -1
  82. package/dist/src/stopping-run.js +29 -7
  83. package/dist/src/stopping-run.js.map +1 -1
  84. package/dist/src/stopping-run.spec.js +30 -1
  85. package/dist/src/stopping-run.spec.js.map +1 -1
  86. package/dist/src/types.d.ts +47 -41
  87. package/dist/src/types.d.ts.map +1 -1
  88. package/package.json +5 -5
@@ -2,12 +2,16 @@
2
2
  * Copyright (c) 2025 Elara AI Pty Ltd
3
3
  * Licensed under BSL 1.1. See LICENSE for details.
4
4
  */
5
- import { NullType, ArrayType, StringType, compareFor, encodeBeast2For, openBeast2PagesFor, parseFor, some, none, variant, toEastTypeValue, isVariant } from '@elaraai/east';
5
+ import { NullType, ArrayType, StringType, encodeBeast2For, some, none, variant, toEastTypeValue, isVariant } from '@elaraai/east';
6
6
  import { BEAST2_CONTENT_TYPE } from '@elaraai/e3-types';
7
- import { workspaceListTree, workspaceGetDatasetHash, workspaceGetDatasetStatus, workspaceSetDatasetBytes, workspaceGetTree, openDatasetObject, recordIndexNames, resolveRecordIndex, DatasetSegments, } from '@elaraai/e3-core/portable';
7
+ import { workspaceListTree, workspaceGetDatasetHash, workspaceGetDatasetStatus, workspaceSetDatasetBytes, workspaceGetTree, openDatasetObject, DatasetSegments, } from '@elaraai/e3-core/portable';
8
8
  import { sendSuccess, sendError } from '../beast2.js';
9
9
  import { errorToVariant, sendJsonError } from '../errors.js';
10
10
  import { DatasetStatusDetailType, ListEntryType } from '../types.js';
11
+ import { PAGE_BYTE_BUDGET_DEFAULT, PAGE_DEFAULT_LIMIT, PAGE_MAX_LIMIT, cachedSegments, collectionOf, corruptRefusal, elementsOf, indexOf, openForRead, openTarget, pageError, pinnedCacheControl, readDataset, rowsByKey, searchTarget, } from './dataset-reads.js';
12
+ import { compileKeySearch, locateAll } from './key-search.js';
13
+ import { decodedSegment } from './segments.js';
14
+ export { PAGE_BYTE_BUDGET_DEFAULT } from './dataset-reads.js';
11
15
  /**
12
16
  * List dataset fields at the given path.
13
17
  */
@@ -131,83 +135,6 @@ export async function getDataset(storage, repoPath, workspace, treePath, repo, r
131
135
  return sendJsonError(err);
132
136
  }
133
137
  }
134
- /** Elements returned per page when the request names no limit. */
135
- const PAGE_DEFAULT_LIMIT = 1_000;
136
- /** Hard cap on elements per page. */
137
- const PAGE_MAX_LIMIT = 10_000;
138
- /** Default cap on a page's share of the source blob, in bytes. The
139
- * effective limit shrinks so `limit × avgElementBytes` stays under the
140
- * budget, bounding page payloads even for very wide rows. Deployments with
141
- * tighter response limits (e.g. Lambda proxy's 6 MB, base64-inflated) pass
142
- * a smaller budget through the route options. */
143
- export const PAGE_BYTE_BUDGET_DEFAULT = 4 * 1024 * 1024;
144
- const SEGMENTS_CACHE_MAX_ENTRIES = 64;
145
- /** Cap on the cache's total retained bytes. The newest entry always stays
146
- * (serving the request needs it regardless), so one giant index can still
147
- * be held — but never alongside others. */
148
- const SEGMENTS_CACHE_MAX_BYTES = 16 * 1024 * 1024;
149
- const segmentsCache = new Map();
150
- let segmentsCacheBytes = 0;
151
- /** Evicts oldest entries until the count and byte budgets hold, always
152
- * keeping at least the newest entry. */
153
- function evictSegments() {
154
- while (segmentsCache.size > 1 &&
155
- (segmentsCache.size > SEGMENTS_CACHE_MAX_ENTRIES || segmentsCacheBytes > SEGMENTS_CACHE_MAX_BYTES)) {
156
- const oldest = segmentsCache.keys().next().value;
157
- segmentsCacheBytes -= segmentsCache.get(oldest).bytes;
158
- segmentsCache.delete(oldest);
159
- }
160
- }
161
- /** Identifies a storage backend for the cache key — lazily, and without
162
- * keeping it alive. */
163
- const storageIds = new WeakMap();
164
- let nextStorageId = 0;
165
- /** Opens (or reuses) a stored collection, LRU-cached per backend, repository
166
- * and content hash, and bounded by retained bytes.
167
- *
168
- * All three key parts are load-bearing. An opened dataset holds the backend
169
- * it reads segment objects through, and a manifest names objects that exist
170
- * in the repository it was read from and nowhere else — so two backends, or
171
- * two repositories, that happen to hold the same bytes under the same name
172
- * must not share an entry. `size` is the object's, when the caller knows it;
173
- * the opener reads it on a miss otherwise. */
174
- async function cachedSegments(storage, repoPath, hash, size) {
175
- let backendId = storageIds.get(storage);
176
- if (backendId === undefined) {
177
- backendId = nextStorageId++;
178
- storageIds.set(storage, backendId);
179
- }
180
- const key = `${backendId}\u0000${repoPath}\u0000${hash}`;
181
- const cached = segmentsCache.get(key);
182
- if (cached) {
183
- segmentsCache.delete(key);
184
- segmentsCache.set(key, cached); // refresh recency
185
- return cached.segments;
186
- }
187
- const segments = await DatasetSegments.open(storage, repoPath, hash, size);
188
- // counts + prefix sums at 8 bytes each, plus the manifest's stored fences.
189
- let bytes = 16 * segments.segmentCount;
190
- for (const entry of segments.manifest.entries)
191
- bytes += entry.fence.byteLength + 80;
192
- segmentsCache.set(key, { segments, bytes });
193
- segmentsCacheBytes += bytes;
194
- evictSegments();
195
- return segments;
196
- }
197
- /** The `Cache-Control` of a hash-pinned answer: kept for a year, never
198
- * revalidated, by the caches {@link PinnedCache} lets keep it. */
199
- function pinnedCacheControl(cache) {
200
- return `${cache ?? 'private'}, max-age=31536000, immutable`;
201
- }
202
- /** The opener's refusal of a collection stored as one blob, which an older
203
- * e3 wrote: answered as `dataset_not_indexed`, in the refusal's own words. */
204
- const BLOB_REFUSAL = /^the collection [0-9a-f]{64} is stored as one blob:/;
205
- function pageError(type, message, status = 400, headers) {
206
- return new Response(JSON.stringify({ error: { type, message } }), {
207
- status,
208
- headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', ...headers },
209
- });
210
- }
211
138
  /**
212
139
  * Get one window of a collection dataset as raw BEAST2 bytes.
213
140
  *
@@ -219,10 +146,12 @@ function pageError(type, message, status = 400, headers) {
219
146
  * ranges. Segment windows return one writer batch verbatim.
220
147
  *
221
148
  * Collection datasets are stored as segment manifests by every writer at
222
- * every size, so every window decodes only the touched segments (Set/Dict
223
- * windows verify the segment fences first and reject non-canonical ones as
224
- * corrupt). A collection stored as one blob is an older e3's and is refused as
225
- * `dataset_not_indexed`, naming the fix — there is no whole-decode fallback.
149
+ * every size, so every window decodes only the touched segments — each once,
150
+ * through the decoded segments the API process keeps (Set/Dict windows check
151
+ * each segment against the manifest's fences, and refuse a non-canonical one
152
+ * as corrupt). A collection stored as one blob is an older e3's and is refused
153
+ * as `dataset_not_indexed`, naming the fix — there is no whole-decode
154
+ * fallback.
226
155
  *
227
156
  * The window is the stored value's ({@link getValuePage}): the dataset's
228
157
  * status and pin are checked here first, and an index window is a record's.
@@ -230,33 +159,17 @@ function pageError(type, message, status = 400, headers) {
230
159
  export async function getDatasetPage(storage, repoPath, workspace, treePath, window, limits) {
231
160
  const byteBudget = limits?.byteBudget ?? PAGE_BYTE_BUDGET_DEFAULT;
232
161
  try {
233
- if (treePath.length === 0) {
234
- return pageError('bad_request', 'Path required for paged get');
235
- }
236
- const status = await workspaceGetDatasetStatus(storage, repoPath, workspace, treePath);
237
- if (status.refType === 'unassigned') {
238
- return pageError('dataset_unassigned', 'Dataset is unassigned (pending task output)', 404);
239
- }
240
- if (status.refType === 'null' || !status.hash) {
241
- return pageError('dataset_null', 'Dataset is null', 404);
242
- }
243
- // A hash-pinned window must never answer with different bytes — refuse
244
- // stale pins (the client refetches status for the current hash) so a
245
- // hash-keyed URL is a pure function of the response and caches stay sound.
246
- if (window.hash !== undefined && window.hash !== status.hash) {
247
- return pageError('dataset_hash_mismatch', `Dataset content is ${status.hash}, not ${window.hash} — refetch status and retry`, 409, { 'X-Content-SHA256': status.hash });
248
- }
249
- const typeValue = isVariant(status.datasetType)
250
- ? status.datasetType
251
- : toEastTypeValue(status.datasetType);
252
- const kind = typeValue.type;
162
+ const dataset = await readDataset(storage, repoPath, workspace, treePath, window.hash, 'paged get');
163
+ if (dataset instanceof Response)
164
+ return dataset;
165
+ const kind = dataset.typeValue.type;
253
166
  if (kind !== 'Array' && kind !== 'Set' && kind !== 'Dict') {
254
167
  return pageError('dataset_not_pageable', `Paged reads address Array, Set or Dict datasets; this dataset holds ${kind}`);
255
168
  }
256
169
  if (window.index !== undefined) {
257
- return await indexPage(storage, repoPath, workspace, treePath, status.hash, window, byteBudget, limits?.cache);
170
+ return await indexPage(storage, repoPath, workspace, treePath, dataset.hash, window, byteBudget, limits?.cache);
258
171
  }
259
- return await valuePage(storage, repoPath, status.hash, typeValue, window, byteBudget, limits?.cache, status.size ?? undefined);
172
+ return await valuePage(storage, repoPath, dataset.hash, dataset.typeValue, window, byteBudget, limits?.cache, dataset.size);
260
173
  }
261
174
  catch (err) {
262
175
  return sendJsonError(err);
@@ -304,14 +217,13 @@ export async function getValuePage(storage, repoPath, hash, type, window, limits
304
217
  }
305
218
  /**
306
219
  * One window of a stored collection of a collection's type: the effective
307
- * limit under the byte budget, the `X-*` headers, the span of segments the
308
- * window touches, and its slice.
220
+ * limit under the byte budget, the `X-*` headers, the segments the window
221
+ * touches, and its slice.
309
222
  *
310
223
  * @param cache - Who may keep the window, when it is pinned
311
224
  * @param size - The stored object's size, when the caller knows it
312
225
  */
313
226
  async function valuePage(storage, repoPath, hash, typeValue, window, byteBudget, cache, size) {
314
- const kind = typeValue.type;
315
227
  const segmentMode = window.segment !== undefined;
316
228
  if (segmentMode && (window.offset !== undefined || window.limit !== undefined)) {
317
229
  return pageError('bad_request', 'Pass either segment or offset/limit, not both');
@@ -324,19 +236,9 @@ async function valuePage(storage, repoPath, hash, typeValue, window, byteBudget,
324
236
  if (!segmentMode && (!Number.isInteger(offset) || offset < 0 || !Number.isInteger(requestedLimit) || requestedLimit < 1)) {
325
237
  return pageError('bad_request', `offset must be a non-negative integer and limit a positive integer, got offset=${offset} limit=${requestedLimit}`);
326
238
  }
327
- let segments;
328
- try {
329
- segments = await cachedSegments(storage, repoPath, hash, size);
330
- }
331
- catch (err) {
332
- // Only the opener's refusal of a blob-stored collection means "not
333
- // indexed". Anything else (storage I/O, a missing or corrupt object) is
334
- // a real failure and must surface as one.
335
- const message = err instanceof Error ? err.message : String(err);
336
- if (!BLOB_REFUSAL.test(message))
337
- throw err;
338
- return pageError('dataset_not_indexed', message);
339
- }
239
+ const segments = await openForRead(storage, repoPath, hash, size);
240
+ if (segments instanceof Response)
241
+ return segments;
340
242
  const segmentCount = segments.segmentCount;
341
243
  const totalElements = segments.elementCount;
342
244
  const totalBytes = segments.bytes;
@@ -369,61 +271,36 @@ async function valuePage(storage, repoPath, hash, typeValue, window, byteBudget,
369
271
  'X-Page-Offset': String(pageOffset),
370
272
  'X-Page-Count': String(pageCount),
371
273
  });
372
- // The touched segment span [from, to) and the window placement.
373
- let from;
374
- let to;
375
- let limit = 0;
274
+ let windowValue;
275
+ let pageOffset;
276
+ let pageCount;
376
277
  if (segmentMode) {
377
278
  const seg = window.segment;
378
279
  if (seg >= segmentCount) {
379
280
  return pageError('bad_request', `segment ${seg} out of range (${segmentCount} segments)`);
380
281
  }
381
- from = seg;
382
- to = seg + 1;
383
- }
384
- else {
385
- limit = effectiveLimit();
386
- if (offset >= totalElements) {
387
- from = 0;
388
- to = 0; // empty window past the end
389
- }
390
- else {
391
- from = 0;
392
- while (cumulative[from] <= offset)
393
- from++;
394
- const lastRow = Math.min(offset + limit, totalElements) - 1;
395
- to = from;
396
- while (cumulative[to] <= lastRow)
397
- to++;
398
- to++;
399
- }
400
- }
401
- const windowBlob = await segments.span(from, to);
402
- const pages = openBeast2PagesFor(typeValue)(windowBlob);
403
- let windowValue;
404
- let pageOffset;
405
- let pageCount;
406
- if (segmentMode) {
407
282
  try {
408
- windowValue = pages.segment(0);
283
+ windowValue = (await decodedSegment(storage, repoPath, segments, seg)).value;
409
284
  }
410
285
  catch (err) {
411
- return pageError('dataset_not_segmented', err instanceof Error ? err.message : String(err));
286
+ return corruptRefusal(err, 'dataset_not_segmented');
412
287
  }
413
- pageCount = segments.counts[from];
414
- pageOffset = from === 0 ? 0 : cumulative[from - 1];
288
+ pageCount = segments.counts[seg];
289
+ pageOffset = seg === 0 ? 0 : cumulative[seg - 1];
415
290
  }
416
291
  else {
417
- const base = from > 0 ? cumulative[from - 1] : 0;
292
+ const limit = effectiveLimit();
293
+ // An empty window past the end touches no segment.
294
+ const end = Math.min(offset + limit, totalElements);
295
+ let elements;
418
296
  try {
419
- windowValue = pages.slice(to > from ? offset - base : 0, limit);
297
+ elements = offset < totalElements ? await elementsOf(storage, repoPath, segments, [{ from: offset, to: end }]) : [];
420
298
  }
421
299
  catch (err) {
422
- return pageError('dataset_not_canonical', err instanceof Error ? err.message : String(err));
300
+ return corruptRefusal(err, 'dataset_not_canonical');
423
301
  }
424
- pageCount = kind === 'Array'
425
- ? windowValue.length
426
- : windowValue.size;
302
+ windowValue = collectionOf(typeValue, elements);
303
+ pageCount = elements.length;
427
304
  pageOffset = offset;
428
305
  }
429
306
  const body = encodeBeast2For(typeValue)(windowValue);
@@ -439,22 +316,18 @@ async function valuePage(storage, repoPath, hash, typeValue, window, byteBudget,
439
316
  * One window of a record read through one of its secondary indexes.
440
317
  *
441
318
  * @remarks
442
- * The window comes from the index's OWN segments — the same fence bisect and
443
- * window slice a primary page uses, over the index manifest — so with a
444
- * covering projection the window IS the answer and the primary is never
445
- * touched. `join` fills the rows: the window's primary keys are bucketed by
446
- * owning primary segment, each distinct segment read once, and the rows
447
- * projected out, so a page whose entries share an index key usually costs a
448
- * handful of reads rather than one per row.
319
+ * The window comes from the index's OWN segments — the same row span a primary
320
+ * page reads, over the index manifest — so with a covering projection the
321
+ * window IS the answer and the primary is never touched. `join` fills the
322
+ * rows: each primary key is placed in the primary segment that holds it by the
323
+ * primary's fences, and each such segment read once, so a page whose entries
324
+ * share an index key usually costs a handful of reads rather than one per
325
+ * row.
449
326
  */
450
327
  async function indexPage(storage, repoPath, workspace, treePath, stateHash, window, byteBudget, cache) {
451
- const refPath = treePath.map((s) => s.value).join('/');
452
- const resolved = await resolveRecordIndex(storage, repoPath, workspace, refPath, stateHash, window.index);
453
- if (resolved === null) {
454
- const declared = await recordIndexNames(storage, repoPath, stateHash);
455
- return pageError('index_not_found', `Dataset '${refPath}' has no index '${window.index}'`
456
- + (declared.length > 0 ? ` — it has ${declared.join(', ')}` : ' — it declares none'), 404);
457
- }
328
+ const resolved = await indexOf(storage, repoPath, workspace, treePath, stateHash, window.index, window.join === true);
329
+ if (resolved instanceof Response)
330
+ return resolved;
458
331
  const offset = window.offset ?? 0;
459
332
  const requestedLimit = window.limit ?? PAGE_DEFAULT_LIMIT;
460
333
  if (!Number.isInteger(offset) || offset < 0 || !Number.isInteger(requestedLimit) || requestedLimit < 1) {
@@ -471,49 +344,23 @@ async function indexPage(storage, repoPath, workspace, treePath, stateHash, wind
471
344
  const perRow = (primary !== null && primary.elementCount > 0 ? primary.bytes / primary.elementCount : 0)
472
345
  + (totalElements > 0 ? index.bytes / totalElements : 1);
473
346
  const limit = Math.max(1, Math.min(requestedLimit, PAGE_MAX_LIMIT, Math.max(1, Math.floor(byteBudget / Math.max(1, perRow)))));
474
- // The index window, as the index's own collection.
475
- let from = 0;
476
- let to = 0;
477
- if (offset < totalElements) {
478
- while (index.cumulative[from] <= offset)
479
- from++;
480
- const lastRow = Math.min(offset + limit, totalElements) - 1;
481
- to = from;
482
- while (index.cumulative[to] <= lastRow)
483
- to++;
484
- to++;
347
+ // The index window, as the index's own entries, and the rows, if asked
348
+ // for. An index's order is not the record's, so a page's primary keys
349
+ // scatter across the record: each is placed by the primary's fences, and
350
+ // each segment holding one is read once.
351
+ let windowValue;
352
+ try {
353
+ const entries = (offset < totalElements
354
+ ? await elementsOf(storage, repoPath, index, [{ from: offset, to: Math.min(offset + limit, totalElements) }])
355
+ : []);
356
+ const rows = primary !== null
357
+ ? await rowsByKey(storage, repoPath, primary, entries.map(([entry]) => entry.k))
358
+ : entries.map(() => none);
359
+ windowValue = entries.map(([entry, value], i) => ({ ik: entry.ik, key: entry.k, value, row: rows[i] }));
485
360
  }
486
- const base = from > 0 ? index.cumulative[from - 1] : 0;
487
- const slice = openBeast2PagesFor(resolved.collectionType)(await index.span(from, to))
488
- .slice(to > from ? offset - base : 0, limit);
489
- // The rows, if asked for. An index's order is not the record's, so a page's
490
- // primary keys scatter across the record: they are grouped by the segment
491
- // that holds them, and each segment is decoded once and dropped before the
492
- // next. A page holds one decoded segment at a time however widely its keys
493
- // scatter, and reads at most one segment per row it returns.
494
- const entries = [...slice];
495
- const rows = entries.map(() => none);
496
- if (primary !== null) {
497
- const bySegment = new Map();
498
- for (let i = 0; i < entries.length; i++) {
499
- const segment = await primary.segmentFor(entries[i][0].k);
500
- const held = bySegment.get(segment);
501
- if (held === undefined)
502
- bySegment.set(segment, [i]);
503
- else
504
- held.push(i);
505
- }
506
- const decodeSegment = openBeast2PagesFor(primary.typeValue);
507
- for (const [segment, indices] of bySegment) {
508
- const decoded = decodeSegment(await primary.segment(segment)).segment(0);
509
- for (const i of indices) {
510
- const row = decoded.get(entries[i][0].k);
511
- if (row !== undefined)
512
- rows[i] = some(row);
513
- }
514
- }
361
+ catch (err) {
362
+ return corruptRefusal(err, 'dataset_not_canonical');
515
363
  }
516
- const windowValue = entries.map(([entry, value], i) => ({ ik: entry.ik, key: entry.k, value, row: rows[i] }));
517
364
  const body = encodeBeast2For(resolved.windowType)(windowValue);
518
365
  return new Response(body, {
519
366
  status: 200,
@@ -535,54 +382,6 @@ async function indexPage(storage, repoPath, workspace, treePath, stateHash, wind
535
382
  },
536
383
  });
537
384
  }
538
- /**
539
- * A key type's leaves, in declaration order, recursing into nested structs.
540
- *
541
- * @remarks
542
- * Struct keys compare field by field in declaration order, so this flattening
543
- * IS the key's sort order — which is what makes a bound on a leading prefix of
544
- * it one contiguous row range. A scalar key flattens to one leaf with an empty
545
- * path.
546
- */
547
- function flattenKeyFields(keyType) {
548
- if (keyType.type !== 'Struct')
549
- return [{ path: [], type: keyType }];
550
- const out = [];
551
- for (const field of keyType.value) {
552
- for (const leaf of flattenKeyFields(field.type)) {
553
- out.push({ path: [field.name, ...leaf.path], type: leaf.type });
554
- }
555
- }
556
- return out;
557
- }
558
- /** The value at a flattened field path. */
559
- function fieldAt(key, path) {
560
- let value = key;
561
- for (const segment of path)
562
- value = value[segment];
563
- return value;
564
- }
565
- /**
566
- * A monotone "is this key at or past the bound?" predicate over a leading
567
- * prefix of the flattened key.
568
- *
569
- * @remarks
570
- * Monotone over the canonical key order because it reads only the leading
571
- * fields, which are exactly the ones the order sorts by first — so one fence
572
- * bisect finds its boundary row, and a pair of them bound one contiguous
573
- * range.
574
- */
575
- function boundPredicate(leaves, values) {
576
- const comparators = leaves.slice(0, values.length).map((leaf) => compareFor(leaf.type));
577
- return (key) => {
578
- for (let i = 0; i < values.length; i++) {
579
- const order = comparators[i](fieldAt(key, leaves[i].path), values[i]);
580
- if (order !== 0)
581
- return order > 0;
582
- }
583
- return true; // equal on the prefix: at the bound, so past it
584
- };
585
- }
586
385
  /**
587
386
  * Locate a key (or string-prefix range) in a Set/Dict dataset by global
588
387
  * element row, without decoding the collection.
@@ -591,9 +390,10 @@ function boundPredicate(leaves, values) {
591
390
  * {@link getDatasetPage} element windows serve — so the result plugs
592
391
  * straight into the paged preview's scroll position. The search
593
392
  * binary-searches the manifest's segment fences (each segment's first key)
594
- * with the key type's East comparator, then decodes at most the one owning
595
- * segment (exact key) or the two edge segments (a range — which is what an
596
- * exact key is through an index: every entry under it).
393
+ * with the key type's East comparator, then binary-searches the keys of at
394
+ * most the one owning segment (exact key) or the two edge segments (a range —
395
+ * which is what an exact key is through an index: every entry under it), each
396
+ * read and decoded once, through the decoded segments the API process keeps.
597
397
  *
598
398
  * Responds with JSON `{ found, row, count }`: `row` is the match's global
599
399
  * element index (for a prefix, the range's first row; for a miss, the
@@ -603,291 +403,26 @@ function boundPredicate(leaves, values) {
603
403
  */
604
404
  export async function findDatasetKey(storage, repoPath, workspace, treePath, query, options = {}) {
605
405
  try {
606
- if (treePath.length === 0) {
607
- return pageError('bad_request', 'Path required for key search');
608
- }
609
- const status = await workspaceGetDatasetStatus(storage, repoPath, workspace, treePath);
610
- if (status.refType === 'unassigned') {
611
- return pageError('dataset_unassigned', 'Dataset is unassigned (pending task output)', 404);
612
- }
613
- if (status.refType === 'null' || !status.hash) {
614
- return pageError('dataset_null', 'Dataset is null', 404);
615
- }
616
- if (query.hash !== undefined && query.hash !== status.hash) {
617
- return pageError('dataset_hash_mismatch', `Dataset content is ${status.hash}, not ${query.hash} — refetch status and retry`, 409, { 'X-Content-SHA256': status.hash });
618
- }
619
- // An index selector searches the index's own collection, whose rows the
620
- // answer is in — the same row space an index page serves.
621
- let typeValue = isVariant(status.datasetType)
622
- ? status.datasetType
623
- : toEastTypeValue(status.datasetType);
624
- let searchHash = status.hash;
625
- const indexed = query.index !== undefined;
626
- if (query.index !== undefined) {
627
- const refPath = treePath.map((seg) => seg.value).join('/');
628
- const resolved = await resolveRecordIndex(storage, repoPath, workspace, refPath, status.hash, query.index);
629
- if (resolved === null) {
630
- const declared = await recordIndexNames(storage, repoPath, status.hash);
631
- return pageError('index_not_found', `Dataset '${refPath}' has no index '${query.index}'`
632
- + (declared.length > 0 ? ` — it has ${declared.join(', ')}` : ' — it declares none'), 404);
633
- }
634
- typeValue = resolved.collectionType;
635
- searchHash = resolved.manifest;
636
- }
637
- const kind = typeValue.type;
638
- if (kind !== 'Set' && kind !== 'Dict') {
639
- return pageError('dataset_not_searchable', `Key search addresses Set or Dict datasets; this dataset holds ${kind}`);
640
- }
641
- const keyTypeValue = kind === 'Dict'
642
- ? typeValue.value.key
643
- : typeValue.value;
644
- // Through an index, the key, prefix and fields forms address the index key
645
- // `ik` — the key a client holds, as the record's signature names it — not
646
- // the collection's `{ik, k}`, which pairs it with each row's own key. The
647
- // collection sorts by `ik` first, so a predicate over it is monotone over
648
- // the collection's order. The range form bounds the collection's
649
- // flattened key, which begins inside `ik`.
650
- const formKeyType = indexed
651
- ? keyTypeValue.value.find((f) => f.name === 'ik').type
652
- : keyTypeValue;
653
- const formKey = indexed ? (k) => k.ik : (k) => k;
654
- const keysNoun = indexed ? `the keys of index '${query.index}'` : "this dataset's keys";
655
- const fields = query.fields !== undefined && query.fields.length > 0 ? query.fields : undefined;
656
- const ranged = (query.from !== undefined && query.from.length > 0) || (query.to !== undefined && query.to.length > 0);
657
- const forms = [query.key !== undefined, query.prefix !== undefined || fields !== undefined, ranged];
658
- if (forms.filter(Boolean).length !== 1) {
659
- return pageError('bad_request', 'Pass a key literal, or a prefix and/or leading fields, or a from/to range — exactly one form');
660
- }
661
- // The range form's bounds are leading prefixes of the FLATTENED key, which
662
- // is the order the collection is sorted in, so each bounds one contiguous
663
- // row range.
664
- const leaves = flattenKeyFields(keyTypeValue);
665
- const parseBound = (label, literals) => {
666
- if (literals === undefined || literals.length === 0)
667
- return { values: [] };
668
- if (literals.length > leaves.length) {
669
- return pageError('bad_request', `${label} names ${literals.length} key fields, but the key flattens to ${leaves.length}: `
670
- + leaves.map((leaf) => leaf.path.join('.') || '(the key)').join(', '));
671
- }
672
- const values = [];
673
- for (let i = 0; i < literals.length; i++) {
674
- const parsed = parseFor(leaves[i].type)(literals[i]);
675
- if (!parsed.success) {
676
- return pageError('key_parse_error', `${label} field '${leaves[i].path.join('.') || '(the key)'}': ${parsed.error}`);
677
- }
678
- values.push(parsed.value);
679
- }
680
- return { values };
681
- };
682
- const lowerBound = parseBound('from', query.from);
683
- if (lowerBound instanceof Response)
684
- return lowerBound;
685
- const upperBound = parseBound('to', query.to);
686
- if (upperBound instanceof Response)
687
- return upperBound;
688
- const structMeta = formKeyType.type === 'Struct'
689
- ? formKeyType.value
690
- : null;
691
- if (fields !== undefined) {
692
- if (structMeta === null) {
693
- return pageError('bad_request', `Leading-field search addresses Struct keys; ${keysNoun} are ${formKeyType.type}`);
694
- }
695
- if (fields.length > structMeta.length) {
696
- return pageError('bad_request', `Key has ${structMeta.length} fields, got ${fields.length}`);
697
- }
698
- }
699
- const fieldValues = [];
700
- if (fields !== undefined && structMeta !== null) {
701
- for (let j = 0; j < fields.length; j++) {
702
- const parsed = parseFor(structMeta[j].type)(fields[j]);
703
- if (!parsed.success) {
704
- return pageError('key_parse_error', `field '${structMeta[j].name}': ${parsed.error}`);
705
- }
706
- fieldValues.push(parsed.value);
707
- }
708
- }
709
- let optionalPrefix = false;
710
- let prefixValue = query.prefix;
711
- if (query.prefix !== undefined) {
712
- const prefixIdx = fieldValues.length;
713
- const prefixFieldType = structMeta !== null
714
- ? (prefixIdx < structMeta.length ? structMeta[prefixIdx].type : undefined)
715
- : formKeyType;
716
- if (prefixFieldType === undefined) {
717
- return pageError('bad_request', `All ${structMeta.length} key fields are exact — nothing left for a prefix`);
718
- }
719
- if (prefixFieldType.type === 'Variant') {
720
- const cases = prefixFieldType.value;
721
- optionalPrefix = cases.length === 2
722
- && cases.some(c => c.name === 'none' && c.type.type === 'Null')
723
- && cases.some(c => c.name === 'some' && c.type.type === 'String');
724
- }
725
- if (prefixFieldType.type !== 'String' && !optionalPrefix) {
726
- return pageError('bad_request', structMeta !== null
727
- ? `prefix continues key field '${structMeta[prefixIdx].name}', which is ${prefixFieldType.type}, not String or Option<String>`
728
- : `prefix search needs String or Option<String> keys; ${keysNoun} are ${formKeyType.type}`);
729
- }
730
- if (optionalPrefix)
731
- prefixValue = some(query.prefix);
732
- }
733
- const matchesPrefix = (value) => {
734
- if (!optionalPrefix)
735
- return value.startsWith(query.prefix);
736
- const option = value;
737
- return option.type === 'some' && option.value.startsWith(query.prefix);
738
- };
739
- let keyValue;
740
- if (query.key !== undefined) {
741
- const parsed = parseFor(formKeyType)(query.key);
742
- if (!parsed.success) {
743
- return pageError('key_parse_error', parsed.error);
744
- }
745
- keyValue = parsed.value;
746
- }
747
- const cmp = compareFor(formKeyType);
748
- const objectSize = searchHash === status.hash
749
- ? status.size ?? (await storage.objects.stat(repoPath, status.hash)).size
750
- : (await storage.objects.stat(repoPath, searchHash)).size;
751
- let segments;
406
+ const dataset = await readDataset(storage, repoPath, workspace, treePath, query.hash, 'key search');
407
+ if (dataset instanceof Response)
408
+ return dataset;
409
+ const target = await searchTarget(storage, repoPath, workspace, treePath, dataset, query.index);
410
+ if (target instanceof Response)
411
+ return target;
412
+ const search = compileKeySearch(query, target);
413
+ if ('type' in search)
414
+ return pageError(search.type, search.message);
415
+ const segments = await openTarget(storage, repoPath, target);
416
+ if (segments instanceof Response)
417
+ return segments;
418
+ let located;
752
419
  try {
753
- segments = await cachedSegments(storage, repoPath, searchHash, objectSize);
420
+ located = await locateAll(storage, repoPath, segments, search.bounds);
754
421
  }
755
422
  catch (err) {
756
- const message = err instanceof Error ? err.message : String(err);
757
- if (!BLOB_REFUSAL.test(message))
758
- throw err;
759
- return pageError('dataset_not_indexed', message);
760
- }
761
- // The fence-search surface: the segment geometry, a fence probe, and a
762
- // one-segment key iterator. A manifest answers every fence from its own
763
- // entries, so a bisect over one reads no frames at all.
764
- const segmentCount = segments.segmentCount;
765
- const elementCount = segments.elementCount;
766
- const cumulative = segments.cumulative;
767
- const fenceAt = (i) => segments.fence(i);
768
- const keysAt = async (i) => {
769
- const segment = openBeast2PagesFor(typeValue)(await segments.segment(i)).segment(0);
770
- return kind === 'Set' ? segment : segment.keys();
771
- };
772
- // First row whose key satisfies a monotone predicate (false… then
773
- // true… over the canonical key order), plus that row's key. Fences
774
- // bound the candidate segment, so at most ONE segment decodes: when the
775
- // boundary is the first row of a later segment, its fence already IS
776
- // the boundary key.
777
- const locate = async (pred) => {
778
- if (segmentCount === 0)
779
- return { row: 0, key: undefined, hasKey: false };
780
- const first = await fenceAt(0);
781
- if (pred(first))
782
- return { row: 0, key: first, hasKey: true };
783
- // Greatest segment whose fence is before the boundary.
784
- let lo = 0, hi = segmentCount - 1;
785
- while (lo < hi) {
786
- const mid = (lo + hi + 1) >> 1;
787
- if (!pred(await fenceAt(mid)))
788
- lo = mid;
789
- else
790
- hi = mid - 1;
791
- }
792
- const base = lo === 0 ? 0 : cumulative[lo - 1];
793
- let idx = 0;
794
- for (const k of await keysAt(lo)) {
795
- if (pred(k))
796
- return { row: base + idx, key: k, hasKey: true };
797
- idx++;
798
- }
799
- if (lo + 1 < segmentCount) {
800
- const next = await fenceAt(lo + 1);
801
- return { row: cumulative[lo], key: next, hasKey: true };
802
- }
803
- return { row: elementCount, key: undefined, hasKey: false };
804
- };
805
- let found;
806
- let row;
807
- let count;
808
- if (ranged) {
809
- // Two bisects, one contiguous range: `[from, to)` on the flattened
810
- // prefix. An absent bound is the collection's own end.
811
- const lower = query.from === undefined || query.from.length === 0
812
- ? { row: 0 }
813
- : await locate(boundPredicate(leaves, lowerBound.values));
814
- const upper = query.to === undefined || query.to.length === 0
815
- ? { row: elementCount }
816
- : await locate(boundPredicate(leaves, upperBound.values));
817
- row = lower.row;
818
- count = Math.max(0, upper.row - lower.row);
819
- found = count > 0;
820
- }
821
- else if (query.key !== undefined) {
822
- const at = await locate((k) => cmp(formKey(k), keyValue) >= 0);
823
- if (indexed) {
824
- // An index holds an entry per row under a key, so a key is a run.
825
- const past = await locate((k) => cmp(formKey(k), keyValue) > 0);
826
- row = at.row;
827
- count = past.row - at.row;
828
- found = count > 0;
829
- }
830
- else {
831
- found = at.hasKey && cmp(at.key, keyValue) === 0;
832
- row = at.row;
833
- count = found ? 1 : 0;
834
- }
835
- }
836
- else {
837
- // Range query — a String prefix, or a struct key's exact leading
838
- // fields with an optional prefix on the next field. Both predicates
839
- // depend only on the leading field tuple, and struct keys compare
840
- // field-by-field in declaration order, so they are monotone over the
841
- // canonical key order; prefix-extending strings form one contiguous
842
- // interval in East (code-point) order.
843
- let lowerPred;
844
- let upperPred;
845
- const prefix = query.prefix;
846
- if (structMeta !== null) {
847
- const fieldCmps = structMeta.map((f) => compareFor(f.type));
848
- const lead = (k) => {
849
- const key = formKey(k);
850
- for (let j = 0; j < fieldValues.length; j++) {
851
- const c = fieldCmps[j](key[structMeta[j].name], fieldValues[j]);
852
- if (c !== 0)
853
- return c;
854
- }
855
- return 0;
856
- };
857
- if (prefix === undefined) {
858
- lowerPred = (k) => lead(k) >= 0;
859
- upperPred = (k) => lead(k) > 0;
860
- }
861
- else {
862
- const prefixIdx = fieldValues.length;
863
- const prefixName = structMeta[prefixIdx].name;
864
- const prefixCmp = fieldCmps[prefixIdx];
865
- lowerPred = (k) => {
866
- const c = lead(k);
867
- return c !== 0 ? c > 0 : prefixCmp(formKey(k)[prefixName], prefixValue) >= 0;
868
- };
869
- upperPred = (k) => {
870
- const c = lead(k);
871
- if (c !== 0)
872
- return c > 0;
873
- const field = formKey(k)[prefixName];
874
- return prefixCmp(field, prefixValue) > 0 && !matchesPrefix(field);
875
- };
876
- }
877
- }
878
- else {
879
- // Scalar String / Option<String> keys: none sorts before every
880
- // some(String), so the same pair of monotone predicates bounds only
881
- // present strings, including for an empty prefix.
882
- lowerPred = (k) => cmp(formKey(k), prefixValue) >= 0;
883
- upperPred = (k) => cmp(formKey(k), prefixValue) > 0 && !matchesPrefix(formKey(k));
884
- }
885
- const lower = await locate(lowerPred);
886
- const upper = await locate(upperPred);
887
- row = lower.row;
888
- count = upper.row - lower.row;
889
- found = count > 0;
423
+ return corruptRefusal(err, 'dataset_not_canonical');
890
424
  }
425
+ const { found, row, count } = search.answer(located, segments.elementCount);
891
426
  return new Response(JSON.stringify({ found, row, count }), {
892
427
  status: 200,
893
428
  headers: {
@@ -895,7 +430,7 @@ export async function findDatasetKey(storage, repoPath, workspace, treePath, que
895
430
  // Hash-pinned queries are content-addressed: same URL ⇒ same
896
431
  // answer, forever — as for page windows.
897
432
  'Cache-Control': query.hash !== undefined ? pinnedCacheControl(options.cache) : 'no-store',
898
- 'X-Content-SHA256': status.hash,
433
+ 'X-Content-SHA256': dataset.hash,
899
434
  },
900
435
  });
901
436
  }