@onda-lang/processor-abi 0.8.5 → 0.8.7

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.
package/README.md CHANGED
@@ -65,17 +65,27 @@ Wire payloads are packed little-endian in canonical structure-of-arrays leaf ord
65
65
  `sizes(lengths)` when only dynamic slice lengths are known, or `requiredWorkspace(payload)` to
66
66
  preflight encoded bytes. Allocate payload, workspace, and the 16-byte `EventInput` descriptor before
67
67
  realtime dispatch, and keep their memory regions disjoint from one another and processor storage.
68
+ `plan.tensorMetadata` exposes the same flattened contract as immutable records containing the leaf
69
+ `path`, primitive `encoding`, fixed `shape`, owning `parameterIndex`, `isSlice`, and
70
+ `fixedElementCount`. It is suitable for generating typed host storage or diagnostics without
71
+ walking the recursive schema again.
68
72
  `PayloadPlan.encode()` itself allocates and therefore belongs on a host/control thread, as does
69
73
  decoding published delegate records. An event result of `PROCESSOR_EXECUTION_INPUT_REJECTED` (`2`)
70
- means preflight failed without handler or output mutation.
74
+ means preflight failed after output was reset but before handler or processor-state mutation.
75
+
76
+ WebAssembly intentionally exposes only the packed checked event entry. JavaScript values cross a
77
+ thread boundary and must enter Wasm linear memory, so the native synchronous borrowed-view contract
78
+ cannot provide end-to-end zero-copy dispatch on the Web. Web hosts should prepare capacity ahead of
79
+ time and reuse the payload and workspace regions.
71
80
 
72
81
  ## Delegate batches
73
82
 
74
83
  The package exports `DELEGATE_RECORD_HEADER_SIZE_BYTES`, `DELEGATE_BATCH_SIZE_BYTES`,
75
- `writeDelegateBatch()`, `readDelegateBatch()`, and `decodeDelegateRecords()` for allocation-free
76
- call-scoped delegate collection. Descriptor entries expose exact fixed payload sizes or dynamic
77
- minimum sizes. A complete fixed record occupies the twelve-byte header (index, payload size, and
78
- call-local output sequence) plus its payload; no exact
84
+ `writeDelegateBatch()`, `readDelegateBatch()`, and `decodeDelegateBatch()` for call-scoped delegate
85
+ collection. Batch preparation and generated publication are allocation-free;
86
+ `decodeDelegateRecords()` remains available for an already-isolated storage region. Descriptor
87
+ entries expose exact fixed payload sizes or dynamic minimum sizes. A complete fixed record occupies
88
+ the twelve-byte header (index, payload size, and call-local output sequence) plus its payload; no exact
79
89
  whole-call capacity exists because occurrence counts and slice lengths may be runtime-dependent.
80
90
 
81
91
  ```js
@@ -84,8 +94,7 @@ import {
84
94
  writeDelegateBatch,
85
95
  writeExecutionOutput,
86
96
  resetExecutionOutput,
87
- readDelegateBatch,
88
- decodeDelegateRecords,
97
+ decodeDelegateBatch,
89
98
  } from "@onda-lang/processor-abi";
90
99
 
91
100
  const delegates = artifact.metadata.metadata.delegates;
@@ -99,16 +108,13 @@ writeDelegateBatch(memory, batchAddress, storageAddress, capacityBytes);
99
108
  writeExecutionOutput(memory, outputAddress, batchAddress, 0);
100
109
  // Before onda_process (or initialization):
101
110
  resetExecutionOutput(memory, outputAddress);
102
- // Pass outputAddress as the final entry argument. onda_event_N resets it itself after preflight.
103
- const batch = readDelegateBatch(memory, batchAddress);
104
- const storage = new Uint8Array(memory.buffer, storageAddress, batch.usedBytes);
105
- const occurrences = decodeDelegateRecords(
106
- storage,
107
- batch.usedBytes,
108
- delegates,
109
- artifact.metadata.target.byte_order,
111
+ // Pass outputAddress as the final entry argument. onda_event_N resets it before preflight.
112
+ const { occurrences, overflowCount } = decodeDelegateBatch(
113
+ memory,
114
+ batchAddress,
115
+ artifact.metadata,
110
116
  );
111
- if (batch.overflowCount) reportOverflow(batch.overflowCount);
117
+ if (overflowCount) reportOverflow(overflowCount);
112
118
  ```
113
119
 
114
120
  Allocate the descriptor and storage before realtime execution and consume records before the next
package/api.md CHANGED
@@ -121,8 +121,10 @@ versions rather than guessing layout compatibility.
121
121
  `createParamControl(metadata)` validates one scalar parameter descriptor and returns a reusable
122
122
  `OndaPreparedParamControl`. For an array, `createParamControl(metadata, index)` prepares one element;
123
123
  `paramElementMetadata(metadata, index)` projects its scalar descriptor, default, and storage offset.
124
- The Web Audio adapter accepts indexed names such as `offsets[1]` in `setParam` and
125
- `setParamNormalized`, and exact-length arrays in `setParam("offsets", values)`.
124
+ The Web Audio adapter exposes `setParamElement(nameOrIndex, element, value)` and
125
+ `setParamElementNormalized(nameOrIndex, element, normalized)` for individual scalar or fixed-array
126
+ elements. Indexed names such as `offsets[1]` remain accepted by `setParam` and
127
+ `setParamNormalized`; exact-length arrays use `setParam("offsets", values)`.
126
128
  `createParamDomain(domain)` does the same from already-decoded values.
127
129
  Prepared controls expose `constrainPlain`, `normalizedToPlain`, and `plainToNormalized` methods.
128
130
 
@@ -135,14 +137,17 @@ endpoints, apply linear, logarithmic, or curved scale, and clamp and snap to the
135
137
 
136
138
  Complete wasm32 processor exports receive an optional execution-output descriptor containing
137
139
  independently nullable delegate and print batches. Allocate all descriptors and storage before
138
- real-time execution.
140
+ real-time execution. Their linear-memory regions must be mutually disjoint and must not overlap any
141
+ other region accessed by the processor call, matching the processor ABI's execution-output
142
+ contract.
139
143
 
140
144
  `writeDelegateBatch` and `writePrintBatch` initialize reusable batch descriptors.
141
145
  `writeExecutionOutput` connects their addresses. Call `resetExecutionOutput` immediately before
142
- every generated init or process entry. Generated event entries reset after successful input
143
- preflight instead, so rejected input preserves existing records. After a successful generated call,
146
+ every generated init or process entry. Generated event entries reset before input preflight, so
147
+ rejected input returns empty batches. After a successful generated call,
144
148
  `readDelegateBatch` or `readPrintBatch` validates the result counters.
145
- `decodeDelegateRecords` converts delegate payloads using `metadata.delegates`.
149
+ `decodeDelegateBatch` validates and decodes a complete delegate batch in one call;
150
+ `decodeDelegateRecords` decodes an already-isolated storage region using `metadata.delegates`.
146
151
  `decodePrintRecords` preserves primitive types and source sites; `formatPrintRecords` and
147
152
  `formatPrintBatch` add canonical text formatting. Both decoded record types expose a `sequence` from
148
153
  the host-reset call-local counter; merge that call's two arrays by this field when presenting one
@@ -184,27 +189,36 @@ The package root re-exports the common artifact validation and file helpers. The
184
189
  - `compileOndaProcessorModule(artifact)` validates and compiles a reusable module off the render thread.
185
190
  - `ondaAudioWorkletNodeOptions(artifact, options?)` builds low-level node options.
186
191
  - `createOndaAudioProcessor(context, artifact, options?)` allocates an uninitialized adapter.
187
- - `createOndaAudioProcessorInitialized(context, artifact, options?)` allocates and fully initializes it.
192
+ - `createOndaAudioProcessorInitialized(context, artifact, options?)` allocates it, requests full
193
+ initialization through the status-bearing control protocol, and resolves only on success.
188
194
  - `flattenedAudioChannelCount(ports?)` totals declared physical channels with validation.
189
195
 
190
196
  `OndaAudioProcessorOptions` accepts initial plain parameter values, external buffers, event,
191
197
  delegate, and print capacities, an optional construction-time `onPrint` listener, a precompiled
192
198
  module, custom node options, and an `AudioWorkletNode` constructor. Pass `onPrint` when using the
193
- initialized constructor if initialization output must be observed; registering a listener after
199
+ initialized factory if initialization output must be observed; registering a listener after
194
200
  construction cannot replay output from an execution that has already completed. The artifact sample
195
201
  rate must equal the context sample rate and it must expose at least one audio input or output.
196
202
  Print and delegate delivery uses a bounded `SharedArrayBuffer` ring and requires cross-origin
197
203
  isolation in browsers; ordinary audio processing remains available when shared memory is absent.
198
204
  Low-level callers that manually pair the returned node options with `OndaAudioProcessor` must pass
199
- `processorOptions.executionOutputRing` as the adapter constructor's fourth argument.
205
+ the artifact metadata as the adapter constructor's second argument and
206
+ `processorOptions.executionOutputRing` as its fourth argument. Event encoding and numeric
207
+ unknown-index classification require that metadata.
200
208
 
201
209
  ### `OndaAudioProcessor`
202
210
 
203
211
  The adapter exposes its `node` and validated `metadata`, plus these operations:
204
212
 
205
- - `setParam(nameOrIndex, plain)` and `setParamNormalized(nameOrIndex, normalized)`.
206
- - `trigger(nameOrIndex, values?)` for input events.
207
- - `onDelegates(listener)` and `onPrint(listener)`, each returning an unsubscribe function.
213
+ - `setParam(nameOrIndex, plain)` and `setParamNormalized(nameOrIndex, normalized)` for whole
214
+ parameters.
215
+ - `setParamElement(nameOrIndex, element, plain)` and
216
+ `setParamElementNormalized(nameOrIndex, element, normalized)` for one scalar or fixed-array
217
+ element.
218
+ - `trigger(nameOrIndex, values?)` for input events. Unknown nonnegative numeric indices are
219
+ successful no-ops, matching native dispatch; unknown names and negative indices are rejected.
220
+ - `onExecutionError(listener)`, `onDelegates(listener)`, and `onPrint(listener)`, each returning an
221
+ unsubscribe function.
208
222
  - `init(mode)`, `snapshot()`, and `restoreSnapshot(bytes)`.
209
223
  - `readControlOutputs()` and `readBuffer(nameOrIndex)`.
210
224
  - `request(type, fields?, transfer?)` for adapter protocol extensions.
@@ -222,7 +236,24 @@ each init, event, or process segment.
222
236
 
223
237
  `ONDA_INIT_FULL` clears and initializes all physical state. `ONDA_INIT_PRESERVE_PINNED` retains
224
238
  pinned state according to the processor ABI. The package also re-exports the prepared and one-shot
225
- parameter conversion helpers.
239
+ parameter conversion helpers. Snapshot restoration performs its internal full initialization
240
+ silently, without delivering init prints or delegates.
241
+
242
+ Raw WebAssembly exports use the same generated status values as native processor objects:
243
+ `PROCESSOR_EXECUTION_OK` (`0`), `PROCESSOR_EXECUTION_RUNTIME_SAFETY_FAILURE` (`1`), and event-only
244
+ `PROCESSOR_EXECUTION_INPUT_REJECTED` (`2`). The Web Audio adapter translates host-side validation
245
+ problems into rejected promises before generated execution. It also rejects init and event promises
246
+ when generated code returns a nonzero status: status `1` invalidates the live processor, while event
247
+ status `2` preserves it. These generated failures use `OndaExecutionError`, whose `operation` and
248
+ `status` fields retain the machine-readable failure. The Web Audio root re-exports all three
249
+ `PROCESSOR_EXECUTION_*` constants for direct comparison. Render-time process failure invalidates the
250
+ processor and silences subsequent callbacks. `onExecutionError(listener)` receives its typed
251
+ `OndaExecutionError`; requested init and event failures remain on their promise rejection path and
252
+ are not reported twice.
253
+ The raw `@onda-lang/processor-abi` package exposes `PROCESSOR_BEGIN_BLOCK`,
254
+ `PROCESSOR_END_BLOCK`, and `PROCESSOR_FULL_BLOCK` for native and direct WebAssembly hosts that use
255
+ segmented processing. Web Audio schedules render quanta internally and has no segmented-process
256
+ method.
226
257
 
227
258
  `@onda-lang/webaudio/worklet` is the side-effect-only AudioWorklet registration module and has no
228
259
  named exports.
@@ -269,8 +300,11 @@ PRINT_RECORD_HEADER_SIZE_BYTES
269
300
  PROCESSOR_ABI_VERSION
270
301
  PROCESSOR_ARTIFACT_FORMAT
271
302
  PROCESSOR_ARTIFACT_FORMAT_VERSION
303
+ PROCESSOR_BEGIN_BLOCK
304
+ PROCESSOR_END_BLOCK
272
305
  PROCESSOR_EXECUTION_OK
273
306
  PROCESSOR_EXECUTION_RUNTIME_SAFETY_FAILURE
307
+ PROCESSOR_FULL_BLOCK
274
308
  PROCESSOR_INIT_FULL
275
309
  PROCESSOR_INIT_PRESERVE_PINNED
276
310
  PROCESSOR_SNAPSHOT_FORMAT_VERSION
@@ -279,6 +313,7 @@ createParamControl
279
313
  paramElementMetadata
280
314
  createParamDomain
281
315
  createProcessorArtifactFiles
316
+ decodeDelegateBatch
282
317
  decodeDelegateRecords
283
318
  decodePrintRecords
284
319
  formatPrintBatch
@@ -303,6 +338,7 @@ OndaPayloadSchema
303
338
  OndaPayloadDefault
304
339
  OndaPayloadValue
305
340
  OndaPayloadSizes
341
+ OndaPayloadTensorMetadata
306
342
  PayloadPlan
307
343
  canonicalF32Number
308
344
  EVENT_INPUT_SIZE_BYTES
@@ -317,12 +353,19 @@ OndaArtifactError
317
353
  OndaBinaryenError
318
354
  OndaBinaryenOptions
319
355
  OndaProcessorArtifact
356
+ OndaProcessorInitMode
320
357
  OndaProcessorMetadata
321
358
  PROCESSOR_ABI_VERSION
322
359
  PROCESSOR_ARTIFACT_FORMAT
323
360
  PROCESSOR_ARTIFACT_FORMAT_VERSION
361
+ PROCESSOR_BEGIN_BLOCK
362
+ PROCESSOR_END_BLOCK
363
+ PROCESSOR_EXECUTION_INPUT_REJECTED
324
364
  PROCESSOR_EXECUTION_OK
325
365
  PROCESSOR_EXECUTION_RUNTIME_SAFETY_FAILURE
366
+ PROCESSOR_FULL_BLOCK
367
+ PROCESSOR_INIT_FULL
368
+ PROCESSOR_INIT_PRESERVE_PINNED
326
369
  PROCESSOR_SNAPSHOT_FORMAT_VERSION
327
370
  SUPPORTED_MIR_SCHEMA_VERSION
328
371
  compileTrustedMir
@@ -363,6 +406,7 @@ OndaLspAnalysisOptions
363
406
  OndaLspMessage
364
407
  OndaMaterializedProjectFile
365
408
  OndaProcessorArtifact
409
+ OndaProcessorInitMode
366
410
  OndaProcessorMetadata
367
411
  OndaProjectBufferInfo
368
412
  OndaProjectCapabilities
@@ -380,8 +424,14 @@ OndaWorkerLike
380
424
  PROCESSOR_ABI_VERSION
381
425
  PROCESSOR_ARTIFACT_FORMAT
382
426
  PROCESSOR_ARTIFACT_FORMAT_VERSION
427
+ PROCESSOR_BEGIN_BLOCK
428
+ PROCESSOR_END_BLOCK
429
+ PROCESSOR_EXECUTION_INPUT_REJECTED
383
430
  PROCESSOR_EXECUTION_OK
384
431
  PROCESSOR_EXECUTION_RUNTIME_SAFETY_FAILURE
432
+ PROCESSOR_FULL_BLOCK
433
+ PROCESSOR_INIT_FULL
434
+ PROCESSOR_INIT_PRESERVE_PINNED
385
435
  PROCESSOR_SNAPSHOT_FORMAT_VERSION
386
436
  WorkerCompilerOptions
387
437
  createCompiler
@@ -405,11 +455,16 @@ OndaAudioProcessor
405
455
  OndaAudioProcessorOptions
406
456
  OndaAudioPrintBatch
407
457
  OndaAudioPrintListener
458
+ OndaExecutionError
459
+ OndaExecutionErrorListener
408
460
  OndaInitMode
409
461
  OndaParamDomain
410
462
  OndaPreparedParamControl
411
463
  OndaProcessorArtifact
412
464
  OndaProcessorMetadata
465
+ PROCESSOR_EXECUTION_INPUT_REJECTED
466
+ PROCESSOR_EXECUTION_OK
467
+ PROCESSOR_EXECUTION_RUNTIME_SAFETY_FAILURE
413
468
  compileOndaProcessorModule
414
469
  constrainParamPlain
415
470
  createOndaAudioProcessor
@@ -432,11 +487,21 @@ are rejected. Missing event arguments use declared constant defaults.
432
487
  Supply `i64` as `bigint`, an exact safe integer, or a decimal string. `decode(bytes)` returns named
433
488
  nested values with `bigint` for `i64`. Plans own immutable schema snapshots.
434
489
 
490
+ `tensorMetadata` exposes the schema's flattened SoA contract without reparsing JSON. Each immutable
491
+ record contains `path`, `encoding`, fixed `shape`, `parameterIndex`, `isSlice`, and
492
+ `fixedElementCount`. Tuple path components use `__0`, `__1`, and so on. A slice's runtime tensor
493
+ length is its logical length times `fixedElementCount`; the dynamic outer axis is therefore not
494
+ repeated in `shape`.
495
+
435
496
  `requiredWorkspace(bytes)` preflights packed little-endian input. `sizes(lengths)` reports wire
436
497
  and aligned workspace sizes without allocating payload storage. Low-level wasm hosts provision
437
498
  both regions and a 16-byte descriptor, then call `writeEventInput` before invoking the event.
438
499
  Rejected input returns `PROCESSOR_EXECUTION_INPUT_REJECTED` (2) and leaves processor state usable.
439
500
  `OndaAudioProcessor.trigger` performs logical encoding before transferring bytes to the worklet.
501
+ Web hosts intentionally have no unchecked tensor-view event entry: JavaScript values must cross the
502
+ main-thread/worklet and Wasm linear-memory boundaries, so native borrowed addresses cannot be
503
+ preserved end to end. Web event dispatch remains the packed, checked `onda_event_N` path and uses
504
+ its preallocated workspace.
440
505
  Decoded `f32` leaves use `canonicalF32Number(value)`: the returned JavaScript number has the
441
506
  shortest decimal representation that round-trips to the same `f32`, so JSON and controls do not
442
507
  expose an irrelevant widened binary tail.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onda-lang/processor-abi",
3
- "version": "0.8.5",
3
+ "version": "0.8.7",
4
4
  "type": "module",
5
5
  "description": "Shared Onda processor artifact schema, validation, and integrity helpers",
6
6
  "license": "MIT",
package/src/index.d.ts CHANGED
@@ -1,11 +1,14 @@
1
1
  export const PROCESSOR_ARTIFACT_FORMAT: "onda-processor";
2
2
  // Synchronized from format-versions.json; do not edit these copies directly.
3
3
  export const PROCESSOR_ARTIFACT_FORMAT_VERSION: 6;
4
- export const PROCESSOR_ABI_VERSION: 6;
4
+ export const PROCESSOR_ABI_VERSION: 7;
5
5
  export const PROCESSOR_EXECUTION_OK: 0;
6
6
  export const PROCESSOR_EXECUTION_RUNTIME_SAFETY_FAILURE: 1;
7
7
  export const PROCESSOR_INIT_PRESERVE_PINNED: 0;
8
8
  export const PROCESSOR_INIT_FULL: 1;
9
+ export const PROCESSOR_BEGIN_BLOCK: 1;
10
+ export const PROCESSOR_END_BLOCK: 2;
11
+ export const PROCESSOR_FULL_BLOCK: 3;
9
12
  export type OndaProcessorInitMode = 0 | 1;
10
13
  export const PROCESSOR_SNAPSHOT_FORMAT_VERSION: 1;
11
14
  /** Bytes preceding the payload of every packed delegate occurrence. */
@@ -167,6 +170,18 @@ export interface OndaPayloadField {
167
170
  }
168
171
  export interface OndaPayloadSchema { params: OndaPayloadField[] }
169
172
 
173
+ export interface OndaPayloadTensorMetadata {
174
+ /** Dot-separated top-level parameter and struct-field path. Array axes are described by shape. */
175
+ readonly path: string;
176
+ readonly encoding: OndaScalarType;
177
+ /** Fixed array axes, outermost first. */
178
+ readonly shape: readonly number[];
179
+ readonly parameterIndex: number;
180
+ readonly isSlice: boolean;
181
+ /** Product of all fixed array axes. */
182
+ readonly fixedElementCount: number;
183
+ }
184
+
170
185
  export type OndaPayloadValue = number | bigint | boolean | string | OndaPayloadValue[] | { [name: string]: OndaPayloadValue };
171
186
  export interface OndaPayloadSizes { wire: number; workspace: number }
172
187
  export class PayloadPlan {
@@ -176,6 +191,8 @@ export class PayloadPlan {
176
191
  readonly minimumWorkspace: number;
177
192
  readonly dynamicParameters: number;
178
193
  readonly abiParameterCount: number;
194
+ /** Flattened SoA tensors in event/delegate ABI order. */
195
+ readonly tensorMetadata: readonly OndaPayloadTensorMetadata[];
179
196
  /** Whether scalar representations match this flattened ABI parameter's schema default. */
180
197
  matchesAbiDefault(parameter: number, defaultReprs: readonly string[] | null): boolean;
181
198
  sizes(lengths: readonly number[]): OndaPayloadSizes;
@@ -257,7 +274,7 @@ export interface OndaProcessorMetadata {
257
274
  format: "onda-processor";
258
275
  format_version: 6;
259
276
  artifact_kind: OndaArtifactKind;
260
- abi_version: 6;
277
+ abi_version: 7;
261
278
  backend: string;
262
279
  mir_schema_version: number;
263
280
  target: OndaTargetInfo;
@@ -273,6 +290,8 @@ export interface OndaProcessorMetadata {
273
290
  init: string;
274
291
  process: string;
275
292
  events: string[];
293
+ /** Trusted native SoA entries parallel to events; absent for WebAssembly artifacts. */
294
+ event_views?: string[];
276
295
  };
277
296
  runtime: {
278
297
  state_size_bytes: number;
@@ -399,7 +418,7 @@ export function writeDelegateBatch(
399
418
  storageAddress: number,
400
419
  capacityBytes: number,
401
420
  ): void;
402
- /** Read and validate the result descriptor after successful generated execution. */
421
+ /** Read and validate the complete result envelope and packed record layout. */
403
422
  export function readDelegateBatch(
404
423
  memory: WebAssembly.Memory | ArrayBuffer | ArrayBufferView | DataView,
405
424
  batchAddress: number,
@@ -431,6 +450,14 @@ export function decodePrintRecords(
431
450
  logSites: OndaLogSiteMetadata[],
432
451
  byteOrder?: "little_endian" | "big_endian",
433
452
  ): OndaPrintEntry[];
453
+ export function decodeDelegateBatch(
454
+ memory: WebAssembly.Memory | ArrayBuffer | ArrayBufferView | DataView,
455
+ delegateBatchAddress: number,
456
+ metadata: OndaProcessorMetadata | {
457
+ delegates: OndaDelegateMetadata[];
458
+ target?: OndaTargetInfo;
459
+ },
460
+ ): { occurrences: OndaDelegateOccurrence[]; overflowCount: number };
434
461
  export function formatPrintBatch(
435
462
  memory: WebAssembly.Memory,
436
463
  printBatchAddress: number,
package/src/index.js CHANGED
@@ -7,15 +7,19 @@ const PARAM_CONTROL = globalThis.__ONDA_PARAM_CONTROL_V2__;
7
7
  export const PROCESSOR_ARTIFACT_FORMAT = "onda-processor";
8
8
  // Synchronized from format-versions.json; do not edit these copies directly.
9
9
  export const PROCESSOR_ARTIFACT_FORMAT_VERSION = 6;
10
- export const PROCESSOR_ABI_VERSION = 6;
10
+ export const PROCESSOR_ABI_VERSION = 7;
11
11
  export const PROCESSOR_EXECUTION_OK = 0;
12
12
  export const PROCESSOR_EXECUTION_RUNTIME_SAFETY_FAILURE = 1;
13
13
  export const PROCESSOR_INIT_PRESERVE_PINNED = 0;
14
14
  export const PROCESSOR_INIT_FULL = 1;
15
+ export const PROCESSOR_BEGIN_BLOCK = 1 << 0;
16
+ export const PROCESSOR_END_BLOCK = 1 << 1;
17
+ export const PROCESSOR_FULL_BLOCK = PROCESSOR_BEGIN_BLOCK | PROCESSOR_END_BLOCK;
15
18
  export const PROCESSOR_SNAPSHOT_FORMAT_VERSION = 1;
16
- export const DELEGATE_RECORD_HEADER_SIZE_BYTES = 12;
19
+ const BATCH_RECORD_HEADER_SIZE_BYTES = 12;
20
+ export const DELEGATE_RECORD_HEADER_SIZE_BYTES = BATCH_RECORD_HEADER_SIZE_BYTES;
17
21
  export const DELEGATE_BATCH_SIZE_BYTES = 20;
18
- export const PRINT_RECORD_HEADER_SIZE_BYTES = 12;
22
+ export const PRINT_RECORD_HEADER_SIZE_BYTES = BATCH_RECORD_HEADER_SIZE_BYTES;
19
23
  export const PRINT_BATCH_SIZE_BYTES = 20;
20
24
  export const EXECUTION_OUTPUT_SIZE_BYTES = 12;
21
25
 
@@ -143,6 +147,17 @@ export function validateProcessorMetadata(metadata, expectedKind = null) {
143
147
  for (const name of metadata.exports.events) {
144
148
  requireString(name, "exports.events[]");
145
149
  }
150
+ if (metadata.exports.event_views !== undefined) {
151
+ if (!Array.isArray(metadata.exports.event_views)) {
152
+ throw new OndaArtifactError("exports.event_views must be an array when present");
153
+ }
154
+ if (metadata.exports.event_views.length !== metadata.exports.events.length) {
155
+ throw new OndaArtifactError("exports.event_views must be parallel to exports.events");
156
+ }
157
+ for (const name of metadata.exports.event_views) {
158
+ requireString(name, "exports.event_views[]");
159
+ }
160
+ }
146
161
  if (!Array.isArray(metadata.integration?.required_symbols)) {
147
162
  throw new OndaArtifactError("integration.required_symbols must be an array");
148
163
  }
@@ -154,6 +169,7 @@ export function validateProcessorMetadata(metadata, expectedKind = null) {
154
169
  metadata.exports.init,
155
170
  metadata.exports.process,
156
171
  ...metadata.exports.events,
172
+ ...(metadata.exports.event_views ?? []),
157
173
  ]) {
158
174
  if (!requiredSymbols.has(name)) {
159
175
  throw new OndaArtifactError(
@@ -175,6 +191,11 @@ export function validateProcessorMetadata(metadata, expectedKind = null) {
175
191
  `integration profile '${String(profileKind)}' is incompatible with artifact kind '${metadata.artifact_kind}'`,
176
192
  );
177
193
  }
194
+ if (metadata.exports.event_views !== undefined && profileKind !== "native_relocatable_object") {
195
+ throw new OndaArtifactError(
196
+ "exports.event_views is only valid for native relocatable objects",
197
+ );
198
+ }
178
199
  if (profileKind === "core_webassembly_module") {
179
200
  requireLiteral(metadata.target.byte_order, "target.byte_order", "little_endian");
180
201
  requireString(metadata.exports?.memory, "exports.memory");
@@ -922,6 +943,9 @@ export function writeDelegateBatch(
922
943
  if (storageAddress > 0xffff_ffff || capacityBytes > 0xffff_ffff) {
923
944
  throw new OndaArtifactError("delegate batch addresses and sizes must fit u32");
924
945
  }
946
+ if (storageAddress !== 0 && capacityBytes !== 0) {
947
+ requireMemoryRange(view, storageAddress, capacityBytes, "delegate batch storage");
948
+ }
925
949
  view.setUint32(batchAddress, storageAddress, true);
926
950
  view.setUint32(batchAddress + 4, capacityBytes, true);
927
951
  view.setUint32(batchAddress + 8, 0, true);
@@ -930,15 +954,12 @@ export function writeDelegateBatch(
930
954
  }
931
955
 
932
956
  export function readDelegateBatch(memory, batchAddress) {
933
- const view = writableDataView(memory);
934
- requireMemoryRange(view, batchAddress, DELEGATE_BATCH_SIZE_BYTES, "delegate batch");
935
- return {
936
- storageAddress: view.getUint32(batchAddress, true),
937
- capacityBytes: view.getUint32(batchAddress + 4, true),
938
- usedBytes: view.getUint32(batchAddress + 8, true),
939
- recordCount: view.getUint32(batchAddress + 12, true),
940
- overflowCount: view.getUint32(batchAddress + 16, true),
941
- };
957
+ return readRecordBatch(
958
+ memory,
959
+ batchAddress,
960
+ DELEGATE_BATCH_SIZE_BYTES,
961
+ "delegate batch",
962
+ );
942
963
  }
943
964
 
944
965
  export function writePrintBatch(memory, batchAddress, storageAddress, capacityBytes) {
@@ -949,6 +970,9 @@ export function writePrintBatch(memory, batchAddress, storageAddress, capacityBy
949
970
  if (storageAddress > 0xffff_ffff || capacityBytes > 0xffff_ffff) {
950
971
  throw new OndaArtifactError("print batch addresses and sizes must fit u32");
951
972
  }
973
+ if (storageAddress !== 0 && capacityBytes !== 0) {
974
+ requireMemoryRange(view, storageAddress, capacityBytes, "print batch storage");
975
+ }
952
976
  view.setUint32(batchAddress, storageAddress, true);
953
977
  view.setUint32(batchAddress + 4, capacityBytes, true);
954
978
  view.setUint32(batchAddress + 8, 0, true);
@@ -957,15 +981,65 @@ export function writePrintBatch(memory, batchAddress, storageAddress, capacityBy
957
981
  }
958
982
 
959
983
  export function readPrintBatch(memory, batchAddress) {
984
+ return readRecordBatch(
985
+ memory,
986
+ batchAddress,
987
+ PRINT_BATCH_SIZE_BYTES,
988
+ "print batch",
989
+ );
990
+ }
991
+
992
+ function readRecordBatch(memory, batchAddress, descriptorSize, label) {
960
993
  const view = writableDataView(memory);
961
- requireMemoryRange(view, batchAddress, PRINT_BATCH_SIZE_BYTES, "print batch");
962
- return {
994
+ requireMemoryRange(view, batchAddress, descriptorSize, label);
995
+ const batch = {
963
996
  storageAddress: view.getUint32(batchAddress, true),
964
997
  capacityBytes: view.getUint32(batchAddress + 4, true),
965
998
  usedBytes: view.getUint32(batchAddress + 8, true),
966
999
  recordCount: view.getUint32(batchAddress + 12, true),
967
1000
  overflowCount: view.getUint32(batchAddress + 16, true),
968
1001
  };
1002
+ if (batch.usedBytes > batch.capacityBytes) {
1003
+ throw new OndaArtifactError(`${label} usedBytes exceeds capacityBytes`);
1004
+ }
1005
+ if (batch.recordCount !== 0 && batch.storageAddress === 0) {
1006
+ throw new OndaArtifactError(`${label} has records without storage`);
1007
+ }
1008
+ if (batch.storageAddress !== 0 && batch.capacityBytes !== 0) {
1009
+ requireMemoryRange(
1010
+ view,
1011
+ batch.storageAddress,
1012
+ batch.capacityBytes,
1013
+ `${label} storage`,
1014
+ );
1015
+ }
1016
+ if ((batch.recordCount === 0) !== (batch.usedBytes === 0)) {
1017
+ throw new OndaArtifactError(`${label} recordCount does not match packed storage`);
1018
+ }
1019
+ validateBatchRecordLayout(view, batch, label);
1020
+ return batch;
1021
+ }
1022
+
1023
+ function validateBatchRecordLayout(view, batch, label) {
1024
+ if (batch.recordCount > Math.floor(batch.usedBytes / BATCH_RECORD_HEADER_SIZE_BYTES)) {
1025
+ throw new OndaArtifactError(`${label} recordCount exceeds packed storage`);
1026
+ }
1027
+ let cursor = batch.storageAddress;
1028
+ const end = cursor + batch.usedBytes;
1029
+ for (let record = 0; record < batch.recordCount; record += 1) {
1030
+ if (end - cursor < BATCH_RECORD_HEADER_SIZE_BYTES) {
1031
+ throw new OndaArtifactError(`${label} ends in a partial record header`);
1032
+ }
1033
+ const payloadBytes = view.getUint32(cursor + 4, true);
1034
+ cursor += BATCH_RECORD_HEADER_SIZE_BYTES;
1035
+ if (payloadBytes > end - cursor) {
1036
+ throw new OndaArtifactError(`${label} ends in a partial record payload`);
1037
+ }
1038
+ cursor += payloadBytes;
1039
+ }
1040
+ if (cursor !== end) {
1041
+ throw new OndaArtifactError(`${label} contains trailing record bytes`);
1042
+ }
969
1043
  }
970
1044
 
971
1045
  export function writeExecutionOutput(
@@ -1167,13 +1241,7 @@ function escapedPrintLabel(label) {
1167
1241
 
1168
1242
  export function formatPrintBatch(memory, printBatchAddress, metadata) {
1169
1243
  const batch = readPrintBatch(memory, printBatchAddress);
1170
- const bytes = asUint8Array(memory.buffer ?? memory);
1171
- if (batch.usedBytes > batch.capacityBytes) {
1172
- throw new OndaArtifactError("print batch usedBytes exceeds capacityBytes");
1173
- }
1174
- if (batch.storageAddress + batch.usedBytes > bytes.byteLength) {
1175
- throw new OndaArtifactError("print batch storage exceeds WebAssembly memory");
1176
- }
1244
+ const bytes = memoryBytes(memory);
1177
1245
  const formatted = formatPrintRecords(
1178
1246
  bytes.subarray(batch.storageAddress, batch.storageAddress + batch.usedBytes),
1179
1247
  batch.usedBytes,
@@ -1186,6 +1254,21 @@ export function formatPrintBatch(memory, printBatchAddress, metadata) {
1186
1254
  return formatted;
1187
1255
  }
1188
1256
 
1257
+ export function decodeDelegateBatch(memory, delegateBatchAddress, metadata) {
1258
+ const batch = readDelegateBatch(memory, delegateBatchAddress);
1259
+ const bytes = memoryBytes(memory);
1260
+ const occurrences = decodeDelegateRecords(
1261
+ bytes.subarray(batch.storageAddress, batch.storageAddress + batch.usedBytes),
1262
+ batch.usedBytes,
1263
+ metadata.metadata?.delegates ?? metadata.delegates,
1264
+ metadata.target?.byte_order ?? "little_endian",
1265
+ );
1266
+ if (occurrences.length !== batch.recordCount) {
1267
+ throw new OndaArtifactError("delegate batch recordCount does not match packed storage");
1268
+ }
1269
+ return { occurrences, overflowCount: batch.overflowCount };
1270
+ }
1271
+
1189
1272
  export function formatPrintRecords(storage, usedBytes, metadata, overflowCount = 0) {
1190
1273
  requireInteger(overflowCount, "overflowCount", 0);
1191
1274
  const records = decodePrintRecords(
@@ -1290,9 +1373,14 @@ function writableDataView(memory) {
1290
1373
  throw new OndaArtifactError("delegate batch memory must be WebAssembly memory or a buffer view");
1291
1374
  }
1292
1375
 
1376
+ function memoryBytes(memory) {
1377
+ return asUint8Array(memory instanceof WebAssembly.Memory ? memory.buffer : memory);
1378
+ }
1379
+
1293
1380
  function requireMemoryRange(view, address, size, label) {
1294
1381
  requireInteger(address, `${label} address`, 0);
1295
- if (address + size > view.byteLength) {
1382
+ requireInteger(size, `${label} size`, 0);
1383
+ if (address > view.byteLength || size > view.byteLength - address) {
1296
1384
  throw new OndaArtifactError(`${label} exceeds memory`);
1297
1385
  }
1298
1386
  }
package/src/payload.js CHANGED
@@ -136,6 +136,15 @@ export class PayloadPlan {
136
136
  }
137
137
  this.abiParameterCount = abiParameter;
138
138
  this.dynamicParameters = this.parameters.filter((param) => param.dynamic).length;
139
+ this.tensorMetadata = Object.freeze(this.parameters.flatMap((group, parameterIndex) =>
140
+ this.tensors.slice(group.start, group.end).map((tensor) => Object.freeze({
141
+ path: tensor.path,
142
+ encoding: tensor.encoding,
143
+ shape: Object.freeze([...tensor.shape]),
144
+ parameterIndex,
145
+ isSlice: group.dynamic,
146
+ fixedElementCount: tensor.elements,
147
+ }))));
139
148
  const minimum = this.sizes(Array(this.dynamicParameters).fill(0));
140
149
  this.fixedWireSize = this.dynamicParameters === 0 ? minimum.wire : null;
141
150
  this.minimumWorkspace = minimum.workspace;