@gaganref/confect-test 10.3.1-fork.91 → 10.3.1-fork.93

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/TestConfect.d.ts +26 -0
  2. package/dist/TestConfect.d.ts.map +1 -1
  3. package/dist/TestConfect.js +9 -1
  4. package/dist/TestConfect.js.map +1 -1
  5. package/dist/internal/Attempt.d.ts +14 -1
  6. package/dist/internal/Attempt.d.ts.map +1 -1
  7. package/dist/internal/Attempt.js +18 -1
  8. package/dist/internal/Attempt.js.map +1 -1
  9. package/dist/internal/ConvexTest.d.ts +26 -1
  10. package/dist/internal/ConvexTest.d.ts.map +1 -1
  11. package/dist/internal/ConvexTest.js +55 -27
  12. package/dist/internal/ConvexTest.js.map +1 -1
  13. package/dist/internal/Execution.d.ts +151 -1
  14. package/dist/internal/Execution.d.ts.map +1 -1
  15. package/dist/internal/Execution.js +731 -214
  16. package/dist/internal/Execution.js.map +1 -1
  17. package/dist/internal/KernelQuery.d.ts +8 -3
  18. package/dist/internal/KernelQuery.d.ts.map +1 -1
  19. package/dist/internal/KernelQuery.js +10 -3
  20. package/dist/internal/KernelQuery.js.map +1 -1
  21. package/dist/internal/KernelRefusal.d.ts +134 -0
  22. package/dist/internal/KernelRefusal.d.ts.map +1 -1
  23. package/dist/internal/KernelRefusal.js +134 -1
  24. package/dist/internal/KernelRefusal.js.map +1 -1
  25. package/dist/internal/Metering.d.ts +186 -0
  26. package/dist/internal/Metering.d.ts.map +1 -0
  27. package/dist/internal/Metering.js +401 -0
  28. package/dist/internal/Metering.js.map +1 -0
  29. package/dist/internal/Redaction.d.ts +142 -0
  30. package/dist/internal/Redaction.d.ts.map +1 -0
  31. package/dist/internal/Redaction.js +448 -0
  32. package/dist/internal/Redaction.js.map +1 -0
  33. package/dist/internal/Snapshot.d.ts +298 -0
  34. package/dist/internal/Snapshot.d.ts.map +1 -0
  35. package/dist/internal/Snapshot.js +532 -0
  36. package/dist/internal/Snapshot.js.map +1 -0
  37. package/dist/internal/Subscriptions.d.ts +13 -0
  38. package/dist/internal/Subscriptions.d.ts.map +1 -1
  39. package/dist/internal/Subscriptions.js +27 -3
  40. package/dist/internal/Subscriptions.js.map +1 -1
  41. package/package.json +3 -3
  42. package/src/TestConfect.ts +63 -4
  43. package/src/internal/Attempt.ts +24 -0
  44. package/src/internal/ConvexTest.ts +135 -38
  45. package/src/internal/Execution.ts +1141 -324
  46. package/src/internal/KernelQuery.ts +17 -6
  47. package/src/internal/KernelRefusal.ts +160 -0
  48. package/src/internal/Metering.ts +520 -0
  49. package/src/internal/Redaction.ts +730 -0
  50. package/src/internal/Snapshot.ts +945 -0
  51. package/src/internal/Subscriptions.ts +34 -4
@@ -1 +1 @@
1
- {"version":3,"file":"Execution.js","names":["Globals.own","KernelQuery.exportSchema","Kernel.empty","Kernel.wallClock","KernelRefusal.RegisteredAfterOpen","KernelRefusal.UnknownStandingSource","Invocation.current","KernelRefusal.StaleAttempt","Scheduling.pending","Scheduling.functions","KernelRefusal.DrainBudgetExceeded","Invocation.unbound","Invocation.bind","Invocation.fresh","Scheduling.stateOf","KernelRefusal.CommitTsNotIncreasing","Kernel.apply","Scheduling.table","Scheduling.row","Kernel.conflict","KernelRefusal.OptimisticConcurrencyControlFailure","KernelQuery.stream","KernelQuery.paginate","KernelRefusal.rowPending","KernelRefusal.requiresBinary","KernelRefusal.ClosedAttempt"],"sources":["../../src/internal/Execution.ts"],"sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport {\n actionGeneric,\n getFunctionAddress,\n mutationGeneric,\n queryGeneric,\n type FunctionReference,\n type GenericSchema,\n type SchemaDefinition,\n type UserIdentity,\n} from \"convex/server\";\nimport { convexToJson, jsonToConvex, type Value } from \"convex/values\";\nimport { KernelAttempt } from \"./Attempt.js\";\nimport * as Clock from \"./Clock.js\";\nimport * as Globals from \"./Globals.js\";\nimport * as Invocation from \"./Invocation.js\";\nimport * as Kernel from \"./Kernel.js\";\nimport * as KernelQuery from \"./KernelQuery.js\";\nimport * as KernelRefusal from \"./KernelRefusal.js\";\nimport type * as ReadSet from \"./ReadSet.js\";\nimport * as Scheduling from \"./Scheduling.js\";\nimport type {\n DocumentId,\n FunctionPath,\n StoredDocument,\n ValidatorJSON,\n} from \"./KernelValues.js\";\nimport {\n createFunctionHandle,\n createTestJwt,\n deserializeConvexErrorData,\n evaluateValue,\n hasPendingValues,\n parseArgs,\n parseFunctionHandle,\n resolveCommittedValues,\n simpleHash,\n tableNameFromId,\n validateFunctionArgs,\n validateReturnValue,\n} from \"./KernelValues.js\";\n\nconst ROOT = \"\";\nconst TYPICAL_CONVEX_ID_LENGTH = 32;\n\ntype Modules = Record<string, () => Promise<any>>;\n\n/**\n * One registered component: its schema, its function modules, each loaded once\n * when the world opens, and its standing sources.\n */\ninterface Component {\n readonly path: string;\n readonly schema: KernelQuery.KernelSchema | null;\n readonly loaders: ReadonlyMap<string, () => Promise<any>>;\n readonly loaded: Map<string, any>;\n /**\n * The functions, as `module:export`, that schedule their own next run. A job\n * that runs one, or that one schedules, is never drain work.\n */\n readonly standing: ReadonlySet<string>;\n}\n\n/**\n * Who is calling: the identity and the request attributes a test accessor set.\n */\nexport interface Caller {\n readonly identity: UserIdentity | null;\n readonly token: string | null;\n readonly ip: string | null;\n readonly userAgent: string | null;\n}\n\nexport const anonymous: Caller = {\n identity: null,\n token: null,\n ip: null,\n userAgent: null,\n};\n\nexport const withIdentity = (\n caller: Caller,\n identity: Partial<UserIdentity>,\n): Caller => {\n const subject = identity.subject ?? \"\" + simpleHash(JSON.stringify(identity));\n const issuer = identity.issuer ?? \"https://convex.test\";\n const tokenIdentifier = identity.tokenIdentifier ?? `${issuer}|${subject}`;\n const full = { ...identity, subject, issuer, tokenIdentifier };\n return { ...caller, identity: full, token: createTestJwt(full) };\n};\n\ninterface Request {\n readonly ip: string | null;\n readonly userAgent: string | null;\n readonly requestId: string;\n readonly scheduledFunctionId: string | null;\n readonly authToken: string | null;\n}\n\ntype UdfType = \"query\" | \"mutation\" | \"action\";\n\n/**\n * How a prepared attempt's function ended.\n */\nexport type Outcome =\n | { readonly _tag: \"returned\"; readonly value: Value }\n | { readonly _tag: \"failed\"; readonly error: unknown };\n\n/**\n * A mutation attempt run to its commit point and held until `apply`.\n */\nexport interface HeldAttempt {\n readonly id: string;\n readonly request: string;\n readonly number: Invocation.Attempt;\n readonly snapshot: Kernel.Version;\n readonly reads: ReadonlyArray<ReadSet.Read>;\n readonly outcome: Outcome;\n}\n\n/**\n * What `apply` did with a held attempt. A conflict discards the attempt and\n * holds exactly one next attempt, run against the latest commit. Nothing is\n * retried until that one is applied in turn.\n */\nexport type KernelApply =\n | {\n readonly kind: \"applied\";\n readonly version: Kernel.Version;\n readonly commitTs: bigint;\n readonly result: Value;\n }\n | { readonly kind: \"conflict\"; readonly next: HeldAttempt }\n | {\n readonly kind: \"exhausted\";\n readonly error: KernelRefusal.OptimisticConcurrencyControlFailure;\n }\n | { readonly kind: \"refused\"; readonly tag: string; readonly error: unknown };\n\n/**\n * One top-level query run and every dependency it took: the commit and reads it\n * read, whether it asked for the caller's identity, the pinned time it read and\n * the end of its paginated read.\n */\nexport interface QueryRun {\n readonly outcome: Outcome;\n readonly snapshot: Kernel.Version;\n readonly reads: ReadonlyArray<ReadSet.Read>;\n readonly observedIdentity: boolean;\n /**\n * The pinned time the query read, or `null` when it never read the time.\n */\n readonly time: number | null;\n /**\n * Where the query's paginated read ended, or `null` when it ran none. A rerun\n * ends its page there, as the binary's query journal does.\n */\n readonly journal: string | null;\n}\n\n/**\n * The one paginated read a query and its nested calls may run. `journal` is\n * where a previous run's page ended, and `end` where this run's page ends.\n */\ninterface Pagination {\n calls: number;\n readonly journal: string | null;\n end: string | null;\n}\n\n/**\n * A top-level query whose attempt and page the caller keeps, at a pinned start\n * time or the kernel's time now.\n */\ninterface TopQuery {\n readonly attempt: KernelAttempt;\n readonly pagination: Pagination;\n readonly startTime: number | undefined;\n}\n\ninterface Held {\n readonly view: HeldAttempt;\n readonly attempt: KernelAttempt;\n readonly again: (number: Invocation.Attempt) => Promise<Held>;\n}\n\nconst lastAttempt: Invocation.Attempt = 5;\n\nconst tagOf = (error: unknown): string => {\n const tagged = (value: unknown): value is { readonly _tag: string } =>\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { _tag?: unknown })._tag === \"string\";\n const data = (error as { data?: unknown } | null)?.data;\n if (tagged(data)) return data._tag;\n if (tagged(error)) return error._tag;\n return error instanceof Error ? error.name : \"Error\";\n};\n\n/**\n * One running function. Queries and mutations read and write through their\n * attempt. Every async syscall of a query or a mutation, nested calls included,\n * takes its turn on `turn` in the order the function made it.\n */\ninterface Execution {\n readonly world: World;\n readonly componentPath: string;\n readonly udfPath: string;\n readonly udfType: UdfType;\n readonly attempt: KernelAttempt | undefined;\n readonly identity: UserIdentity | null;\n readonly request: Request;\n /**\n * The kernel's time when the outermost query or mutation began. Its nested\n * calls share it, and `Date` answers it inside them.\n */\n readonly startTime: number;\n readonly pagination: Pagination | undefined;\n readonly turn: Turn;\n}\n\n/**\n * A queue that runs one task at a time, in the order they were taken.\n */\nclass Turn {\n private tail: Promise<unknown> = Promise.resolve();\n\n take<A>(task: () => A | Promise<A>): Promise<A> {\n const result = this.tail.then(task);\n this.tail = result.then(\n () => undefined,\n () => undefined,\n );\n return result;\n }\n\n /**\n * Resolves once every task taken so far has settled, including the tasks\n * taken while waiting.\n */\n idle(): Promise<void> {\n const tail = this.tail;\n return tail.then(() => (this.tail === tail ? undefined : this.idle()));\n }\n}\n\n/**\n * A function's invocation finishes once its handler returned and every syscall\n * it started has run. On the binary a query or mutation keeps running the\n * syscalls in its queue after its promise resolves, then returns (`run_inner`\n * in `crates/isolate/src/environment/udf/mod.rs`, 1.49), so an unawaited write\n * still lands in its own transaction.\n */\nconst settled = <A>(execution: Execution, result: A): Promise<A> =>\n execution.turn.idle().then(() => result);\n\nconst executions = new AsyncLocalStorage<Execution>();\n\n/**\n * Run a function's code as `execution`, with its own copy of the globals a test\n * invocation pins.\n */\nconst enter = <A>(execution: Execution, run: () => A): A => {\n installConvexGlobal();\n return Globals.own(() => executions.run(execution, run));\n};\nconst kernelBrand = Symbol.for(\"@confect/test/Kernel\");\n\n/**\n * The time `Date` answers inside a kernel invocation: a query's or mutation's\n * start, or the clock as it runs in an action. Outside one, none. A query or\n * mutation that reads it takes a dependency on that time.\n */\nconst pinnedTime = (): number | undefined => {\n const execution = executions.getStore();\n if (execution === undefined) return undefined;\n if (execution.udfType === \"action\") return execution.world.now();\n execution.attempt?.observeTime(execution.startTime);\n return execution.startTime;\n};\n\n/**\n * How many jobs one drain or advance runs before it gives up, as convex-test's\n * `finishAllScheduledFunctions` defaults to.\n */\nconst defaultBudget = 100;\n\nconst current = (): Execution => {\n const execution = executions.getStore();\n if (execution === undefined) {\n throw new Error(\n \"A Convex syscall ran outside any function the test kernel started.\",\n );\n }\n return execution;\n};\n\nlet nextRequestId = 0;\nconst newRequest = (caller: Caller): Request => ({\n ip: caller.ip,\n userAgent: caller.userAgent,\n requestId: `kernel-request-${nextRequestId++}`,\n scheduledFunctionId: null,\n authToken: caller.token,\n});\n\n/**\n * A scheduled call is a request of its own: no caller's attributes, and its\n * job's ID.\n */\nconst jobRequest = (jobId: DocumentId): Request => ({\n ...newRequest(anonymous),\n scheduledFunctionId: jobId,\n});\n\nconst findModulesRoot = (paths: ReadonlyArray<string>): string => {\n const generated = paths.find((path) => path.includes(\"_generated\"));\n if (generated === undefined) {\n throw new Error(\n 'Could not find the \"_generated\" directory, make sure to run ' +\n \"`npx convex dev` or `npx convex codegen`. Make sure your \" +\n '`import.meta.glob` includes the files in the \"_generated\" directory',\n );\n }\n return generated.split(\"_generated\", 2)[0]!;\n};\n\nconst makeComponent = (\n path: string,\n schema: SchemaDefinition<GenericSchema, boolean> | null | undefined,\n modules: Modules,\n standing: ReadonlyArray<string> = [],\n): Component => {\n const root = findModulesRoot(Object.keys(modules));\n const relative = Object.entries(modules)\n .filter(([key]) => key.startsWith(root))\n .map(([key, load]) => [key.slice(root.length), load] as const);\n const nested = relative\n .map(([file]) => file)\n .filter((file) => file.endsWith(\"/convex.config.ts\"))\n .map((file) => file.slice(0, -\"convex.config.ts\".length));\n return {\n path,\n schema: KernelQuery.exportSchema(schema),\n loaders: new Map(\n relative\n .filter(\n ([file]) =>\n isFunctionModule(file) &&\n !nested.some((dir) => file.startsWith(dir)),\n )\n .map(([file, load]) => [file.replace(/\\.[^.]+$/, \"\"), load]),\n ),\n loaded: new Map(),\n standing: new Set(standing),\n };\n};\n\nconst entryExtensions = [\n \".js\",\n \".mjs\",\n \".cjs\",\n \".ts\",\n \".tsx\",\n \".mts\",\n \".cts\",\n \".jsx\",\n];\n\n/**\n * Whether Convex's bundler deploys this file as a function module, by the rule\n * `entryPoints` applies in `convex/src/bundler/index.ts` (1.49). A test file, a\n * schema, a config and `_generated` never reach the binary, so the kernel\n * neither loads them nor resolves a function in them.\n */\nconst isFunctionModule = (file: string): boolean => {\n const base = file.split(\"/\").pop()!;\n return (\n entryExtensions.some((extension) => file.endsWith(extension)) &&\n !file.startsWith(\"_generated/\") &&\n !base.startsWith(\".\") &&\n !base.startsWith(\"#\") &&\n base !== \"schema.ts\" &&\n base !== \"schema.js\" &&\n (base.match(/\\./g) ?? []).length <= 1 &&\n !file.includes(\" \")\n );\n};\n\nconst unregistered = (world: World, componentPath: string) => {\n const registered = [...world.components.keys()].filter((p) => p !== ROOT);\n return new Error(\n `Component \"${componentPath}\" is not registered on this test backend. ` +\n (registered.length === 0\n ? \"No components have been registered.\"\n : `Registered components: ${registered.map((p) => `\"${p}\"`).join(\", \")}.`),\n );\n};\n\ntype FunctionAddress = {\n readonly name?: string | undefined;\n readonly reference?: string | undefined;\n readonly functionHandle?: string | undefined;\n};\n\n/**\n * Where an address points, read from the calling component.\n */\nconst functionPathOf = (\n address: FunctionAddress,\n from: string,\n): FunctionPath => {\n if (address.functionHandle !== undefined) {\n return parseFunctionHandle(address.functionHandle);\n }\n if (address.name !== undefined) {\n return { udfPath: address.name, componentPath: from };\n }\n if (address.reference !== undefined) {\n // \"_reference/childComponent/<child>/path/to/file/fn\"\n const parts = address.reference.split(\"/\");\n const child = parts[2]!;\n const rest = parts.slice(3);\n return {\n componentPath: from.length > 0 ? `${from}/${child}` : child,\n udfPath: `${rest.slice(0, -1).join(\"/\")}:${rest[rest.length - 1]}`,\n };\n }\n throw new Error(\"Function address not supported\");\n};\n\nconst pathOfReference = (\n reference: FunctionReference<any, any, any, any> | string,\n from: string,\n) =>\n functionPathOf(getFunctionAddress(reference as any) as FunctionAddress, from);\n\ninterface Resolved {\n readonly func: any;\n readonly handler: (ctx: any, args: any) => any;\n readonly args: ValidatorJSON;\n readonly returns: ValidatorJSON | null;\n}\n\nconst kindCheck = {\n query: \"isQuery\",\n mutation: \"isMutation\",\n action: \"isAction\",\n} as const;\n\n/**\n * A test backend: its registered components and the kernel state they share.\n */\nexport class World {\n readonly components = new Map<string, Component>();\n state: Kernel.State = Kernel.empty;\n private opened: Promise<void> | undefined;\n private nextDocId = 10000;\n private lastCreationTime = 0;\n private nextQueryId = 1;\n private readonly queries = new Map<number, Iterator<any>>();\n private readonly holding = new Map<string, Held>();\n private nextAttemptId = 1;\n /**\n * The latest deadline time has been advanced to. The clock never reads\n * earlier.\n */\n private floor = Number.NEGATIVE_INFINITY;\n private readonly targets = new Map<DocumentId, Scheduling.Target>();\n\n constructor(\n schema: SchemaDefinition<GenericSchema, boolean> | null | undefined,\n modules: Modules,\n private readonly runtime: Kernel.KernelRuntime = Kernel.wallClock(),\n ) {\n installConvexGlobal();\n Clock.install(pinnedTime, () => executions.getStore() !== undefined);\n this.components.set(ROOT, makeComponent(ROOT, schema, modules));\n }\n\n register(\n componentPath: string,\n schema: SchemaDefinition<GenericSchema, boolean>,\n modules: Modules,\n standing: ReadonlyArray<string> = [],\n ) {\n if (this.opened !== undefined) {\n throw new KernelRefusal.RegisteredAfterOpen({\n componentPath,\n message: `Component \"${componentPath}\" was registered after the test backend opened. Register every component before the first call.`,\n });\n }\n this.components.set(\n componentPath,\n makeComponent(componentPath, schema, modules, standing),\n );\n }\n\n /**\n * Load every registered module of every component, once, before any function\n * runs, then check that each standing source names an exported function.\n */\n open(): Promise<void> {\n this.opened ??= Promise.all(\n Array.from(this.components.values(), (component) =>\n Promise.all(\n Array.from(component.loaders, ([path, load]) =>\n load().then((module) => component.loaded.set(path, module)),\n ),\n ),\n ),\n ).then(() => this.checkStanding());\n return this.opened;\n }\n\n /**\n * Refuse a standing source no module of its component exports.\n */\n private checkStanding() {\n for (const component of this.components.values()) {\n for (const name of component.standing) {\n const [modulePath, exportName = \"default\"] = name.split(\":\");\n const func = component.loaded.get(modulePath!)?.[exportName];\n if (func?.isMutation !== true && func?.isAction !== true) {\n throw new KernelRefusal.UnknownStandingSource({\n componentPath: component.path,\n name,\n message: `Component \"${component.path}\" declares \"${name}\" standing, but exports no mutation or action by that name. Name the self-rescheduling function as module:export.`,\n });\n }\n }\n }\n }\n\n /**\n * The kernel's time: the runtime's, never earlier than the latest deadline\n * time was advanced to.\n */\n now(): number {\n return Math.max(this.runtime.now(), this.floor);\n }\n\n private component(componentPath: string): Component {\n const component = this.components.get(componentPath);\n if (component === undefined) throw unregistered(this, componentPath);\n return component;\n }\n\n private resolve(functionPath: FunctionPath, kind: UdfType | \"any\"): Resolved {\n const [modulePath, maybeExport] = functionPath.udfPath.split(\":\") as [\n string,\n string | undefined,\n ];\n const exportName = maybeExport ?? \"default\";\n const component = this.component(functionPath.componentPath);\n const module = component.loaded.get(modulePath);\n if (module === undefined) {\n throw new Error(`Could not find module for: \"${modulePath}\"`);\n }\n const func = module[exportName];\n if (func === undefined) {\n throw new Error(\n `Expected a Convex function exported from module \"${modulePath}\" as \\`${exportName}\\`, but there is no such export.`,\n );\n }\n const handler = \"_handler\" in func ? func._handler : func;\n if (typeof handler !== \"function\") {\n throw new Error(\n `Expected a Convex function exported from module \"${modulePath}\" as \\`${exportName}\\`, but got: ${func}`,\n );\n }\n if (kind !== \"any\" && !func[kindCheck[kind]]) {\n throw new Error(\n `Expected a ${kind} function, but the function exported from module \"${modulePath}\" as \\`${exportName}\\` is not a ${kind}.`,\n );\n }\n const args = JSON.parse(func.exportArgs()) as ValidatorJSON;\n if (args.type !== \"object\" && args.type !== \"any\") {\n throw new Error(\n `Invalid JSON returned from ${modulePath}.js:${exportName}.exportArgs(): ` +\n `Args validator must be an object or any`,\n );\n }\n return { func, handler, args, returns: JSON.parse(func.exportReturns()) };\n }\n\n // Calls from the test.\n\n query(caller: Caller, reference: any, args: any): Promise<any> {\n return this.open().then(() => {\n const from = { caller, request: newRequest(caller) };\n return typeof reference === \"function\"\n ? this.runQuery(\n { componentPath: ROOT, udfPath: \"inline\" },\n { handler: reference, args: { type: \"any\" }, returns: null },\n args ?? {},\n from,\n )\n : this.queryAt(pathOfReference(reference, ROOT), args, from);\n });\n }\n\n mutation(caller: Caller, reference: any, args: any): Promise<any> {\n return this.open().then(() => {\n const from = { caller, request: newRequest(caller) };\n return typeof reference === \"function\"\n ? this.runMutation(\n { componentPath: ROOT, udfPath: \"inline\" },\n { handler: reference, args: { type: \"any\" }, returns: null },\n args ?? {},\n from,\n )\n : this.mutationAt(pathOfReference(reference, ROOT), args, from);\n });\n }\n\n action(caller: Caller, reference: any, args: any): Promise<any> {\n return this.open().then(() => {\n const from = { caller, request: newRequest(caller) };\n return typeof reference === \"function\"\n ? this.runAction(\n { componentPath: ROOT, udfPath: \"inline\" },\n { handler: reference, args: { type: \"any\" }, returns: null },\n args ?? {},\n from,\n )\n : this.actionAt(pathOfReference(reference, ROOT), args, from);\n });\n }\n\n run(\n caller: Caller,\n componentPath: string,\n handler: (ctx: any) => any,\n ): Promise<any> {\n return this.open().then(() => {\n this.component(componentPath);\n return this.runMutation(\n { componentPath, udfPath: \"custom\" },\n { handler, args: { type: \"any\" }, returns: null },\n {},\n { caller, request: newRequest(caller) },\n );\n });\n }\n\n // Held attempts.\n\n /**\n * Run a mutation to its commit point and hold it as attempt 1.\n */\n prepare(caller: Caller, reference: any, args: any): Promise<HeldAttempt> {\n return this.open().then(() => {\n const functionPath = pathOfReference(reference, ROOT);\n const resolved = this.resolve(functionPath, \"mutation\");\n validateFunctionArgs(resolved.args, args ?? {}, functionPath, false);\n return this.prepareMutation(\n functionPath,\n resolved,\n args,\n { caller, request: newRequest(caller) },\n 1,\n Invocation.current(),\n ).then((held) => held.view);\n });\n }\n\n apply(id: string): Promise<KernelApply> {\n const held = this.holding.get(id);\n return held === undefined\n ? Promise.reject(\n new KernelRefusal.StaleAttempt({\n id,\n message: `The test kernel holds no attempt \"${id}\". It was already applied, or never prepared.`,\n }),\n )\n : this.applyHeld(held);\n }\n\n /**\n * The held attempts, oldest first.\n */\n held(): ReadonlyArray<HeldAttempt> {\n return Array.from(this.holding.values(), (held) => held.view);\n }\n\n // Subscribed queries.\n\n /**\n * Run a query at the latest commit as a subscription runs it, under `caller`,\n * and return its answer with every dependency it took. `time` pins the time\n * it reads, the kernel's time now by default. `journal` ends its paginated\n * read where an earlier run's ended.\n */\n subscribed(\n caller: Caller,\n reference: any,\n args: any,\n pinned: { readonly time?: number; readonly journal: string | null },\n ): Promise<QueryRun> {\n return this.open().then(() => {\n const functionPath = pathOfReference(reference, ROOT);\n const resolved = this.resolve(functionPath, \"query\");\n validateFunctionArgs(resolved.args, args ?? {}, functionPath, false);\n const top: TopQuery = {\n attempt: new KernelAttempt(this.state),\n pagination: { calls: 0, journal: pinned.journal, end: null },\n startTime: pinned.time,\n };\n const run = (outcome: Outcome): QueryRun => ({\n outcome,\n snapshot: top.attempt.snapshot.version,\n reads: top.attempt.reads,\n observedIdentity: top.attempt.observedIdentity,\n time: top.attempt.observedTime,\n journal: pinned.journal ?? top.pagination.end,\n });\n return this.runQuery(\n functionPath,\n resolved,\n args,\n { caller, request: newRequest(caller) },\n false,\n top,\n ).then(\n (value: Value) => run({ _tag: \"returned\", value }),\n (error: unknown) => run({ _tag: \"failed\", error }),\n );\n });\n }\n\n // Scheduled functions, on the kernel's clock.\n\n /**\n * The committed pending jobs, earliest deadline first.\n */\n jobs(): ReadonlyArray<Scheduling.Job> {\n return Scheduling.pending(this.state, this.targets).map(\n ({ id, componentPath, name, scheduledTime, standing }) => ({\n id,\n componentPath,\n name,\n scheduledTime,\n standing,\n }),\n );\n }\n\n /**\n * Move the clock forward `ms`, running every job whose deadline falls on the\n * way, in deadline order, each starting at its deadline. Jobs those jobs\n * schedule inside the window run too. `advance(0)` runs what is due now and\n * crosses no future deadline.\n */\n advance(ms: number, budget = defaultBudget): Promise<void> {\n return this.open().then(() => {\n const until = this.now() + ms;\n return this.walk(\n (pending) => pending.filter((job) => job.scheduledTime <= until),\n budget,\n ).then(() => this.raiseFloor(until));\n });\n }\n\n /**\n * Run jobs, earliest deadline first and each at its deadline, until only\n * standing jobs are pending. Every job run counts against `budget`.\n */\n drain(budget = defaultBudget): Promise<void> {\n return this.open().then(() =>\n this.walk((pending) => pending.filter((job) => !job.standing), budget),\n );\n }\n\n /**\n * Run the first of `select(pending)` until it is empty, moving the clock to\n * each job's deadline as it starts.\n */\n private walk(\n select: (pending: Array<Scheduling.Due>) => Array<Scheduling.Due>,\n budget: number,\n ): Promise<void> {\n const step = (ran: number): Promise<void> => {\n const left = select(Scheduling.pending(this.state, this.targets));\n const next = left[0];\n if (next === undefined) return Promise.resolve();\n if (ran === budget) {\n const pending = Scheduling.functions(left);\n return Promise.reject(\n new KernelRefusal.DrainBudgetExceeded({\n budget,\n pending,\n message: `Scheduled functions ran ${budget} jobs and work remains: ${pending\n .map(({ componentPath, name }) =>\n componentPath === ROOT ? name : `${name} in \"${componentPath}\"`,\n )\n .join(\n \", \",\n )}. A function that schedules its own next run never lets the drain end, so its kit declares it with registerComponent's \\`standing\\` option.`,\n }),\n );\n }\n this.raiseFloor(next.scheduledTime);\n return this.runJob(next).then(() => step(ran + 1));\n };\n return step(0);\n }\n\n private raiseFloor(to: number) {\n this.floor = Math.max(this.floor, to);\n }\n\n /**\n * Run one pending job as its own request, moving its row through in progress\n * to success or failed. `walk` picks it from the committed pending jobs and\n * starts it in the same turn, so no cancel can land in between. The job runs\n * as a fresh invocation of the world that scheduled it, whatever invocation\n * the drain itself runs under.\n */\n private runJob(job: Scheduling.Due): Promise<void> {\n this.commitNow((attempt) => {\n const doc = attempt.get(job.componentPath, job.id)!;\n attempt.write(job.componentPath, job.id, {\n ...doc,\n state: { kind: \"inProgress\" },\n });\n });\n const request = jobRequest(job.id);\n const from: From = { caller: anonymous, request };\n const run = () =>\n Promise.resolve().then(() => {\n const { func } = this.resolve(job.target, \"any\");\n return func.isQuery\n ? this.queryAt(job.target, job.args, from)\n : func.isMutation\n ? this.mutationAt(job.target, job.args, from)\n : this.actionAt(job.target, job.args, from);\n });\n return (\n job.world === undefined\n ? Invocation.unbound(run)\n : Invocation.bind(\n Invocation.fresh(job.world, job.target.componentPath, request),\n run,\n )\n )\n .then(\n (): Scheduling.JobState => ({ kind: \"success\" }),\n (error: unknown): Scheduling.JobState => ({\n kind: \"failed\",\n error: error instanceof Error ? error.message : String(error),\n }),\n )\n .then((state) =>\n this.commitNow((attempt) => {\n const doc = attempt.get(job.componentPath, job.id);\n if (doc === null || Scheduling.stateOf(doc).kind !== \"inProgress\")\n return;\n attempt.write(job.componentPath, job.id, {\n ...doc,\n state,\n completedTime: this.now(),\n });\n }),\n );\n }\n\n /**\n * Write through a fresh attempt and publish it at once, as the scheduler does\n * for an action's schedule and a job's state. Nothing runs between the\n * snapshot and the commit, so no other commit can conflict with it.\n */\n private commitNow<A>(write: (attempt: KernelAttempt) => A): A {\n const attempt = new KernelAttempt(this.state);\n const result = write(attempt);\n this.publishWrites(attempt.writes());\n return result;\n }\n\n /**\n * Publish `writes` as the next commit, at the runtime's timestamp for it. No\n * writes publish nothing and ask the runtime for no timestamp, which answers\n * the latest commit's.\n */\n private publishWrites(writes: ReadonlyArray<Kernel.Write>): bigint {\n if (writes.length === 0) return this.state.commitTs;\n const commitTs = this.runtime.commitTs(this.state.version + 1);\n if (commitTs <= this.state.commitTs) {\n throw new KernelRefusal.CommitTsNotIncreasing({\n version: this.state.version + 1,\n previous: this.state.commitTs,\n commitTs,\n message: `The runtime answered commit timestamp ${commitTs} for version ${this.state.version + 1}, which is not greater than the previous commit's ${this.state.commitTs}.`,\n });\n }\n this.state = Kernel.apply(this.state, writes, commitTs);\n return commitTs;\n }\n\n /**\n * Write a pending job into `attempt`, so the job exists only once that\n * attempt publishes. A job that a standing function schedules, or that runs\n * one, is standing.\n */\n private scheduleJob(\n attempt: KernelAttempt,\n execution: Execution,\n args: any,\n ): DocumentId {\n const target = functionPathOf(args, execution.componentPath);\n this.component(target.componentPath);\n const jobArgs = jsonToConvex(args.args);\n if (hasPendingValues(jobArgs)) {\n throw new Error(\n `Invalid arguments for \"${target.udfPath}\": a scheduled function cannot take an unresolved placeholder value.`,\n );\n }\n const id = this.generateId(Scheduling.table);\n attempt.write(\n execution.componentPath,\n id,\n Scheduling.row(\n id,\n this.creationTime(execution.startTime),\n target.udfPath,\n jobArgs,\n args.ts * 1000,\n ),\n );\n this.targets.set(id, {\n functionPath: target,\n standing:\n this.isStanding({\n componentPath: execution.componentPath,\n udfPath: execution.udfPath,\n }) || this.isStanding(target),\n world: Invocation.current()?.world,\n });\n return id;\n }\n\n /**\n * Cancel a job that has not finished. A finished job stays as it ended.\n */\n private cancelJob(attempt: KernelAttempt, componentPath: string, id: any) {\n validateId(Scheduling.table, id);\n attempt.readDocument(componentPath, id);\n const doc = attempt.get(componentPath, id);\n if (doc === null) {\n throw new Error(`Patch on non-existent document with ID \"${id}\"`);\n }\n const { kind } = Scheduling.stateOf(doc);\n if (kind === \"pending\" || kind === \"inProgress\") {\n attempt.write(componentPath, id, { ...doc, state: { kind: \"canceled\" } });\n }\n }\n\n private isStanding({ componentPath, udfPath }: FunctionPath): boolean {\n return this.components.get(componentPath)?.standing.has(udfPath) ?? false;\n }\n\n // Calls by address, from the test or from a running function.\n\n private queryAt(\n functionPath: FunctionPath,\n args: any,\n from: From,\n snapshotOnly = false,\n ) {\n const resolved = this.resolve(functionPath, \"query\");\n validateFunctionArgs(\n resolved.args,\n args ?? {},\n functionPath,\n from.parent?.attempt !== undefined,\n );\n return this.runQuery(functionPath, resolved, args, from, snapshotOnly);\n }\n\n private mutationAt(functionPath: FunctionPath, args: any, from: From) {\n const resolved = this.resolve(functionPath, \"mutation\");\n validateFunctionArgs(\n resolved.args,\n args ?? {},\n functionPath,\n from.parent?.attempt !== undefined,\n );\n return this.runMutation(functionPath, resolved, args, from);\n }\n\n private actionAt(functionPath: FunctionPath, args: any, from: From) {\n const resolved = this.resolve(functionPath, \"action\");\n validateFunctionArgs(resolved.args, args ?? {}, functionPath, false);\n return this.runAction(functionPath, resolved, args, from);\n }\n\n // Runners.\n\n private execution(\n functionPath: FunctionPath,\n udfType: UdfType,\n attempt: KernelAttempt | undefined,\n from: From,\n pagination: Pagination | undefined,\n startTime?: number,\n ): Execution {\n // A function in a component runs with no identity, whoever called it, as\n // Convex gives a component no `ctx.auth` of the caller's. A nested call in\n // the host takes its parent's identity, even when that is none.\n const identity =\n functionPath.componentPath !== ROOT\n ? null\n : from.parent !== undefined\n ? from.parent.identity\n : from.caller.identity;\n return {\n world: this,\n componentPath: functionPath.componentPath,\n udfPath: functionPath.udfPath,\n udfType,\n attempt,\n identity,\n request: from.request,\n startTime:\n startTime ??\n (from.parent !== undefined && from.parent.udfType !== \"action\"\n ? from.parent.startTime\n : this.now()),\n pagination,\n turn: new Turn(),\n };\n }\n\n private runQuery(\n functionPath: FunctionPath,\n resolved: Pick<Resolved, \"handler\" | \"args\" | \"returns\">,\n args: any,\n from: From,\n snapshotOnly = false,\n top?: TopQuery,\n ): Promise<any> {\n const parentAttempt = from.parent?.attempt;\n const isNested = parentAttempt !== undefined;\n const attempt =\n top?.attempt ??\n (parentAttempt === undefined\n ? new KernelAttempt(this.state)\n : snapshotOnly\n ? new KernelAttempt(parentAttempt.snapshot)\n : parentAttempt);\n const execution = this.execution(\n functionPath,\n \"query\",\n attempt,\n from,\n top?.pagination ??\n ((isNested && from.parent?.pagination) || {\n calls: 0,\n journal: null,\n end: null,\n }),\n top?.startTime,\n );\n const q = queryGeneric({\n handler: (ctx: any, a: any) =>\n resolved.handler({ ...ctx, auth: queryAuth(execution) }, a),\n }) as unknown as { invokeQuery: (args: string) => Promise<string> };\n return enter(execution, () =>\n q.invokeQuery(JSON.stringify(convexToJson([parseArgs(args)]))),\n )\n .then((raw) => settled(execution, raw))\n .then((raw) => {\n const result = jsonToConvex(JSON.parse(raw));\n if (!isNested && hasPendingValues(result)) {\n throw new Error(\n `Function ${functionPath.udfPath} return value invalid: queries ` +\n `cannot return an unresolved placeholder value.`,\n );\n }\n validateReturnValue(resolved.returns, result, \"query\", functionPath);\n return result;\n })\n .catch((error: unknown) => {\n throw deserializeConvexErrorData(error);\n });\n }\n\n private invokeMutation(\n execution: Execution,\n resolved: Pick<Resolved, \"handler\" | \"returns\">,\n args: any,\n ): Promise<Value> {\n const m = mutationGeneric({\n handler: (ctx: any, a: any) =>\n resolved.handler({ ...ctx, auth: mutationAuth(execution) }, a),\n }) as unknown as { invokeMutation: (args: string) => Promise<string> };\n return enter(execution, () =>\n m.invokeMutation(JSON.stringify(convexToJson([parseArgs(args)]))),\n )\n .then((raw) => settled(execution, raw))\n .then((raw) => {\n const result = jsonToConvex(JSON.parse(raw));\n validateReturnValue(resolved.returns, result, \"mutation\", {\n componentPath: execution.componentPath,\n udfPath: execution.udfPath,\n });\n return result;\n });\n }\n\n private runMutation(\n functionPath: FunctionPath,\n resolved: Pick<Resolved, \"handler\" | \"args\" | \"returns\">,\n args: any,\n from: From,\n ): Promise<any> {\n const parentAttempt = from.parent?.attempt;\n if (parentAttempt !== undefined) {\n const frame = parentAttempt.child();\n const execution = this.execution(\n functionPath,\n \"mutation\",\n frame,\n from,\n undefined,\n );\n // As at the top level, a nested mutation ends once its function has\n // returned and every syscall it started has settled. Convex runs a\n // nested function's syscall queue to the end before it commits its\n // subtransaction, so a detached fiber's late write lands in this frame\n // and merges with it. A failed one ends at once and rolls back.\n return this.invokeMutation(execution, resolved, args).then(\n (result) =>\n frame.drained().then(() => {\n frame.close();\n frame.merge();\n return result;\n }),\n (error: unknown) => {\n frame.close();\n throw deserializeConvexErrorData(error);\n },\n );\n }\n return this.prepareMutation(\n functionPath,\n resolved,\n args,\n from,\n 1,\n Invocation.current(),\n ).then((held) => this.publish(held));\n }\n\n /**\n * Run one attempt of a top-level mutation against the latest commit, then\n * hold it. The commit point is once the function has returned and every\n * syscall it started has settled. A test invocation bound when the mutation\n * was first called reaches each attempt's handler with that attempt's\n * number.\n */\n private prepareMutation(\n functionPath: FunctionPath,\n resolved: Pick<Resolved, \"handler\" | \"returns\">,\n args: any,\n from: From,\n number: Invocation.Attempt,\n bound: Invocation.Invocation | undefined,\n ): Promise<Held> {\n const attempt = new KernelAttempt(this.state, number);\n const execution = this.execution(\n functionPath,\n \"mutation\",\n attempt,\n from,\n undefined,\n );\n const run = () => this.invokeMutation(execution, resolved, args);\n const started =\n bound === undefined\n ? run()\n : Invocation.bind({ ...bound, attempt: number }, run);\n return started\n .then(\n (value) =>\n attempt.drained().then((): Outcome => ({ _tag: \"returned\", value })),\n (error: unknown): Outcome => ({\n _tag: \"failed\",\n error: deserializeConvexErrorData(error),\n }),\n )\n .then((outcome) => {\n attempt.close();\n const held: Held = {\n view: {\n id: `attempt-${this.nextAttemptId++}`,\n request: from.request.requestId,\n number,\n snapshot: attempt.snapshot.version,\n reads: attempt.reads,\n outcome,\n },\n attempt,\n again: (next) =>\n this.prepareMutation(\n functionPath,\n resolved,\n args,\n from,\n next,\n bound,\n ),\n };\n this.holding.set(held.view.id, held);\n return held;\n });\n }\n\n /**\n * Validate a held attempt's reads against every commit since its snapshot,\n * then publish its writes or prepare its next attempt. An attempt that wrote\n * nothing publishes nothing and has nothing to validate. It answers its\n * snapshot's version and commit timestamp.\n */\n private applyHeld({ view, attempt, again }: Held): Promise<KernelApply> {\n this.holding.delete(view.id);\n const { outcome } = view;\n if (outcome._tag === \"failed\") {\n return Promise.resolve({\n kind: \"refused\",\n tag: tagOf(outcome.error),\n error: outcome.error,\n });\n }\n const writes = attempt.writes();\n if (writes.length === 0) {\n // As on the binary, a mutation that wrote nothing is serialized at its\n // snapshot and allocates no timestamp for a later commit.\n const { version, commitTs } = attempt.snapshot;\n return Promise.resolve({\n kind: \"applied\",\n version,\n commitTs,\n result: resolveCommittedValues(outcome.value, commitTs),\n });\n }\n if (\n Kernel.conflict(this.state, view.snapshot, attempt.reads) !== undefined\n ) {\n if (view.number === lastAttempt) {\n return Promise.resolve({\n kind: \"exhausted\",\n error: new KernelRefusal.OptimisticConcurrencyControlFailure({\n attempts: lastAttempt,\n message: `Documents read by the mutation changed before each of its ${lastAttempt} attempts could commit.`,\n }),\n });\n }\n return again((view.number + 1) as Invocation.Attempt).then(\n (next): KernelApply => ({ kind: \"conflict\", next: next.view }),\n );\n }\n // Validation, publication and the version read share one synchronous turn,\n // so no other commit lands between them.\n let commitTs: bigint;\n try {\n commitTs = this.publishWrites(writes);\n } catch (error) {\n return Promise.reject(error);\n }\n return Promise.resolve({\n kind: \"applied\",\n version: this.state.version,\n commitTs,\n result: resolveCommittedValues(outcome.value, commitTs),\n });\n }\n\n /**\n * Apply until the mutation publishes, is refused or is exhausted, as the\n * binary retries a mutation that conflicts.\n */\n private publish(held: Held): Promise<Value> {\n return this.applyHeld(held).then((applied) => {\n if (applied.kind === \"applied\") return applied.result;\n if (applied.kind === \"conflict\") {\n return this.publish(this.holding.get(applied.next.id)!);\n }\n throw applied.error;\n });\n }\n\n private runAction(\n functionPath: FunctionPath,\n resolved: Pick<Resolved, \"handler\" | \"args\" | \"returns\">,\n args: any,\n from: From,\n ): Promise<any> {\n const execution = this.execution(\n functionPath,\n \"action\",\n undefined,\n from,\n undefined,\n );\n const inner: From = { request: from.request, parent: execution };\n const a = actionGeneric({\n handler: (ctx: any, innerArgs: any) =>\n resolved.handler(\n {\n ...ctx,\n runQuery: (reference: any, queryArgs: any) =>\n this.queryAt(\n pathOfReference(reference, functionPath.componentPath),\n queryArgs,\n inner,\n ),\n runMutation: (reference: any, mutationArgs: any) =>\n this.mutationAt(\n pathOfReference(reference, functionPath.componentPath),\n mutationArgs,\n inner,\n ),\n runAction: (reference: any, actionArgs: any) =>\n this.actionAt(\n pathOfReference(reference, functionPath.componentPath),\n actionArgs,\n inner,\n ),\n auth: queryAuth(execution),\n },\n innerArgs,\n ),\n }) as unknown as {\n invokeAction: (requestId: string, args: string) => Promise<string>;\n };\n const run = () =>\n enter(execution, () =>\n a.invokeAction(\n from.request.requestId,\n JSON.stringify(convexToJson([parseArgs(args)])),\n ),\n );\n // An action another function calls is an invocation of its own, with its\n // world's services, a start time read from its world's clock and its\n // world's random stream, as a scheduled job is.\n const bound = from.parent === undefined ? undefined : Invocation.current();\n const started =\n bound === undefined\n ? run()\n : Invocation.bind(\n Invocation.fresh(\n bound.world,\n functionPath.componentPath,\n from.request,\n ),\n run,\n );\n return started\n .then((raw) => {\n const result = jsonToConvex(JSON.parse(raw));\n validateReturnValue(resolved.returns, result, \"action\", functionPath);\n return result;\n })\n .catch((error: unknown) => {\n throw deserializeConvexErrorData(error);\n });\n }\n\n // Syscalls.\n\n private schema(componentPath: string) {\n return this.component(componentPath).schema;\n }\n\n private view(execution: Execution): KernelQuery.TableView {\n const attempt = transaction(execution);\n return {\n schema: this.schema(execution.componentPath),\n scan: (tableName) => attempt.scan(execution.componentPath, tableName),\n read: (interval, after) =>\n attempt.readInterval({\n ...interval,\n componentPath: execution.componentPath,\n after,\n }),\n };\n }\n\n private generateId(table: string): DocumentId {\n const counter = String(this.nextDocId++).padStart(\n TYPICAL_CONVEX_ID_LENGTH - table.length,\n \"0\",\n );\n return (counter + table) as DocumentId;\n }\n\n syscall(op: string, jsonArgs: string): string {\n const args = JSON.parse(jsonArgs);\n const execution = current();\n if (execution.attempt?.closed === true) throw closed(execution, op);\n switch (op) {\n case \"1.0/getSnapshotTs\":\n return JSON.stringify(\n convexToJson(transaction(execution).snapshot.commitTs),\n );\n case \"1.0/queryStream\": {\n // The binary reads a query at each `1.0/queryStreamNext`, which waits\n // its turn in the queue, so the stream opens at its first read and sees\n // every write made before it.\n const queryId = this.nextQueryId++;\n const view = this.view(execution);\n let results: Iterator<any> | undefined;\n this.queries.set(queryId, {\n next: () => (results ??= KernelQuery.stream(view, args.query)).next(),\n });\n return JSON.stringify({ queryId });\n }\n case \"1.0/queryCleanup\":\n this.queries.delete(args.queryId);\n return JSON.stringify({});\n case \"1.0/db/normalizeId\": {\n const tableName = tableNameFromId(args.idString);\n return JSON.stringify({\n id: tableName === args.table ? args.idString : null,\n });\n }\n default:\n throw new Error(`The test kernel does not support syscall: \"${op}\"`);\n }\n }\n\n /**\n * The binary queues a query's or mutation's async syscalls and runs them one\n * at a time, oldest first (`start_async_syscall` and `run_inner` in\n * `crates/isolate/src/environment/udf/mod.rs`, 1.49). A write and a nested\n * call never share a batch (`AsyncSyscallBatch::can_push` in\n * `async_syscall.rs`), and a nested call holds the queue until it has\n * committed or rolled back its subtransaction (`run_udf` in\n * `async_syscall.rs`). So a caller's write made after its nested call runs\n * after that call, and a nested mutation sees every write made before it. An\n * action's calls run side by side.\n */\n asyncSyscall(op: string, jsonArgs: string): Promise<string> {\n const execution = current();\n const attempt = execution.attempt;\n if (attempt === undefined) {\n return Promise.resolve().then(() =>\n this.dispatchAsync(op, JSON.parse(jsonArgs), execution),\n );\n }\n if (attempt.closed) return Promise.reject(closed(execution, op));\n // A syscall counts toward its frame's lifetime from the moment it is\n // queued, so a frame never closes with a write still waiting its turn.\n const end = attempt.begin();\n return execution.turn\n .take(() => this.dispatchAsync(op, JSON.parse(jsonArgs), execution))\n .finally(end);\n }\n\n private dispatchAsync(\n op: string,\n args: any,\n execution: Execution,\n ): string | Promise<string> {\n switch (op) {\n case \"1.0/get\": {\n const { table, id } = args;\n return JSON.stringify(convexToJson(this.get(execution, table, id)));\n }\n case \"1.0/queryStreamNext\": {\n const results = this.queries.get(args.queryId);\n if (results === undefined) throw new Error(\"Bad queryId\");\n const { value, done } = results.next();\n return JSON.stringify(\n convexToJson(\n done ? { value: null, done: true } : { value, done: false },\n ),\n );\n }\n case \"1.0/queryPage\": {\n const pagination = execution.pagination;\n if (pagination) {\n pagination.calls += 1;\n if (pagination.calls > 1) {\n throw new Error(\n \"Only a single paginated query (`.paginate()`) is allowed per \" +\n \"query, including nested query calls and component calls. \" +\n \"This is a Convex limit: https://docs.convex.dev/database/pagination\",\n );\n }\n }\n const page = KernelQuery.paginate(this.view(execution), {\n ...args,\n endCursor: args.endCursor ?? pagination?.journal ?? null,\n });\n if (pagination) pagination.end = page.continueCursor;\n return JSON.stringify(convexToJson(page as any));\n }\n case \"1.0/insert\":\n return JSON.stringify({\n _id: this.insert(execution, args.table, jsonToConvex(args.value)),\n });\n case \"1.0/shallowMerge\":\n this.patch(execution, args.table, args.id, args.value);\n return JSON.stringify({});\n case \"1.0/replace\":\n this.replace(execution, args.table, args.id, args.value);\n return JSON.stringify({});\n case \"1.0/remove\":\n this.remove(execution, args.table, args.id);\n return JSON.stringify({});\n case \"1.0/count\": {\n const attempt = transaction(execution);\n attempt.readInterval({\n kind: \"interval\",\n componentPath: execution.componentPath,\n table: args.table,\n fields: [\"_creationTime\", \"_id\"],\n order: \"asc\",\n range: [],\n after: null,\n })(\"end\");\n return JSON.stringify(\n attempt.scan(execution.componentPath, args.table).length,\n );\n }\n case \"1.0/getFunctionMetadata\":\n return JSON.stringify(\n convexToJson({\n name: execution.udfPath,\n componentPath: execution.componentPath,\n }),\n );\n case \"1.0/getRequestMetadata\":\n if (execution.udfType === \"query\") {\n throw new Error(\n \"getRequestMetadata() can only be called from a mutation, action \" +\n \"or HTTP action. It is not available in queries.\",\n );\n }\n return JSON.stringify(convexToJson(execution.request as any));\n case \"1.0/getDeploymentMetadata\":\n return JSON.stringify(\n convexToJson({ name: \"test\", region: null, class: \"s16\" }),\n );\n case \"1.0/actions/query\":\n case \"1.0/actions/mutation\":\n case \"1.0/actions/action\": {\n const from: From = { request: execution.request, parent: execution };\n const functionPath = functionPathOf(args, execution.componentPath);\n const run =\n op === \"1.0/actions/query\"\n ? this.queryAt(functionPath, args.args, from)\n : op === \"1.0/actions/mutation\"\n ? this.mutationAt(functionPath, args.args, from)\n : this.actionAt(functionPath, args.args, from);\n return run.then((value) => JSON.stringify(convexToJson(value)));\n }\n case \"1.0/runUdf\": {\n const { udfType, args: udfArgs } = args;\n const from: From = { request: execution.request, parent: execution };\n const functionPath = functionPathOf(args, execution.componentPath);\n const value = jsonToConvex(udfArgs);\n const run =\n udfType === \"query\"\n ? this.queryAt(functionPath, value, from)\n : udfType === \"snapshotQuery\"\n ? this.queryAt(functionPath, value, from, true)\n : udfType === \"mutation\"\n ? this.mutationAt(functionPath, value, from)\n : Promise.reject(\n new Error(\n `The test kernel does not support udf type: \"${udfType}\"`,\n ),\n );\n return run.then((result) => JSON.stringify(convexToJson(result)));\n }\n case \"1.0/createFunctionHandle\": {\n const functionPath = functionPathOf(args, execution.componentPath);\n this.component(functionPath.componentPath);\n return JSON.stringify(createFunctionHandle(functionPath));\n }\n case \"1.0/auditLog\":\n return JSON.stringify(null);\n case \"1.0/schedule\":\n return JSON.stringify(\n convexToJson(\n this.scheduleJob(transaction(execution), execution, args),\n ),\n );\n case \"1.0/actions/schedule\":\n return JSON.stringify(\n convexToJson(\n this.commitNow((attempt) =>\n this.scheduleJob(attempt, execution, args),\n ),\n ),\n );\n case \"1.0/cancel_job\":\n this.cancelJob(\n transaction(execution),\n execution.componentPath,\n args.id,\n );\n return JSON.stringify({});\n case \"1.0/actions/cancel_job\":\n this.commitNow((attempt) =>\n this.cancelJob(attempt, execution.componentPath, args.id),\n );\n return JSON.stringify({});\n case \"1.0/storageDelete\":\n case \"1.0/storageGetUrl\":\n case \"1.0/storageGenerateUploadUrl\":\n throw KernelRefusal.rowPending(\"storage\", 6);\n case \"1.0/getTransactionMetrics\":\n throw KernelRefusal.rowPending(\"transaction limits\", 6);\n case \"1.0/actions/vectorSearch\":\n throw KernelRefusal.requiresBinary(\"vectorSearch\");\n default:\n throw new Error(\n `The test kernel does not support async syscall: \"${op}\"`,\n );\n }\n }\n\n jsSyscall(op: string): Promise<never> {\n return Promise.reject(\n op.startsWith(\"storage/\")\n ? KernelRefusal.rowPending(\"storage\", 6)\n : new Error(`The test kernel does not support js syscall: \"${op}\"`),\n );\n }\n\n // Documents. The checks and messages are convex-test's.\n\n private get(execution: Execution, tableName: unknown, id: unknown) {\n validateId(tableName, id);\n const attempt = transaction(execution);\n attempt.readDocument(execution.componentPath, id);\n return attempt.get(execution.componentPath, id);\n }\n\n private insert(execution: Execution, table: string, value: any): DocumentId {\n const attempt = transaction(execution);\n KernelQuery.validateDocument(\n this.schema(execution.componentPath),\n table,\n value,\n );\n const _id = this.generateId(table);\n attempt.write(execution.componentPath, _id, {\n ...value,\n _id,\n _creationTime: this.creationTime(execution.startTime),\n });\n return _id;\n }\n\n /**\n * A new document's creation time: `at`, or just past the latest one, so no\n * two documents share one.\n */\n private creationTime(at: number): number {\n const time =\n at <= this.lastCreationTime ? this.lastCreationTime + 0.001 : at;\n this.lastCreationTime = time;\n return time;\n }\n\n private existing(\n execution: Execution,\n tableName: unknown,\n id: unknown,\n write: string,\n value: unknown,\n ): StoredDocument {\n validateId(tableName, id);\n if (value !== undefined && typeof value !== \"object\") {\n throw new Error(\n `Invalid argument \\`value\\` in \\`db.${write}\\`, expected object but got '${typeof value}': ${value as any}`,\n );\n }\n const attempt = transaction(execution);\n attempt.readDocument(execution.componentPath, id);\n const document = attempt.get(execution.componentPath, id);\n if (document === null) {\n throw new Error(\n write === \"delete\"\n ? \"Delete on non-existent doc\"\n : `${write === \"patch\" ? \"Patch\" : \"Replace\"} on non-existent document with ID \"${id}\"`,\n );\n }\n return document;\n }\n\n private fields(document: StoredDocument, value: Record<string, any>) {\n if (value._id !== undefined && value._id !== document._id) {\n throw new Error(\n `Provided \\`_id\\` field value \"${value._id}\" ` +\n `does not match the document ID \"${document._id}\"`,\n );\n }\n if (\n value._creationTime !== undefined &&\n value._creationTime !== document._creationTime\n ) {\n throw new Error(\n `Provided \\`_creationTime\\` field value ${value._creationTime} ` +\n `does not match the document's creation time ${document._creationTime}`,\n );\n }\n const convexValue: Record<string, Value | undefined> = {};\n for (const [key, v] of Object.entries(value)) {\n if (key !== \"_id\" && key !== \"_creationTime\") {\n convexValue[key] = evaluateValue(v);\n }\n }\n return convexValue;\n }\n\n private patch(\n execution: Execution,\n tableName: unknown,\n id: unknown,\n value: Record<string, any>,\n ) {\n const document = this.existing(execution, tableName, id, \"patch\", value);\n const { _id, _creationTime, ...fields } = document;\n const merged = { ...fields, ...this.fields(document, value) };\n KernelQuery.validateDocument(\n this.schema(execution.componentPath),\n tableNameFromId(_id)!,\n merged,\n );\n transaction(execution).write(execution.componentPath, _id, {\n _id,\n _creationTime,\n ...merged,\n } as StoredDocument);\n }\n\n private replace(\n execution: Execution,\n tableName: unknown,\n id: unknown,\n value: Record<string, any>,\n ) {\n const document = this.existing(execution, tableName, id, \"replace\", value);\n const fields = this.fields(document, value);\n KernelQuery.validateDocument(\n this.schema(execution.componentPath),\n tableNameFromId(document._id)!,\n fields,\n );\n transaction(execution).write(execution.componentPath, document._id, {\n ...fields,\n _id: document._id,\n _creationTime: document._creationTime,\n } as StoredDocument);\n }\n\n private remove(execution: Execution, tableName: unknown, id: unknown) {\n const document = this.existing(\n execution,\n tableName,\n id,\n \"delete\",\n undefined,\n );\n transaction(execution).write(execution.componentPath, document._id, null);\n }\n}\n\n/**\n * Where a call comes from. A call from the test carries its accessor's caller.\n * A nested call carries its parent execution and takes its identity from it.\n */\ntype From =\n | {\n readonly caller: Caller;\n readonly request: Request;\n readonly parent?: undefined;\n }\n | { readonly parent: Execution; readonly request: Request };\n\nconst closed = (execution: Execution, operation: string) =>\n new KernelRefusal.ClosedAttempt({\n operation,\n message: `\"${operation}\" reached mutation ${execution.udfPath} after it returned and its syscalls settled. Await every read and write inside the handler.`,\n });\n\nconst transaction = (execution: Execution): KernelAttempt => {\n if (execution.attempt === undefined) {\n throw new Error(\n \"The database is only available in queries and mutations. An action reads and writes through `ctx.runQuery` and `ctx.runMutation`.\",\n );\n }\n return execution.attempt;\n};\n\nconst queryAuth = (execution: Execution) => ({\n getUserIdentity: () => {\n execution.attempt?.observeIdentity();\n return Promise.resolve(execution.identity);\n },\n});\n\nconst mutationAuth = (execution: Execution) => ({\n ...queryAuth(execution),\n signJwt: () => Promise.reject(KernelRefusal.rowPending(\"JWT signing\", 6)),\n});\n\nfunction validateId(\n expectedTableName: unknown,\n id: unknown,\n): asserts id is DocumentId {\n if (typeof id !== \"string\") {\n throw new Error(\n `Invalid argument \\`id\\`, expected string but got '${typeof id}': ${id as any}`,\n );\n }\n if (expectedTableName === undefined) return;\n if (typeof expectedTableName !== \"string\") {\n throw new Error(\n `Invalid argument \\`tableName\\`, expected string but got '${typeof expectedTableName}': ${expectedTableName as any}`,\n );\n }\n const actualTableName = tableNameFromId(id);\n if (actualTableName === null) {\n throw new Error(\n `Invalid argument \\`id\\`, expected ID value but got '${id}'`,\n );\n }\n if (actualTableName !== expectedTableName) {\n throw new Error(\n `Invalid argument \\`id\\`, expected ID in table '${expectedTableName}' but got ID in table '${actualTableName}'`,\n );\n }\n}\n\ninterface Syscalls {\n readonly syscall: (op: string, args: string) => string;\n readonly asyncSyscall: (op: string, args: string) => Promise<string>;\n readonly jsSyscall: (op: string, args: unknown) => unknown;\n}\n\ntype Branded = { readonly [kernelBrand]?: true };\n\n/**\n * The backend another library installed as `globalThis.Convex`, which answers\n * every syscall made outside a kernel function.\n */\nlet forwarded: Syscalls | undefined;\n\n// With neither, `current` refuses the syscall.\nconst backend = (): Syscalls =>\n executions.getStore()?.world ?? forwarded ?? current().world;\n\nconst dispatcher: Syscalls & Branded = {\n [kernelBrand]: true,\n syscall: (op, args) => backend().syscall(op, args),\n asyncSyscall: (op, args) => backend().asyncSyscall(op, args),\n jsSyscall: (op, args) => backend().jsSyscall(op, args),\n};\n\n/**\n * Convex's server library reaches the backend through `globalThis.Convex`, one\n * global for the whole test runtime. convex-test 0.0.65 assigns its own the\n * first time it builds a world (its `dist/index.js:1936-1951`), whenever that\n * is. The kernel keeps the global an accessor that always reads its dispatcher,\n * and takes an assignment, or the global it found, as the backend for syscalls\n * made outside a kernel function. So a kernel world and a convex-test world\n * stay live together, whichever was built first, and no world restores the\n * global when it ends. A test that redefines the global removes the accessor,\n * so every kernel function installs it again over what the test left.\n */\nconst installConvexGlobal = () => {\n const found = (globalThis as { Convex?: Syscalls & Branded }).Convex;\n if (found?.[kernelBrand] === true) return;\n forwarded = found;\n Object.defineProperty(globalThis, \"Convex\", {\n get: () => dispatcher,\n set: (value: (Syscalls & Branded) | undefined) => {\n if (value?.[kernelBrand] !== true) forwarded = value;\n },\n configurable: true,\n enumerable: true,\n });\n};\n\n/**\n * Whether `globalThis.Convex` is the kernel's, and no other backend installed\n * one behind it.\n */\nexport const ownsConvexGlobal = (): boolean =>\n (globalThis as { Convex?: Branded }).Convex?.[kernelBrand] === true &&\n forwarded === undefined;\n"],"mappings":";;;;;;;;;;;;;AA0CA,MAAM,OAAO;AACb,MAAM,2BAA2B;AA8BjC,MAAa,YAAoB;CAC/B,UAAU;CACV,OAAO;CACP,IAAI;CACJ,WAAW;AACb;AAEA,MAAa,gBACX,QACA,aACW;CACX,MAAM,UAAU,SAAS,WAAW,KAAK,WAAW,KAAK,UAAU,QAAQ,CAAC;CAC5E,MAAM,SAAS,SAAS,UAAU;CAClC,MAAM,kBAAkB,SAAS,mBAAmB,GAAG,OAAO,GAAG;CACjE,MAAM,OAAO;EAAE,GAAG;EAAU;EAAS;EAAQ;CAAgB;CAC7D,OAAO;EAAE,GAAG;EAAQ,UAAU;EAAM,OAAO,cAAc,IAAI;CAAE;AACjE;AAiGA,MAAM,cAAkC;AAExC,MAAM,SAAS,UAA2B;CACxC,MAAM,UAAU,UACd,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAA6B,SAAS;CAChD,MAA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AAoB,mBACtB,MAAM,IAAI,MACR,kDAAkD,kBAAkB,yBAAyB,gBAAgB,EAC/G;AAEJ;;;;;AAcA,IAAI;AAGJ,MAAM,gBACJ,WAAW,SAAS,CAAC,EAAE,SAAS,aAAa,QAAQ,CAAC,CAAC;AAEzD,MAAM,aAAiC;EACpC,cAAc;CACf,UAAU,IAAI,SAAS,QAAQ,CAAC,CAAC,QAAQ,IAAI,IAAI;CACjD,eAAe,IAAI,SAAS,QAAQ,CAAC,CAAC,aAAa,IAAI,IAAI;CAC3D,YAAY,IAAI,SAAS,QAAQ,CAAC,CAAC,UAAU,IAAI,IAAI;AACvD;;;;;;;;;;;;AAaA,MAAM,4BAA4B;CAChC,MAAM,QAAS,WAA+C;CAC9D,IAAI,QAAQ,iBAAiB,MAAM;CACnC,YAAY;CACZ,OAAO,eAAe,YAAY,UAAU;EAC1C,WAAW;EACX,MAAM,UAA4C;GAChD,IAAI,QAAQ,iBAAiB,MAAM,YAAY;EACjD;EACA,cAAc;EACd,YAAY;CACd,CAAC;AACH;;;;;AAMA,MAAa,yBACV,WAAoC,SAAS,iBAAiB,QAC/D,cAAc,KAAA"}
1
+ {"version":3,"file":"Execution.js","names":["Globals.own","KernelRefusal.SnapshotWorldUnresolved","KernelRefusal.SnapshotWorldRunning","KernelQuery.exportSchema","Kernel.empty","Redaction.Secrets","Kernel.wallClock","Redaction.none","KernelRefusal.RegisteredAfterOpen","KernelRefusal.UnknownStandingSource","Invocation.current","KernelRefusal.StaleAttempt","Snapshot.encode","Redaction.mark","Snapshot.decode","Redaction.unmark","Snapshot.check","Scheduling.table","KernelRefusal.SnapshotComponentMismatch","KernelRefusal.SnapshotJobInconsistent","KernelRefusal.SnapshotWorldBusy","KernelRefusal.SnapshotSubscribed","Scheduling.pending","Scheduling.functions","KernelRefusal.DrainBudgetExceeded","Invocation.unbound","Invocation.bind","Invocation.fresh","Scheduling.stateOf","KernelRefusal.CommitTsNotIncreasing","Kernel.apply","Metering.point","Scheduling.row","Metering.defaults","Metering.fromBudget","Kernel.conflict","KernelRefusal.OptimisticConcurrencyControlFailure","table","Redaction.failure","Redaction.markValue","Redaction.sensitiveAt","Redaction.marker","examined","Metering.examined","KernelQuery.stream","KernelQuery.paginate","Metering.everything","KernelRefusal.rowPending","KernelRefusal.requiresBinary","KernelRefusal.ClosedAttempt"],"sources":["../../src/internal/Execution.ts"],"sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport {\n actionGeneric,\n getFunctionAddress,\n mutationGeneric,\n queryGeneric,\n type FunctionReference,\n type GenericSchema,\n type SchemaDefinition,\n type UserIdentity,\n} from \"convex/server\";\nimport {\n CommitTsPlaceholder,\n compareValues,\n convexToJson,\n jsonToConvex,\n type Value,\n} from \"convex/values\";\nimport * as Result from \"effect/Result\";\nimport { KernelAttempt } from \"./Attempt.js\";\nimport * as Clock from \"./Clock.js\";\nimport * as Globals from \"./Globals.js\";\nimport * as Invocation from \"./Invocation.js\";\nimport * as Kernel from \"./Kernel.js\";\nimport * as KernelQuery from \"./KernelQuery.js\";\nimport * as KernelRefusal from \"./KernelRefusal.js\";\nimport * as Metering from \"./Metering.js\";\nimport type * as ReadSet from \"./ReadSet.js\";\nimport * as Redaction from \"./Redaction.js\";\nimport * as Scheduling from \"./Scheduling.js\";\nimport * as Snapshot from \"./Snapshot.js\";\nimport type {\n DocumentId,\n FunctionPath,\n StoredDocument,\n ValidatorJSON,\n} from \"./KernelValues.js\";\nimport {\n createFunctionHandle,\n createTestJwt,\n deserializeConvexErrorData,\n evaluateValue,\n hasPendingValues,\n isSimpleObject,\n parseArgs,\n parseFunctionHandle,\n resolveCommittedValues,\n simpleHash,\n tableNameFromId,\n validateFunctionArgs,\n validateReturnValue,\n} from \"./KernelValues.js\";\n\nconst ROOT = \"\";\nconst TYPICAL_CONVEX_ID_LENGTH = 32;\n\ntype Modules = Record<string, () => Promise<any>>;\n\n/**\n * One registered component: its schema, its function modules, each loaded once\n * when the world opens, and its standing sources.\n */\ninterface Component {\n readonly path: string;\n readonly schema: KernelQuery.KernelSchema | null;\n readonly loaders: ReadonlyMap<string, () => Promise<any>>;\n readonly loaded: Map<string, any>;\n /**\n * The functions, as `module:export`, that schedule their own next run. A job\n * that runs one, or that one schedules, is never drain work.\n */\n readonly standing: ReadonlySet<string>;\n}\n\n/**\n * Who is calling: the identity and the request attributes a test accessor set.\n */\nexport interface Caller {\n readonly identity: UserIdentity | null;\n readonly token: string | null;\n readonly ip: string | null;\n readonly userAgent: string | null;\n}\n\nexport const anonymous: Caller = {\n identity: null,\n token: null,\n ip: null,\n userAgent: null,\n};\n\nexport const withIdentity = (\n caller: Caller,\n identity: Partial<UserIdentity>,\n): Caller => {\n const subject = identity.subject ?? \"\" + simpleHash(JSON.stringify(identity));\n const issuer = identity.issuer ?? \"https://convex.test\";\n const tokenIdentifier = identity.tokenIdentifier ?? `${issuer}|${subject}`;\n const full = { ...identity, subject, issuer, tokenIdentifier };\n return { ...caller, identity: full, token: createTestJwt(full) };\n};\n\ninterface Request {\n readonly ip: string | null;\n readonly userAgent: string | null;\n readonly requestId: string;\n readonly scheduledFunctionId: string | null;\n readonly authToken: string | null;\n}\n\ntype UdfType = \"query\" | \"mutation\" | \"action\";\n\n/**\n * How a prepared attempt's function ended.\n */\nexport type Outcome =\n | { readonly _tag: \"returned\"; readonly value: Value }\n | { readonly _tag: \"failed\"; readonly error: unknown };\n\n/**\n * A mutation attempt run to its commit point and held until `apply`.\n */\nexport interface HeldAttempt {\n readonly id: string;\n /**\n * The mutation the attempt runs, whose return shape marks its outcome in an\n * artifact.\n */\n readonly functionPath: FunctionPath;\n readonly request: string;\n readonly number: Invocation.Attempt;\n readonly snapshot: Kernel.Version;\n readonly reads: ReadonlyArray<ReadSet.Read>;\n readonly outcome: Outcome;\n}\n\n/**\n * What `apply` did with a held attempt. A conflict discards the attempt and\n * holds exactly one next attempt, run against the latest commit. Nothing is\n * retried until that one is applied in turn.\n */\nexport type KernelApply =\n | {\n readonly kind: \"applied\";\n readonly version: Kernel.Version;\n readonly commitTs: bigint;\n readonly result: Value;\n }\n | { readonly kind: \"conflict\"; readonly next: HeldAttempt }\n | {\n readonly kind: \"exhausted\";\n readonly error: KernelRefusal.OptimisticConcurrencyControlFailure;\n }\n | { readonly kind: \"refused\"; readonly tag: string; readonly error: unknown };\n\n/**\n * One top-level query run and every dependency it took: the commit and reads it\n * read, whether it asked for the caller's identity, the pinned time it read and\n * the end of its paginated read.\n */\nexport interface QueryRun {\n readonly outcome: Outcome;\n readonly snapshot: Kernel.Version;\n readonly reads: ReadonlyArray<ReadSet.Read>;\n readonly observedIdentity: boolean;\n /**\n * The pinned time the query read, or `null` when it never read the time.\n */\n readonly time: number | null;\n /**\n * Where the query's paginated read ended, or `null` when it ran none. A rerun\n * ends its page there, as the binary's query journal does.\n */\n readonly journal: string | null;\n}\n\n/**\n * The one paginated read a query and its nested calls may run. `journal` is\n * where a previous run's page ended, and `end` where this run's page ends.\n */\ninterface Pagination {\n calls: number;\n readonly journal: string | null;\n end: string | null;\n}\n\n/**\n * A top-level query whose attempt and page the caller keeps, at a pinned start\n * time or the kernel's time now.\n */\ninterface TopQuery {\n readonly attempt: KernelAttempt;\n readonly pagination: Pagination;\n readonly startTime: number | undefined;\n}\n\ninterface Held {\n readonly view: HeldAttempt;\n readonly attempt: KernelAttempt;\n readonly again: (number: Invocation.Attempt) => Promise<Held>;\n}\n\nconst lastAttempt: Invocation.Attempt = 5;\n\nconst tagOf = (error: unknown): string => {\n const tagged = (value: unknown): value is { readonly _tag: string } =>\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { _tag?: unknown })._tag === \"string\";\n const data = (error as { data?: unknown } | null)?.data;\n if (tagged(data)) return data._tag;\n if (tagged(error)) return error._tag;\n return error instanceof Error ? error.name : \"Error\";\n};\n\n/**\n * One running function. Queries and mutations read and write through their\n * attempt. Every async syscall of a query or a mutation, nested calls included,\n * takes its turn on `turn` in the order the function made it.\n */\ninterface Execution {\n readonly world: World;\n readonly componentPath: string;\n readonly udfPath: string;\n readonly udfType: UdfType;\n readonly attempt: KernelAttempt | undefined;\n readonly identity: UserIdentity | null;\n readonly request: Request;\n /**\n * The kernel's time when the outermost query or mutation began. Its nested\n * calls share it, and `Date` answers it inside them.\n */\n readonly startTime: number;\n readonly pagination: Pagination | undefined;\n readonly turn: Turn;\n /**\n * The transaction limits this function runs under: the defaults at the top\n * level, its caller's inside a nested call, tightened by the call's budget.\n */\n readonly limits: Metering.Limits;\n}\n\n/**\n * A queue that runs one task at a time, in the order they were taken.\n */\nclass Turn {\n private tail: Promise<unknown> = Promise.resolve();\n\n take<A>(task: () => A | Promise<A>): Promise<A> {\n const result = this.tail.then(task);\n this.tail = result.then(\n () => undefined,\n () => undefined,\n );\n return result;\n }\n\n /**\n * Resolves once every task taken so far has settled, including the tasks\n * taken while waiting.\n */\n idle(): Promise<void> {\n const tail = this.tail;\n return tail.then(() => (this.tail === tail ? undefined : this.idle()));\n }\n}\n\n/**\n * A function's invocation finishes once its handler returned and every syscall\n * it started has run. On the binary a query or mutation keeps running the\n * syscalls in its queue after its promise resolves, then returns (`run_inner`\n * in `crates/isolate/src/environment/udf/mod.rs`, 1.49), so an unawaited write\n * still lands in its own transaction.\n */\nconst settled = <A>(execution: Execution, result: A): Promise<A> =>\n execution.turn.idle().then(() => result);\n\nconst executions = new AsyncLocalStorage<Execution>();\n\n/**\n * Run a function's code as `execution`, with its own copy of the globals a test\n * invocation pins.\n */\nconst enter = <A>(execution: Execution, run: () => A): A => {\n installConvexGlobal();\n return Globals.own(() => executions.run(execution, run));\n};\nconst kernelBrand = Symbol.for(\"@confect/test/Kernel\");\n\n/**\n * The time `Date` answers inside a kernel invocation: a query's or mutation's\n * start, or the clock as it runs in an action. Outside one, none. A query or\n * mutation that reads it takes a dependency on that time.\n */\nconst pinnedTime = (): number | undefined => {\n const execution = executions.getStore();\n if (execution === undefined) return undefined;\n if (execution.udfType === \"action\") return execution.world.now();\n execution.attempt?.observeTime(execution.startTime);\n return execution.startTime;\n};\n\n/**\n * How many jobs one drain or advance runs before it gives up, as convex-test's\n * `finishAllScheduledFunctions` defaults to.\n */\nconst defaultBudget = 100;\n\nconst unresolvedWorld = (\n name: string,\n reason: \"missing\" | \"ambiguous\",\n): KernelRefusal.SnapshotWorldUnresolved =>\n new KernelRefusal.SnapshotWorldUnresolved({\n name,\n reason,\n message:\n reason === \"missing\"\n ? `A snapshot job runs under the test world \"${name}\", which no world passed to restore is named. Pass that world.`\n : `Two different test worlds are named \"${name}\", so a snapshot cannot tell their jobs apart. Name each world uniquely.`,\n });\n\n/**\n * `shape` placed at `at`, or no placement when there is no shape.\n */\nconst placed = (\n shape: Redaction.Shape | undefined,\n at: ReadonlyArray<string> = [],\n): ReadonlyArray<Redaction.Placement> =>\n shape === undefined ? [] : [{ at, shape }];\n\nconst running = (\n registry: KernelRefusal.SnapshotWorldRunning[\"registry\"],\n count: number,\n what: string,\n) =>\n new KernelRefusal.SnapshotWorldRunning({\n registry,\n count,\n message: `The test backend is running ${count} ${what}, whose effects a snapshot would split. Await them first.`,\n });\n\nconst current = (): Execution => {\n const execution = executions.getStore();\n if (execution === undefined) {\n throw new Error(\n \"A Convex syscall ran outside any function the test kernel started.\",\n );\n }\n return execution;\n};\n\nlet nextRequestId = 0;\nconst newRequest = (caller: Caller): Request => ({\n ip: caller.ip,\n userAgent: caller.userAgent,\n requestId: `kernel-request-${nextRequestId++}`,\n scheduledFunctionId: null,\n authToken: caller.token,\n});\n\n/**\n * A scheduled call is a request of its own: no caller's attributes, and its\n * job's ID.\n */\nconst jobRequest = (jobId: DocumentId): Request => ({\n ...newRequest(anonymous),\n scheduledFunctionId: jobId,\n});\n\nconst findModulesRoot = (paths: ReadonlyArray<string>): string => {\n const generated = paths.find((path) => path.includes(\"_generated\"));\n if (generated === undefined) {\n throw new Error(\n 'Could not find the \"_generated\" directory, make sure to run ' +\n \"`npx convex dev` or `npx convex codegen`. Make sure your \" +\n '`import.meta.glob` includes the files in the \"_generated\" directory',\n );\n }\n return generated.split(\"_generated\", 2)[0]!;\n};\n\nconst makeComponent = (\n path: string,\n schema: SchemaDefinition<GenericSchema, boolean> | null | undefined,\n modules: Modules,\n standing: ReadonlyArray<string> = [],\n): Component => {\n const root = findModulesRoot(Object.keys(modules));\n const relative = Object.entries(modules)\n .filter(([key]) => key.startsWith(root))\n .map(([key, load]) => [key.slice(root.length), load] as const);\n const nested = relative\n .map(([file]) => file)\n .filter((file) => file.endsWith(\"/convex.config.ts\"))\n .map((file) => file.slice(0, -\"convex.config.ts\".length));\n return {\n path,\n schema: KernelQuery.exportSchema(schema),\n loaders: new Map(\n relative\n .filter(\n ([file]) =>\n isFunctionModule(file) &&\n !nested.some((dir) => file.startsWith(dir)),\n )\n .map(([file, load]) => [file.replace(/\\.[^.]+$/, \"\"), load]),\n ),\n loaded: new Map(),\n standing: new Set(standing),\n };\n};\n\nconst entryExtensions = [\n \".js\",\n \".mjs\",\n \".cjs\",\n \".ts\",\n \".tsx\",\n \".mts\",\n \".cts\",\n \".jsx\",\n];\n\n/**\n * Whether Convex's bundler deploys this file as a function module, by the rule\n * `entryPoints` applies in `convex/src/bundler/index.ts` (1.49). A test file, a\n * schema, a config and `_generated` never reach the binary, so the kernel\n * neither loads them nor resolves a function in them.\n */\nconst isFunctionModule = (file: string): boolean => {\n const base = file.split(\"/\").pop()!;\n return (\n entryExtensions.some((extension) => file.endsWith(extension)) &&\n !file.startsWith(\"_generated/\") &&\n !base.startsWith(\".\") &&\n !base.startsWith(\"#\") &&\n base !== \"schema.ts\" &&\n base !== \"schema.js\" &&\n (base.match(/\\./g) ?? []).length <= 1 &&\n !file.includes(\" \")\n );\n};\n\nconst unregistered = (world: World, componentPath: string) => {\n const registered = [...world.components.keys()].filter((p) => p !== ROOT);\n return new Error(\n `Component \"${componentPath}\" is not registered on this test backend. ` +\n (registered.length === 0\n ? \"No components have been registered.\"\n : `Registered components: ${registered.map((p) => `\"${p}\"`).join(\", \")}.`),\n );\n};\n\ntype FunctionAddress = {\n readonly name?: string | undefined;\n readonly reference?: string | undefined;\n readonly functionHandle?: string | undefined;\n};\n\n/**\n * Where an address points, read from the calling component.\n */\nconst functionPathOf = (\n address: FunctionAddress,\n from: string,\n): FunctionPath => {\n if (address.functionHandle !== undefined) {\n return parseFunctionHandle(address.functionHandle);\n }\n if (address.name !== undefined) {\n return { udfPath: address.name, componentPath: from };\n }\n if (address.reference !== undefined) {\n // \"_reference/childComponent/<child>/path/to/file/fn\"\n const parts = address.reference.split(\"/\");\n const child = parts[2]!;\n const rest = parts.slice(3);\n return {\n componentPath: from.length > 0 ? `${from}/${child}` : child,\n udfPath: `${rest.slice(0, -1).join(\"/\")}:${rest[rest.length - 1]}`,\n };\n }\n throw new Error(\"Function address not supported\");\n};\n\nconst pathOfReference = (\n reference: FunctionReference<any, any, any, any> | string,\n from: string,\n) =>\n functionPathOf(getFunctionAddress(reference as any) as FunctionAddress, from);\n\ninterface Resolved {\n readonly func: any;\n readonly handler: (ctx: any, args: any) => any;\n readonly args: ValidatorJSON;\n readonly returns: ValidatorJSON | null;\n}\n\nconst kindCheck = {\n query: \"isQuery\",\n mutation: \"isMutation\",\n action: \"isAction\",\n} as const;\n\n/**\n * A test backend: its registered components and the kernel state they share.\n */\nexport class World {\n readonly components = new Map<string, Component>();\n state: Kernel.State = Kernel.empty;\n private opened: Promise<void> | undefined;\n private nextDocId = 10000;\n private lastCreationTime = 0;\n private nextQueryId = 1;\n private readonly queries = new Map<number, Iterator<any>>();\n private readonly holding = new Map<string, Held>();\n private nextAttemptId = 1;\n /**\n * The latest deadline time has been advanced to. The clock never reads\n * earlier.\n */\n private floor = Number.NEGATIVE_INFINITY;\n private readonly targets = new Map<DocumentId, Scheduling.Target>();\n /**\n * The raw secrets this world has seen under a secret schema node. Replay\n * state, kept in memory and never written to an artifact.\n */\n private secrets = new Redaction.Secrets();\n /**\n * The live registries `Snapshot.contract.live` names, each a count: calls\n * from the test, scheduler walks, function executions (nested and detached\n * ones included) and registered subscribers. Held attempts are `holding`.\n */\n private readonly live = {\n running: 0,\n walks: 0,\n functions: 0,\n subscribers: 0,\n };\n /**\n * The latest identity version a subscriber's `authenticate` reached. Each\n * subscriber starts at the epoch, and each identity change advances it, so a\n * restored world never hands out a version its source already used.\n */\n private identityEpoch = 0;\n\n constructor(\n schema: SchemaDefinition<GenericSchema, boolean> | null | undefined,\n modules: Modules,\n private readonly runtime: Kernel.KernelRuntime = Kernel.wallClock(),\n private readonly redaction: Redaction.Policy = Redaction.none,\n ) {\n installConvexGlobal();\n Clock.install(pinnedTime, () => executions.getStore() !== undefined);\n this.components.set(ROOT, makeComponent(ROOT, schema, modules));\n }\n\n register(\n componentPath: string,\n schema: SchemaDefinition<GenericSchema, boolean>,\n modules: Modules,\n standing: ReadonlyArray<string> = [],\n ) {\n if (this.opened !== undefined) {\n throw new KernelRefusal.RegisteredAfterOpen({\n componentPath,\n message: `Component \"${componentPath}\" was registered after the test backend opened. Register every component before the first call.`,\n });\n }\n this.components.set(\n componentPath,\n makeComponent(componentPath, schema, modules, standing),\n );\n }\n\n /**\n * Load every registered module of every component, once, before any function\n * runs, then check that each standing source names an exported function.\n */\n open(): Promise<void> {\n this.opened ??= Promise.all(\n Array.from(this.components.values(), (component) =>\n Promise.all(\n Array.from(component.loaders, ([path, load]) =>\n load().then((module) => component.loaded.set(path, module)),\n ),\n ),\n ),\n ).then(() => this.checkStanding());\n return this.opened;\n }\n\n /**\n * Refuse a standing source no module of its component exports.\n */\n private checkStanding() {\n for (const component of this.components.values()) {\n for (const name of component.standing) {\n const [modulePath, exportName = \"default\"] = name.split(\":\");\n const func = component.loaded.get(modulePath!)?.[exportName];\n if (func?.isMutation !== true && func?.isAction !== true) {\n throw new KernelRefusal.UnknownStandingSource({\n componentPath: component.path,\n name,\n message: `Component \"${component.path}\" declares \"${name}\" standing, but exports no mutation or action by that name. Name the self-rescheduling function as module:export.`,\n });\n }\n }\n }\n }\n\n /**\n * The kernel's time: the runtime's, never earlier than the latest deadline\n * time was advanced to.\n */\n now(): number {\n return Math.max(this.runtime.now(), this.floor);\n }\n\n private component(componentPath: string): Component {\n const component = this.components.get(componentPath);\n if (component === undefined) throw unregistered(this, componentPath);\n return component;\n }\n\n private resolve(functionPath: FunctionPath, kind: UdfType | \"any\"): Resolved {\n const [modulePath, maybeExport] = functionPath.udfPath.split(\":\") as [\n string,\n string | undefined,\n ];\n const exportName = maybeExport ?? \"default\";\n const component = this.component(functionPath.componentPath);\n const module = component.loaded.get(modulePath);\n if (module === undefined) {\n throw new Error(`Could not find module for: \"${modulePath}\"`);\n }\n const func = module[exportName];\n if (func === undefined) {\n throw new Error(\n `Expected a Convex function exported from module \"${modulePath}\" as \\`${exportName}\\`, but there is no such export.`,\n );\n }\n const handler = \"_handler\" in func ? func._handler : func;\n if (typeof handler !== \"function\") {\n throw new Error(\n `Expected a Convex function exported from module \"${modulePath}\" as \\`${exportName}\\`, but got: ${func}`,\n );\n }\n if (kind !== \"any\" && !func[kindCheck[kind]]) {\n throw new Error(\n `Expected a ${kind} function, but the function exported from module \"${modulePath}\" as \\`${exportName}\\` is not a ${kind}.`,\n );\n }\n const args = JSON.parse(func.exportArgs()) as ValidatorJSON;\n if (args.type !== \"object\" && args.type !== \"any\") {\n throw new Error(\n `Invalid JSON returned from ${modulePath}.js:${exportName}.exportArgs(): ` +\n `Args validator must be an object or any`,\n );\n }\n return { func, handler, args, returns: JSON.parse(func.exportReturns()) };\n }\n\n // Calls from the test.\n\n query(caller: Caller, reference: any, args: any): Promise<any> {\n return this.during(() => {\n return this.open().then(() => {\n const from = { caller, request: newRequest(caller) };\n return typeof reference === \"function\"\n ? this.runQuery(\n { componentPath: ROOT, udfPath: \"inline\" },\n { handler: reference, args: { type: \"any\" }, returns: null },\n args ?? {},\n from,\n )\n : this.queryAt(pathOfReference(reference, ROOT), args, from);\n });\n });\n }\n\n mutation(caller: Caller, reference: any, args: any): Promise<any> {\n return this.during(() => {\n return this.open().then(() => {\n const from = { caller, request: newRequest(caller) };\n return typeof reference === \"function\"\n ? this.runMutation(\n { componentPath: ROOT, udfPath: \"inline\" },\n { handler: reference, args: { type: \"any\" }, returns: null },\n args ?? {},\n from,\n )\n : this.mutationAt(pathOfReference(reference, ROOT), args, from);\n });\n });\n }\n\n action(caller: Caller, reference: any, args: any): Promise<any> {\n return this.during(() => {\n return this.open().then(() => {\n const from = { caller, request: newRequest(caller) };\n return typeof reference === \"function\"\n ? this.runAction(\n { componentPath: ROOT, udfPath: \"inline\" },\n { handler: reference, args: { type: \"any\" }, returns: null },\n args ?? {},\n from,\n )\n : this.actionAt(pathOfReference(reference, ROOT), args, from);\n });\n });\n }\n\n run(\n caller: Caller,\n componentPath: string,\n handler: (ctx: any) => any,\n ): Promise<any> {\n return this.during(() => {\n return this.open().then(() => {\n this.component(componentPath);\n return this.runMutation(\n { componentPath, udfPath: \"custom\" },\n { handler, args: { type: \"any\" }, returns: null },\n {},\n { caller, request: newRequest(caller) },\n );\n });\n });\n }\n\n // Held attempts.\n\n /**\n * Run a mutation to its commit point and hold it as attempt 1.\n */\n prepare(caller: Caller, reference: any, args: any): Promise<HeldAttempt> {\n return this.during(() => {\n return this.open().then(() => {\n const functionPath = pathOfReference(reference, ROOT);\n const resolved = this.resolve(functionPath, \"mutation\");\n this.keepArgs(functionPath, args);\n validateFunctionArgs(resolved.args, args ?? {}, functionPath, false);\n return this.prepareMutation(\n functionPath,\n resolved,\n args,\n { caller, request: newRequest(caller) },\n 1,\n Invocation.current(),\n ).then((held) => held.view);\n });\n });\n }\n\n apply(id: string): Promise<KernelApply> {\n return this.during(() => {\n const held = this.holding.get(id);\n return held === undefined\n ? Promise.reject(\n new KernelRefusal.StaleAttempt({\n id,\n message: `The test kernel holds no attempt \"${id}\". It was already applied, or never prepared.`,\n }),\n )\n : this.applyHeld(held);\n });\n }\n\n /**\n * The held attempts, oldest first.\n */\n held(): ReadonlyArray<HeldAttempt> {\n return Array.from(this.holding.values(), (held) => held.view);\n }\n\n // Subscribed queries.\n\n /**\n * Run a query at the latest commit as a subscription runs it, under `caller`,\n * and return its answer with every dependency it took. `time` pins the time\n * it reads, the kernel's time now by default. `journal` ends its paginated\n * read where an earlier run's ended.\n */\n subscribed(\n caller: Caller,\n reference: any,\n args: any,\n pinned: { readonly time?: number; readonly journal: string | null },\n ): Promise<QueryRun> {\n return this.during(() => {\n return this.open().then(() => {\n const functionPath = pathOfReference(reference, ROOT);\n const resolved = this.resolve(functionPath, \"query\");\n this.keepArgs(functionPath, args);\n validateFunctionArgs(resolved.args, args ?? {}, functionPath, false);\n const top: TopQuery = {\n attempt: new KernelAttempt(this.state),\n pagination: { calls: 0, journal: pinned.journal, end: null },\n startTime: pinned.time,\n };\n const run = (outcome: Outcome): QueryRun => ({\n outcome,\n snapshot: top.attempt.snapshot.version,\n reads: top.attempt.reads,\n observedIdentity: top.attempt.observedIdentity,\n time: top.attempt.observedTime,\n journal: pinned.journal ?? top.pagination.end,\n });\n return this.runQuery(\n functionPath,\n resolved,\n args,\n { caller, request: newRequest(caller) },\n false,\n top,\n ).then(\n (value: Value) => run({ _tag: \"returned\", value }),\n (error: unknown) => run({ _tag: \"failed\", error }),\n );\n });\n });\n }\n\n /**\n * Run `call`, a call from the test, counted as running until it settles.\n */\n private during<A>(call: () => Promise<A>): Promise<A> {\n return this.track(\"running\", call);\n }\n\n /**\n * Run `work` counted in the live registry `registry` until it settles.\n */\n private track<A>(\n registry: \"running\" | \"walks\" | \"functions\",\n work: () => Promise<A>,\n ): Promise<A> {\n this.live[registry]++;\n const settle = () => {\n this.live[registry]--;\n };\n try {\n return work().finally(settle);\n } catch (error) {\n settle();\n throw error;\n }\n }\n\n /**\n * How many entries each live registry holds now.\n */\n liveCounts(): {\n readonly [K in keyof typeof Snapshot.contract.live]: number;\n } {\n return {\n running: this.live.running,\n walks: this.live.walks,\n functions: this.live.functions,\n held: this.holding.size,\n subscribers: this.live.subscribers,\n };\n }\n\n /**\n * Count a subscriber the shim's registry created. Subscribers live as long as\n * their test, so the count never falls.\n */\n registerSubscriber() {\n this.live.subscribers++;\n }\n\n // Identity versions.\n\n /**\n * The identity version a new subscriber starts at.\n */\n currentIdentityEpoch(): number {\n return this.identityEpoch;\n }\n\n /**\n * The next identity version, for a subscriber whose identity changed.\n */\n nextIdentityEpoch(): number {\n return ++this.identityEpoch;\n }\n\n // Snapshots.\n\n /**\n * The committed state as snapshot bytes: every component's rows and the\n * version that wrote each, the write log, the jobs and their targets, the\n * clock's floor and the identity counters. Each job's world is recorded by\n * name. Two exports of the same state are the same bytes. A world running a\n * call or holding attempts refuses, since a snapshot carries neither.\n */\n exportSnapshot(): Uint8Array {\n this.refuseBusy(0, \"export\");\n const names = new Map<string, Invocation.World>();\n const jobs = new Map<DocumentId, Snapshot.JobTarget>();\n for (const byTable of this.state.tables.values()) {\n for (const id of byTable.get(Scheduling.table)?.keys() ?? []) {\n const target = this.targets.get(id);\n if (target === undefined) continue;\n const world = target.world;\n if (world !== undefined) {\n if ((names.get(world.name) ?? world) !== world) {\n throw unresolvedWorld(world.name, \"ambiguous\");\n }\n names.set(world.name, world);\n }\n jobs.set(id, {\n functionPath: target.functionPath,\n standing: target.standing,\n world: world?.name ?? null,\n });\n }\n }\n return Snapshot.encode(\n {\n components: [...this.components.keys()],\n state: this.state,\n floor: this.floor,\n identity: {\n nextDocumentId: this.nextDocId,\n lastCreationTime: this.lastCreationTime,\n nextAttemptId: this.nextAttemptId,\n identityEpoch: this.identityEpoch,\n },\n jobs,\n },\n (componentPath, table, json) =>\n Redaction.mark(\n json,\n this.documentPlacements(\n componentPath,\n table,\n json as { readonly _id: unknown; readonly name?: unknown },\n ),\n this.secrets,\n ),\n );\n }\n\n /**\n * Replace this world's state with a snapshot's. The world must register the\n * snapshot's components, run nothing, and have committed nothing and hold\n * nothing. Each job's world resolves by name among `worlds`. Bytes whose\n * digest does not match, and state the kernel could not have reached, refuse\n * before anything changes.\n */\n restoreSnapshot(\n bytes: Uint8Array,\n options: {\n readonly worlds?: ReadonlyArray<Invocation.World>;\n readonly secrets?: Redaction.Secrets;\n } = {},\n ): Promise<void> {\n return this.open().then(() =>\n this.restore(\n bytes,\n options.worlds ?? [],\n options.secrets ?? new Redaction.Secrets(),\n ),\n );\n }\n\n private restore(\n bytes: Uint8Array,\n worlds: ReadonlyArray<Invocation.World>,\n secrets: Redaction.Secrets,\n ) {\n this.refuseBusy(this.state.version, \"restore\");\n const decoded = Snapshot.decode(bytes, (json) =>\n Redaction.unmark(json, secrets),\n );\n if (Result.isFailure(decoded)) throw decoded.failure;\n const image = decoded.success;\n const checked = Snapshot.check(image, Scheduling.table);\n if (Result.isFailure(checked)) throw checked.failure;\n const registered = [...this.components.keys()].sort();\n const snapshot = [...image.components].sort();\n if (registered.join(\"\\u0000\") !== snapshot.join(\"\\u0000\")) {\n throw new KernelRefusal.SnapshotComponentMismatch({\n snapshot,\n registered,\n message: `The snapshot holds components ${snapshot.map((p) => `\"${p}\"`).join(\", \")}, but this test backend registers ${registered.map((p) => `\"${p}\"`).join(\", \")}. Register the same components before restoring.`,\n });\n }\n for (const [id, { functionPath }] of image.jobs) {\n if (!this.exports(functionPath)) {\n throw new KernelRefusal.SnapshotJobInconsistent({\n id,\n reason: \"function\",\n message: `The snapshot's job ${id} targets ${functionPath.udfPath} in \"${functionPath.componentPath}\", which that component does not export.`,\n });\n }\n }\n const byName = new Map<string, Invocation.World>();\n for (const world of worlds) {\n if ((byName.get(world.name) ?? world) !== world) {\n throw unresolvedWorld(world.name, \"ambiguous\");\n }\n byName.set(world.name, world);\n }\n const targets = Array.from(\n image.jobs,\n ([id, { functionPath, standing, world }]): [\n DocumentId,\n Scheduling.Target,\n ] => {\n const resolved = world === null ? undefined : byName.get(world);\n if (world !== null && resolved === undefined) {\n throw unresolvedWorld(world, \"missing\");\n }\n return [id, { functionPath, standing, world: resolved }];\n },\n );\n this.state = image.state;\n this.floor = image.floor;\n this.nextDocId = image.identity.nextDocumentId;\n this.lastCreationTime = image.identity.lastCreationTime;\n this.nextAttemptId = image.identity.nextAttemptId;\n this.identityEpoch = image.identity.identityEpoch;\n this.targets.clear();\n for (const [id, target] of targets) this.targets.set(id, target);\n this.secrets = secrets.copy();\n }\n\n /**\n * Whether `functionPath`'s component exports a Convex function there.\n */\n private exports({ componentPath, udfPath }: FunctionPath): boolean {\n const [modulePath, exportName = \"default\"] = udfPath.split(\":\");\n const func = this.components.get(componentPath)?.loaded.get(modulePath!)?.[\n exportName\n ];\n return (\n func?.isQuery === true ||\n func?.isMutation === true ||\n func?.isAction === true\n );\n }\n\n /**\n * Refuse a snapshot while any live registry `operation` waits on is\n * non-empty, or, restoring, once `version` shows the world committed\n * something of its own.\n */\n private refuseBusy(version: Kernel.Version, operation: \"export\" | \"restore\") {\n const counts = this.liveCounts();\n const refusals: {\n readonly [K in keyof typeof counts]: (count: number) => Error;\n } = {\n running: (count) => running(\"running\", count, \"calls from the test\"),\n walks: (count) => running(\"walks\", count, \"scheduler walks\"),\n functions: (count) =>\n running(\n \"functions\",\n count,\n \"functions, nested and detached ones included\",\n ),\n held: () => {\n const held = [...this.holding.keys()];\n return new KernelRefusal.SnapshotWorldBusy({\n version,\n held,\n message: `The test backend holds attempts ${held.join(\", \")}, which a snapshot does not carry. Apply them first.`,\n });\n },\n subscribers: (count) =>\n new KernelRefusal.SnapshotSubscribed({\n subscribers: count,\n message: `The test backend has ${count} subscribers, whose identity versions a restore would rewind. Restore into a test backend no client has subscribed to.`,\n }),\n };\n for (const key of Object.keys(refusals) as Array<keyof typeof counts>) {\n const { blocks } = Snapshot.contract.live[key];\n if (operation === \"export\" && blocks === \"restore\") continue;\n if (counts[key] > 0) throw refusals[key](counts[key]);\n }\n if (operation === \"restore\" && version !== 0) {\n throw new KernelRefusal.SnapshotWorldBusy({\n version,\n held: [],\n message: `The test backend has committed ${version} versions of its own. Restore a snapshot into a fresh test backend.`,\n });\n }\n }\n\n // Scheduled functions, on the kernel's clock.\n\n /**\n * The committed pending jobs, earliest deadline first.\n */\n jobs(): ReadonlyArray<Scheduling.Job> {\n return Scheduling.pending(this.state, this.targets).map(\n ({ id, componentPath, name, scheduledTime, standing }) => ({\n id,\n componentPath,\n name,\n scheduledTime,\n standing,\n }),\n );\n }\n\n /**\n * Move the clock forward `ms`, running every job whose deadline falls on the\n * way, in deadline order, each starting at its deadline. Jobs those jobs\n * schedule inside the window run too. `advance(0)` runs what is due now and\n * crosses no future deadline.\n */\n advance(ms: number, budget = defaultBudget): Promise<void> {\n return this.track(\"walks\", () => {\n return this.open().then(() => {\n const until = this.now() + ms;\n return this.walk(\n (pending) => pending.filter((job) => job.scheduledTime <= until),\n budget,\n ).then(() => this.raiseFloor(until));\n });\n });\n }\n\n /**\n * Run jobs, earliest deadline first and each at its deadline, until only\n * standing jobs are pending. Every job run counts against `budget`.\n */\n drain(budget = defaultBudget): Promise<void> {\n return this.track(\"walks\", () => {\n return this.open().then(() =>\n this.walk((pending) => pending.filter((job) => !job.standing), budget),\n );\n });\n }\n\n /**\n * Run the first of `select(pending)` until it is empty, moving the clock to\n * each job's deadline as it starts.\n */\n private walk(\n select: (pending: Array<Scheduling.Due>) => Array<Scheduling.Due>,\n budget: number,\n ): Promise<void> {\n const step = (ran: number): Promise<void> => {\n const left = select(Scheduling.pending(this.state, this.targets));\n const next = left[0];\n if (next === undefined) return Promise.resolve();\n if (ran === budget) {\n const pending = Scheduling.functions(left);\n return Promise.reject(\n new KernelRefusal.DrainBudgetExceeded({\n budget,\n pending,\n message: `Scheduled functions ran ${budget} jobs and work remains: ${pending\n .map(({ componentPath, name }) =>\n componentPath === ROOT ? name : `${name} in \"${componentPath}\"`,\n )\n .join(\n \", \",\n )}. A function that schedules its own next run never lets the drain end, so its kit declares it with registerComponent's \\`standing\\` option.`,\n }),\n );\n }\n this.raiseFloor(next.scheduledTime);\n return this.runJob(next).then(() => step(ran + 1));\n };\n return step(0);\n }\n\n private raiseFloor(to: number) {\n this.floor = Math.max(this.floor, to);\n }\n\n /**\n * Run one pending job as its own request, moving its row through in progress\n * to success or failed. `walk` picks it from the committed pending jobs and\n * starts it in the same turn, so no cancel can land in between. The job runs\n * as a fresh invocation of the world that scheduled it, whatever invocation\n * the drain itself runs under.\n */\n private runJob(job: Scheduling.Due): Promise<void> {\n this.commitNow((attempt) => {\n const doc = attempt.get(job.componentPath, job.id)!;\n attempt.write(job.componentPath, job.id, {\n ...doc,\n state: { kind: \"inProgress\" },\n });\n });\n const request = jobRequest(job.id);\n const from: From = { caller: anonymous, request };\n const run = () =>\n Promise.resolve().then(() => {\n const { func } = this.resolve(job.target, \"any\");\n return func.isQuery\n ? this.queryAt(job.target, job.args, from)\n : func.isMutation\n ? this.mutationAt(job.target, job.args, from)\n : this.actionAt(job.target, job.args, from);\n });\n return (\n job.world === undefined\n ? Invocation.unbound(run)\n : Invocation.bind(\n Invocation.fresh(job.world, job.target.componentPath, request),\n run,\n )\n )\n .then(\n (): Scheduling.JobState => ({ kind: \"success\" }),\n (error: unknown): Scheduling.JobState => ({\n kind: \"failed\",\n error: error instanceof Error ? error.message : String(error),\n }),\n )\n .then((state) =>\n this.commitNow((attempt) => {\n const doc = attempt.get(job.componentPath, job.id);\n if (doc === null || Scheduling.stateOf(doc).kind !== \"inProgress\")\n return;\n attempt.write(job.componentPath, job.id, {\n ...doc,\n state,\n completedTime: this.now(),\n });\n }),\n );\n }\n\n /**\n * Write through a fresh attempt and publish it at once, as the scheduler does\n * for an action's schedule and a job's state. Nothing runs between the\n * snapshot and the commit, so no other commit can conflict with it.\n */\n private commitNow<A>(write: (attempt: KernelAttempt) => A): A {\n const attempt = new KernelAttempt(this.state);\n const result = write(attempt);\n this.publishWrites(attempt.writes());\n return result;\n }\n\n /**\n * Publish `writes` as the next commit, at the runtime's timestamp for it. No\n * writes publish nothing and ask the runtime for no timestamp, which answers\n * the latest commit's.\n */\n private publishWrites(writes: ReadonlyArray<Kernel.Write>): bigint {\n if (writes.length === 0) return this.state.commitTs;\n const commitTs = this.runtime.commitTs(this.state.version + 1);\n if (commitTs <= this.state.commitTs) {\n throw new KernelRefusal.CommitTsNotIncreasing({\n version: this.state.version + 1,\n previous: this.state.commitTs,\n commitTs,\n message: `The runtime answered commit timestamp ${commitTs} for version ${this.state.version + 1}, which is not greater than the previous commit's ${this.state.commitTs}.`,\n });\n }\n this.state = Kernel.apply(this.state, writes, commitTs);\n return commitTs;\n }\n\n /**\n * Write a pending job into `attempt`, so the job exists only once that\n * attempt publishes. A job that a standing function schedules, or that runs\n * one, is standing.\n */\n private scheduleJob(\n attempt: KernelAttempt,\n execution: Execution,\n args: any,\n ): DocumentId {\n const target = functionPathOf(args, execution.componentPath);\n this.component(target.componentPath);\n const jobArgs = jsonToConvex(args.args);\n this.keepArgs(target, jobArgs);\n if (hasPendingValues(jobArgs)) {\n throw new Error(\n `Invalid arguments for \"${target.udfPath}\": a scheduled function cannot take an unresolved placeholder value.`,\n );\n }\n refuse(attempt.meter.schedule(jobArgs, execution.limits));\n const jobsIndex = indexKey(\n execution.componentPath,\n Scheduling.table,\n \"by_id\",\n );\n // A scheduled function that schedules reads its own job first\n // (`SchedulerModel::schedule`, `crates/model/src/scheduled_jobs/mod.rs:238-300`).\n const parentJob = execution.request.scheduledFunctionId;\n if (parentJob !== null) {\n refuse(\n attempt.meter.readInterval(\n jobsIndex,\n Metering.point([parentJob]),\n execution.limits,\n ),\n );\n }\n const id = this.generateId(Scheduling.table);\n attempt.meter.deriveInterval(jobsIndex, Metering.point([id]));\n attempt.write(\n execution.componentPath,\n id,\n Scheduling.row(\n id,\n this.creationTime(execution.startTime),\n target.udfPath,\n jobArgs,\n args.ts * 1000,\n ),\n );\n this.targets.set(id, {\n functionPath: target,\n standing:\n this.isStanding({\n componentPath: execution.componentPath,\n udfPath: execution.udfPath,\n }) || this.isStanding(target),\n world: Invocation.current()?.world,\n });\n return id;\n }\n\n /**\n * Cancel a job that has not finished. A finished job stays as it ended.\n */\n private cancelJob(attempt: KernelAttempt, execution: Execution, id: any) {\n const { componentPath } = execution;\n validateId(Scheduling.table, id);\n const doc = this.readById(attempt, execution, id);\n if (doc === null) {\n throw new Error(`Patch on non-existent document with ID \"${id}\"`);\n }\n const { kind } = Scheduling.stateOf(doc);\n if (kind === \"pending\" || kind === \"inProgress\") {\n attempt.write(componentPath, id, { ...doc, state: { kind: \"canceled\" } });\n }\n }\n\n private isStanding({ componentPath, udfPath }: FunctionPath): boolean {\n return this.components.get(componentPath)?.standing.has(udfPath) ?? false;\n }\n\n // Calls by address, from the test or from a running function.\n\n private queryAt(\n functionPath: FunctionPath,\n args: any,\n from: From,\n snapshotOnly = false,\n ) {\n const resolved = this.resolve(functionPath, \"query\");\n this.keepArgs(functionPath, args);\n validateFunctionArgs(\n resolved.args,\n args ?? {},\n functionPath,\n from.parent?.attempt !== undefined,\n );\n return this.runQuery(functionPath, resolved, args, from, snapshotOnly);\n }\n\n private mutationAt(functionPath: FunctionPath, args: any, from: From) {\n const resolved = this.resolve(functionPath, \"mutation\");\n this.keepArgs(functionPath, args);\n validateFunctionArgs(\n resolved.args,\n args ?? {},\n functionPath,\n from.parent?.attempt !== undefined,\n );\n return this.runMutation(functionPath, resolved, args, from);\n }\n\n private actionAt(functionPath: FunctionPath, args: any, from: From) {\n const resolved = this.resolve(functionPath, \"action\");\n this.keepArgs(functionPath, args);\n validateFunctionArgs(resolved.args, args ?? {}, functionPath, false);\n return this.runAction(functionPath, resolved, args, from);\n }\n\n // Runners.\n\n private execution(\n functionPath: FunctionPath,\n udfType: UdfType,\n attempt: KernelAttempt | undefined,\n from: From,\n pagination: Pagination | undefined,\n startTime?: number,\n ): Execution {\n // A function in a component runs with no identity, whoever called it, as\n // Convex gives a component no `ctx.auth` of the caller's. A nested call in\n // the host takes its parent's identity, even when that is none.\n const identity =\n functionPath.componentPath !== ROOT\n ? null\n : from.parent !== undefined\n ? from.parent.identity\n : from.caller.identity;\n // A nested call runs under its caller's limits, which its budget can only\n // tighten, and gives them back when it ends (`run_udf`,\n // `crates/isolate/src/environment/udf/async_syscall.rs:700-706`, and\n // `commit_subtransaction`, `crates/database/src/transaction.rs:431-441`).\n const inherited =\n attempt === undefined || from.parent?.attempt === undefined\n ? Metering.defaults\n : from.parent.limits;\n const limits =\n attempt === undefined || from.budget === undefined\n ? inherited\n : Metering.fromBudget(from.budget, attempt.meter.used(), inherited);\n return {\n world: this,\n componentPath: functionPath.componentPath,\n udfPath: functionPath.udfPath,\n udfType,\n attempt,\n identity,\n request: from.request,\n startTime:\n startTime ??\n (from.parent !== undefined && from.parent.udfType !== \"action\"\n ? from.parent.startTime\n : this.now()),\n pagination,\n turn: new Turn(),\n limits,\n };\n }\n\n private runQuery(\n functionPath: FunctionPath,\n resolved: Pick<Resolved, \"handler\" | \"args\" | \"returns\">,\n args: any,\n from: From,\n snapshotOnly = false,\n top?: TopQuery,\n ): Promise<any> {\n return this.track(\"functions\", () => {\n const parentAttempt = from.parent?.attempt;\n const isNested = parentAttempt !== undefined;\n const attempt =\n top?.attempt ??\n (parentAttempt === undefined\n ? new KernelAttempt(this.state)\n : snapshotOnly\n ? parentAttempt.staleSnapshot()\n : parentAttempt);\n const execution = this.execution(\n functionPath,\n \"query\",\n attempt,\n from,\n top?.pagination ??\n ((isNested && from.parent?.pagination) || {\n calls: 0,\n journal: null,\n end: null,\n }),\n top?.startTime,\n );\n const q = queryGeneric({\n handler: (ctx: any, a: any) =>\n resolved.handler({ ...ctx, auth: queryAuth(execution) }, a),\n }) as unknown as { invokeQuery: (args: string) => Promise<string> };\n return enter(execution, () =>\n q.invokeQuery(JSON.stringify(convexToJson([parseArgs(args)]))),\n )\n .then((raw) => settled(execution, raw))\n .then((raw) => {\n const result = jsonToConvex(JSON.parse(raw));\n if (!isNested && hasPendingValues(result)) {\n throw new Error(\n `Function ${functionPath.udfPath} return value invalid: queries ` +\n `cannot return an unresolved placeholder value.`,\n );\n }\n this.keepReturns(functionPath, result);\n validateReturnValue(resolved.returns, result, \"query\", functionPath);\n return result;\n })\n .catch((error: unknown) => {\n throw deserializeConvexErrorData(error);\n });\n });\n }\n\n private invokeMutation(\n execution: Execution,\n resolved: Pick<Resolved, \"handler\" | \"returns\">,\n args: any,\n ): Promise<Value> {\n const m = mutationGeneric({\n handler: (ctx: any, a: any) =>\n resolved.handler({ ...ctx, auth: mutationAuth(execution) }, a),\n }) as unknown as { invokeMutation: (args: string) => Promise<string> };\n return enter(execution, () =>\n m.invokeMutation(JSON.stringify(convexToJson([parseArgs(args)]))),\n )\n .then((raw) => settled(execution, raw))\n .then((raw) => {\n const result = jsonToConvex(JSON.parse(raw));\n const functionPath = {\n componentPath: execution.componentPath,\n udfPath: execution.udfPath,\n };\n this.keepReturns(functionPath, result);\n validateReturnValue(resolved.returns, result, \"mutation\", functionPath);\n return result;\n });\n }\n\n private runMutation(\n functionPath: FunctionPath,\n resolved: Pick<Resolved, \"handler\" | \"args\" | \"returns\">,\n args: any,\n from: From,\n ): Promise<any> {\n return this.track(\"functions\", () => {\n const parentAttempt = from.parent?.attempt;\n if (parentAttempt !== undefined) {\n const frame = parentAttempt.child();\n const execution = this.execution(\n functionPath,\n \"mutation\",\n frame,\n from,\n undefined,\n );\n // As at the top level, a nested mutation ends once its function has\n // returned and every syscall it started has settled. Convex runs a\n // nested function's syscall queue to the end before it commits its\n // subtransaction, so a detached fiber's late write lands in this frame\n // and merges with it. A failed one ends at once and rolls back.\n return this.invokeMutation(execution, resolved, args).then(\n (result) =>\n frame.drained().then(() => {\n frame.close();\n frame.merge();\n return result;\n }),\n (error: unknown) => {\n frame.close();\n throw deserializeConvexErrorData(error);\n },\n );\n }\n return this.prepareMutation(\n functionPath,\n resolved,\n args,\n from,\n 1,\n Invocation.current(),\n ).then((held) => this.publish(held));\n });\n }\n\n /**\n * Run one attempt of a top-level mutation against the latest commit, then\n * hold it. The commit point is once the function has returned and every\n * syscall it started has settled. A test invocation bound when the mutation\n * was first called reaches each attempt's handler with that attempt's\n * number.\n */\n private prepareMutation(\n functionPath: FunctionPath,\n resolved: Pick<Resolved, \"handler\" | \"returns\">,\n args: any,\n from: From,\n number: Invocation.Attempt,\n bound: Invocation.Invocation | undefined,\n ): Promise<Held> {\n return this.track(\"functions\", () => {\n const attempt = new KernelAttempt(this.state, number);\n const execution = this.execution(\n functionPath,\n \"mutation\",\n attempt,\n from,\n undefined,\n );\n const run = () => this.invokeMutation(execution, resolved, args);\n const started =\n bound === undefined\n ? run()\n : Invocation.bind({ ...bound, attempt: number }, run);\n return started\n .then(\n (value) =>\n attempt\n .drained()\n .then((): Outcome => ({ _tag: \"returned\", value })),\n (error: unknown): Outcome => ({\n _tag: \"failed\",\n error: deserializeConvexErrorData(error),\n }),\n )\n .then((outcome) => {\n attempt.close();\n const held: Held = {\n view: {\n id: `attempt-${this.nextAttemptId++}`,\n functionPath,\n request: from.request.requestId,\n number,\n snapshot: attempt.snapshot.version,\n reads: attempt.reads,\n outcome,\n },\n attempt,\n again: (next) =>\n this.prepareMutation(\n functionPath,\n resolved,\n args,\n from,\n next,\n bound,\n ),\n };\n this.holding.set(held.view.id, held);\n return held;\n });\n });\n }\n\n /**\n * Validate a held attempt's reads against every commit since its snapshot,\n * then publish its writes or prepare its next attempt. An attempt that wrote\n * nothing publishes nothing and has nothing to validate. It answers its\n * snapshot's version and commit timestamp.\n */\n private applyHeld({ view, attempt, again }: Held): Promise<KernelApply> {\n this.holding.delete(view.id);\n const { outcome } = view;\n if (outcome._tag === \"failed\") {\n return Promise.resolve({\n kind: \"refused\",\n tag: tagOf(outcome.error),\n error: outcome.error,\n });\n }\n const writes = attempt.writes();\n if (writes.length === 0) {\n // As on the binary, a mutation that wrote nothing is serialized at its\n // snapshot and allocates no timestamp for a later commit.\n const { version, commitTs } = attempt.snapshot;\n return Promise.resolve({\n kind: \"applied\",\n version,\n commitTs,\n result: resolveCommittedValues(outcome.value, commitTs),\n });\n }\n if (\n Kernel.conflict(this.state, view.snapshot, attempt.reads) !== undefined\n ) {\n if (view.number === lastAttempt) {\n return Promise.resolve({\n kind: \"exhausted\",\n error: new KernelRefusal.OptimisticConcurrencyControlFailure({\n attempts: lastAttempt,\n message: `Documents read by the mutation changed before each of its ${lastAttempt} attempts could commit.`,\n }),\n });\n }\n return again((view.number + 1) as Invocation.Attempt).then(\n (next): KernelApply => ({ kind: \"conflict\", next: next.view }),\n );\n }\n // Validation, publication and the version read share one synchronous turn,\n // so no other commit lands between them.\n let commitTs: bigint;\n try {\n commitTs = this.publishWrites(writes);\n } catch (error) {\n return Promise.reject(error);\n }\n return Promise.resolve({\n kind: \"applied\",\n version: this.state.version,\n commitTs,\n result: resolveCommittedValues(outcome.value, commitTs),\n });\n }\n\n /**\n * Apply until the mutation publishes, is refused or is exhausted, as the\n * binary retries a mutation that conflicts.\n */\n private publish(held: Held): Promise<Value> {\n return this.applyHeld(held).then((applied) => {\n if (applied.kind === \"applied\") return applied.result;\n if (applied.kind === \"conflict\") {\n return this.publish(this.holding.get(applied.next.id)!);\n }\n throw applied.error;\n });\n }\n\n private runAction(\n functionPath: FunctionPath,\n resolved: Pick<Resolved, \"handler\" | \"args\" | \"returns\">,\n args: any,\n from: From,\n ): Promise<any> {\n return this.track(\"functions\", () => {\n const execution = this.execution(\n functionPath,\n \"action\",\n undefined,\n from,\n undefined,\n );\n const inner: From = { request: from.request, parent: execution };\n const a = actionGeneric({\n handler: (ctx: any, innerArgs: any) =>\n resolved.handler(\n {\n ...ctx,\n runQuery: (reference: any, queryArgs: any) =>\n this.queryAt(\n pathOfReference(reference, functionPath.componentPath),\n queryArgs,\n inner,\n ),\n runMutation: (reference: any, mutationArgs: any) =>\n this.mutationAt(\n pathOfReference(reference, functionPath.componentPath),\n mutationArgs,\n inner,\n ),\n runAction: (reference: any, actionArgs: any) =>\n this.actionAt(\n pathOfReference(reference, functionPath.componentPath),\n actionArgs,\n inner,\n ),\n auth: queryAuth(execution),\n },\n innerArgs,\n ),\n }) as unknown as {\n invokeAction: (requestId: string, args: string) => Promise<string>;\n };\n const run = () =>\n enter(execution, () =>\n a.invokeAction(\n from.request.requestId,\n JSON.stringify(convexToJson([parseArgs(args)])),\n ),\n );\n // An action another function calls is an invocation of its own, with its\n // world's services, a start time read from its world's clock and its\n // world's random stream, as a scheduled job is.\n const bound =\n from.parent === undefined ? undefined : Invocation.current();\n const started =\n bound === undefined\n ? run()\n : Invocation.bind(\n Invocation.fresh(\n bound.world,\n functionPath.componentPath,\n from.request,\n ),\n run,\n );\n return started\n .then((raw) => {\n const result = jsonToConvex(JSON.parse(raw));\n this.keepReturns(functionPath, result);\n validateReturnValue(resolved.returns, result, \"action\", functionPath);\n return result;\n })\n .catch((error: unknown) => {\n throw deserializeConvexErrorData(error);\n });\n });\n }\n\n // Secrets.\n\n private keepArgs(functionPath: FunctionPath, args: unknown) {\n Redaction.keep(\n args ?? {},\n placed(this.redaction.args(functionPath)),\n this.secrets,\n );\n }\n\n private keepReturns(functionPath: FunctionPath, result: Value) {\n Redaction.keep(\n result,\n placed(this.redaction.returns(functionPath)),\n this.secrets,\n );\n }\n\n private keepRow(componentPath: string, table: string, value: unknown) {\n Redaction.keep(\n value,\n placed(this.redaction.table(componentPath, table)),\n this.secrets,\n );\n }\n\n /**\n * Where a stored document holds secrets: its table's shape at its root, and\n * for a job's row, its target's argument shape at `args.0`.\n */\n private documentPlacements(\n componentPath: string,\n table: string,\n doc: { readonly _id: unknown; readonly name?: unknown },\n ): ReadonlyArray<Redaction.Placement> {\n const own = placed(this.redaction.table(componentPath, table));\n if (table !== Scheduling.table) return own;\n const target = this.targets.get(doc._id as DocumentId)?.functionPath ?? {\n componentPath,\n udfPath: String(doc.name),\n };\n return own.concat(placed(this.redaction.args(target), [\"args\", \"0\"]));\n }\n\n /**\n * A copy of the raw secrets this world has kept, for a restore of its\n * snapshots. It lives in memory only.\n */\n keptSecrets(): Redaction.Secrets {\n return this.secrets.copy();\n }\n\n /**\n * The failure report for `thrown`, whatever was thrown, with every kept\n * secret marked. `thrown` itself is never changed.\n */\n redactFailure(thrown: unknown): unknown {\n return Redaction.failure(thrown, this.secrets);\n }\n\n /**\n * `outcome` as an artifact writes it: a value marked by the shape of what\n * `functionPath` returns, a failure as its report.\n */\n redactOutcome(outcome: Outcome, functionPath?: FunctionPath): Outcome {\n return outcome._tag === \"returned\"\n ? {\n _tag: \"returned\",\n value: Redaction.markValue(\n outcome.value,\n placed(\n functionPath === undefined\n ? undefined\n : this.redaction.returns(functionPath),\n ),\n this.secrets,\n ),\n }\n : { _tag: \"failed\", error: this.redactFailure(outcome.error) };\n }\n\n /**\n * A changed document as an artifact writes it, marked by its table's shape.\n */\n redactChange(change: Kernel.Change): Kernel.Change {\n const document = (doc: StoredDocument | null) =>\n doc === null\n ? null\n : (Redaction.markValue(\n doc as Value,\n this.documentPlacements(\n change.componentPath,\n tableNameFromId(doc._id) ?? \"\",\n doc,\n ),\n this.secrets,\n ) as StoredDocument);\n return {\n ...change,\n before: document(change.before),\n after: document(change.after),\n };\n }\n\n /**\n * The function a subscription's or call's reference names, if it names one.\n */\n functionPathOf(reference: unknown): FunctionPath | undefined {\n try {\n return typeof reference === \"function\"\n ? undefined\n : pathOfReference(reference as FunctionReference<any>, ROOT);\n } catch {\n return undefined;\n }\n }\n\n /**\n * Read records as an artifact writes them. A key or range bound on a field\n * its table's shape holds secret is the marker, and so is any string holding\n * a kept secret.\n */\n projectReads(\n reads: ReadonlyArray<ReadSet.Read>,\n ): ReadonlyArray<ReadSet.Read> {\n return reads.map((read) => {\n if (read.kind === \"document\") return read;\n const shape = this.redaction.table(read.componentPath, read.table);\n const sensitive = (fieldPath: string) =>\n shape !== undefined &&\n Redaction.sensitiveAt(shape, fieldPath.split(\".\"));\n const value = (fieldPath: string, v: Value): Value =>\n sensitive(fieldPath)\n ? Redaction.marker\n : Redaction.markValue(v, [], this.secrets);\n const key = (k: ReadSet.Key | null) =>\n k === null\n ? null\n : k.map((v, i) =>\n v === undefined ? undefined : value(read.fields[i] ?? \"\", v),\n );\n return {\n ...read,\n range: read.range.map((bound) => ({\n ...bound,\n value: sensitive(bound.fieldPath)\n ? Redaction.marker\n : convexToJson(\n Redaction.markValue(\n jsonToConvex(bound.value),\n [],\n this.secrets,\n ),\n ),\n })),\n after: key(read.after),\n through:\n read.through === \"end\" || read.through === null\n ? read.through\n : key(read.through),\n };\n });\n }\n\n /**\n * A held attempt as an artifact writes it: its read records projected and its\n * outcome marked.\n */\n projectHeld(view: HeldAttempt): HeldAttempt {\n return {\n ...view,\n reads: this.projectReads(view.reads),\n outcome: this.redactOutcome(view.outcome, view.functionPath),\n };\n }\n\n /**\n * What `apply` answered as an artifact writes it: an applied result marked by\n * the shape of what `functionPath` returns, a conflict's next attempt\n * projected, a refusal as its report.\n */\n projectApplied(\n applied: KernelApply,\n functionPath: FunctionPath | undefined,\n ): KernelApply {\n switch (applied.kind) {\n case \"applied\": {\n const outcome = this.redactOutcome(\n { _tag: \"returned\", value: applied.result },\n functionPath,\n );\n return outcome._tag === \"returned\"\n ? { ...applied, result: outcome.value }\n : applied;\n }\n case \"conflict\":\n return { ...applied, next: this.projectHeld(applied.next) };\n case \"refused\":\n return { ...applied, error: this.redactFailure(applied.error) };\n case \"exhausted\":\n return {\n ...applied,\n error: this.redactFailure(applied.error) as typeof applied.error,\n };\n }\n }\n\n /**\n * A function's arguments as an artifact writes them, marked by the shape of\n * its arguments. A command log of provider calls (#137's `commands()`) writes\n * each command's input through this.\n */\n projectArguments(functionPath: FunctionPath, args: Value): Value {\n return Redaction.markValue(\n args,\n placed(this.redaction.args(functionPath)),\n this.secrets,\n );\n }\n\n // Syscalls.\n\n private schema(componentPath: string) {\n return this.component(componentPath).schema;\n }\n\n private view(execution: Execution): KernelQuery.TableView {\n const attempt = transaction(execution);\n const { componentPath, limits } = execution;\n return {\n schema: this.schema(componentPath),\n scan: (tableName) => attempt.scan(componentPath, tableName),\n read: ({ index, ...interval }, after) => {\n const advance = attempt.readInterval({\n ...interval,\n componentPath,\n after,\n });\n return (through) => {\n advance(through);\n const examined = Metering.examined(\n interval.range,\n interval.order,\n after,\n through,\n );\n if (examined !== null) {\n refuse(\n attempt.meter.readInterval(\n indexKey(componentPath, interval.table, index),\n examined,\n limits,\n ),\n );\n }\n };\n },\n examine: (table, doc) =>\n refuse(attempt.meter.readDocument(doc, isSystemTable(table), limits)),\n };\n }\n\n /**\n * Read one document by ID, as the binary's `get_inner` does for a get and for\n * the document a patch, replace, delete or cancel changes: it reads the ID's\n * interval of the table's `by_id` index, then charges the document if there\n * is one (`crates/database/src/transaction.rs:1188-1250`).\n */\n private readById(\n attempt: KernelAttempt,\n execution: Execution,\n id: DocumentId,\n ): StoredDocument | null {\n const { componentPath, limits } = execution;\n const table = tableNameFromId(id)!;\n attempt.readDocument(componentPath, id);\n refuse(\n attempt.meter.readInterval(\n indexKey(componentPath, table, \"by_id\"),\n Metering.point([id]),\n limits,\n ),\n );\n const doc = attempt.get(componentPath, id);\n if (doc !== null) {\n refuse(attempt.meter.readDocument(doc, isSystemTable(table), limits));\n }\n return doc;\n }\n\n /**\n * Stage a write to a user table, counted against the execution's limits\n * first. A write over a limit is not staged (`Writes::update`,\n * `crates/database/src/writes.rs:241-310`).\n */\n private stage(\n execution: Execution,\n id: DocumentId,\n doc: StoredDocument | null,\n ) {\n const attempt = transaction(execution);\n refuse(attempt.meter.write(doc, execution.limits));\n attempt.write(execution.componentPath, id, doc);\n }\n\n private generateId(table: string): DocumentId {\n const counter = String(this.nextDocId++).padStart(\n TYPICAL_CONVEX_ID_LENGTH - table.length,\n \"0\",\n );\n return (counter + table) as DocumentId;\n }\n\n syscall(op: string, jsonArgs: string): string {\n const args = JSON.parse(jsonArgs);\n const execution = current();\n if (execution.attempt?.closed === true) throw closed(execution, op);\n switch (op) {\n case \"1.0/getSnapshotTs\":\n return JSON.stringify(\n convexToJson(transaction(execution).snapshot.commitTs),\n );\n case \"1.0/queryStream\": {\n // The binary reads a query at each `1.0/queryStreamNext`, which waits\n // its turn in the queue, so the stream opens at its first read and sees\n // every write made before it.\n const queryId = this.nextQueryId++;\n const view = this.view(execution);\n let results: Iterator<any> | undefined;\n this.queries.set(queryId, {\n next: () => (results ??= KernelQuery.stream(view, args.query)).next(),\n });\n return JSON.stringify({ queryId });\n }\n case \"1.0/queryCleanup\":\n this.queries.delete(args.queryId);\n return JSON.stringify({});\n case \"1.0/db/normalizeId\": {\n const tableName = tableNameFromId(args.idString);\n return JSON.stringify({\n id: tableName === args.table ? args.idString : null,\n });\n }\n default:\n throw new Error(`The test kernel does not support syscall: \"${op}\"`);\n }\n }\n\n /**\n * The binary queues a query's or mutation's async syscalls and runs them one\n * at a time, oldest first (`start_async_syscall` and `run_inner` in\n * `crates/isolate/src/environment/udf/mod.rs`, 1.49). A write and a nested\n * call never share a batch (`AsyncSyscallBatch::can_push` in\n * `async_syscall.rs`), and a nested call holds the queue until it has\n * committed or rolled back its subtransaction (`run_udf` in\n * `async_syscall.rs`). So a caller's write made after its nested call runs\n * after that call, and a nested mutation sees every write made before it. An\n * action's calls run side by side.\n */\n asyncSyscall(op: string, jsonArgs: string): Promise<string> {\n const execution = current();\n const attempt = execution.attempt;\n if (attempt === undefined) {\n return Promise.resolve().then(() =>\n this.dispatchAsync(op, JSON.parse(jsonArgs), execution),\n );\n }\n if (attempt.closed) return Promise.reject(closed(execution, op));\n // A syscall counts toward its frame's lifetime from the moment it is\n // queued, so a frame never closes with a write still waiting its turn.\n const end = attempt.begin();\n return execution.turn\n .take(() => this.dispatchAsync(op, JSON.parse(jsonArgs), execution))\n .finally(end);\n }\n\n private dispatchAsync(\n op: string,\n args: any,\n execution: Execution,\n ): string | Promise<string> {\n switch (op) {\n case \"1.0/get\": {\n const { table, id } = args;\n return JSON.stringify(convexToJson(this.get(execution, table, id)));\n }\n case \"1.0/queryStreamNext\": {\n const results = this.queries.get(args.queryId);\n if (results === undefined) throw new Error(\"Bad queryId\");\n const { value, done } = results.next();\n return JSON.stringify(\n convexToJson(\n done ? { value: null, done: true } : { value, done: false },\n ),\n );\n }\n case \"1.0/queryPage\": {\n const pagination = execution.pagination;\n if (pagination) {\n pagination.calls += 1;\n if (pagination.calls > 1) {\n throw new Error(\n \"Only a single paginated query (`.paginate()`) is allowed per \" +\n \"query, including nested query calls and component calls. \" +\n \"This is a Convex limit: https://docs.convex.dev/database/pagination\",\n );\n }\n }\n const page = KernelQuery.paginate(this.view(execution), {\n ...args,\n endCursor: args.endCursor ?? pagination?.journal ?? null,\n });\n if (pagination) pagination.end = page.continueCursor;\n return JSON.stringify(convexToJson(page as any));\n }\n case \"1.0/insert\":\n return JSON.stringify({\n _id: this.insert(execution, args.table, jsonToConvex(args.value)),\n });\n case \"1.0/shallowMerge\":\n this.patch(execution, args.table, args.id, args.value);\n return JSON.stringify({});\n case \"1.0/replace\":\n this.replace(execution, args.table, args.id, args.value);\n return JSON.stringify({});\n case \"1.0/remove\":\n this.remove(execution, args.table, args.id);\n return JSON.stringify({});\n case \"1.0/count\": {\n const attempt = transaction(execution);\n // The binary counts a table by reading its whole `by_id` index, and no\n // document (`count_tablet`, `crates/database/src/bootstrap_model/table.rs:133-160`).\n refuse(\n attempt.meter.readInterval(\n indexKey(execution.componentPath, args.table, \"by_id\"),\n Metering.everything,\n execution.limits,\n ),\n );\n attempt.readInterval({\n kind: \"interval\",\n componentPath: execution.componentPath,\n table: args.table,\n fields: [\"_creationTime\", \"_id\"],\n order: \"asc\",\n range: [],\n after: null,\n })(\"end\");\n return JSON.stringify(\n attempt.scan(execution.componentPath, args.table).length,\n );\n }\n case \"1.0/getFunctionMetadata\":\n return JSON.stringify(\n convexToJson({\n name: execution.udfPath,\n componentPath: execution.componentPath,\n }),\n );\n case \"1.0/getRequestMetadata\":\n if (execution.udfType === \"query\") {\n throw new Error(\n \"getRequestMetadata() can only be called from a mutation, action \" +\n \"or HTTP action. It is not available in queries.\",\n );\n }\n return JSON.stringify(convexToJson(execution.request as any));\n case \"1.0/getDeploymentMetadata\":\n return JSON.stringify(\n convexToJson({ name: \"test\", region: null, class: \"s16\" }),\n );\n case \"1.0/actions/query\":\n case \"1.0/actions/mutation\":\n case \"1.0/actions/action\": {\n const from: From = { request: execution.request, parent: execution };\n const functionPath = functionPathOf(args, execution.componentPath);\n const run =\n op === \"1.0/actions/query\"\n ? this.queryAt(functionPath, args.args, from)\n : op === \"1.0/actions/mutation\"\n ? this.mutationAt(functionPath, args.args, from)\n : this.actionAt(functionPath, args.args, from);\n return run.then((value) => JSON.stringify(convexToJson(value)));\n }\n case \"1.0/runUdf\": {\n const { udfType, args: udfArgs, transactionLimits } = args;\n const from: From = {\n request: execution.request,\n parent: execution,\n budget: budgetOf(transactionLimits),\n };\n const functionPath = functionPathOf(args, execution.componentPath);\n const value = jsonToConvex(udfArgs);\n const run =\n udfType === \"query\"\n ? this.queryAt(functionPath, value, from)\n : udfType === \"snapshotQuery\"\n ? this.queryAt(functionPath, value, from, true)\n : udfType === \"mutation\"\n ? this.mutationAt(functionPath, value, from)\n : Promise.reject(\n new Error(\n `The test kernel does not support udf type: \"${udfType}\"`,\n ),\n );\n return run.then((result) => JSON.stringify(convexToJson(result)));\n }\n case \"1.0/createFunctionHandle\": {\n const functionPath = functionPathOf(args, execution.componentPath);\n this.component(functionPath.componentPath);\n return JSON.stringify(createFunctionHandle(functionPath));\n }\n case \"1.0/auditLog\":\n return JSON.stringify(null);\n case \"1.0/schedule\":\n return JSON.stringify(\n convexToJson(\n this.scheduleJob(transaction(execution), execution, args),\n ),\n );\n case \"1.0/actions/schedule\":\n return JSON.stringify(\n convexToJson(\n this.commitNow((attempt) =>\n this.scheduleJob(attempt, execution, args),\n ),\n ),\n );\n case \"1.0/cancel_job\":\n this.cancelJob(transaction(execution), execution, args.id);\n return JSON.stringify({});\n case \"1.0/actions/cancel_job\":\n this.commitNow((attempt) =>\n this.cancelJob(attempt, execution, args.id),\n );\n return JSON.stringify({});\n case \"1.0/storageDelete\":\n case \"1.0/storageGetUrl\":\n case \"1.0/storageGenerateUploadUrl\":\n throw KernelRefusal.rowPending(\"storage\", 6);\n case \"1.0/getTransactionMetrics\":\n // An action has no transaction, and the binary's action syscalls do\n // not know this one (`crates/isolate/src/environment/action/async_syscall.rs:105`).\n if (execution.attempt === undefined) {\n throw new Error(`Unknown async operation ${op}`);\n }\n return JSON.stringify(\n execution.attempt.meter.metrics(execution.limits),\n );\n case \"1.0/actions/vectorSearch\":\n throw KernelRefusal.requiresBinary(\"vectorSearch\");\n default:\n throw new Error(\n `The test kernel does not support async syscall: \"${op}\"`,\n );\n }\n }\n\n jsSyscall(op: string): Promise<never> {\n return Promise.reject(\n op.startsWith(\"storage/\")\n ? KernelRefusal.rowPending(\"storage\", 6)\n : new Error(`The test kernel does not support js syscall: \"${op}\"`),\n );\n }\n\n // Documents. The checks and messages are convex-test's.\n\n private get(execution: Execution, tableName: unknown, id: unknown) {\n validateId(tableName, id);\n return this.readById(transaction(execution), execution, id);\n }\n\n private insert(execution: Execution, table: string, value: any): DocumentId {\n const attempt = transaction(execution);\n this.keepRow(execution.componentPath, table, value);\n KernelQuery.validateDocument(\n this.schema(execution.componentPath),\n table,\n value,\n );\n const _id = this.generateId(table);\n // A new ID joins the table's `by_id` reads without counting as one.\n attempt.meter.deriveInterval(\n indexKey(execution.componentPath, table, \"by_id\"),\n Metering.point([_id]),\n );\n this.stage(execution, _id, {\n ...value,\n _id,\n _creationTime: this.creationTime(execution.startTime),\n });\n return _id;\n }\n\n /**\n * A new document's creation time: `at`, or just past the latest one, so no\n * two documents share one.\n */\n private creationTime(at: number): number {\n const time =\n at <= this.lastCreationTime ? this.lastCreationTime + 0.001 : at;\n this.lastCreationTime = time;\n return time;\n }\n\n private existing(\n execution: Execution,\n tableName: unknown,\n id: unknown,\n write: string,\n value: unknown,\n ): StoredDocument {\n validateId(tableName, id);\n if (value !== undefined && typeof value !== \"object\") {\n throw new Error(\n `Invalid argument \\`value\\` in \\`db.${write}\\`, expected object but got '${typeof value}': ${value as any}`,\n );\n }\n const document = this.readById(transaction(execution), execution, id);\n if (document === null) {\n throw new Error(\n write === \"delete\"\n ? \"Delete on non-existent doc\"\n : `${write === \"patch\" ? \"Patch\" : \"Replace\"} on non-existent document with ID \"${id}\"`,\n );\n }\n return document;\n }\n\n private fields(document: StoredDocument, value: Record<string, any>) {\n if (value._id !== undefined && value._id !== document._id) {\n throw new Error(\n `Provided \\`_id\\` field value \"${value._id}\" ` +\n `does not match the document ID \"${document._id}\"`,\n );\n }\n if (\n value._creationTime !== undefined &&\n value._creationTime !== document._creationTime\n ) {\n throw new Error(\n `Provided \\`_creationTime\\` field value ${value._creationTime} ` +\n `does not match the document's creation time ${document._creationTime}`,\n );\n }\n const convexValue: Record<string, Value | undefined> = {};\n for (const [key, v] of Object.entries(value)) {\n if (key !== \"_id\" && key !== \"_creationTime\") {\n convexValue[key] = evaluateValue(v);\n }\n }\n return convexValue;\n }\n\n private patch(\n execution: Execution,\n tableName: unknown,\n id: unknown,\n value: Record<string, any>,\n ) {\n const document = this.existing(execution, tableName, id, \"patch\", value);\n const { _id, _creationTime, ...fields } = document;\n const merged = { ...fields, ...this.fields(document, value) };\n this.keepRow(execution.componentPath, tableNameFromId(_id)!, merged);\n const next = { _id, _creationTime, ...merged } as StoredDocument;\n if (sameDocument(document, next)) return;\n KernelQuery.validateDocument(\n this.schema(execution.componentPath),\n tableNameFromId(_id)!,\n merged,\n );\n this.stage(execution, _id, next);\n }\n\n private replace(\n execution: Execution,\n tableName: unknown,\n id: unknown,\n value: Record<string, any>,\n ) {\n const document = this.existing(execution, tableName, id, \"replace\", value);\n const fields = this.fields(document, value);\n this.keepRow(\n execution.componentPath,\n tableNameFromId(document._id)!,\n fields,\n );\n const next = {\n ...fields,\n _id: document._id,\n _creationTime: document._creationTime,\n } as StoredDocument;\n if (sameDocument(document, next)) return;\n KernelQuery.validateDocument(\n this.schema(execution.componentPath),\n tableNameFromId(document._id)!,\n fields,\n );\n this.stage(execution, document._id, next);\n }\n\n private remove(execution: Execution, tableName: unknown, id: unknown) {\n const document = this.existing(\n execution,\n tableName,\n id,\n \"delete\",\n undefined,\n );\n this.stage(execution, document._id, null);\n }\n}\n\n/**\n * Where a call comes from. A call from the test carries its accessor's caller.\n * A nested call carries its parent execution and takes its identity from it.\n */\ntype From =\n | {\n readonly caller: Caller;\n readonly request: Request;\n readonly parent?: undefined;\n readonly budget?: undefined;\n }\n | {\n readonly parent: Execution;\n readonly request: Request;\n readonly budget?: Metering.Budget | undefined;\n };\n\nconst refuse = (error: Metering.TransactionLimitExceeded | undefined) => {\n if (error !== undefined) throw error;\n};\n\n/**\n * One index of one table in one component, as the binary keys a read set.\n */\nconst indexKey = (componentPath: string, table: string, index: string) =>\n `${componentPath}\\u0000${table}\\u0000${index}`;\n\nconst isSystemTable = (table: string) => table.startsWith(\"_\");\n\nconst isFieldMap = (value: unknown): value is object =>\n typeof value === \"object\" && value !== null && isSimpleObject(value);\n\n/**\n * Whether two stored values are the same value, an unresolved commit timestamp\n * included. The binary compares pending values structurally, so a pending\n * timestamp equals only another pending timestamp, at any depth (`PendingValue`\n * derives `PartialEq`, `crates/value/src/pending.rs:56-75`, as\n * `PendingDocument` does, `crates/common/src/document.rs:624-632`). Concrete\n * values compare by `ConvexValue`'s total order\n * (`crates/value/src/sorting.rs:468-472`), which `compareValues` follows.\n * `compareValues` alone ranks a pending timestamp as the largest int64, so it\n * cannot tell the two apart. An object field set to `undefined` is absent.\n */\nconst sameValue = (a: unknown, b: unknown): boolean => {\n const aPending = a instanceof CommitTsPlaceholder;\n const bPending = b instanceof CommitTsPlaceholder;\n if (aPending || bPending) return aPending && bPending;\n if (Array.isArray(a) || Array.isArray(b)) {\n return (\n Array.isArray(a) &&\n Array.isArray(b) &&\n a.length === b.length &&\n a.every((value, i) => sameValue(value, b[i]))\n );\n }\n if (isFieldMap(a) || isFieldMap(b)) {\n if (!isFieldMap(a) || !isFieldMap(b)) return false;\n const fields = (value: object) =>\n Object.entries(value).filter(([, field]) => field !== undefined);\n const aFields = fields(a);\n const bFields = new Map(fields(b));\n return (\n aFields.length === bFields.size &&\n aFields.every(\n ([key, field]) =>\n bFields.has(key) && sameValue(field, bFields.get(key)),\n )\n );\n }\n return compareValues(a as Value, b as Value) === 0;\n};\n\n/**\n * Whether a patch or replace leaves a document as it was. The binary then\n * writes nothing (`patch_inner` and `replace_inner`,\n * `crates/database/src/transaction.rs:713-790`).\n */\nconst sameDocument = (before: StoredDocument, after: StoredDocument) =>\n sameValue(before, after);\n\n/**\n * A nested call's `transactionLimits`. The binary reads each field as an\n * unsigned integer and ignores fields it does not know (`TransactionLimits`,\n * `crates/database/src/execution_size.rs:62-95`).\n */\nconst budgetOf = (limits: unknown): Metering.Budget | undefined => {\n if (limits === undefined || limits === null) return undefined;\n const budget: Partial<Record<keyof Metering.Limits, number>> = {};\n for (const metric of Object.keys(Metering.defaults) as Array<\n keyof Metering.Limits\n >) {\n const value = (limits as Record<string, unknown>)[metric];\n if (value === undefined) continue;\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < 0) {\n throw new Error(\n `Invalid arguments for \\`runUdf\\`: transactionLimits.${metric} must be a non-negative integer, got ${JSON.stringify(value)}`,\n );\n }\n budget[metric] = value;\n }\n return budget;\n};\n\nconst closed = (execution: Execution, operation: string) =>\n new KernelRefusal.ClosedAttempt({\n operation,\n message: `\"${operation}\" reached mutation ${execution.udfPath} after it returned and its syscalls settled. Await every read and write inside the handler.`,\n });\n\nconst transaction = (execution: Execution): KernelAttempt => {\n if (execution.attempt === undefined) {\n throw new Error(\n \"The database is only available in queries and mutations. An action reads and writes through `ctx.runQuery` and `ctx.runMutation`.\",\n );\n }\n return execution.attempt;\n};\n\nconst queryAuth = (execution: Execution) => ({\n getUserIdentity: () => {\n execution.attempt?.observeIdentity();\n return Promise.resolve(execution.identity);\n },\n});\n\nconst mutationAuth = (execution: Execution) => ({\n ...queryAuth(execution),\n signJwt: () => Promise.reject(KernelRefusal.rowPending(\"JWT signing\", 6)),\n});\n\nfunction validateId(\n expectedTableName: unknown,\n id: unknown,\n): asserts id is DocumentId {\n if (typeof id !== \"string\") {\n throw new Error(\n `Invalid argument \\`id\\`, expected string but got '${typeof id}': ${id as any}`,\n );\n }\n if (expectedTableName === undefined) return;\n if (typeof expectedTableName !== \"string\") {\n throw new Error(\n `Invalid argument \\`tableName\\`, expected string but got '${typeof expectedTableName}': ${expectedTableName as any}`,\n );\n }\n const actualTableName = tableNameFromId(id);\n if (actualTableName === null) {\n throw new Error(\n `Invalid argument \\`id\\`, expected ID value but got '${id}'`,\n );\n }\n if (actualTableName !== expectedTableName) {\n throw new Error(\n `Invalid argument \\`id\\`, expected ID in table '${expectedTableName}' but got ID in table '${actualTableName}'`,\n );\n }\n}\n\ninterface Syscalls {\n readonly syscall: (op: string, args: string) => string;\n readonly asyncSyscall: (op: string, args: string) => Promise<string>;\n readonly jsSyscall: (op: string, args: unknown) => unknown;\n}\n\ntype Branded = { readonly [kernelBrand]?: true };\n\n/**\n * The backend another library installed as `globalThis.Convex`, which answers\n * every syscall made outside a kernel function.\n */\nlet forwarded: Syscalls | undefined;\n\n// With neither, `current` refuses the syscall.\nconst backend = (): Syscalls =>\n executions.getStore()?.world ?? forwarded ?? current().world;\n\nconst dispatcher: Syscalls & Branded = {\n [kernelBrand]: true,\n syscall: (op, args) => backend().syscall(op, args),\n asyncSyscall: (op, args) => backend().asyncSyscall(op, args),\n jsSyscall: (op, args) => backend().jsSyscall(op, args),\n};\n\n/**\n * Convex's server library reaches the backend through `globalThis.Convex`, one\n * global for the whole test runtime. convex-test 0.0.65 assigns its own the\n * first time it builds a world (its `dist/index.js:1936-1951`), whenever that\n * is. The kernel keeps the global an accessor that always reads its dispatcher,\n * and takes an assignment, or the global it found, as the backend for syscalls\n * made outside a kernel function. So a kernel world and a convex-test world\n * stay live together, whichever was built first, and no world restores the\n * global when it ends. A test that redefines the global removes the accessor,\n * so every kernel function installs it again over what the test left.\n */\nconst installConvexGlobal = () => {\n const found = (globalThis as { Convex?: Syscalls & Branded }).Convex;\n if (found?.[kernelBrand] === true) return;\n forwarded = found;\n Object.defineProperty(globalThis, \"Convex\", {\n get: () => dispatcher,\n set: (value: (Syscalls & Branded) | undefined) => {\n if (value?.[kernelBrand] !== true) forwarded = value;\n },\n configurable: true,\n enumerable: true,\n });\n};\n\n/**\n * Whether `globalThis.Convex` is the kernel's, and no other backend installed\n * one behind it.\n */\nexport const ownsConvexGlobal = (): boolean =>\n (globalThis as { Convex?: Branded }).Convex?.[kernelBrand] === true &&\n forwarded === undefined;\n"],"mappings":";;;;;;;;;;;;;;;;;AAqDA,MAAM,OAAO;AACb,MAAM,2BAA2B;AA8BjC,MAAa,YAAoB;CAC/B,UAAU;CACV,OAAO;CACP,IAAI;CACJ,WAAW;AACb;AAEA,MAAa,gBACX,QACA,aACW;CACX,MAAM,UAAU,SAAS,WAAW,KAAK,WAAW,KAAK,UAAU,QAAQ,CAAC;CAC5E,MAAM,SAAS,SAAS,UAAU;CAClC,MAAM,kBAAkB,SAAS,mBAAmB,GAAG,OAAO,GAAG;CACjE,MAAM,OAAO;EAAE,GAAG;EAAU;EAAS;EAAQ;CAAgB;CAC7D,OAAO;EAAE,GAAG;EAAQ,UAAU;EAAM,OAAO,cAAc,IAAI;CAAE;AACjE;AAsGA,MAAM,cAAkC;AAExC,MAAM,SAAS,UAA2B;CACxC,MAAM,UAAU,UACd,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAA6B,SAAS;CAChD,MAAM,OAAQ,OAAqC;CACnD,IAAI,OAAO,IAAI,GAAG,OAAO,KAAK;CAC9B,IAAI,OAAO,KAAK,GAAG,OAAO,MAAM;CAChC,OAAO,iBAAiB,QAAQ,MAAM,OAAO;AAC/C;;;;AAgCA,IAAM,OAAN,MAAW;CACT,OAAiC,QAAQ,QAAQ;CAEjD,KAAQ,MAAwC;EAC9C,MAAM,SAAS,KAAK,KAAK,KAAK,IAAI;EAClC,KAAK,OAAO,OAAO,WACX,KAAA,SACA,KAAA,CACR;EACA,OAAO;CACT;;;;;CAMA,OAAsB;EACpB,MAAM,OAAO,KAAK;EAClB,OAAO,KAAK,WAAY,KAAK,SAAS,OAAO,KAAA,IAAY,KAAK,KAAK,CAAE;CACvE;AACF;;;;;;;;AASA,MAAM,WAAc,WAAsB,WACxC,UAAU,KAAK,KAAK,CAAC,CAAC,WAAW,MAAM;AAEz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sBAAsB,KAAA,GAAW;CACrC,IAAI,OAAO,sBAAsB,UAC/B,MAAM,IAAI,MACR,4DAA4D,OAAO,kBAAkB,KAAK,mBAC5F;CAEF,MAAM,kBAAkB,gBAAgB,EAAE;CAC1C,IAAI,oBAAoB,MACtB,MAAM,IAAI,MACR,uDAAuD,GAAG,EAC5D;CAEF,IAAI,oBAAoB,mBACtB,MAAM,IAAI,MACR,kDAAkD,kBAAkB,yBAAyB,gBAAgB,EAC/G;AAEJ;;;;;AAcA,IAAI;AAGJ,MAAM,gBACJ,WAAW,SAAS,CAAC,EAAE,SAAS,aAAa,QAAQ,CAAC,CAAC;AAEzD,MAAM,aAAiC;EACpC,cAAc;CACf,UAAU,IAAI,SAAS,QAAQ,CAAC,CAAC,QAAQ,IAAI,IAAI;CACjD,eAAe,IAAI,SAAS,QAAQ,CAAC,CAAC,aAAa,IAAI,IAAI;CAC3D,YAAY,IAAI,SAAS,QAAQ,CAAC,CAAC,UAAU,IAAI,IAAI;AACvD;;;;;;;;;;;;AAaA,MAAM,4BAA4B;CAChC,MAAM,QAAS,WAA+C;CAC9D,IAAI,QAAQ,iBAAiB,MAAM;CACnC,YAAY;CACZ,OAAO,eAAe,YAAY,UAAU;EAC1C,WAAW;EACX,MAAM,UAA4C;GAChD,IAAI,QAAQ,iBAAiB,MAAM,YAAY;EACjD;EACA,cAAc;EACd,YAAY;CACd,CAAC;AACH;;;;;AAMA,MAAa,yBACV,WAAoC,SAAS,iBAAiB,QAC/D,cAAc,KAAA"}
@@ -18,18 +18,23 @@ export declare const exportSchema: (schema: SchemaDefinition<GenericSchema, bool
18
18
  */
19
19
  export declare const validateDocument: (schema: KernelSchema | null, tableName: string, doc: Record<string, unknown>) => void;
20
20
  /**
21
- * An interval a query reads, before it says where it starts and how far it got.
21
+ * An interval a query reads, before it says where it starts and how far it got,
22
+ * and the index it reads it from.
22
23
  */
23
- export type Interval = Omit<ReadSet.IntervalRead, "componentPath" | "after" | "through">;
24
+ export type Interval = Omit<ReadSet.IntervalRead, "componentPath" | "after" | "through"> & {
25
+ readonly index: string;
26
+ };
24
27
  /**
25
28
  * What a query reads: one table of one component, as the running attempt sees
26
29
  * it. `read` records an interval in the attempt's read set and returns how to
27
- * advance it.
30
+ * advance it. `examine` charges one document the query examined, before the
31
+ * query's filters see it.
28
32
  */
29
33
  export interface TableView {
30
34
  readonly schema: KernelSchema | null;
31
35
  readonly scan: (tableName: string) => ReadonlyArray<StoredDocument>;
32
36
  readonly read: (interval: Interval, after: ReadSet.Key | null) => (through: ReadSet.Key | "end") => void;
37
+ readonly examine: (table: string, doc: GenericDocument) => void;
33
38
  }
34
39
  /**
35
40
  * A query's documents in order. The source is read when the query starts, as a
@@ -1 +1 @@
1
- {"version":3,"file":"KernelQuery.d.ts","sourceRoot":"","sources":["../../src/internal/KernelQuery.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EACV,eAAe,EACf,aAAa,EACb,gBAAgB,EACjB,MAAM,eAAe,CAAC;AAQvB,OAAO,KAAK,OAAO,MAAM,cAAc,CAAC;AACxC,OAAO,KAAK,EAEV,KAAK,EACL,eAAe,EAEf,cAAc,EACd,aAAa,EACd,MAAM,mBAAmB,CAAC;AAY3B;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,gBAAgB,EAAE,OAAO,CAAC;IACnC,QAAQ,CAAC,MAAM,EAAE,WAAW,CAC1B,MAAM,EACN;QACE,QAAQ,CAAC,OAAO,EAAE,aAAa,CAAC,KAAK,CAAC,CAAC;QACvC,QAAQ,CAAC,YAAY,EAAE,aAAa,CAAC;KACtC,CACF,CAAC;CACH;AAED,eAAO,MAAM,YAAY,WACf,gBAAgB,CAAC,aAAa,EAAE,OAAO,CAAC,GAAG,IAAI,GAAG,SAAS,KAClE,YAAY,GAAG,IA4BjB,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,gBAAgB,WACnB,YAAY,GAAG,IAAI,aAChB,MAAM,OACZ,MAAM,CAAC,MAAM,EAAE,OA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