@elaraai/east 1.0.104 → 1.0.105

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 (62) hide show
  1. package/dist/src/compile/builtins/primitives.d.ts +1 -1
  2. package/dist/src/compile/control.d.ts.map +1 -1
  3. package/dist/src/compile/control.js +10 -5
  4. package/dist/src/compile/control.js.map +1 -1
  5. package/dist/src/compile.open_beast.spec.js +7 -3
  6. package/dist/src/compile.open_beast.spec.js.map +1 -1
  7. package/dist/src/query/jq/narrow.d.ts +68 -0
  8. package/dist/src/query/jq/narrow.d.ts.map +1 -0
  9. package/dist/src/query/jq/narrow.js +691 -0
  10. package/dist/src/query/jq/narrow.js.map +1 -0
  11. package/dist/src/query/jq/split.d.ts +35 -11
  12. package/dist/src/query/jq/split.d.ts.map +1 -1
  13. package/dist/src/query/jq/split.js +205 -35
  14. package/dist/src/query/jq/split.js.map +1 -1
  15. package/dist/src/query/jq/translate-builtins.d.ts.map +1 -1
  16. package/dist/src/query/jq/translate-builtins.js +43 -8
  17. package/dist/src/query/jq/translate-builtins.js.map +1 -1
  18. package/dist/src/query/jq/translate.d.ts +55 -4
  19. package/dist/src/query/jq/translate.d.ts.map +1 -1
  20. package/dist/src/query/jq/translate.js +174 -21
  21. package/dist/src/query/jq/translate.js.map +1 -1
  22. package/dist/src/runner_exec.d.ts +10 -0
  23. package/dist/src/runner_exec.d.ts.map +1 -1
  24. package/dist/src/runner_exec.js +11 -3
  25. package/dist/src/runner_exec.js.map +1 -1
  26. package/dist/src/runner_exec.spec.js +40 -2
  27. package/dist/src/runner_exec.spec.js.map +1 -1
  28. package/dist/src/serialization/beast2/index.d.ts +2 -1
  29. package/dist/src/serialization/beast2/index.d.ts.map +1 -1
  30. package/dist/src/serialization/beast2/index.js +2 -1
  31. package/dist/src/serialization/beast2/index.js.map +1 -1
  32. package/dist/src/serialization/beast2/v5/codec.d.ts +30 -1
  33. package/dist/src/serialization/beast2/v5/codec.d.ts.map +1 -1
  34. package/dist/src/serialization/beast2/v5/codec.js +24 -3
  35. package/dist/src/serialization/beast2/v5/codec.js.map +1 -1
  36. package/dist/src/serialization/beast2/v5/lazy.d.ts +23 -4
  37. package/dist/src/serialization/beast2/v5/lazy.d.ts.map +1 -1
  38. package/dist/src/serialization/beast2/v5/lazy.js +84 -19
  39. package/dist/src/serialization/beast2/v5/lazy.js.map +1 -1
  40. package/dist/src/serialization/beast2/v5/project.d.ts +156 -0
  41. package/dist/src/serialization/beast2/v5/project.d.ts.map +1 -0
  42. package/dist/src/serialization/beast2/v5/project.js +830 -0
  43. package/dist/src/serialization/beast2/v5/project.js.map +1 -0
  44. package/dist/src/serialization/beast2/v5/project.spec.d.ts +6 -0
  45. package/dist/src/serialization/beast2/v5/project.spec.d.ts.map +1 -0
  46. package/dist/src/serialization/beast2/v5/project.spec.js +273 -0
  47. package/dist/src/serialization/beast2/v5/project.spec.js.map +1 -0
  48. package/dist/src/serialization/beast2/v5/runs.d.ts +78 -7
  49. package/dist/src/serialization/beast2/v5/runs.d.ts.map +1 -1
  50. package/dist/src/serialization/beast2/v5/runs.js +218 -7
  51. package/dist/src/serialization/beast2/v5/runs.js.map +1 -1
  52. package/dist/src/serialization/beast2/v5/runs.spec.js +223 -6
  53. package/dist/src/serialization/beast2/v5/runs.spec.js.map +1 -1
  54. package/dist/src/serialization/beast2/v5/stream.d.ts +30 -2
  55. package/dist/src/serialization/beast2/v5/stream.d.ts.map +1 -1
  56. package/dist/src/serialization/beast2/v5/stream.js +30 -5
  57. package/dist/src/serialization/beast2/v5/stream.js.map +1 -1
  58. package/dist/src/serialization/index.d.ts +1 -1
  59. package/dist/src/serialization/index.d.ts.map +1 -1
  60. package/dist/src/serialization/index.js +1 -1
  61. package/dist/src/serialization/index.js.map +1 -1
  62. package/package.json +1 -1
@@ -25,6 +25,17 @@
25
25
  * flush, not a pair per row. A table that gathers more keys than its rows
26
26
  * repay sends them on, and the piece's rows from there go straight on.
27
27
  *
28
+ * `first(f)` and `limit(n; f)` over a stream of a dataset's rows keep its first
29
+ * outputs in input order (#1113): each piece stops once it has `n`, and the
30
+ * split call's `first` output keeps the first `n` of all, which e3 stops for
31
+ * once the pieces before the rest hold them (#1110). A `many` query whose
32
+ * first rows nothing follows keeps no more than its sink does — its most
33
+ * outputs, and one more — so `n` is at most that many.
34
+ *
35
+ * A split plans the program the translator runs, its rows narrowed to the
36
+ * fields its later steps read (#1141), so its pieces build, keep and send
37
+ * only those, and a re-keyed join's re-key call sends each row as those.
38
+ *
28
39
  * @packageDocumentation
29
40
  */
30
41
  import { compareFor } from "../../comparison.js";
@@ -34,6 +45,7 @@ import { none } from "../../containers/variant.js";
34
45
  import { func } from "../../expr/block.js";
35
46
  import { withLocationCapture } from "../../location.js";
36
47
  import { ArrayType, BooleanType, DictType, FunctionType, IntegerType, NullType, OptionType, SetType, StructType, isImmutableType, isTypeEqual, } from "../../types.js";
48
+ import { checkAgain, narrowRows, rowsRead } from "./narrow.js";
37
49
  import { nullablePayload, unwrap } from "./shapes.js";
38
50
  import { childPath, jqChildren } from "./spans.js";
39
51
  import { addInto } from "./translate-builtins.js";
@@ -198,10 +210,11 @@ function spanning(checked, from, to) {
198
210
  }
199
211
  /**
200
212
  * Finds a query's row work: the bindings before it, the dataset it streams,
201
- * the steps done to each row, and the steps after.
213
+ * the steps done to each row, and the steps after. `path` is the program's,
214
+ * the root's by default.
202
215
  */
203
- function findRows(checked, program) {
204
- const steps = pipeline(program, "");
216
+ function findRows(checked, program, path = "") {
217
+ const steps = pipeline(program, path);
205
218
  let i = 0;
206
219
  const binds = [];
207
220
  while (i < steps.length && steps[i].kind === "bind")
@@ -269,7 +282,7 @@ function findRows(checked, program) {
269
282
  });
270
283
  }
271
284
  else {
272
- return { whole: earlyOrNested(checked, first) };
285
+ return firstRows(checked, first, binds, steps.slice(i + 1)) ?? { whole: earlyOrNested(checked, first) };
273
286
  }
274
287
  i += 1;
275
288
  // The collection's row work: `map`, `flatten`, `[.[] | f]`; or `.[]` making a stream of the dataset.
@@ -362,6 +375,41 @@ function earlyOrNested(checked, first) {
362
375
  return reason(checked, node.type === "reduce" ? "shape" : "state", first.path, node.type);
363
376
  return nestedOrNone(checked, first);
364
377
  }
378
+ /**
379
+ * `first(f)` or `limit(n; f)`, `n` a whole number of at least 1, over a stream
380
+ * of a dataset's rows (#1113): the stream's row work, which keeps its first
381
+ * `n` outputs — the bindings before it and in it, and the steps after it,
382
+ * which run on each. `undefined` when the node is neither, or `f` is no such
383
+ * stream; the stream's own reason when its row work cannot split.
384
+ */
385
+ function firstRows(checked, first, binds, after) {
386
+ const node = first.node;
387
+ if (node.type !== "call")
388
+ return undefined;
389
+ const { name, args } = node.value;
390
+ let rows;
391
+ if (name === "first" && args.length === 1) {
392
+ rows = 1;
393
+ }
394
+ else if (name === "limit" && args.length === 2) {
395
+ // A count the query computes, or one below 1, is the one unit's to read: `limit(0; f)` keeps nothing, and a negative one raises.
396
+ const count = args[0];
397
+ const n = count.type === "literal" ? integerOf(count.value) : undefined;
398
+ if (n === undefined || n < 1n || n > BigInt(Number.MAX_SAFE_INTEGER))
399
+ return undefined;
400
+ rows = Number(n);
401
+ }
402
+ else {
403
+ return undefined;
404
+ }
405
+ const at = args.length - 1;
406
+ const inner = findRows(checked, args[at], childPath(first.path, `call.args[${at}]`));
407
+ if ("whole" in inner)
408
+ return inner.whole.code === "calls" || inner.whole.code === "state" ? inner : undefined;
409
+ if (!inner.rows.stream || inner.rows.first !== undefined)
410
+ return undefined;
411
+ return checkBinds(checked, { ...inner.rows, binds: [...binds, ...inner.rows.binds], after, first: { path: first.path, rows } });
412
+ }
365
413
  /** `nested` when a stream over a root field is somewhere inside the node; `no_stream` otherwise. */
366
414
  function nestedOrNone(checked, first) {
367
415
  const inner = findNode(first.node, first.path, n => rootStream(n) !== undefined || (n.type === "pipe" && rootField(n.value.left, true) !== undefined));
@@ -897,6 +945,13 @@ export function splitJq(checked, options = {}) {
897
945
  }
898
946
  if (!checked.source.root)
899
947
  throw new TranslationError("splitJq splits a query checked as an e3 root");
948
+ // The query as it runs: its rows narrowed to the fields its later steps read (#1141).
949
+ const narrowed = narrowRows(checked);
950
+ const planned = planOf(narrowed);
951
+ return "plan" in planned ? splitCall(narrowed, planned.plan, options, planned.pruning) : planned;
952
+ }
953
+ /** How a checked query splits — its row work, how its rows combine and the steps after — or why it runs as one unit. */
954
+ function planOf(checked) {
900
955
  const program = checked.program;
901
956
  const pruning = pruningOf(checked, program);
902
957
  const whole = (r) => ({ kind: "whole", reason: r, pruning });
@@ -904,6 +959,11 @@ export function splitJq(checked, options = {}) {
904
959
  if ("whole" in found)
905
960
  return whole(found.whole);
906
961
  const rows = found.rows;
962
+ if (rows.first !== undefined) {
963
+ // The first outputs of a stream, in input order, and the steps after them on each (#1113).
964
+ const combine = { kind: "first", path: rows.first.path, rows: rows.first.rows };
965
+ return { plan: { rows, combine, rest: rows.after, rowType: rowTypeOf(checked, rows), cutType: typeAfter(checked, rows.end) }, pruning };
966
+ }
907
967
  if (rows.stream && rows.after.length === 0) {
908
968
  // A stream is the query's outputs, which its caller caps: one unit stops as soon as it has them.
909
969
  return { kind: "whole", reason: reason(checked, "stops_early", null, rows.source.over), pruning: [...pruning, { kind: "stop", name: rows.source.over, range: rangeOf(checked, rows.source.path) }] };
@@ -935,8 +995,7 @@ export function splitJq(checked, options = {}) {
935
995
  combine = { kind: "concat" };
936
996
  rest = rows.after;
937
997
  }
938
- const plan = { rows, combine, rest, rowType: rowTypeOf(checked, rows), cutType: typeAfter(checked, rows.end) };
939
- return splitCall(checked, plan, options, pruning);
998
+ return { plan: { rows, combine, rest, rowType: rowTypeOf(checked, rows), cutType: typeAfter(checked, rows.end) }, pruning };
940
999
  }
941
1000
  /** Why the step after a query's row work keeps it one unit, when no work is done row by row. */
942
1001
  function whyNot(checked, step, over) {
@@ -1000,6 +1059,26 @@ function keepsInput(node) {
1000
1059
  return true;
1001
1060
  return node.type === "pipe" && keepsInput(node.value.left) && keepsInput(node.value.right);
1002
1061
  }
1062
+ /**
1063
+ * Whether a filter gives its input, nothing, or an object of some of its
1064
+ * input's fields under their own names — `{a, b}`, `{a: .a}` — and pipes of
1065
+ * them: what #1141's narrowing makes of a stage that passes its rows on,
1066
+ * `map(select(p) | {a, b})`. Each field such an object gives is its input's,
1067
+ * so a later step reads it at the field of the input it reads.
1068
+ */
1069
+ function keepsInputFields(node) {
1070
+ if (keepsInput(node))
1071
+ return true;
1072
+ if (node.type === "object") {
1073
+ return node.value.length > 0 && node.value.every(entry => entry.key.type === "name"
1074
+ && (entry.value.type === "none" || isInputField(entry.value.value, entry.key.value)));
1075
+ }
1076
+ return node.type === "pipe" && keepsInputFields(node.value.left) && keepsInputFields(node.value.right);
1077
+ }
1078
+ /** Whether a node reads its input's field `name`: `.name`. */
1079
+ function isInputField(node, name) {
1080
+ return node.type === "field" && !node.value.optional && node.value.target.type === "identity" && node.value.name === name;
1081
+ }
1003
1082
  /** The field names from the row to a node's value, when it reads a field of the row: `.a.b` where `.` is the row, `$r.a` where `$r` holds it, `$k` where `$k` holds one. */
1004
1083
  function rowField(node, cx) {
1005
1084
  if (node.type === "variable")
@@ -1076,7 +1155,7 @@ function lookupsOnly(node, path, cx, name, found) {
1076
1155
  found.push({ fields, path: childPath(hasPath, "call.args[0]") });
1077
1156
  return true;
1078
1157
  }
1079
- return visit(left, "pipe.left") && visit(right, "pipe.right", { ...cx, row: cx.row && keepsInput(left) });
1158
+ return visit(left, "pipe.left") && visit(right, "pipe.right", { ...cx, row: cx.row && keepsInputFields(left) });
1080
1159
  }
1081
1160
  case "bind": {
1082
1161
  const { body, patterns, source } = node.value;
@@ -1146,7 +1225,8 @@ function rowLookups(plan, name) {
1146
1225
  if (binds.slice(bound + 1).some(b => variablesIn(b.node.value.source).has(name)))
1147
1226
  return undefined;
1148
1227
  let cx = { row: true, rows: new Set(), fields: new Map(), defs: new Set() };
1149
- // The rows are the dataset's own until a step makes others.
1228
+ // The rows are the dataset's own until a step makes others: keeping some of
1229
+ // their fields under their own names, as #1141's narrowing does, keeps them.
1150
1230
  let intact = true;
1151
1231
  for (const step of plan.rows.steps) {
1152
1232
  const here = { ...cx, row: intact };
@@ -1160,13 +1240,13 @@ function rowLookups(plan, name) {
1160
1240
  const arg = step.node.value.args[0];
1161
1241
  if (!lookupsOnly(arg, childPath(step.path, "call.args[0]"), here, name, found))
1162
1242
  return undefined;
1163
- intact = intact && keepsInput(arg);
1243
+ intact = intact && keepsInputFields(arg);
1164
1244
  break;
1165
1245
  }
1166
1246
  case "each":
1167
1247
  if (!lookupsOnly(step.node, step.path, here, name, found))
1168
1248
  return undefined;
1169
- intact = intact && keepsInput(step.node);
1249
+ intact = intact && keepsInputFields(step.node);
1170
1250
  break;
1171
1251
  case "bind": {
1172
1252
  const { patterns, source } = step.node.value;
@@ -1363,19 +1443,40 @@ function inputsOf(checked) {
1363
1443
  const fields = parts(unwrap(checked.inputType)).fields;
1364
1444
  return checked.reads.map(name => ({ name, type: fields[name] }));
1365
1445
  }
1446
+ /**
1447
+ * A plan whose stream's first rows are no more than a `many` query's sink
1448
+ * keeps — its most outputs, and one more — when nothing runs after them to
1449
+ * pass some by: e3 then stops once the pieces before the rest hold those, and
1450
+ * the rows it assembles are the result, with no final function to cut them.
1451
+ */
1452
+ function sinkFirst(plan, multiplicity, options) {
1453
+ const c = plan.combine;
1454
+ if (c.kind !== "first" || plan.rest.length > 0 || multiplicity !== "many" || options.maxOutputs === undefined)
1455
+ return plan;
1456
+ const most = options.maxOutputs + 1;
1457
+ return c.rows <= most ? plan : { ...plan, combine: { ...c, rows: most } };
1458
+ }
1366
1459
  /** The parts of the split call for a plan. */
1367
- function splitCall(checked, plan, options, pruning) {
1460
+ function splitCall(checked, planned, options, pruning) {
1461
+ const element = checked.elementType;
1462
+ const multiplicity = checked.multiplicity;
1463
+ const plan = sinkFirst(planned, multiplicity, options);
1368
1464
  const inputs = inputsOf(checked);
1369
1465
  if (!inputs.some(i => i.name === plan.rows.source.over))
1370
1466
  throw new TranslationError(`.${plan.rows.source.over} is not one of the query's inputs`);
1371
- const element = checked.elementType;
1372
- const multiplicity = checked.multiplicity;
1373
1467
  const resultType = multiplicity === "one" ? element : multiplicity === "maybe" ? OptionType(element) : ArrayType(element);
1374
1468
  const output = outputOf(checked, plan);
1375
1469
  const rangeEnd = plan.rest.length === 0 ? null : spanning(checked, plan.rest[0].path, plan.rest[plan.rest.length - 1].path);
1376
- // The assembled rows are the result when nothing follows them and they are its type.
1377
- const thenNeeded = !(plan.combine.kind === "concat" && plan.rest.length === 0 && multiplicity === "one" && isTypeEqual(output.type, resultType));
1378
- const copartitioned = copartitionedOf(plan, inputs);
1470
+ // The assembled rows are the result when nothing follows them and they are its type: all of them, or a stream's
1471
+ // first rows, no more than a `many` query's sink keeps.
1472
+ const c = plan.combine;
1473
+ const assembledIsResult = plan.rest.length === 0 && isTypeEqual(output.type, resultType) && ((c.kind === "concat" && multiplicity === "one")
1474
+ || (c.kind === "first" && multiplicity === "many" && (options.maxOutputs === undefined || c.rows <= options.maxOutputs + 1)));
1475
+ const thenNeeded = !assembledIsResult;
1476
+ // The final function is given only the inputs not partitioned (#1107), so a dict it reads is not.
1477
+ const thenReads = thenNeeded ? finalRootReads(plan) : new Set();
1478
+ const copartitioned = copartitionedOf(plan, inputs).filter(name => !thenReads.has(name));
1479
+ const thenInputs = inputs.filter(i => i.name !== plan.rows.source.over && !copartitioned.includes(i.name));
1379
1480
  return {
1380
1481
  kind: "split",
1381
1482
  over: plan.rows.source.over,
@@ -1383,7 +1484,7 @@ function splitCall(checked, plan, options, pruning) {
1383
1484
  resultType,
1384
1485
  output,
1385
1486
  piece: () => pieceProgram(checked, plan, inputs, output, options),
1386
- then: () => thenNeeded ? thenProgram(checked, plan, inputs, output, resultType, options) : null,
1487
+ then: () => thenNeeded ? thenProgram(checked, plan, thenInputs, output, resultType, options) : null,
1387
1488
  stages: {
1388
1489
  piece: spanning(checked, plan.rows.start, plan.rows.end),
1389
1490
  combine: combineOf(checked, plan),
@@ -1391,7 +1492,7 @@ function splitCall(checked, plan, options, pruning) {
1391
1492
  },
1392
1493
  broadcast: [...new Set(plan.rows.binds.flatMap(bind => rootFieldsRead(bind.node.value.source)))].filter(name => !copartitioned.includes(name)),
1393
1494
  copartitioned,
1394
- rekey: copartitioned.length > 0 ? null : rekeyOf(checked, plan, inputs, output, resultType, thenNeeded, options),
1495
+ rekey: copartitioned.length > 0 ? null : rekeyOf(checked, plan, inputs, output, resultType, thenNeeded, thenReads, options),
1395
1496
  pruning,
1396
1497
  };
1397
1498
  }
@@ -1400,9 +1501,10 @@ function splitCall(checked, plan, options, pruning) {
1400
1501
  * piece (#942): the one dict, bound before the stream, that the pieces read
1401
1502
  * only at one field of the row as the dataset gives it — of the dict's key
1402
1503
  * type — when the combine is order-blind; `null` when there is none, or more
1403
- * than one.
1504
+ * than one. A dict the final function reads is none: the join call partitions
1505
+ * it, and its final function is given only the inputs not partitioned (#1107).
1404
1506
  */
1405
- function rekeyOf(checked, plan, inputs, output, resultType, thenNeeded, options) {
1507
+ function rekeyOf(checked, plan, inputs, output, resultType, thenNeeded, thenReads, options) {
1406
1508
  const source = plan.rows.source;
1407
1509
  if (source.entries !== undefined || !orderBlind(plan))
1408
1510
  return null;
@@ -1414,7 +1516,7 @@ function rekeyOf(checked, plan, inputs, output, resultType, thenNeeded, options)
1414
1516
  const joins = [];
1415
1517
  for (const dataset of new Set(plan.rows.binds.flatMap(b => rootFieldsRead(b.node.value.source)))) {
1416
1518
  const B = inputs.find(i => i.name === dataset);
1417
- if (dataset === source.over || B === undefined)
1519
+ if (dataset === source.over || B === undefined || thenReads.has(dataset))
1418
1520
  continue;
1419
1521
  const t = unwrap(B.type);
1420
1522
  if (t.type !== "Dict")
@@ -1431,7 +1533,12 @@ function rekeyOf(checked, plan, inputs, output, resultType, thenNeeded, options)
1431
1533
  if (joins.length !== 1)
1432
1534
  return null;
1433
1535
  const join = joins[0];
1434
- const Rows = ArrayType(R);
1536
+ // Each row as the re-key call sends it and the join call's pieces read it: the fields the query reads of it (#1141).
1537
+ const narrowed = narrowedRows(checked, plan, A.type, R, output);
1538
+ const sent = narrowed?.row ?? R;
1539
+ const joinChecked = narrowed?.checked ?? checked;
1540
+ const joinPlan = narrowed?.plan ?? plan;
1541
+ const Rows = ArrayType(sent);
1435
1542
  const Keyed = DictType(join.key, Rows);
1436
1543
  const joinInputs = inputs.map(i => i.name === source.over ? { name: i.name, type: Keyed } : i);
1437
1544
  // Each key's rows, in input order: a re-keyed piece's rows.
@@ -1440,25 +1547,53 @@ function rekeyOf(checked, plan, inputs, output, resultType, thenNeeded, options)
1440
1547
  name: join.name,
1441
1548
  key: join.range,
1442
1549
  keyType: join.key,
1443
- output: { kind: "dict", type: Keyed, merge: () => mergeFunction(checked, join.key, Rows, (t, _$, earlier, later) => t.b("ArrayConcat", [R], [earlier, later], Rows, source.path)) },
1444
- piece: () => rekeyPiece(checked, A.type, R, join.fields, join.key, source, options),
1550
+ output: { kind: "dict", type: Keyed, merge: () => mergeFunction(checked, join.key, Rows, (t, _$, earlier, later) => t.b("ArrayConcat", [sent], [earlier, later], Rows, source.path)) },
1551
+ piece: () => rekeyPiece(checked, A.type, R, sent, join.fields, join.key, source, options),
1445
1552
  inputs: joinInputs,
1446
- joinPiece: () => pieceProgram(checked, plan, joinInputs, output, options, rekeyed),
1447
- joinThen: () => thenNeeded ? thenProgram(checked, plan, joinInputs, output, resultType, options) : null,
1553
+ joinPiece: () => pieceProgram(joinChecked, joinPlan, joinInputs, output, options, rekeyed),
1554
+ joinThen: () => thenNeeded ? thenProgram(joinChecked, joinPlan, joinInputs.filter(i => i.name !== source.over && i.name !== join.name), output, resultType, options) : null,
1448
1555
  };
1449
1556
  }
1557
+ /**
1558
+ * A dataset's rows narrowed to the fields the query reads of them (#1141):
1559
+ * the struct of those fields, in the row's order, and the query checked again
1560
+ * and planned over rows of it; `undefined` when the query reads a row whole,
1561
+ * or every field, or does not plan alike over them.
1562
+ */
1563
+ function narrowedRows(checked, plan, A, R, output) {
1564
+ const source = plan.rows.source;
1565
+ const read = rowsRead(checked, source.path);
1566
+ const row = unwrap(R);
1567
+ const root = unwrap(checked.inputType);
1568
+ if (read === undefined || row.type !== "Struct" || root.type !== "Struct" || unwrap(A).type !== "Array")
1569
+ return undefined;
1570
+ const fields = Object.entries(row.fields);
1571
+ const kept = fields.filter(([name]) => read.has(name));
1572
+ if (kept.length === fields.length)
1573
+ return undefined;
1574
+ const narrowed = StructType(Object.fromEntries(kept));
1575
+ const input = StructType(Object.fromEntries(Object.entries(root.fields)
1576
+ .map(([name, type]) => [name, name === source.over ? ArrayType(narrowed) : type])));
1577
+ const again = checkAgain(checked, checked.program, checked.source.spans, input);
1578
+ if (again === undefined)
1579
+ return undefined;
1580
+ const planned = planOf(again);
1581
+ if (!("plan" in planned) || planned.plan.combine.kind !== plan.combine.kind || !isTypeEqual(outputOf(again, planned.plan).type, output.type))
1582
+ return undefined;
1583
+ return { row: narrowed, checked: again, plan: planned.plan };
1584
+ }
1450
1585
  /**
1451
1586
  * The re-key call's piece program (#942): each row of the piece sent on under
1452
1587
  * its join key, a key's rows gathered first in the piece's table, appended in
1453
1588
  * place, since the table alone holds them until it sends them on.
1454
1589
  */
1455
- function rekeyPiece(checked, A, R, fields, K, source, options) {
1456
- const Rows = ArrayType(R);
1590
+ function rekeyPiece(checked, A, R, sent, fields, K, source, options) {
1591
+ const Rows = ArrayType(sent);
1457
1592
  return withLocationCapture(false, () => func([A, FunctionType([K, Rows], NullType)], NullType, ($, piece, emit) => {
1458
1593
  const t = new SplitTranslator(checked, {});
1459
1594
  const send = ($2, ...args) => t.stmt($2, t.callFn(emit, args, source.path));
1460
1595
  const append = (t2, $2, earlier, later) => {
1461
- t2.stmt($2, t2.b("ArrayAppend", [R], [earlier, later], NullType, source.path));
1596
+ t2.stmt($2, t2.b("ArrayAppend", [sent], [earlier, later], NullType, source.path));
1462
1597
  return earlier;
1463
1598
  };
1464
1599
  const table = pieceTable(t, $, K, { type: Rows, fold: append }, source.path, options, send);
@@ -1467,8 +1602,10 @@ function rekeyPiece(checked, A, R, fields, K, source, options) {
1467
1602
  let key = row;
1468
1603
  for (const name of fields)
1469
1604
  key = t.field(key, name);
1470
- const one = t.declare($2, t.emptyArray(R), "rows");
1471
- t.push($2, one, row, source.path);
1605
+ // The row as the query reads it: the fields it reads, where it reads only some (#1141).
1606
+ const value = sent === R ? row : t.struct(sent, Object.fromEntries(Object.keys(parts(sent).fields).map(name => [name, t.field(row, name)])));
1607
+ const one = t.declare($2, t.emptyArray(sent), "rows");
1608
+ t.push($2, one, value, source.path);
1472
1609
  table.add($2, key, one);
1473
1610
  }, source.path);
1474
1611
  table.flush($);
@@ -1501,6 +1638,7 @@ function combineOf(checked, plan) {
1501
1638
  case "distinct_by": return { kind: "distinct_by", range: rangeOf(checked, c.path), key: rangeOf(checked, c.key.path) };
1502
1639
  case "reduce": return { kind: "reduce", range: rangeOf(checked, c.path), key: rangeOf(checked, childPath(c.path, "reduce.update.update.path.index.index")), update: c.update };
1503
1640
  case "top": return { kind: "top", range: spanning(checked, c.path, c.keepPath), key: c.key === null ? null : rangeOf(checked, c.key.path), rows: c.rows };
1641
+ case "first": return { kind: "first", range: rangeOf(checked, c.path), rows: c.rows };
1504
1642
  }
1505
1643
  }
1506
1644
  /** The struct of a set of totals' partials: a field each, `p0`, `p1`, … */
@@ -1545,6 +1683,8 @@ function outputOf(checked, plan) {
1545
1683
  const T = ArrayType(topPair(c));
1546
1684
  return { kind: "fold", type: T, zero: [], combine: () => combineFunction(checked, T, (t, $, a, b) => firstSorted(t, $, t.b("ArrayConcat", [topPair(c)], [a, b], T, c.path), c)) };
1547
1685
  }
1686
+ case "first":
1687
+ return { kind: "first", type: ArrayType(R), limit: c.rows };
1548
1688
  }
1549
1689
  }
1550
1690
  /** A row the first rows of a sort keep, with its key: the pairs `sort_by` sorts. */
@@ -1807,13 +1947,20 @@ function pieceProgram(checked, plan, inputs, output, options, rowsOf = datasetRo
1807
1947
  : undefined;
1808
1948
  // The first rows of a sort are kept in the piece, and emitted once.
1809
1949
  const top = c.kind === "top" ? topRows(t, $, c) : undefined;
1810
- genBinds(t, $, root, binds, emptyEnv(), ($2, env) => {
1950
+ // A stream's first rows are sent as they come, and the piece stops once it has sent them (#1113).
1951
+ const kept = c.kind === "first" ? t.declare($, t.int(0), "kept") : undefined;
1952
+ const rowsOfPiece = ($1, stop) => genBinds(t, $1, root, binds, emptyEnv(), ($2, env) => {
1811
1953
  const piece = root.fields.get(plan.rows.source.over);
1812
1954
  rowsOf(t, $2, piece, ($3, item) => genRow(t, $3, item, plan.rows.steps, 0, env, ($4, row, scope) => {
1813
1955
  switch (c.kind) {
1814
1956
  case "concat":
1815
1957
  send($4, t.widenTo($4, row, plan.rowType, plan.rows.end));
1816
1958
  return;
1959
+ case "first":
1960
+ send($4, t.widenTo($4, row, plan.rowType, plan.rows.end));
1961
+ t.assign($4, kept, t.add(kept, t.int(1), c.path));
1962
+ t.ifElse($4, t.b("GreaterEqual", [IntegerType], [kept, t.int(c.rows)], BooleanType, c.path), stop, undefined, c.path);
1963
+ return;
1817
1964
  case "distinct":
1818
1965
  table.add($4, t.widenTo($4, row, plan.rowType, plan.rows.end));
1819
1966
  return;
@@ -1854,6 +2001,10 @@ function pieceProgram(checked, plan, inputs, output, options, rowsOf = datasetRo
1854
2001
  }
1855
2002
  }));
1856
2003
  });
2004
+ if (c.kind === "first")
2005
+ t.once($, ($1, label) => rowsOfPiece($1, ($2) => t.brk($2, label)), c.path);
2006
+ else
2007
+ rowsOfPiece($, undefined);
1857
2008
  if (c.kind === "totals")
1858
2009
  send($, t.struct(output.type, Object.fromEntries(folded.map((acc, i) => [`p${i}`, acc]))));
1859
2010
  if (top !== undefined)
@@ -1973,8 +2124,8 @@ function pieceTable(t, $, key, value, path, options, send) {
1973
2124
  };
1974
2125
  }
1975
2126
  // ─── The final function ─────────────────────────────────────────────────────
1976
- /** The final function: the value the combine gives, the rest of the query on it, and the query's sink. */
1977
- function thenProgram(checked, plan, inputs, output, resultType, options) {
2127
+ /** The variables the final function reads: in what follows the combine, and in the expression its totals make. */
2128
+ function finalVariables(plan) {
1978
2129
  const c = plan.combine;
1979
2130
  const reads = new Set();
1980
2131
  for (const step of plan.rest)
@@ -1983,7 +2134,20 @@ function thenProgram(checked, plan, inputs, output, resultType, options) {
1983
2134
  variablesIn(c.node, reads);
1984
2135
  if (c.kind === "group")
1985
2136
  variablesIn(c.body.node, reads);
1986
- const binds = bindsFor(plan.rows.binds, reads);
2137
+ return reads;
2138
+ }
2139
+ /** The root fields the final function reads: those the bindings it needs read. */
2140
+ function finalRootReads(plan) {
2141
+ return new Set(bindsFor(plan.rows.binds, finalVariables(plan)).flatMap(bind => rootFieldsRead(bind.node.value.source)));
2142
+ }
2143
+ /**
2144
+ * The final function: the value the combine gives, the rest of the query on
2145
+ * it, and the query's sink. It takes the assembled output, then `inputs`: the
2146
+ * inputs not partitioned, each of the root fields it reads among them.
2147
+ */
2148
+ function thenProgram(checked, plan, inputs, output, resultType, options) {
2149
+ const c = plan.combine;
2150
+ const binds = bindsFor(plan.rows.binds, finalVariables(plan));
1987
2151
  const element = checked.elementType;
1988
2152
  const multiplicity = checked.multiplicity;
1989
2153
  return withLocationCapture(false, () => func([output.type, ...inputs.map(i => i.type)], resultType, ($, assembled, ...values) => {
@@ -2016,6 +2180,12 @@ function thenProgram(checked, plan, inputs, output, resultType, options) {
2016
2180
  rest($2, t.bind($2, t.widenTo($2, out, typeAfter(checked, c.path), c.path), "rows"));
2017
2181
  return;
2018
2182
  }
2183
+ case "first": {
2184
+ // The stream's first outputs, in input order, each on through the steps after them (#1113).
2185
+ const each = typeAfter(checked, c.path);
2186
+ t.forEach($2, all, ($3, row) => rest($3, t.widenTo($3, row, each, c.path)), c.path, "row");
2187
+ return;
2188
+ }
2019
2189
  case "totals": {
2020
2190
  const value = withTotals(t, $2, c.totals, all, env, c.node, c.path, plan.cutType);
2021
2191
  rest($2, value);