{"version":3,"file":"calls-hm44gLA_.cjs","names":["printFor","StringType","StructType","fromEastTypeValue","none","some","checkJq","variant","translateJq","encodeEastIR","samePath","equalFor","TreePathType","pathToString","decodeBeast2For","OptionType","ArrayType","encodeBeast2For","runtimeErrorAt","pieceSizesFor","PIECE_SIZES","checkJq","splitJq","encodeEastIR","variant","some","none","encodeBeast2For","equalFor","TreePathType","encodeBeast2For","sha256Hex","variant","none","pathToString","decodeEastIR","fromEastTypeValue","EastError","compareFor","SortedSet","SortedMap","isTypeEqual","decodeBeast2","ArrayType","SetType","DictType","printFor","decodeBeast2For"],"sources":["../src/query/one-shot.ts","../src/query/plan.ts","../src/query/in-memory-call.ts"],"sourcesContent":["/**\n * Copyright (c) 2025 Elara AI Pty Ltd\n * Dual-licensed under AGPL-3.0 and commercial license. See LICENSE for details.\n */\n\n/**\n * A query's one-shot call (#935, with #928 folded in): the builder runs a\n * query with no query code on the server. The query is checked once against\n * the whole root its data sources make, translated to East IR here, and run\n * as a function, as one-shot runs any caller's IR (#1031), with one dataset\n * argument per data source it reads (`devdocs/QUERY.md` §17). The call is\n * platform-free — east-c given no platform package, and a body that calls no\n * platform function — so a caller who may read the workspace may run it.\n *\n * The builder sends {@link PreparedQuery.request} with e3-api-client's\n * `oneShotExecute` and reads what comes back with {@link queryResultOf}.\n * Everything here is a pure function: nothing reaches the network or the DOM.\n *\n * @packageDocumentation\n */\n\nimport {\n    ArrayType, OptionType, StringType, StructType,\n    checkJq, decodeBeast2For, encodeBeast2For, encodeEastIR, equalFor, fromEastTypeValue, none, printFor, runtimeErrorAt, some,\n    translateJq, variant,\n    type CheckJqResult, type EastType, type EastTypeValue, type JqMultiplicity, type JqNode, type QueryDiagnostic, type ValueTypeOf,\n} from \"@elaraai/east\";\nimport { TreePathType, pathToString, type ExecuteResult, type OneShotRequest, type RunnerValue } from \"@elaraai/e3-types\";\nimport type { QueryInputType, QueryResultType, QueryRootEntryType } from \"@elaraai/e3-ui/internal\";\n\n// ─── The root ────────────────────────────────────────────────────────────────\n\n/**\n * A data source of a query's root, as the builder binds it: the root field a\n * query reads it by, its dataset's path, and the dataset's type.\n *\n * @remarks\n * `name` and `path` are a {@link QueryRootEntryType} value, what a saved query\n * keeps of its root; `type` is the dataset's East type, as e3 lists it.\n */\nexport type QueryRootEntry = ValueTypeOf<typeof QueryRootEntryType> & {\n    /** The dataset's East type, as e3 lists it. */\n    type: EastTypeValue;\n};\n\n/**\n * A query's root: the type every query of the builder is checked against, and\n * the data sources it is made of.\n *\n * @property type - The root's type: a Struct of the data sources' types, in entry order\n * @property entries - The data sources, in root order\n */\nexport interface QueryRoot {\n    /** The root's type: a Struct of the data sources' types, in entry order. */\n    readonly type: EastType;\n    /** The data sources, in root order. */\n    readonly entries: QueryRootEntry[];\n}\n\n/** A name `.name` reads: the jq lexer's field name, a letter or `_`, then letters, digits and `_`. */\nconst JQ_IDENTIFIER = /^[A-Za-z_][A-Za-z_0-9]*$/;\n\n/** A name as East's text writes a string, for a message. */\nconst printString = printFor(StringType);\n\n/**\n * The root a query's data sources make: the builder's `useQueryRoot` gives it\n * from the data sources a page binds.\n *\n * @param entries - the data sources, in root order\n * @returns the root: a Struct of the data sources' types, in entry order, and\n *   the data sources\n * @throws {Error} When a name is not a jq identifier, or is given twice,\n *   naming it.\n *\n * @remarks\n * The root is only a type. Its entries become the translation's parameters,\n * one dataset each, because a lazy dataset put into a struct is read whole\n * (`devdocs/QUERY.md` §15.6). A name is a jq identifier — a letter or `_`,\n * then letters, digits and `_` — so `.name` reads it. A root of no data\n * sources is the empty Struct, and a query that reads a data source of it is\n * refused when it is checked.\n *\n * @example\n * ```ts\n * const root = queryRoot([\n *     { name: \"customers\", path: [variant(\"field\", \"inputs\"), variant(\"field\", \"customers\")], type: toEastTypeValue(Customers) },\n *     { name: \"orders\", path: [variant(\"field\", \"inputs\"), variant(\"field\", \"orders\")], type: toEastTypeValue(Orders) },\n * ]);\n * // root.type is StructType({ customers: Customers, orders: Orders })\n *\n * queryRoot([{ name: \"order lines\", path, type }]);\n * // throws: queryRoot: \"order lines\" is not a jq identifier: …\n * ```\n */\nexport function queryRoot(entries: readonly QueryRootEntry[]): QueryRoot {\n    const names = new Set<string>();\n    for (const { name } of entries) {\n        if (!JQ_IDENTIFIER.test(name)) {\n            throw new Error(`queryRoot: ${printString(name)} is not a jq identifier: a data source's name is a letter or _, then letters, digits and _, so .name reads it`);\n        }\n        if (names.has(name)) throw new Error(`queryRoot: ${printString(name)} is given twice: each data source of a root has a name of its own`);\n        names.add(name);\n    }\n    return {\n        type: StructType(entries.map(entry => [entry.name, fromEastTypeValue(entry.type)] as const)),\n        entries: [...entries],\n    };\n}\n\n// ─── Preparing a call ────────────────────────────────────────────────────────\n\n/** The most outputs a `many` query returns, by default: as many as `long_range` warns past (`devdocs/QUERY.md` §12). */\nconst DEFAULT_MAX_OUTPUTS = 1_000;\n\n/** The most outputs a `many` query may be asked for. */\nconst MAX_OUTPUTS = 100_000;\n\n/** The largest answer a call returns, in bytes, by default: 1 MiB. */\nconst DEFAULT_MAX_BYTES = 1_048_576;\n\n/**\n * Options for {@link prepareQuery}: the call's limits, and its runner.\n *\n * @property maxOutputs - The most outputs a `many` query returns: 1 000 by default, at most 100 000\n * @property maxBytes - The largest answer the call returns, in bytes: 1 MiB by default\n * @property timeoutMs - The call's time limit, in milliseconds: the server's when omitted\n * @property runner - The runner: east-c given no platform package, by default\n */\nexport interface QueryOptions {\n    /** The most outputs a `many` query returns: 1 000 by default, at most 100 000. */\n    readonly maxOutputs?: number;\n    /** The largest answer the call returns, in bytes: 1 MiB by default. */\n    readonly maxBytes?: number;\n    /**\n     * The call's time limit, in milliseconds. Omitted, the call names none and\n     * the server's applies: its default for a call that names none, under the\n     * longest a request to it may take (#1131).\n     */\n    readonly timeoutMs?: number;\n    /** The runner: east-c given no platform package by default, which any caller who may read the workspace may run. */\n    readonly runner?: RunnerValue;\n}\n\n/** What a run of a query answered: a {@link QueryResultType} value. */\nexport type QueryResult = ValueTypeOf<typeof QueryResultType>;\n\n/** How a run of a query ended. */\ntype QueryOutcome = QueryResult[\"outcome\"];\n\n/** A dataset a run read, pinned at its hash. */\ntype QueryInput = ValueTypeOf<typeof QueryInputType>;\n\n/**\n * What the checker made of a program that checks: the program as written, the\n * type of each output and how many there are, each present.\n */\nexport type CheckedProgram = CheckJqResult & {\n    /** The program as written. */\n    readonly program: JqNode;\n    /** The type of each output. */\n    readonly elementType: EastType;\n    /** How many outputs the program gives. */\n    readonly multiplicity: JqMultiplicity;\n};\n\n/**\n * Whether a program checks: its program, the type of each output and how many\n * there are are present exactly when no diagnostic is an error.\n *\n * @param checked - what `checkJq` made of the program\n * @returns whether it checks\n */\nexport function programChecks(checked: CheckJqResult): checked is CheckedProgram {\n    return checked.program !== null && checked.elementType !== null && checked.multiplicity !== null;\n}\n\n/**\n * A query's one-shot call, ready to send, and what reading its answer needs.\n *\n * @property checked - What the checker made of the program: the program as written, the type of each output and how many there are, and the spans a runtime error is placed by\n * @property entries - The data sources the query reads, one per argument of the call, in its order\n * @property request - The call, which e3-api-client's `oneShotExecute` sends\n * @property maxOutputs - The most outputs a `many` query returns\n */\nexport interface PreparedQuery {\n    /** What the checker made of the program: the program as written, the type of each output and how many there are, and the spans a runtime error is placed by. */\n    readonly checked: CheckedProgram;\n    /** The data sources the query reads, one per argument of the call, in its order: the order the query first reads them. */\n    readonly entries: QueryRootEntry[];\n    /** The call, which e3-api-client's `oneShotExecute` sends. */\n    readonly request: OneShotRequest;\n    /** The most outputs a `many` query returns; the call gives one more, which says the answer was cut short. */\n    readonly maxOutputs: number;\n}\n\n/**\n * What reading a call's answer needs ({@link queryResultOf}): the checker's\n * record of the query that ran — the type of each output, and how many there\n * are — the data sources in the call's argument order, and its most outputs. A\n * one-shot call's {@link PreparedQuery} is one; so is a split call's, which\n * the planner gives (`plan.ts`).\n */\nexport type QueryReading = Pick<PreparedQuery, \"checked\" | \"entries\" | \"maxOutputs\">;\n\n/** A call's limits and runner, as its options set them: what a one-shot call and a split call both send. */\nexport interface QueryLimits {\n    /** The most outputs a `many` query returns. */\n    readonly maxOutputs: number;\n    /** The call's limits: its largest answer as `maxResultBytes`, and its time limit when the options name one. */\n    readonly limits: OneShotRequest[\"limits\"];\n    /** The runner: east-c given no platform package, unless the options name another. */\n    readonly runner: RunnerValue;\n}\n\n/**\n * A call's limits and runner, from its options: its most outputs and its\n * largest answer their defaults when the options give none, and no time limit\n * unless the options name one, so the server's applies (#1131).\n *\n * @param options - the call's limits and its runner\n * @returns the most outputs, the limits and the runner\n * @throws {RangeError} When a limit is not a whole number of at least 1.\n */\nexport function queryLimits(options: QueryOptions = {}): QueryLimits {\n    const maxOutputs = Math.min(limitOf(options.maxOutputs, DEFAULT_MAX_OUTPUTS, \"maxOutputs\"), MAX_OUTPUTS);\n    const maxBytes = limitOf(options.maxBytes, DEFAULT_MAX_BYTES, \"maxBytes\");\n    const timeoutMs = options.timeoutMs === undefined ? none : some(BigInt(checkedLimit(options.timeoutMs, \"timeoutMs\")));\n    return {\n        maxOutputs,\n        limits: some({ timeoutMs, maxResultBytes: some(BigInt(maxBytes)), maxLogBytes: none }),\n        runner: options.runner ?? platformFreeEastC(),\n    };\n}\n\n/**\n * Prepares a query's one-shot call: checks the program once against the whole\n * root, translates it, and builds the request.\n *\n * @param program - the query's jq text\n * @param root - the root its data sources make ({@link queryRoot})\n * @param options - the call's limits and its runner\n * @returns the prepared call; or, for a program that does not check, the\n *   `error` result a run of it gives\n * @throws {RangeError} When a limit is not a whole number of at least 1.\n * @throws {TranslationError} When the checked program holds something the\n *   translator cannot express: a gap in the translation, never a mistake in\n *   the query.\n *\n * @remarks\n * - **One check.** The program is checked with\n *   `checkJq(program, root.type, { root: true })`, once, against the whole\n *   root, which is never narrowed to what the query reads (#1041): `keys` on\n *   the root answers every name. A problem of error severity is an `error`\n *   result holding the checker's diagnostics, lints included, and no input,\n *   since nothing ran; reading the whole root is one.\n * - **The translation.** `translateJq` translates it, a `many` query asked\n *   for at most `maxOutputs + 1` outputs (#923). Its parameters are the\n *   datasets it reads, in the order it first reads them.\n * - **The request.** `bodyIr` is the translation as an East function, its IR\n *   encoded with its source map, so a runtime error names its place in the\n *   jq; `args` is one `dataset` argument per dataset read, in the\n *   translation's order; `runner` is east-c given no platform package, unless\n *   the options name another; `limits` holds `maxBytes` as `maxResultBytes`,\n *   and `timeoutMs` when the options give one. A call that names no time limit\n *   runs under the server's: its default for a call that names none, under\n *   the longest a request to it may take (#1131).\n * - **Platform-free.** A translation calls East's builtins only, so the body\n *   holds no `Platform` node, and with the default runner any caller who may\n *   read the workspace may run the call (#1031).\n *\n * @example\n * ```ts\n * const prepared = prepareQuery(\".orders | map(.total) | add\", root, { timeoutMs: 10_000 });\n * if (\"result\" in prepared) return prepared.result;   // the checker's problems\n * const result = await oneShotExecute(url, repo, workspace, prepared.prepared.request, { token });\n * return queryResultOf(prepared.prepared, result);\n * ```\n */\nexport function prepareQuery(program: string, root: QueryRoot, options: QueryOptions = {}): { prepared: PreparedQuery } | { result: QueryResult } {\n    // The limits are checked before the program, so a wrong one is refused whatever the program.\n    queryLimits(options);\n    return prepareCheckedQuery(checkJq(program, root.type, { root: true }), root, options);\n}\n\n/**\n * Prepares a query's one-shot call from what the checker made of it: what\n * {@link prepareQuery} does once it has checked the program, for a caller that\n * has checked it already — the planner, which checks a query once to split it\n * and to call it.\n *\n * @param checked - what `checkJq` made of the program, against `root.type`, as an e3 root\n * @param root - the root\n * @param options - the call's limits and its runner\n * @returns the prepared call; or, for a program that does not check, the `error` result a run of it gives\n * @throws {RangeError} When a limit is not a whole number of at least 1.\n * @throws {TranslationError} When the checked program holds something the translator cannot express.\n */\nexport function prepareCheckedQuery(checked: CheckJqResult, root: QueryRoot, options: QueryOptions = {}): { prepared: PreparedQuery } | { result: QueryResult } {\n    const { maxOutputs, limits, runner } = queryLimits(options);\n    if (!programChecks(checked)) return { result: { inputs: [], outcome: variant(\"error\", checked.diagnostics) } };\n    const translation = translateJq(checked, checked.multiplicity === \"many\" ? { maxOutputs } : {});\n    const entries = translation.inputs.map(input => entryNamed(root, input.name));\n    const request: OneShotRequest = {\n        bodyIr: encodeEastIR(translation.fn().toIR()),\n        args: entries.map(entry => variant(\"dataset\", entry.path)),\n        runner,\n        limits,\n    };\n    return { prepared: { checked, entries, request, maxOutputs } };\n}\n\n/**\n * A limit of a call: its default when the options give none.\n *\n * @param value - the limit the options give\n * @param fallback - its default\n * @param name - its name, for the error\n * @returns the limit\n * @throws {RangeError} When it is not a whole number of at least 1.\n */\nfunction limitOf(value: number | undefined, fallback: number, name: string): number {\n    return value === undefined ? fallback : checkedLimit(value, name);\n}\n\n/**\n * A limit the options give, checked.\n *\n * @param value - the limit\n * @param name - its name, for the error\n * @returns the limit\n * @throws {RangeError} When it is not a whole number of at least 1.\n */\nfunction checkedLimit(value: number, name: string): number {\n    if (!Number.isSafeInteger(value) || value < 1) throw new RangeError(`prepareQuery: ${name} is ${value}, not a whole number of at least 1`);\n    return value;\n}\n\n/**\n * The data source of a root a query reads by a name.\n *\n * @param root - the root\n * @param name - the root field the translation, or the split, reads\n * @param caller - what asks, for the error: `prepareQuery` by default\n * @returns the data source\n * @throws {Error} When the root has none of that name: its type was not made from its entries.\n */\nexport function entryNamed(root: QueryRoot, name: string | null, caller = \"prepareQuery\"): QueryRootEntry {\n    const entry = root.entries.find(e => e.name === name);\n    if (entry === undefined) throw new Error(`${caller}: the query reads .${name ?? \"\"}, which no data source of the root is`);\n    return entry;\n}\n\n/**\n * east-c given no platform package, each collection read lazily: the runner of\n * a platform-free call, which any caller who may read the workspace may run.\n *\n * @returns the runner\n */\nfunction platformFreeEastC(): RunnerValue {\n    return variant(\"east_c\", { platforms: [], decode: variant(\"lazy\", null) });\n}\n\n// ─── Reading the answer ──────────────────────────────────────────────────────\n\n/**\n * What a query's call answered: a one-shot call's, or a split call's.\n *\n * @param prepared - the call, as {@link prepareQuery} prepared it; or a split\n *   call's reading, as the planner gives it — both a {@link QueryReading}\n * @param result - what e3-api-client's `oneShotExecute` returned for it, or a\n *   split call's result (`splitCall`'s `result`)\n * @returns the answer: how the run ended, and the datasets it read\n * @throws {Error} When the call read a dataset other than the one the query\n *   reads there: the result is not this call's.\n *\n * @remarks\n * - `success` is `ok`, the value decoded with the translation's result type.\n *   A `many` answer of more than `maxOutputs` outputs — the translation gives\n *   one more — is `truncated`, its last output dropped. `result` is\n *   self-describing beast2 of the answer kept, at the result type, and\n *   `outputs` counts its outputs: one for a `one` query, none or one for\n *   `maybe`.\n * - `failed` for a platform function the runner could not find is\n *   `needs_platform`, naming each: a function value in the data may call one\n *   (`devdocs/QUERY.md` §9).\n * - `failed` otherwise is an `error` of one `runtime` diagnostic: the\n *   runner's message, at the jq node that raised it, placed by east's\n *   `runtimeErrorAt` as `evaluateJq` places one (`devdocs/QUERY.md` §15.3).\n *   A failure with no message says what the runner last said, or its exit\n *   code.\n * - `invalid` is an `error`: `no_value` for a dataset e3 found unassigned\n *   (\"orders has no value yet\"), and `invalid` for anything else it refused.\n * - `timed_out` and `too_large` are as e3 reported them.\n *\n * `inputs` names each dataset the run read, with the hash e3 pinned it at, in\n * the call's argument order: empty when nothing ran.\n *\n * @example\n * ```ts\n * const result = queryResultOf(prepared, await oneShotExecute(url, repo, workspace, prepared.request, { token }));\n * if (result.outcome.type === \"ok\") show(decodeBeast2(result.outcome.value.result), result.outcome.value.truncated);\n * ```\n */\nexport function queryResultOf(prepared: QueryReading, result: ExecuteResult): QueryResult {\n    const inputs = inputsOf(prepared, result);\n    const outcome = result.outcome;\n    switch (outcome.type) {\n        case \"success\":\n            return { inputs, outcome: answered(prepared, outcome.value.value) };\n        case \"failed\":\n            return { inputs, outcome: failed(prepared.checked, outcome.value.exitCode, result.stderr) };\n        case \"invalid\":\n            return { inputs, outcome: variant(\"error\", outcome.value.diagnostics.map(d => refused(prepared, d.message))) };\n        case \"timed_out\":\n            return { inputs, outcome: variant(\"timed_out\", { ms: outcome.value.ms }) };\n        case \"too_large\":\n            return { inputs, outcome: variant(\"too_large\", { bytes: outcome.value.bytes, limit: outcome.value.limit }) };\n    }\n}\n\n/** Equality of dataset paths. */\nconst samePath = equalFor(TreePathType);\n\n/**\n * The datasets a call read, each with the name of the data source it is.\n *\n * @param prepared - the call\n * @param result - what it returned: one pinned dataset per argument, in order\n * @returns the datasets read\n * @throws {Error} When an argument read a dataset other than the data source the query reads there.\n */\nfunction inputsOf(prepared: QueryReading, result: ExecuteResult): QueryInput[] {\n    return result.inputs.map((input, i) => {\n        const entry = prepared.entries[i];\n        if (entry === undefined || !samePath(entry.path, input.path)) {\n            throw new Error(`queryResultOf: the call's argument ${i} read ${pathToString(input.path)}, which is not the data source the query reads there`);\n        }\n        return { hash: input.hash, name: entry.name, path: input.path };\n    });\n}\n\n/**\n * A successful run's answer, decoded with the query's result type: a `many`\n * answer cut to `maxOutputs` outputs.\n *\n * @param prepared - the call\n * @param bytes - the answer, beast2 at the result type\n * @returns the `ok` outcome\n * @throws {Error} When the answer does not decode at the query's result type.\n */\nfunction answered(prepared: QueryReading, bytes: Uint8Array): QueryOutcome {\n    const element = prepared.checked.elementType;\n    switch (prepared.checked.multiplicity) {\n        case \"one\":\n            // Decoded, so an answer of another type is refused.\n            decodeBeast2For(element)(bytes);\n            return variant(\"ok\", { outputs: 1n, result: bytes, truncated: false });\n        case \"maybe\": {\n            const answer = decodeBeast2For(OptionType(element))(bytes);\n            return variant(\"ok\", { outputs: answer.type === \"some\" ? 1n : 0n, result: bytes, truncated: false });\n        }\n        case \"many\": {\n            const type = ArrayType(element);\n            const answer = decodeBeast2For(type)(bytes);\n            if (answer.length <= prepared.maxOutputs) return variant(\"ok\", { outputs: BigInt(answer.length), result: bytes, truncated: false });\n            return variant(\"ok\", { outputs: BigInt(prepared.maxOutputs), result: encodeBeast2For(type)(answer.slice(0, prepared.maxOutputs)), truncated: true });\n        }\n    }\n}\n\n/** A failure as every stock runner reports it on stderr. */\ninterface RunnerFailure {\n    /** The error's message. */\n    readonly message: string;\n    /** Where it was raised, innermost first: a file, and a 1-based line and column. */\n    readonly places: readonly { readonly file: string; readonly line: number; readonly column: number }[];\n}\n\n/** The line that leads a runner's failure. */\nconst FAILURE_LEAD = \"Error: \";\n\n/** A place a failure was raised at, as a runner lists it under the failure. */\nconst FAILURE_PLACE = /^ {2}at (.+):(\\d+):(\\d+)$/;\n\n/**\n * The failure a runner reported: `Error: <message>`, then `  at <file>:<line>:<column>`\n * for each place, innermost first, as east-c, east-node and east-py all write it.\n *\n * @param stderr - the tail of the runner's stderr\n * @returns the failure, or `undefined` when the runner reported none\n */\nfunction failureOf(stderr: string): RunnerFailure | undefined {\n    const lines = stderr.replace(/\\r\\n?/g, \"\\n\").split(\"\\n\");\n    while (lines.length > 0 && lines[lines.length - 1] === \"\") lines.pop();\n    const places: { file: string; line: number; column: number }[] = [];\n    let end = lines.length;\n    for (; end > 0; end--) {\n        const place = FAILURE_PLACE.exec(lines[end - 1]!);\n        if (place === null) break;\n        places.unshift({ file: place[1]!, line: Number(place[2]), column: Number(place[3]) });\n    }\n    let start = end - 1;\n    while (start >= 0 && !lines[start]!.startsWith(FAILURE_LEAD)) start--;\n    if (start < 0) return undefined;\n    return { message: [lines[start]!.slice(FAILURE_LEAD.length), ...lines.slice(start + 1, end)].join(\"\\n\"), places };\n}\n\n/**\n * How each runtime says it cannot find a platform function: east-c's\n * `Unknown platform function: name`; and `Platform function 'name' not found`,\n * or `… is not available` for one marked optional, from the others and from\n * east-c's optional ones.\n */\nconst MISSING_PLATFORM = /Unknown platform function: ([^\\s'\"]+)|Platform function '([^']+)' (?:not found|is not available)/g;\n\n/**\n * A failed run's outcome: `needs_platform` for platform functions the runner\n * could not find, else the error it raised.\n *\n * @param checked - the program, as the checker read it\n * @param exitCode - the runner's exit code\n * @param stderr - the tail of its stderr\n * @returns the outcome\n */\nfunction failed(checked: CheckJqResult, exitCode: bigint, stderr: string): QueryOutcome {\n    const failure = failureOf(stderr);\n    const functions: string[] = [];\n    // The failure's message names them; with no failure in the runners' framing, anything the runner said may.\n    for (const match of (failure?.message ?? stderr).matchAll(MISSING_PLATFORM)) {\n        const name = match[1] ?? match[2];\n        if (name !== undefined && !functions.includes(name)) functions.push(name);\n    }\n    if (functions.length > 0) return variant(\"needs_platform\", { functions });\n    if (failure === undefined) {\n        const said = stderr.split(/\\r\\n?|\\n/).map(line => line.trim()).filter(line => line !== \"\").at(-1);\n        return variant(\"error\", [runtimeErrorAt(checked, said ?? `the run failed with exit code ${exitCode}`)]);\n    }\n    const place = failure.places.find(p => p.file === \"jq\");\n    return variant(\"error\", [runtimeErrorAt(checked, failure.message, place)]);\n}\n\n/** How e3 says a dataset argument has no value: `Dataset argument <i> is not assigned (ref type: …)`. */\nconst UNASSIGNED = /^Dataset argument (\\d+) is not assigned\\b/;\n\n/**\n * What e3 refused a call for, as a diagnostic: a dataset with no value yet,\n * by its data source's name, or what e3 said.\n *\n * @param prepared - the call\n * @param message - e3's diagnostic\n * @returns the diagnostic\n */\nfunction refused(prepared: QueryReading, message: string): QueryDiagnostic {\n    const unassigned = UNASSIGNED.exec(message);\n    const entry = unassigned === null ? undefined : prepared.entries[Number(unassigned[1])];\n    if (entry !== undefined) return problem(\"no_value\", `no_value: ${entry.name} has no value yet.`, none);\n    return problem(\"invalid\", `invalid: ${message}`, none);\n}\n\n/**\n * A diagnostic of error severity, with no fixes and no suggestions.\n *\n * @param code - its code\n * @param message - its sentence, led by its code\n * @param span - the jq text it is about, when it is about some\n * @returns the diagnostic\n */\nfunction problem(code: string, message: string, span: QueryDiagnostic[\"span\"]): QueryDiagnostic {\n    return { code, fixes: [], message, severity: variant(\"error\", null), span, suggestions: [] };\n}\n","/**\n * Copyright (c) 2025 Elara AI Pty Ltd\n * Dual-licensed under AGPL-3.0 and commercial license. See LICENSE for details.\n */\n\n/**\n * Plans (#941) — how a run of a query reads its data: as one one-shot call\n * (#935), or as a split call (#1032) over the pieces of the dataset it works\n * through, which e3 runs as a job of pieces and merges, and the builder\n * launches and polls.\n *\n * - **The split** is east's (`splitJq`): the stage of the query that works row\n *   by row, the program each piece runs, how the pieces' outputs combine and\n *   what runs once after them — or why the query runs as one unit. A stream's\n *   first rows, `first(f)` and `limit(n; f)`, are a `first` split call, which\n *   e3 stops once the pieces before the rest hold them (#1110, #1113).\n * - **The path**: a query that splits runs as a split call only when the\n *   datasets it would cut weigh more than one piece — `PIECE_SIZES.min`\n *   (16 MiB), unless the options name another — so a small dataset keeps a\n *   one-shot call's latency. e3 sizes the pieces by what the dataset weighs\n *   (`pieceSizesFor`, #1108): one of at most 16 MiB is one piece, and a larger\n *   one is cut into several, however much larger it is. Over one piece, the\n *   path is the one estimated faster, from the rows e3's status counts and\n *   what a row of the split's output kind costs ({@link PLAN_COSTS}, #1143);\n *   one whose one call is estimated to hold more than the options'\n *   `memoryBytes` is split. A stream's first rows are estimated to stop both\n *   paths once they have them. A run whose one call the estimates chose, and\n *   which answered too large for one answer, goes on as its split call, whose\n *   output is read a page at a time. A query that runs as one unit is one call, and so\n *   is one whose datasets' weight is not known; one whose rows are not known\n *   is planned by weight alone. A join both of\n *   whose sides weigh more than one piece is re-keyed (#942): two split calls,\n *   the first re-keying the rows by the join key, the second joining its\n *   output and the other side cut at the same keys.\n * - **The request** ({@link splitCallRequest}): the piece program; one\n *   `dataset` argument per data source the query reads, at its path, the one\n *   cut partitioned, and those cut at the same keys with it; the output kind,\n *   with its programs and a fold's zero; the final function; and a one-shot\n *   call's runner, so a caller who may read the workspace may run it, and its\n *   limits, which name no time limit unless the options do: e3 gives a split\n *   call's job the server's. A re-keyed join's two ({@link rekeyCallRequests}).\n * - **The explanation** ({@link PlanExplanation}): the path and why; both\n *   paths' estimated time and memory, and what the estimates assumed; for a\n *   split, what each piece runs, how the pieces combine, what runs once after\n *   them, what every piece reads whole and what it reads cut at the same keys,\n *   and a re-key and what it is estimated to weigh; and the reads that skip\n *   what they don't need — as data, which the builder's words say\n *   (`planWords`).\n *\n * A split call answers an `ExecuteResult`, read as a one-shot call's is\n * (`queryResultOf`): the final function gives the query's result at the type\n * the translation gives it, so the two paths answer alike.\n *\n * Everything here is a pure function: nothing reaches the network or the DOM.\n *\n * @packageDocumentation\n */\n\nimport {\n    checkJq, encodeBeast2For, encodeEastIR, none, some, splitJq, variant,\n    type CheckJqResult, type JqCombine, type JqPruning, type JqRange, type JqSplit, type JqSplitCall, type JqSplitStages, type JqWholeReason,\n} from \"@elaraai/east\";\nimport { PIECE_SIZES, pieceSizesFor, type ExecuteResult, type SplitCallRequest } from \"@elaraai/e3-types\";\nimport {\n    entryNamed, prepareCheckedQuery, prepareQuery, programChecks, queryLimits,\n    type PreparedQuery, type QueryOptions, type QueryReading, type QueryResult, type QueryRoot,\n} from \"./one-shot.js\";\n\n// ─── What planning takes ─────────────────────────────────────────────────────\n\n/**\n * Options for planning a run: a call's limits and runner, as a one-shot call's\n * ({@link QueryOptions}); the most a dataset may weigh and still be read by\n * one call; and what the estimates take of the server (#1143): the memory one\n * call may use, and how many pieces it runs at once.\n */\nexport interface PlanOptions extends QueryOptions {\n    /**\n     * The most a dataset may weigh, in stored bytes, and still be read by one\n     * call: by default `PIECE_SIZES.min` (16 MiB), the most e3 cuts into one\n     * piece (`pieceSizesFor`). A test against a server whose pieces are small\n     * sets it small too, and its runs are planned by weight alone: the\n     * estimates are of the pieces e3 cuts by its own sizes.\n     */\n    readonly pieceBytes?: number;\n    /**\n     * The memory one call may use, in bytes (#1143): a query whose one call is\n     * estimated to hold more is split, however fast one call would be. When\n     * not given, the path is the one estimated faster.\n     */\n    readonly memoryBytes?: number;\n    /**\n     * How many of a split call's pieces the server runs at once — its\n     * budget's cores (`DataflowBudgetType`): by default\n     * {@link PLAN_COSTS}' `cores`.\n     */\n    readonly cores?: number;\n}\n\n/** What a data source weighs, as e3's status says: its stored bytes, and the rows of a stored collection. */\nexport interface SourceWeight {\n    /** What its value weighs in the store, in bytes — a collection's segments and its manifest; `undefined` when not known. */\n    readonly bytes: number | undefined;\n    /** How many elements a stored collection holds; `undefined` for a value that is not one, or when not known. */\n    readonly rows: number | undefined;\n}\n\n/**\n * The programs a run plans from: the query, and what each kind of call runs\n * of it.\n *\n * @remarks\n * In the jq view all three are the jq. In the visual view a one-shot call runs\n * the program that counts every stage's rows, and a split call runs the query\n * itself — a rows result followed by `{counts: [length], result: .[:1000]}`,\n * which the split runs once after the rows are joined — since a split run\n * counts the source and the result only.\n */\nexport interface PlanPrograms {\n    /** The query as its author reads it: what the plan splits and explains. */\n    readonly query: string;\n    /** What a one-shot call runs: the query by default. */\n    readonly oneShot?: string;\n    /** What a split call runs: the query by default. */\n    readonly split?: string;\n}\n\n// ─── What a plan is ──────────────────────────────────────────────────────────\n\n/**\n * Why a run reads its data in one call.\n *\n * @remarks\n * - `whole`: the query runs as one unit, for east's reason (`JqWhole`).\n * - `small`: it would split over a dataset that weighs no more than one piece.\n * - `unweighed`: it would split over a dataset whose weight is not known.\n * - `unsplit`: it would split, and the split call could not be made — what\n *   went wrong, so it shows rather than hides. `over` is `null` when the split\n *   itself failed.\n * - `faster`: it would split over a dataset larger than one piece, and one\n *   call is estimated no slower (#1143), as the explanation's estimates say.\n */\nexport type OneCallWhy =\n    | { readonly kind: \"whole\"; readonly reason: JqWholeReason }\n    | { readonly kind: \"small\"; readonly over: string; readonly bytes: number; readonly pieceBytes: number }\n    | { readonly kind: \"unweighed\"; readonly over: string }\n    | { readonly kind: \"unsplit\"; readonly over: string | null; readonly message: string }\n    | { readonly kind: \"faster\"; readonly over: string };\n\n/**\n * Why a run that splits over a dataset larger than one piece is a split call\n * (#1143).\n *\n * @remarks\n * - `time`: it is estimated faster than one call.\n * - `memory`: one call is estimated to hold more than the options'\n *   `memoryBytes`.\n * - `weight`: the dataset's rows are not known, or the options name their own\n *   piece, so there is nothing to estimate: it weighs more than one piece.\n * - `size`: one call was estimated no slower, and its answer was too large for\n *   one; a split call's output is read a page at a time (#1113), so the run\n *   goes on as its split call ({@link weighPlan}'s `tooLarge`).\n */\nexport type SplitWhy = \"time\" | \"memory\" | \"weight\" | \"size\";\n\n/** How a run reads its data, as its explanation says it. */\nexport type PlanPath =\n    /** One call, and why. */\n    | { readonly kind: \"one_shot\"; readonly why: OneCallWhy }\n    | {\n        readonly kind: \"split\";\n        /** Why it splits (#1143). */\n        readonly why: SplitWhy;\n        /** The dataset the pieces work through, by its data source's name. */\n        readonly over: string;\n        /** The dataset e3 cuts the pieces by, the heaviest of those partitioned: `over`, or one cut at the same keys with it. */\n        readonly heaviest: string;\n        /** What it weighs in the store, in bytes. */\n        readonly bytes: number;\n        /** The most a dataset may weigh and still be read by one call. */\n        readonly pieceBytes: number;\n        /** How the pieces' outputs combine: the split call's output kind. */\n        readonly output: JqSplitCall[\"output\"][\"kind\"];\n        /** What runs where, as ranges of the query's text. */\n        readonly stages: JqSplitStages;\n        /** The data sources every piece reads whole. */\n        readonly broadcast: readonly string[];\n        /** The data sources partitioned with `over`, each piece holding the same keys of them (#942). */\n        readonly copartitioned: readonly string[];\n        /**\n         * A re-keyed join (#942): `over`'s rows re-keyed first by the join key,\n         * the jq of it, then joined with `name` cut at the same keys; `bytes`\n         * what the re-keyed rows are estimated to weigh, from `over`'s manifest.\n         * `null` when the join, if any, reads its other side whole.\n         */\n        readonly rekey: { readonly name: string; readonly key: JqRange; readonly bytes: number } | null;\n    };\n\n/**\n * A plan's explanation, as data: the builder's words say it (`planWords`),\n * beside the run's read-outs.\n */\nexport interface PlanExplanation {\n    /** The query's text: every range of the explanation is of it. */\n    readonly program: string;\n    /** The path, and why. */\n    readonly path: PlanPath;\n    /**\n     * Both paths' estimates, and what they assumed (#1143); `null` when the\n     * path was not chosen by them — a query that runs as one unit, a dataset\n     * within one piece or of a weight or rows not known, a split call that\n     * could not be made, or the options' own piece.\n     */\n    readonly estimates: PlanEstimates | null;\n    /** The reads that skip what they don't need: a count from the index, a key seek, a stream that stops. */\n    readonly pruning: readonly JqPruning[];\n}\n\n/** What a path is estimated to take (#1143). */\nexport interface PathEstimate {\n    /** Its time, in seconds: from its launch to its answer. */\n    readonly seconds: number;\n    /** The most one of its units holds at once, in bytes: the one call's, or a piece's. */\n    readonly peakBytes: number;\n}\n\n/**\n * A run's two paths as the planner estimates them, and what the estimates\n * assumed (#1143): the rows e3's status counts, the costs a row of the\n * split's output kind is taken at ({@link PLAN_COSTS}), the pieces e3 would\n * cut and how many run at once.\n */\nexport interface PlanEstimates {\n    /** As one call. */\n    readonly oneCall: PathEstimate;\n    /** As a split call, or a re-keyed join's two (#942). */\n    readonly split: PathEstimate;\n    /** The dataset the pieces would work through, by its data source's name. */\n    readonly over: string;\n    /** The rows they would work through: `over`'s, as e3's status counts them. */\n    readonly rows: number;\n    /**\n     * For a stream's first rows (`first(f)`, `limit(n; f)`, #1113), the rows\n     * both paths are taken to read before they stop: the first `limit` the\n     * stream gives, as if each row gave one — one call stops once it has\n     * them, and a split call once the pieces before the rest hold them, never\n     * running the pieces after. `null` when the paths read every row.\n     */\n    readonly firstRows: number | null;\n    /** The kind a row's costs are taken at: the split's output kind, or a re-keyed join. */\n    readonly kind: PlanCostKind;\n    /** What a row of that kind costs ({@link PLAN_COSTS}). */\n    readonly row: RowCosts;\n    /**\n     * Whether one call holds every row it works through: a sort, a group, the\n     * distinct rows, the last row or the distinct values of a total hold them\n     * all; a total folds each row as it is made (#1140), a reduce holds its\n     * keys and a stream's first rows stop it.\n     */\n    readonly holdsRows: boolean;\n    /** The pieces e3 would cut, by its piece sizes for what the heaviest dataset cut weighs (`pieceSizesFor`, #1108); a re-keyed join cuts as many in each of its calls. */\n    readonly pieces: number;\n    /** How many pieces run at once: the options' `cores`, else {@link PLAN_COSTS}'. */\n    readonly cores: number;\n    /** The memory one call may use, as the options give it; `null` when they don't. */\n    readonly memoryBytes: number | null;\n}\n\n/** A run's plan: the call it makes, what reading the call's answer needs, and its explanation. */\nexport type QueryPlan =\n    /** One one-shot call, which e3-api-client's `oneShotExecute` sends. */\n    | { readonly kind: \"one_shot\"; readonly prepared: PreparedQuery; readonly explanation: PlanExplanation }\n    /** A split call, which e3-api-client's `splitCall` launches and polls; its answer is read as a one-shot call's. */\n    | { readonly kind: \"split\"; readonly request: SplitCallRequest; readonly reading: QueryReading; readonly explanation: PlanExplanation }\n    /**\n     * A re-keyed join (#942): two split calls, the second over the first's\n     * output by its hash; the second's answer, with what the first read\n     * ({@link RekeyCalls.answer}), is read as a one-shot call's.\n     */\n    | ({ readonly kind: \"rekey\"; readonly reading: QueryReading; readonly explanation: PlanExplanation } & RekeyCalls);\n\n/** A re-keyed join's two split calls ({@link rekeyCallRequests}), and how their answers make the run's. */\nexport interface RekeyCalls {\n    /** The re-key call: the dataset's rows, each under its join key, its output read by its hash, never inline. */\n    readonly first: SplitCallRequest;\n    /**\n     * The join call, over the re-key call's output.\n     *\n     * @param output - the hash of the re-key call's output, as its completed status gives it\n     * @returns the request\n     */\n    join(output: string): SplitCallRequest;\n    /**\n     * The run's answer: the join call's, or the re-key call's when it gave no\n     * output to join, with every dataset the run read — the re-key call's\n     * dataset, pinned as it pinned it, then the join call's — in the order\n     * the reading's entries name them.\n     *\n     * @param first - the re-key call's result\n     * @param join - the join call's result; `undefined` when the re-key call gave no output\n     * @returns the run's answer\n     */\n    answer(first: ExecuteResult, join: ExecuteResult | undefined): ExecuteResult;\n}\n\n/**\n * A query checked and split, waiting to be weighed ({@link weighPlan}): the\n * first half of a plan, which says which data source's weight decides it.\n */\nexport interface PlanDraft {\n    /** The data sources the query reads, in the order it first reads them: what a run says it reads. */\n    readonly reads: readonly string[];\n    /** The data source a split call would cut, whose weight decides the path; `undefined` when the query runs as one unit. */\n    readonly over: string | undefined;\n    /**\n     * The data sources whose weights decide the path: `over`, those cut at the\n     * same keys with it, and the other side of a join it could re-key (#942);\n     * none when the query runs as one unit.\n     */\n    readonly weighs: readonly string[];\n    /** The programs, each given. @internal */\n    readonly programs: Required<PlanPrograms>;\n    /** The root. @internal */\n    readonly root: QueryRoot;\n    /** The options. @internal */\n    readonly options: PlanOptions;\n    /** What the checker made of the query. @internal */\n    readonly checked: CheckJqResult;\n    /** How the query splits, or why it does not; or what went wrong splitting it. @internal */\n    readonly split: JqSplit | { readonly kind: \"failed\"; readonly message: string };\n}\n\n// ─── What a path costs (#1143) ───────────────────────────────────────────────\n\n/** The costs a row is taken at: a split's output kind's, or a re-keyed join's (#942). */\nexport type PlanCostKind = JqSplitCall[\"output\"][\"kind\"] | \"rekey\";\n\n/** What a row of one kind costs, and what holding it takes (#1143). */\nexport interface RowCosts {\n    /** A row's time in one call, in microseconds. */\n    readonly oneCallUs: number;\n    /** A row's time in a piece, in microseconds, the pieces running side by side. */\n    readonly pieceUs: number;\n    /** What one call holds of each row, in bytes, when it holds every row ({@link PlanEstimates.holdsRows}). */\n    readonly heldBytes: number;\n    /** The most a piece holds, in bytes: e3's pieces weigh at most a few of its piece sizes, so a piece's peak does not grow with the dataset. */\n    readonly pieceBytes: number;\n    /** A split call's time after its last piece, in seconds: its output merged and read — a dict's or a set's keys, which may be many. */\n    readonly finishSeconds: number;\n}\n\n/** What the planner takes a run to cost ({@link PLAN_COSTS}). */\nexport interface PlanCosts {\n    /** A one-shot call's own time, in seconds: east-c starting, reading its program and answering. */\n    readonly oneCallSeconds: number;\n    /** A split call's own time, in seconds: e3 launching and ending it, and the builder polling it. */\n    readonly splitSeconds: number;\n    /** e3's time planning a split call, in seconds, for each piece it cuts. */\n    readonly planSecondsPerPiece: number;\n    /** A piece's own time, in seconds: east-c starting and reading its program. */\n    readonly pieceSeconds: number;\n    /** How many pieces the server runs at once, when the options don't say. */\n    readonly cores: number;\n    /** What one call holds before it holds a row, in bytes: east-c, its program and the buffers it reads through. */\n    readonly unitBytes: number;\n    /** What a row costs, by the kind it is taken at. */\n    readonly rows: Readonly<Record<PlanCostKind, RowCosts>>;\n}\n\nconst MiB = 2 ** 20;\n\n/**\n * What the planner takes a run to cost (#1143): the scale test's measures\n * (`E3_QUERY_SCALE=1` with `E3_QUERY_SCALE_ONE_SHOT=1`, #1093) of its\n * benchmark's queries over 0.5 to 29 million orders (18 MB to 1 GB), each as\n * a split call and as the builder's one-shot call, on a Release east-c with\n * 14 cores to run on.\n *\n * @remarks\n * A run's estimates ({@link PlanEstimates}) are, for `R` rows taken at kind\n * `k`, cut into `P` pieces run `C` at a time:\n * - **one call**: `oneCallSeconds + R × oneCallUs[k]`, holding `unitBytes`,\n *   and `R × heldBytes[k]` more when it holds every row;\n * - **a split call**: `splitSeconds + finishSeconds[k] + P × planSecondsPerPiece\n *   + ⌈P / C⌉ × (pieceSeconds + R / P × pieceUs[k])`, each piece holding\n *   `pieceBytes[k]`. A re-keyed join is two calls of `P` pieces each, a row's\n *   cost its two calls'.\n *\n * A stream's first rows (`first`) stop both paths early: one call once it has\n * them, and a split call once the pieces before the rest hold them. Both are\n * taken to read the first `F = min(R, limit)` rows the stream gives, as if\n * each row gave one: one call costs `F × oneCallUs[k]` for its rows, and a\n * split call, which still plans all `P` pieces, runs the `N = ⌈F / (R / P)⌉`\n * pieces that hold them, `⌈N / C⌉` at a time.\n *\n * Each kind's costs lie between those of the benchmark's queries that split\n * into it: a fold's the total of the orders, several totals at once and the\n * top 100 (0.6 to 1.9 µs a row in one call); a dict's revenue by region, by\n * customer and by carrier (2.2 to 7.3 µs); a set's the distinct customers\n * (2.7 µs); an array's the ids of the orders over a total (0.65 µs); a\n * re-keyed join's revenue by carrier's (5 µs in one call, 7.7 µs over its two\n * calls' pieces). A row costs less in a piece than in one call where one call\n * sorts every row and a piece folds it. One call held about 440 B of each\n * order it grouped or joined and 105 B of each customer id it kept distinct,\n * and a piece 10 to 50 MB, whatever the size. A dataset every piece reads\n * whole is not counted apart: its cost is in the measures of the queries that\n * read one, revenue by region the customers.\n */\nexport const PLAN_COSTS: PlanCosts = {\n    oneCallSeconds: 0.05,\n    splitSeconds: 0.15,\n    planSecondsPerPiece: 0.009,\n    pieceSeconds: 0.1,\n    cores: 8,\n    unitBytes: 10 * MiB,\n    rows: {\n        array: { oneCallUs: 0.65, pieceUs: 0.9, heldBytes: 0, pieceBytes: 10 * MiB, finishSeconds: 0.1 },\n        set: { oneCallUs: 2.7, pieceUs: 2.3, heldBytes: 105, pieceBytes: 30 * MiB, finishSeconds: 1 },\n        dict: { oneCallUs: 5, pieceUs: 3.5, heldBytes: 440, pieceBytes: 50 * MiB, finishSeconds: 1 },\n        fold: { oneCallUs: 0.8, pieceUs: 1, heldBytes: 440, pieceBytes: 14 * MiB, finishSeconds: 0.1 },\n        first: { oneCallUs: 0.65, pieceUs: 0.9, heldBytes: 0, pieceBytes: 10 * MiB, finishSeconds: 0.1 },\n        rekey: { oneCallUs: 5, pieceUs: 7.7, heldBytes: 440, pieceBytes: 30 * MiB, finishSeconds: 1.2 },\n    },\n};\n\n/**\n * Whether one call holds every row the pieces' stage makes, by how the\n * pieces' outputs combine ({@link PlanEstimates.holdsRows}).\n */\nfunction holdsEveryRow(combine: JqCombine): boolean {\n    switch (combine.kind) {\n        case \"group\": case \"distinct\": case \"distinct_by\": case \"top\":\n            // A sort, a group or the distinct rows need every row at once.\n            return true;\n        case \"totals\":\n            // A total folds each row as it is made (#1140), but for the last row and the distinct values.\n            return combine.totals.some(total => total.rule === \"last\" || total.rule === \"union\");\n        case \"concat\": case \"reduce\": case \"first\":\n            // The rows a run answers with, which its limits hold small; a reduce's keys; a stream's first rows.\n            return false;\n    }\n}\n\n/**\n * A draft's two paths estimated (#1143), by {@link PLAN_COSTS}.\n *\n * @param split - the query's split\n * @param rekeyed - whether the split call is a re-keyed join's two\n * @param rows - the rows the pieces work through\n * @param bytes - what the heaviest dataset cut weighs, which e3 cuts the pieces by\n * @param cores - how many pieces run at once\n * @param memoryBytes - the memory one call may use, if the options say\n * @returns the estimates\n */\nfunction estimatesOf(split: JqSplitCall, rekeyed: boolean, rows: number, bytes: number, cores: number, memoryBytes: number | null): PlanEstimates {\n    const kind: PlanCostKind = rekeyed ? \"rekey\" : split.output.kind;\n    const row = PLAN_COSTS.rows[kind];\n    const holdsRows = holdsEveryRow(split.stages.combine);\n    const pieces = Math.max(1, Math.ceil(bytes / pieceSizesFor(bytes).target));\n    // A re-keyed join is two calls, each cutting as many pieces, each row passing through both.\n    const calls = rekeyed ? 2 : 1;\n    const units = calls * pieces;\n    // A stream's first rows stop both paths: one call once it has them, a split call once the pieces that hold them have run.\n    const firstRows = split.output.kind === \"first\" ? Math.min(rows, split.output.limit) : null;\n    const read = firstRows ?? rows;\n    const ran = firstRows === null ? units : Math.min(units, Math.max(1, Math.ceil(firstRows * units / Math.max(1, rows))));\n    return {\n        oneCall: {\n            seconds: PLAN_COSTS.oneCallSeconds + read * row.oneCallUs / 1e6,\n            peakBytes: PLAN_COSTS.unitBytes + (holdsRows ? rows * row.heldBytes : 0),\n        },\n        split: {\n            seconds: calls * (PLAN_COSTS.splitSeconds + row.finishSeconds) + units * PLAN_COSTS.planSecondsPerPiece\n                + Math.ceil(ran / cores) * (PLAN_COSTS.pieceSeconds + rows / units * row.pieceUs / 1e6),\n            peakBytes: row.pieceBytes,\n        },\n        over: split.over, rows, firstRows, kind, row, holdsRows, pieces, cores, memoryBytes,\n    };\n}\n\n// ─── Planning ────────────────────────────────────────────────────────────────\n\n/**\n * The most a dataset may weigh and still be read by one call, from the options.\n *\n * @param options - the options\n * @returns `pieceBytes`, or `PIECE_SIZES.min`\n * @throws {RangeError} When `pieceBytes` is not a whole number of bytes.\n */\nfunction pieceBytesOf(options: PlanOptions): number {\n    const bytes = options.pieceBytes ?? PIECE_SIZES.min;\n    if (!Number.isSafeInteger(bytes) || bytes < 0) throw new RangeError(`planQuery: pieceBytes is ${bytes}, not a whole number of bytes`);\n    return bytes;\n}\n\n/**\n * What the estimates take of the server, from the options (#1143): the memory\n * one call may use, and how many pieces run at once.\n *\n * @param options - the options\n * @returns `memoryBytes`, or `null`; and `cores`, or {@link PLAN_COSTS}'\n * @throws {RangeError} When `memoryBytes` is not a whole number of bytes, or\n *   `cores` not a whole number of at least 1.\n */\nfunction serverOf(options: PlanOptions): { memoryBytes: number | null; cores: number } {\n    const memoryBytes = options.memoryBytes ?? null;\n    if (memoryBytes !== null && (!Number.isSafeInteger(memoryBytes) || memoryBytes < 0)) {\n        throw new RangeError(`planQuery: memoryBytes is ${memoryBytes}, not a whole number of bytes`);\n    }\n    const cores = options.cores ?? PLAN_COSTS.cores;\n    if (!Number.isSafeInteger(cores) || cores < 1) throw new RangeError(`planQuery: cores is ${cores}, not a whole number of at least 1`);\n    return { memoryBytes, cores };\n}\n\n/** An error's message. */\nfunction messageOf(err: unknown): string {\n    return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Checks and splits a query: the first half of a plan, which says the data\n * source whose weight decides the path ({@link PlanDraft.over}).\n *\n * @param programs - the query, and what each kind of call runs of it; a\n *   string is all three\n * @param root - the root its data sources make\n * @param options - a call's limits and runner, `pieceBytes`, and what the\n *   estimates take of the server\n * @returns the draft; or, for a query that does not check, the `error` result\n *   a run of it gives, as {@link prepareQuery} gives it\n * @throws {RangeError} When a limit, `pieceBytes`, `memoryBytes` or `cores`\n *   is not a whole number.\n *\n * @remarks\n * The query is checked once, against the whole root, as a one-shot call's is.\n * A `many` query is split with the call's most outputs, so its final function\n * keeps as many as the one-shot translation does, and one more. A split that\n * fails — a gap in the splitter, never a mistake in the query — leaves the\n * query one call, the failure in its explanation.\n */\nexport function draftPlan(programs: PlanPrograms | string, root: QueryRoot, options: PlanOptions = {}): { draft: PlanDraft } | { result: QueryResult } {\n    const all: Required<PlanPrograms> = typeof programs === \"string\"\n        ? { query: programs, oneShot: programs, split: programs }\n        : { query: programs.query, oneShot: programs.oneShot ?? programs.query, split: programs.split ?? programs.query };\n    const { maxOutputs } = queryLimits(options);\n    pieceBytesOf(options);\n    serverOf(options);\n    const checked = checkJq(all.query, root.type, { root: true });\n    if (checked.program === null) {\n        const refused = prepareCheckedQuery(checked, root, options);\n        if (\"result\" in refused) return refused;\n    }\n    let split: PlanDraft[\"split\"];\n    try {\n        split = splitJq(checked, checked.multiplicity === \"many\" ? { maxOutputs } : {});\n    } catch (err) {\n        split = { kind: \"failed\", message: messageOf(err) };\n    }\n    return {\n        draft: {\n            reads: [...checked.reads],\n            over: split.kind === \"split\" ? split.over : undefined,\n            weighs: split.kind === \"split\" ? [...new Set([split.over, ...split.copartitioned, ...(split.rekey === null ? [] : [split.rekey.name])])] : [],\n            programs: all, root, options, checked, split,\n        },\n    };\n}\n\n/**\n * Weighs a draft: the path, by what its datasets weigh, and the call it makes.\n *\n * @param draft - the query, checked and split ({@link draftPlan})\n * @param weights - what the data sources whose weights decide the path\n *   weigh ({@link PlanDraft.weighs}), by name; one not given is not known\n * @param weighing - `tooLarge`: whether the run's one call, which the\n *   estimates chose, answered too large for one answer\n * @returns the plan; or, for a one-shot program that does not check, the\n *   `error` result a run of it gives\n * @throws {TranslationError} When a checked program holds something the\n *   translator cannot express.\n *\n * @remarks\n * A query that runs as one unit is one call. One that splits is one call when\n * the datasets it cuts weigh no more than `pieceBytes` — the heaviest of\n * them, which e3 cuts the pieces by, when others are cut at the same keys —\n * or a weight is not known. A join whose other side weighs more than\n * `pieceBytes` too is re-keyed (#942), rather than read whole by every piece:\n * both sides large and unaligned.\n *\n * Over one piece, the path is chosen by its estimates (#1143,\n * {@link PlanEstimates}): a split call when it is estimated faster than one\n * call, or when one call is estimated to hold more than the options'\n * `memoryBytes`, and one call otherwise. With nothing to estimate — the rows\n * of the dataset the pieces work through not known, or the options' own\n * `pieceBytes`, a server whose pieces are not e3's own sizes — it is a split\n * call, by weight, as before. A run whose one call the estimates chose, and\n * which answered too large for one answer (`tooLarge`), is a split call: its\n * output is read a page at a time (#1113), where one call's never is.\n *\n * A split call's request is built from the split program — in the visual\n * view, the query wrapped to count its rows — which must split as the query\n * does: over the same dataset, into the same output kind, cut at the same\n * keys with the same datasets and re-keying the same join; one that cannot be\n * built is one call, and its explanation says why.\n */\nexport function weighPlan(\n    draft: PlanDraft, weights: ReadonlyMap<string, SourceWeight>, { tooLarge = false }: { readonly tooLarge?: boolean } = {},\n): { plan: QueryPlan } | { result: QueryResult } {\n    const { checked, split, programs, root, options } = draft;\n    const program = checked.source.text;\n    const oneCall = (why: OneCallWhy, pruning: readonly JqPruning[], estimates: PlanEstimates | null = null): { plan: QueryPlan } | { result: QueryResult } => {\n        // The query's own check serves its call when the call runs the query.\n        const prepared = programs.oneShot === programs.query ? prepareCheckedQuery(checked, root, options) : prepareQuery(programs.oneShot, root, options);\n        if (\"result\" in prepared) return prepared;\n        return { plan: { kind: \"one_shot\", prepared: prepared.prepared, explanation: { program, path: { kind: \"one_shot\", why }, estimates, pruning } } };\n    };\n    if (split.kind === \"failed\") return oneCall({ kind: \"unsplit\", over: null, message: split.message }, []);\n    if (split.kind === \"whole\") return oneCall({ kind: \"whole\", reason: split.reason }, split.pruning);\n    const pieceBytes = pieceBytesOf(options);\n    const server = serverOf(options);\n    // e3 cuts the pieces by the heaviest of the datasets partitioned together.\n    let heaviest = split.over;\n    let bytes = -1;\n    for (const name of [split.over, ...split.copartitioned]) {\n        const weighs = weights.get(name)?.bytes;\n        if (weighs === undefined) return oneCall({ kind: \"unweighed\", over: name }, split.pruning);\n        if (weighs > bytes) [heaviest, bytes] = [name, weighs];\n    }\n    if (bytes <= pieceBytes) return oneCall({ kind: \"small\", over: heaviest, bytes, pieceBytes }, split.pruning);\n    // Both sides large and unaligned: the join is re-keyed.\n    const joined = split.rekey === null ? undefined : weights.get(split.rekey.name)?.bytes;\n    const rekey = split.rekey !== null && joined !== undefined && joined > pieceBytes ? split.rekey : null;\n    // The estimates are of the pieces e3 cuts by its own sizes, over the rows its status counts.\n    const rows = weights.get(split.over)?.rows;\n    const estimates = options.pieceBytes === undefined && rows !== undefined\n        ? estimatesOf(split, rekey !== null, rows, bytes, server.cores, server.memoryBytes)\n        : null;\n    let why: SplitWhy = \"weight\";\n    if (estimates !== null) {\n        if (estimates.memoryBytes !== null && estimates.oneCall.peakBytes > estimates.memoryBytes) why = \"memory\";\n        else if (estimates.split.seconds < estimates.oneCall.seconds) why = \"time\";\n        else if (tooLarge) why = \"size\";\n        else return oneCall({ kind: \"faster\", over: split.over }, split.pruning, estimates);\n    }\n    let call: { request: SplitCallRequest; reading: QueryReading } | ({ reading: QueryReading } & RekeyCalls);\n    try {\n        call = splitCallOf(draft, split, rekey !== null);\n    } catch (err) {\n        return oneCall({ kind: \"unsplit\", over: split.over, message: messageOf(err) }, split.pruning);\n    }\n    const explanation: PlanExplanation = {\n        program,\n        path: {\n            kind: \"split\", why, over: split.over, heaviest, bytes, pieceBytes, output: split.output.kind, stages: split.stages,\n            // A re-keyed join reads its other side cut at the same keys, not whole.\n            broadcast: rekey === null ? split.broadcast : split.broadcast.filter(name => name !== rekey.name),\n            copartitioned: split.copartitioned,\n            rekey: rekey === null ? null : { name: rekey.name, key: rekey.key, bytes },\n        },\n        estimates,\n        pruning: split.pruning,\n    };\n    return { plan: \"request\" in call ? { kind: \"split\", ...call, explanation } : { kind: \"rekey\", ...call, explanation } };\n}\n\n/**\n * Plans a run: checks and splits the query, and weighs it — {@link draftPlan},\n * then {@link weighPlan} with the weights of the datasets that decide it.\n *\n * @param programs - the query, and what each kind of call runs of it; a\n *   string is all three\n * @param root - the root its data sources make\n * @param weights - what each data source weighs, by name; one not given is\n *   not known\n * @param options - a call's limits and runner, `pieceBytes`, and what the\n *   estimates take of the server: `memoryBytes` and `cores`\n * @returns the plan: one call, a split call or a re-keyed join's two, what\n *   reading its answer needs, and its explanation; or, for a query that does\n *   not check, the `error` result a run of it gives\n * @throws {RangeError} When a limit, `pieceBytes`, `memoryBytes` or `cores`\n *   is not a whole number.\n *\n * @example\n * ```ts\n * const planned = planQuery(\".orders | group_by(.region) | map({region: .[0].region, revenue: map(.total) | add})\",\n *     root, new Map([[\"orders\", { bytes: 1.4e9, rows: 8_000_000 }]]));\n * if (\"result\" in planned) return planned.result;           // the checker's problems\n * const plan = planned.plan;\n * if (plan.kind === \"split\") {\n *     const { result } = await splitCall(url, repo, workspace, plan.request, { token });\n *     return queryResultOf(plan.reading, result);\n * }\n * if (plan.kind === \"rekey\") {\n *     const first = await splitCall(url, repo, workspace, plan.first, { token });\n *     const join = first.output === null ? undefined : (await splitCall(url, repo, workspace, plan.join(first.output), { token })).result;\n *     return queryResultOf(plan.reading, plan.answer(first.result, join));\n * }\n * return queryResultOf(plan.prepared, await oneShotExecute(url, repo, workspace, plan.prepared.request, { token }));\n * ```\n */\nexport function planQuery(\n    programs: PlanPrograms | string, root: QueryRoot, weights: ReadonlyMap<string, SourceWeight>, options: PlanOptions = {},\n): { plan: QueryPlan } | { result: QueryResult } {\n    const drafted = draftPlan(programs, root, options);\n    if (\"result\" in drafted) return drafted;\n    return weighPlan(drafted.draft, weights);\n}\n\n/**\n * The split call of a draft that splits, or a re-keyed join's two calls: the\n * split program's split, which must split as the query's does — the same\n * dataset into the same output kind, cut at the same keys with the same\n * datasets, re-keying the same join — and the requests and reading.\n *\n * @throws {Error} When the split program does not check, or splits otherwise\n *   than the query.\n */\nfunction splitCallOf(draft: PlanDraft, split: JqSplitCall, rekey: boolean): { request: SplitCallRequest; reading: QueryReading } | ({ reading: QueryReading } & RekeyCalls) {\n    const { programs, root, options } = draft;\n    const { maxOutputs } = queryLimits(options);\n    let checked = draft.checked;\n    let call = split;\n    if (programs.split !== programs.query) {\n        checked = checkJq(programs.split, root.type, { root: true });\n        if (checked.program === null) throw new Error(`the run's split program does not check: ${checked.diagnostics[0]?.message ?? \"\"}`);\n        const wrapped = splitJq(checked, checked.multiplicity === \"many\" ? { maxOutputs } : {});\n        const same = wrapped.kind === \"split\" && wrapped.over === split.over && wrapped.output.kind === split.output.kind\n            && wrapped.copartitioned.join(\"\\n\") === split.copartitioned.join(\"\\n\") && wrapped.rekey?.name === split.rekey?.name;\n        if (!same) {\n            throw new Error(`the run's split program splits otherwise than the query: ${wrapped.kind === \"split\" ? `${wrapped.output.kind} over ${wrapped.over}` : wrapped.reason.code}`);\n        }\n        call = wrapped;\n    }\n    if (!programChecks(checked)) throw new Error(\"the query does not check\");\n    const entry = (name: string) => entryNamed(root, name, \"splitCallRequest\");\n    if (!rekey) return { request: splitCallRequest(call, root, options), reading: { checked, entries: call.inputs.map(input => entry(input.name)), maxOutputs } };\n    // The re-key call reads the dataset, and the join call the rest: what the run read, in that order.\n    const joined = call.inputs.filter(input => input.name !== call.over).map(input => entry(input.name));\n    return { ...rekeyCallRequests(call, root, options), reading: { checked, entries: [entry(call.over), ...joined], maxOutputs } };\n}\n\n// ─── The request ─────────────────────────────────────────────────────────────\n\n/**\n * The split call a query split over a dataset's pieces runs as: the request\n * e3-api-client's `splitCall` (or `splitCallLaunch`, `splitCallExplain`)\n * sends, exactly as the builder sends it.\n *\n * @param split - the query's split (`splitJq`), over a root's data sources\n * @param root - the root: each data source the split reads is an argument at\n *   its path\n * @param options - the call's limits and its runner, as a one-shot call's\n * @returns the request\n * @throws {RangeError} When a limit is not a whole number of at least 1.\n * @throws {Error} When the split reads a root field no data source of the root is.\n *\n * @remarks\n * - `bodyIr` is the piece program, and `then` the final function, when there\n *   is one: each `encodeEastIR(fn.toIR())`, as a one-shot call's body is. The\n *   final function takes the assembled output, then the arguments not\n *   partitioned, as e3 gives it them (#1107).\n * - `args` is one `dataset` argument per input of the split, in its order —\n *   the root fields the query reads, as the translation takes them — at its\n *   data source's path; the one the pieces are cut from, `over`, is\n *   partitioned with no `by`, so any key may start a piece, and so is each of\n *   `copartitioned`, which e3 cuts at the same keys (#942); every other\n *   argument reaches each piece whole.\n * - `output` is the split's output kind: a dict's merge and a fold's combine\n *   encoded as the programs are, and a fold's zero as beast2 at its type; a\n *   stream's first rows a `first` output of their count (#1113).\n * - `runner` is a one-shot call's (`QueryOptions`): east-c given no platform\n *   package, and no program calls a platform function, so a caller who may\n *   read the workspace may launch it.\n * - `limits` are a one-shot call's: no time limit unless the options set one,\n *   so e3 gives the job the server's ceiling (ten minutes on a local server),\n *   as it gives a one-shot call that names none the server's default.\n *\n * @example\n * ```ts\n * const split = splitJq(checkJq(\".orders | map(.total) | add\", root.type, { root: true }));\n * if (split.kind === \"split\") {\n *     const { result } = await splitCall(url, repo, workspace, splitCallRequest(split, root), { token });\n * }\n * ```\n */\nexport function splitCallRequest(split: JqSplitCall, root: QueryRoot, options: QueryOptions = {}): SplitCallRequest {\n    const { limits, runner } = queryLimits(options);\n    const then = split.then();\n    return {\n        bodyIr: encodeEastIR(split.piece().toIR()),\n        args: split.inputs.map(input => ({\n            arg: variant(\"dataset\", entryNamed(root, input.name, \"splitCallRequest\").path),\n            partition: input.name === split.over || split.copartitioned.includes(input.name) ? some({ by: [] }) : none,\n        })),\n        output: outputOf(split.output),\n        then: then === null ? none : some(encodeEastIR(then.toIR())),\n        runner,\n        limits,\n    };\n}\n\n/**\n * A re-keyed join's two split calls (#942), as the planner sends them when\n * both sides of a join weigh more than one piece.\n *\n * @param split - the query's split, whose `rekey` is the join\n * @param root - the root\n * @param options - the calls' limits and their runner, as a one-shot call's\n * @returns the re-key call, the join call over its output, and how their\n *   answers make the run's ({@link RekeyCalls})\n * @throws {Error} When the split re-keys no join, or reads a root field no\n *   data source of the root is.\n *\n * @remarks\n * - **The re-key call** runs `rekey.piece()` over `over` partitioned, into a\n *   dict by the join key whose merge concatenates each key's rows in input\n *   order. Its output is read by its hash, so its answer is asked to be one\n *   byte at most: e3 answers `too_large` with the output's hash beside it.\n * - **The join call** runs `rekey.joinPiece()` over the re-key call's output,\n *   an `object` argument by its hash, and the join's other side, both\n *   partitioned, so e3 cuts them at the same keys; every other argument\n *   reaches each piece whole. Its output kind is the split's, and its final\n *   function `rekey.joinThen()`.\n * - **The answer** is the join call's, with the re-key call's dataset first in\n *   what the run read, as the re-key call pinned it; or the re-key call's own\n *   when it ended without an output.\n */\nexport function rekeyCallRequests(split: JqSplitCall, root: QueryRoot, options: QueryOptions = {}): RekeyCalls {\n    const rekey = split.rekey;\n    if (rekey === null) throw new Error(\"rekeyCallRequests: the split re-keys no join\");\n    const { limits, runner } = queryLimits(options);\n    const path = (name: string) => entryNamed(root, name, \"rekeyCallRequests\").path;\n    const first: SplitCallRequest = {\n        bodyIr: encodeEastIR(rekey.piece().toIR()),\n        args: [{ arg: variant(\"dataset\", path(split.over)), partition: some({ by: [] }) }],\n        output: variant(\"dict\", { merge: some(encodeEastIR(rekey.output.merge().toIR())) }),\n        then: none,\n        runner,\n        limits: some({\n            timeoutMs: limits.type === \"some\" ? limits.value.timeoutMs : none,\n            maxResultBytes: some(1n),\n            maxLogBytes: limits.type === \"some\" ? limits.value.maxLogBytes : none,\n        }),\n    };\n    const piece = encodeEastIR(rekey.joinPiece().toIR());\n    const then = rekey.joinThen();\n    const thenIr = then === null ? none : some(encodeEastIR(then.toIR()));\n    return {\n        first,\n        join: (output) => ({\n            bodyIr: piece,\n            args: rekey.inputs.map(input => input.name === split.over\n                ? { arg: variant(\"object\", output), partition: some({ by: [] }) }\n                : { arg: variant(\"dataset\", path(input.name)), partition: input.name === rekey.name ? some({ by: [] }) : none }),\n            output: outputOf(split.output),\n            then: thenIr,\n            runner,\n            limits,\n        }),\n        answer: (firstResult, joinResult) => ({\n            ...(joinResult ?? firstResult),\n            inputs: [...firstResult.inputs, ...(joinResult?.inputs ?? [])],\n        }),\n    };\n}\n\n/** A split's output kind as a split call's request holds it. */\nfunction outputOf(output: JqSplitCall[\"output\"]): SplitCallRequest[\"output\"] {\n    switch (output.kind) {\n        case \"array\":\n            return variant(\"array\", null);\n        case \"set\":\n            return variant(\"set\", null);\n        case \"dict\":\n            return variant(\"dict\", { merge: some(encodeEastIR(output.merge().toIR())) });\n        case \"fold\":\n            return variant(\"fold\", { combine: encodeEastIR(output.combine().toIR()), zero: encodeBeast2For(output.type)(output.zero as never) });\n        case \"first\":\n            // A stream's first rows, in input order: e3 stops once the pieces before the rest hold them (#1110, #1113).\n            return variant(\"first\", { limit: BigInt(output.limit) });\n    }\n}\n","/**\n * Copyright (c) 2025 Elara AI Pty Ltd\n * Dual-licensed under AGPL-3.0 and commercial license. See LICENSE for details.\n */\n\n/**\n * A query's calls answered in memory (#940, #941), where there is no server:\n * a host that answers a query's calls itself, as `createInMemoryFunctionApi`\n * stands in for a deployed function. The builder's tests run its calls on e3\n * itself (#1376); one uses these as a host of its own would.\n *\n * - **A one-shot call** ({@link createInMemoryQueryCall}), which the builder\n *   makes through it when a `QueryCallProvider` hands it over.\n * - **A split call** ({@link createInMemorySplitCall}), run as e3 runs one:\n *   the partitioned dataset cut into pieces — datasets partitioned together\n *   cut at the same keys — each piece's program run, the pieces' outputs\n *   assembled by the output kind and kept by their hash, which a later call's\n *   `object` argument reads, and the final function run once over them and\n *   the arguments not partitioned (#1107) — through a\n *   `QuerySplitCallProvider`; and its explain, the pieces it cuts with none\n *   run (#1132).\n * - **A data source's status** ({@link createInMemorySourceStatus}): what each\n *   dataset holds and weighs — through a `QuerySourceStatusProvider`.\n *\n * @packageDocumentation\n */\n\nimport {\n    ArrayType, DictType, EastError, SetType, SortedMap, SortedSet,\n    compareFor, decodeBeast2, decodeBeast2For, decodeEastIR, encodeBeast2For, equalFor, fromEastTypeValue, isTypeEqual, none, printFor, sha256Hex, variant,\n    type EastType,\n} from \"@elaraai/east\";\nimport type { SplitCallAnswer } from \"@elaraai/e3-api-client\";\nimport {\n    TreePathType, pathToString,\n    type ExecuteResult, type OneShotRequest, type SplitCallProgress, type SplitCallRequest, type TreePath,\n} from \"@elaraai/e3-types\";\nimport type { QueryCall, QuerySourceStatus, QuerySplitCall, QuerySplitExplain } from \"./hooks.js\";\n\n/**\n * A dataset an in-memory call may read.\n *\n * @property path - Its path in the workspace, as a call's argument names it\n * @property type - Its East type\n * @property value - Its value\n * @property hash - The hash a run pins it at; the SHA-256 of its beast2 bytes when omitted\n * @property bytes - What it weighs in the store, as its status says; its beast2 bytes' length when omitted\n */\nexport interface InMemoryDataset {\n    /** Its path in the workspace, as a call's argument names it. */\n    readonly path: TreePath;\n    /** Its East type. */\n    readonly type: EastType;\n    /** Its value. */\n    readonly value: unknown;\n    /** The hash a run pins it at; the SHA-256 of its beast2 bytes when omitted. */\n    readonly hash?: string;\n    /** What it weighs in the store, in bytes, as its status says; its beast2 bytes' length when omitted. A test weighs a small dataset as a large one with it. */\n    readonly bytes?: number;\n}\n\n/** A dataset held in memory, its bytes encoded and hashed once, when first asked for. */\ninterface HeldDataset extends InMemoryDataset {\n    /** The hash a run pins it at. */\n    readonly hashOf: () => string;\n    /** What it weighs. */\n    readonly bytesOf: () => number;\n}\n\nconst samePath = equalFor(TreePathType);\n\n/** Holds the datasets: each encoded, hashed and weighed once, when first asked. */\nfunction hold(datasets: readonly InMemoryDataset[]): HeldDataset[] {\n    return datasets.map((dataset) => {\n        let encoded: Uint8Array | undefined;\n        let hash = dataset.hash;\n        const bytes = () => (encoded ??= encodeBeast2For(dataset.type)(dataset.value as never));\n        return { ...dataset, hashOf: () => (hash ??= sha256Hex(bytes())), bytesOf: () => dataset.bytes ?? bytes().length };\n    });\n}\n\n/** The output streams of a call that said nothing. */\nconst QUIET = { stdout: \"\", stdoutTruncated: false, stderrTruncated: false } as const;\n\n/** The `invalid` result e3 answers a call it refuses, before anything runs. */\nfunction invalid(message: string): ExecuteResult {\n    return { ...QUIET, outcome: variant(\"invalid\", { diagnostics: [{ message, filename: none, line: none, column: none }] }), stderr: \"\", inputs: [] };\n}\n\n/** How e3 refuses a dataset argument with nothing at its path: as it refuses an unassigned dataset. */\nfunction unassigned(i: number, path: TreePath): string {\n    return `Dataset argument ${i} is not assigned (ref type: unassigned): nothing in memory at ${pathToString(path)}`;\n}\n\n/** A call's largest answer, from its limits; `undefined` when it sets none. */\nfunction maxResultBytes(limits: OneShotRequest[\"limits\"]): bigint | undefined {\n    return limits.type === \"some\" && limits.value.maxResultBytes.type === \"some\" ? limits.value.maxResultBytes.value : undefined;\n}\n\n/** A call's answer, as e3 answers it: beast2 at its type, or `too_large` over the call's limit. */\nfunction answer(type: EastType, value: unknown, limits: OneShotRequest[\"limits\"], inputs: ExecuteResult[\"inputs\"]): ExecuteResult {\n    const bytes = encodeBeast2For(type)(value as never);\n    const limit = maxResultBytes(limits);\n    if (limit !== undefined && BigInt(bytes.length) > limit) {\n        return { ...QUIET, outcome: variant(\"too_large\", { bytes: BigInt(bytes.length), limit }), stderr: \"\", inputs };\n    }\n    return { ...QUIET, outcome: variant(\"success\", { value: bytes }), stderr: \"\", inputs };\n}\n\n/** A body that raised an East error, failed as a runner's run fails: exit code 1, and `Error: <message>` with its places. */\nfunction raised(err: EastError, inputs: ExecuteResult[\"inputs\"]): ExecuteResult {\n    return { ...QUIET, outcome: variant(\"failed\", { exitCode: 1n }), stderr: `Error: ${err.toString()}\\n`, inputs };\n}\n\n/**\n * Builds a one-shot call answered in memory, as e3 answers one: the request's\n * body decoded from its IR and compiled with no platform function — a query's\n * call is platform-free — then called with the value of each dataset its\n * arguments name, each pinned at its hash.\n *\n * @param datasets - The datasets a call may read\n * @returns The call\n *\n * @remarks\n * - **Success**: the answer, beast2 at the body's output type, and each\n *   dataset read with its hash.\n * - **Failed**: a body that raises an East error fails as a runner's run does —\n *   exit code 1, and on stderr `Error: <message>` with each place it was\n *   raised, so the builder places it in the jq.\n * - **Invalid**: an argument naming no dataset here is refused as e3 refuses\n *   an unassigned one (\"Dataset argument 0 is not assigned\"), and an inline\n *   value as one this stand-in does not take.\n * - **Too large**: an answer over the request's `maxResultBytes`.\n *\n * The time limit is not kept: a body runs to its end.\n *\n * @example\n * ```tsx\n * const call = createInMemoryQueryCall([\n *     { path: [variant(\"field\", \"inputs\"), variant(\"field\", \"orders\")], type: ArrayType(Order), value: orders },\n * ]);\n * return <QueryCallProvider call={call}>{surface}</QueryCallProvider>;\n * ```\n */\nexport function createInMemoryQueryCall(datasets: readonly InMemoryDataset[]): QueryCall {\n    const held = hold(datasets);\n    return async (request: OneShotRequest): Promise<ExecuteResult> => {\n        const read: HeldDataset[] = [];\n        for (const [i, arg] of request.args.entries()) {\n            const found = arg.type === \"dataset\" ? held.find(d => samePath(d.path, arg.value)) : undefined;\n            if (found === undefined) {\n                return invalid(arg.type === \"dataset\" ? unassigned(i, arg.value) : `Argument ${i} is an inline value, which an in-memory call does not take`);\n            }\n            read.push(found);\n        }\n        const inputs = read.map(d => ({ path: d.path, hash: d.hashOf() }));\n        const body = decodeEastIR(request.bodyIr);\n        const type = fromEastTypeValue(body.ir.value.type);\n        if (type.type !== \"Function\") throw new Error(\"createInMemoryQueryCall: a call's body is a function\");\n        let value: unknown;\n        try {\n            value = body.compile([])(...read.map(d => d.value));\n        } catch (err) {\n            if (!(err instanceof EastError)) throw err;\n            return raised(err, inputs);\n        }\n        return answer(type.output, value, request.limits, inputs);\n    };\n}\n\n/** Options for {@link createInMemorySplitCall}. */\nexport interface InMemorySplitCallOptions {\n    /**\n     * How many pieces the partitioned dataset is cut into, in order: as near\n     * equal runs of its rows as can be, some empty when there are more pieces\n     * than rows.\n     */\n    readonly pieces: number;\n}\n\n/** A program compiled from IR: a function of its arguments. */\ntype Compiled = (...args: unknown[]) => unknown;\n\n/** A program of a request, decoded and compiled with no platform function, and its type. */\nfunction compiled(ir: Uint8Array, what: string): { fn: Compiled; inputs: EastType[]; output: EastType } {\n    const decoded = decodeEastIR(ir);\n    const type = fromEastTypeValue(decoded.ir.value.type);\n    if (type.type !== \"Function\") throw new Error(`createInMemorySplitCall: the call's ${what} is a function`);\n    return { fn: decoded.compile([]) as Compiled, inputs: type.inputs as EastType[], output: type.output as EastType };\n}\n\n/** A collection cut into `k` pieces in order: runs of its rows, as near equal as can be. */\nfunction cut(value: unknown, type: EastType, k: number): unknown[] {\n    const t = type.type === \"Recursive\" ? type.node as EastType : type;\n    const runs = <T>(rows: readonly T[]): T[][] => Array.from({ length: k }, (_, i) => rows.slice(Math.floor(i * rows.length / k), Math.floor((i + 1) * rows.length / k)));\n    switch (t.type) {\n        case \"Array\":\n            return runs(value as readonly unknown[]);\n        case \"Set\": {\n            const compare = compareFor(t.key as EastType);\n            return runs([...(value as SortedSet<unknown>)]).map(rows => new SortedSet(rows, compare));\n        }\n        case \"Dict\": {\n            const compare = compareFor(t.key as EastType);\n            return runs([...(value as SortedMap<unknown, unknown>).entries()]).map(rows => new SortedMap(rows, compare));\n        }\n        default:\n            throw new Error(`createInMemorySplitCall: a partitioned argument is an Array, a Set or a Dict, not ${t.type}`);\n    }\n}\n\n/** The type a value is cut by: its recursive wrapper read through. */\nfunction opened(type: EastType): EastType {\n    return type.type === \"Recursive\" ? type.node as EastType : type;\n}\n\n/** A dict cut at fences: its entries below the first, then from each fence up to the next, then from the last on; empty pieces after, to `k`. */\nfunction cutAt(value: unknown, type: EastType, fences: readonly unknown[], k: number): unknown[] {\n    const compare = compareFor((opened(type) as EastType & { key: EastType }).key);\n    const entries = [...(value as SortedMap<unknown, unknown>).entries()];\n    return Array.from({ length: k }, (_, i) => {\n        if (i > fences.length) return new SortedMap([], compare);\n        const lo = i === 0 ? undefined : fences[i - 1];\n        const hi = i === fences.length ? undefined : fences[i];\n        return new SortedMap(entries.filter(([key]) => (lo === undefined || compare(key, lo) >= 0) && (hi === undefined || compare(key, hi) < 0)), compare);\n    });\n}\n\n/**\n * The partitioned arguments cut into `k` pieces, by argument, and the one\n * they are cut over: one into runs of its rows; several, which must be dicts\n * keyed alike, at the same keys — the first key of each run of the one whose\n * beast2 bytes weigh the most, as e3 cuts datasets partitioned together by\n * the heaviest.\n *\n * @returns the pieces by argument and the argument they are cut over, by its\n *   position, or why the arguments cannot be cut together\n */\nfunction cutTogether(\n    values: readonly unknown[], types: readonly EastType[], partitioned: readonly number[], k: number,\n): { readonly pieces: Map<number, unknown[]>; readonly over: number } | string {\n    if (partitioned.length === 1) return { pieces: new Map([[partitioned[0]!, cut(values[partitioned[0]!], types[partitioned[0]!]!, k)]]), over: partitioned[0]! };\n    const keys = partitioned.map(i => opened(types[i]!));\n    const first = keys[0]!;\n    if (!keys.every(t => t.type === \"Dict\" && first.type === \"Dict\" && isTypeEqual(t.key as EastType, first.key as EastType))) {\n        return \"arguments partitioned together are dicts keyed by one type: their pieces are cut at the same keys\";\n    }\n    let heaviest = partitioned[0]!;\n    let most = -1;\n    for (const i of partitioned) {\n        const bytes = encodeBeast2For(types[i]!)(values[i] as never).length;\n        if (bytes > most) [heaviest, most] = [i, bytes];\n    }\n    const runs = cut(values[heaviest], types[heaviest]!, k) as SortedMap<unknown, unknown>[];\n    // A run's first key starts its piece; an empty run, and every run after the last key, start none.\n    const fences: unknown[] = [];\n    for (const run of runs.slice(1)) {\n        const start = run.keys().next();\n        if (start.done === true) break;\n        fences.push(start.value);\n    }\n    return { pieces: new Map(partitioned.map(i => [i, cutAt(values[i], types[i]!, fences, k)])), over: heaviest };\n}\n\n/** A split call's arguments, resolved: their values and what each weighs, in argument order, each dataset read with its hash, and which are partitioned. */\ninterface CallArguments {\n    readonly values: readonly unknown[];\n    readonly weights: readonly number[];\n    readonly inputs: ExecuteResult[\"inputs\"];\n    readonly partitioned: readonly number[];\n}\n\n/**\n * A split call answered in memory ({@link createInMemorySplitCall}), and its\n * explain (#1132): what e3's explain of the same call answers, with no piece\n * run.\n */\nexport type InMemorySplitCall = QuerySplitCall & {\n    /** How many pieces a call cuts, the argument they are cut over and what it weighs. */\n    readonly explain: QuerySplitExplain;\n};\n\n/** A stage's progress, as a job reports it. */\nfunction progress(phase: \"partition\" | \"merge\" | \"combine\", done: number, units: number): SplitCallProgress {\n    return { phase: variant(phase, null), done: BigInt(done), units: BigInt(units) };\n}\n\n/**\n * Builds a split call answered in memory, run as e3 runs one: the request's\n * programs decoded and compiled with no platform function — a plan's are\n * platform-free — the partitioned dataset cut into a given number of pieces,\n * each piece's program run with an `emit` that collects what it emits, the\n * pieces' outputs assembled by the output kind, and the final function run\n * once over the assembled output and then the arguments not partitioned, in\n * their order, as e3 gives them (#1107).\n *\n * @param datasets - The datasets a call may read\n * @param options - How many pieces the partitioned dataset is cut into\n * @returns The call, and its `explain`\n *\n * @remarks\n * Each output kind assembles as e3 assembles it (`e3-data-architecture.md`\n * §3.7), a piece at a time and then across the pieces in input order:\n * - `array`: each piece's rows, concatenated;\n * - `set`: their union, in East's order;\n * - `dict`: by key, a key emitted again folded with `merge(key, a, b)` in\n *   emission order — within a piece, then across the pieces; without `merge`,\n *   a key emitted twice fails, naming it;\n * - `first` (#1110): the first `limit` rows an `array` would hold, in input\n *   order — every piece run, where e3 stops once it has them;\n * - `fold`: every value a piece emits folded with `combine`, starting from\n *   `zero`; then the pieces' partials folded the same way.\n *\n * Arguments partitioned together — dicts keyed alike (#942) — are cut at the\n * same keys: the first key of each run of the one whose beast2 bytes weigh\n * the most. The assembled output is kept by the SHA-256 of its beast2 bytes,\n * which the answer gives, and a later call of this stand-in reads it by that\n * hash as an `object` argument, as e3 reads an earlier call's output.\n *\n * With no `then`, the call's value is the assembled output. Its answer is as a\n * one-shot call's: beast2 at the value's type with each dataset argument\n * pinned at its hash, `failed` for an East error with its places on stderr,\n * `invalid` for an argument naming nothing here — a dataset, or an object no\n * call of this stand-in assembled — for arguments that cannot be cut\n * together, or for a final function that takes any other count than the\n * assembled output and the arguments not partitioned, and `too_large` over the\n * request's `maxResultBytes`. It reports\n * each piece done, then the merge or the fold, to `onProgress`, yielding\n * between pieces, and rejects with the signal's reason once abandoned. The\n * time limit is not kept, and its answer has no `report`: e3's says how its\n * units ran, and this stand-in runs none.\n *\n * Its `explain` answers what e3's explain of the same call does, and runs no\n * piece (#1132): how many pieces the call cuts — `pieces`, whatever the data —\n * the argument it cuts them over, by its position — the one partitioned, or of\n * several, the one whose beast2 bytes weigh the most — and what that argument\n * weighs: a dataset's weight as its status says it, else its beast2 bytes. It\n * rejects with an `Error` what the call answers `invalid`, as e3-api-client's\n * `splitCallExplain` does — \"Split call explain refused: …\" — reads an object\n * argument an earlier call of this stand-in assembled, and rejects with the\n * signal's reason once abandoned.\n *\n * @example\n * ```tsx\n * const split = createInMemorySplitCall([{ path: ORDERS, type: OrdersType, value: orders }], { pieces: 7 });\n * return <QuerySplitCallProvider call={split} explain={split.explain}>{surface}</QuerySplitCallProvider>;\n * ```\n */\nexport function createInMemorySplitCall(datasets: readonly InMemoryDataset[], options: InMemorySplitCallOptions): InMemorySplitCall {\n    const pieces = options.pieces;\n    if (!Number.isSafeInteger(pieces) || pieces < 1) throw new RangeError(`createInMemorySplitCall: pieces is ${pieces}, not a whole number of at least 1`);\n    const held = hold(datasets);\n    // The outputs the calls assembled, by hash, and what each weighs: what a later call's `object` argument reads.\n    const stored = new Map<string, { readonly value: unknown; readonly bytes: number }>();\n    /** A call's arguments — a dataset by its path, pinned at its hash; an object by its hash; a value as its bytes say — or why e3 refuses them. */\n    const argumentsOf = (request: SplitCallRequest): CallArguments | string => {\n        const values: unknown[] = [];\n        const weights: number[] = [];\n        const inputs: ExecuteResult[\"inputs\"] = [];\n        const partitioned: number[] = [];\n        for (const [i, { arg, partition }] of request.args.entries()) {\n            if (partition.type === \"some\") partitioned.push(i);\n            if (arg.type === \"dataset\") {\n                const found = held.find(d => samePath(d.path, arg.value));\n                if (found === undefined) return unassigned(i, arg.value);\n                values.push(found.value);\n                weights.push(found.bytesOf());\n                inputs.push({ path: found.path, hash: found.hashOf() });\n            } else if (arg.type === \"value\") {\n                values.push(decodeBeast2(arg.value).value);\n                weights.push(arg.value.length);\n            } else {\n                const output = stored.get(arg.value);\n                if (output === undefined) return `Object argument ${i} names ${arg.value}, which the repository does not hold`;\n                values.push(output.value);\n                weights.push(output.bytes);\n            }\n        }\n        if (partitioned.length === 0) return \"a split call partitions at least one of its arguments: its pieces are cut from it\";\n        if (request.output.type === \"first\" && (request.output.value.limit < 1n || request.output.value.limit > BigInt(Number.MAX_SAFE_INTEGER))) {\n            return `a first call answers from 1 to ${Number.MAX_SAFE_INTEGER} elements: its limit is ${request.output.value.limit}`;\n        }\n        if (request.then.type === \"some\") {\n            // The assembled output, then each argument the pieces do not cut, as e3 gives them (#1107).\n            const arity = compiled(request.then.value, \"final function\").inputs.length;\n            const given = 1 + request.args.length - partitioned.length;\n            const count = (n: number): string => `${n} argument${n === 1 ? \"\" : \"s\"}`;\n            if (arity !== given) return `then takes ${count(arity)}, and the call gives it ${count(given)}: the assembled output, then each argument not partitioned, in order`;\n        }\n        return { values, weights, inputs, partitioned };\n    };\n\n    const call: QuerySplitCall = async (request: SplitCallRequest, { signal, onProgress }): Promise<SplitCallAnswer> => {\n        const refused = (message: string): SplitCallAnswer => ({ result: invalid(message), output: null, report: null });\n        const resolved = argumentsOf(request);\n        if (typeof resolved === \"string\") return refused(resolved);\n        const { values, inputs, partitioned } = resolved;\n\n        const body = compiled(request.bodyIr, \"body\");\n        const emitType = body.inputs.at(-1);\n        if (emitType?.type !== \"Function\") throw new Error(\"createInMemorySplitCall: the body's last parameter is its emit function\");\n        const emitted = emitType.inputs as EastType[];\n        const then = request.then.type === \"some\" ? compiled(request.then.value, \"final function\") : undefined;\n        const output = request.output;\n        const cut = cutTogether(values, body.inputs, partitioned, pieces);\n        if (typeof cut === \"string\") return refused(cut);\n        const cuts = cut.pieces;\n        // The assembled output's hash, once the pieces ran: a final function that fails still has it, as e3's job does.\n        let hash: string | null = null;\n        try {\n            // Each piece, its program run over its piece of every partitioned argument and the others whole.\n            const outputs: unknown[][][] = [];\n            onProgress(progress(\"partition\", 0, pieces));\n            for (let p = 0; p < pieces; p++) {\n                signal.throwIfAborted();\n                const args = values.map((value, i) => cuts.get(i)?.[p] ?? value);\n                const out: unknown[][] = [];\n                body.fn(...args, (...emit: unknown[]) => { out.push(emit); return null; });\n                outputs.push(out);\n                onProgress(progress(\"partition\", p + 1, pieces));\n                // A host sees the progress, and may abandon the call, between pieces.\n                await Promise.resolve();\n            }\n            signal.throwIfAborted();\n            let assembled: unknown;\n            let type: EastType;\n            switch (output.type) {\n                case \"array\":\n                    type = ArrayType(emitted[0]!);\n                    assembled = outputs.flatMap(out => out.map(([row]) => row));\n                    break;\n                case \"first\":\n                    // The first rows in input order, as e3 answers them (#1110): this stand-in runs every piece.\n                    type = ArrayType(emitted[0]!);\n                    assembled = outputs.flatMap(out => out.map(([row]) => row)).slice(0, Number(output.value.limit));\n                    break;\n                case \"set\": {\n                    const key = emitted[0]!;\n                    type = SetType(key);\n                    onProgress(progress(\"merge\", 0, 1));\n                    assembled = new SortedSet(outputs.flatMap(out => out.map(([row]) => row)), compareFor(key));\n                    onProgress(progress(\"merge\", 1, 1));\n                    break;\n                }\n                case \"dict\": {\n                    const [key, value] = [emitted[0]!, emitted[1]!];\n                    type = DictType(key, value);\n                    const merge = output.value.merge.type === \"some\" ? compiled(output.value.merge.value, \"merge\").fn : undefined;\n                    const printKey = printFor(key);\n                    const into = (dict: SortedMap<unknown, unknown>, k: unknown, v: unknown): void => {\n                        if (!dict.has(k)) { dict.set(k, v); return; }\n                        if (merge === undefined) throw new EastError(`the key ${printKey(k as never)} is emitted twice, and the dict output has no merge`);\n                        dict.set(k, merge(k, dict.get(k), v));\n                    };\n                    // Within a piece, in emission order; then across the pieces, in input order.\n                    const perPiece = outputs.map(out => {\n                        const dict = new SortedMap<unknown, unknown>([], compareFor(key));\n                        for (const [k, v] of out) into(dict, k, v);\n                        return dict;\n                    });\n                    onProgress(progress(\"merge\", 0, 1));\n                    const all = new SortedMap<unknown, unknown>([], compareFor(key));\n                    for (const dict of perPiece) for (const [k, v] of dict) into(all, k, v);\n                    onProgress(progress(\"merge\", 1, 1));\n                    assembled = all;\n                    break;\n                }\n                case \"fold\": {\n                    type = emitted[0]!;\n                    const combine = compiled(output.value.combine, \"combine\").fn;\n                    const zero = decodeBeast2For(type)(output.value.zero);\n                    // Each piece's values folded from the zero, then the pieces' partials, in input order.\n                    const partials = outputs.map(out => out.reduce((acc: unknown, [v]) => combine(acc, v), zero));\n                    onProgress(progress(\"combine\", 0, 1));\n                    assembled = partials.reduce((acc: unknown, v) => combine(acc, v), zero);\n                    onProgress(progress(\"combine\", 1, 1));\n                    break;\n                }\n            }\n            // Kept by its hash, as e3 stores a call's output.\n            const bytes = encodeBeast2For(type)(assembled as never);\n            hash = sha256Hex(bytes);\n            stored.set(hash, { value: assembled, bytes: bytes.length });\n            if (then === undefined) return { result: answer(type, assembled, request.limits, inputs), output: hash, report: null };\n            const unpartitioned = values.filter((_, i) => !partitioned.includes(i));\n            return { result: answer(then.output, then.fn(assembled, ...unpartitioned), request.limits, inputs), output: hash, report: null };\n        } catch (err) {\n            if (!(err instanceof EastError)) throw err;\n            return { result: raised(err, inputs), output: hash, report: null };\n        }\n    };\n\n    const explain: QuerySplitExplain = async (request, { signal }) => {\n        signal.throwIfAborted();\n        const args = argumentsOf(request);\n        if (typeof args === \"string\") throw new Error(`Split call explain refused: ${args}`);\n        // Cut as the call cuts, so arguments that cannot be cut together are refused alike.\n        const cut = cutTogether(args.values, compiled(request.bodyIr, \"body\").inputs, args.partitioned, pieces);\n        if (typeof cut === \"string\") throw new Error(`Split call explain refused: ${cut}`);\n        return { pieces: BigInt(pieces), over: BigInt(cut.over), bytes: BigInt(args.weights[cut.over]!) };\n    };\n    return Object.assign(call, { explain });\n}\n\n/**\n * Builds a data source's status answered in memory: how many rows each\n * dataset holds, its hash, and what it weighs — its beast2 bytes' length, or\n * the weight a test gives it.\n *\n * @param datasets - The datasets\n * @returns The status\n *\n * @remarks\n * A list's, a set's or a lookup table's rows are its elements; any other\n * value's are not counted. A path with nothing in memory is refused, as e3\n * refuses a dataset it does not hold.\n *\n * @example\n * ```tsx\n * const status = createInMemorySourceStatus([{ path: ORDERS, type: OrdersType, value: orders }]);\n * return <QuerySourceStatusProvider status={status}>{surface}</QuerySourceStatusProvider>;\n * ```\n */\nexport function createInMemorySourceStatus(datasets: readonly InMemoryDataset[]): QuerySourceStatus {\n    const held = hold(datasets);\n    return async (path: TreePath) => {\n        const found = held.find(d => samePath(d.path, path));\n        if (found === undefined) throw new Error(`createInMemorySourceStatus: nothing in memory at ${pathToString(path)}`);\n        return { rows: rowsOf(found), hash: found.hashOf(), bytes: found.bytesOf() };\n    };\n}\n\n/** How many elements a collection holds; `undefined` for a value that is not one. */\nfunction rowsOf(dataset: InMemoryDataset): number | undefined {\n    switch (dataset.type.type) {\n        case \"Array\": return (dataset.value as readonly unknown[]).length;\n        case \"Set\": return (dataset.value as SortedSet<unknown>).size;\n        case \"Dict\": return (dataset.value as SortedMap<unknown, unknown>).size;\n        default: return undefined;\n    }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;A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