tywrap 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/README.md +1 -1
  2. package/dist/index.d.ts +20 -4
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +22 -2
  5. package/dist/index.js.map +1 -1
  6. package/dist/runtime/base.d.ts +17 -7
  7. package/dist/runtime/base.d.ts.map +1 -1
  8. package/dist/runtime/base.js +18 -1
  9. package/dist/runtime/base.js.map +1 -1
  10. package/dist/runtime/bounded-context.d.ts +252 -0
  11. package/dist/runtime/bounded-context.d.ts.map +1 -0
  12. package/dist/runtime/bounded-context.js +454 -0
  13. package/dist/runtime/bounded-context.js.map +1 -0
  14. package/dist/runtime/bridge-protocol.d.ts +167 -0
  15. package/dist/runtime/bridge-protocol.d.ts.map +1 -0
  16. package/dist/runtime/bridge-protocol.js +247 -0
  17. package/dist/runtime/bridge-protocol.js.map +1 -0
  18. package/dist/runtime/disposable.d.ts +40 -0
  19. package/dist/runtime/disposable.d.ts.map +1 -0
  20. package/dist/runtime/disposable.js +49 -0
  21. package/dist/runtime/disposable.js.map +1 -0
  22. package/dist/runtime/http-io.d.ts +91 -0
  23. package/dist/runtime/http-io.d.ts.map +1 -0
  24. package/dist/runtime/http-io.js +195 -0
  25. package/dist/runtime/http-io.js.map +1 -0
  26. package/dist/runtime/http.d.ts +47 -13
  27. package/dist/runtime/http.d.ts.map +1 -1
  28. package/dist/runtime/http.js +55 -74
  29. package/dist/runtime/http.js.map +1 -1
  30. package/dist/runtime/node.d.ts +97 -130
  31. package/dist/runtime/node.d.ts.map +1 -1
  32. package/dist/runtime/node.js +256 -523
  33. package/dist/runtime/node.js.map +1 -1
  34. package/dist/runtime/pooled-transport.d.ts +131 -0
  35. package/dist/runtime/pooled-transport.d.ts.map +1 -0
  36. package/dist/runtime/pooled-transport.js +175 -0
  37. package/dist/runtime/pooled-transport.js.map +1 -0
  38. package/dist/runtime/process-io.d.ts +204 -0
  39. package/dist/runtime/process-io.d.ts.map +1 -0
  40. package/dist/runtime/process-io.js +695 -0
  41. package/dist/runtime/process-io.js.map +1 -0
  42. package/dist/runtime/pyodide-io.d.ts +155 -0
  43. package/dist/runtime/pyodide-io.d.ts.map +1 -0
  44. package/dist/runtime/pyodide-io.js +397 -0
  45. package/dist/runtime/pyodide-io.js.map +1 -0
  46. package/dist/runtime/pyodide.d.ts +51 -19
  47. package/dist/runtime/pyodide.d.ts.map +1 -1
  48. package/dist/runtime/pyodide.js +57 -186
  49. package/dist/runtime/pyodide.js.map +1 -1
  50. package/dist/runtime/safe-codec.d.ts +81 -0
  51. package/dist/runtime/safe-codec.d.ts.map +1 -0
  52. package/dist/runtime/safe-codec.js +345 -0
  53. package/dist/runtime/safe-codec.js.map +1 -0
  54. package/dist/runtime/transport.d.ts +186 -0
  55. package/dist/runtime/transport.d.ts.map +1 -0
  56. package/dist/runtime/transport.js +86 -0
  57. package/dist/runtime/transport.js.map +1 -0
  58. package/dist/runtime/validators.d.ts +131 -0
  59. package/dist/runtime/validators.d.ts.map +1 -0
  60. package/dist/runtime/validators.js +219 -0
  61. package/dist/runtime/validators.js.map +1 -0
  62. package/dist/runtime/worker-pool.d.ts +196 -0
  63. package/dist/runtime/worker-pool.d.ts.map +1 -0
  64. package/dist/runtime/worker-pool.js +371 -0
  65. package/dist/runtime/worker-pool.js.map +1 -0
  66. package/dist/utils/codec.d.ts.map +1 -1
  67. package/dist/utils/codec.js +120 -1
  68. package/dist/utils/codec.js.map +1 -1
  69. package/package.json +2 -2
  70. package/runtime/python_bridge.py +30 -3
  71. package/runtime/safe_codec.py +344 -0
  72. package/src/index.ts +48 -5
  73. package/src/runtime/base.ts +18 -26
  74. package/src/runtime/bounded-context.ts +608 -0
  75. package/src/runtime/bridge-protocol.ts +319 -0
  76. package/src/runtime/disposable.ts +65 -0
  77. package/src/runtime/http-io.ts +244 -0
  78. package/src/runtime/http.ts +71 -117
  79. package/src/runtime/node.ts +358 -691
  80. package/src/runtime/pooled-transport.ts +252 -0
  81. package/src/runtime/process-io.ts +902 -0
  82. package/src/runtime/pyodide-io.ts +485 -0
  83. package/src/runtime/pyodide.ts +75 -215
  84. package/src/runtime/safe-codec.ts +443 -0
  85. package/src/runtime/transport.ts +273 -0
  86. package/src/runtime/validators.ts +241 -0
  87. package/src/runtime/worker-pool.ts +498 -0
  88. package/src/utils/codec.ts +126 -1
@@ -0,0 +1,498 @@
1
+ /**
2
+ * WorkerPool - Manages multiple Transport instances for concurrent request handling.
3
+ *
4
+ * Provides semaphore-based concurrency control with configurable limits per worker
5
+ * and a wait queue for callers when all workers are at capacity.
6
+ *
7
+ * @see https://github.com/bbopen/tywrap/issues/149
8
+ */
9
+
10
+ import { BoundedContext } from './bounded-context.js';
11
+ import { BridgeTimeoutError, BridgeExecutionError, BridgeProtocolError } from './errors.js';
12
+ import type { Transport } from './transport.js';
13
+
14
+ // =============================================================================
15
+ // TYPES
16
+ // =============================================================================
17
+
18
+ /**
19
+ * Configuration options for the WorkerPool.
20
+ */
21
+ export interface WorkerPoolOptions {
22
+ /** Factory function to create transports */
23
+ createTransport: () => Transport;
24
+
25
+ /** Maximum number of workers in the pool */
26
+ maxWorkers: number;
27
+
28
+ /** Minimum number of workers to pre-spawn during init. Default: 0 (lazy) */
29
+ minWorkers?: number;
30
+
31
+ /** Timeout for waiting in queue (ms). Default: 30000 */
32
+ queueTimeoutMs?: number;
33
+
34
+ /** Maximum concurrent requests per worker. Default: 1 */
35
+ maxConcurrentPerWorker?: number;
36
+
37
+ /**
38
+ * Callback invoked after each worker is created and initialized.
39
+ * Use this for per-worker warmup (e.g., importing modules, running setup).
40
+ */
41
+ onWorkerReady?: (worker: PooledWorker) => Promise<void>;
42
+ }
43
+
44
+ /**
45
+ * A pooled worker with its transport and current in-flight request count.
46
+ */
47
+ export interface PooledWorker {
48
+ /** The underlying transport instance */
49
+ transport: Transport;
50
+
51
+ /** Number of requests currently being processed by this worker */
52
+ inFlightCount: number;
53
+ }
54
+
55
+ /**
56
+ * Internal representation of a waiter in the queue.
57
+ */
58
+ interface QueuedWaiter {
59
+ /** Resolve function to fulfill the promise with a worker */
60
+ resolve: (worker: PooledWorker) => void;
61
+
62
+ /** Reject function to reject the promise with an error */
63
+ reject: (error: Error) => void;
64
+
65
+ /** Timeout timer for queue timeout */
66
+ timer: NodeJS.Timeout;
67
+ }
68
+
69
+ // =============================================================================
70
+ // WORKER POOL
71
+ // =============================================================================
72
+
73
+ /**
74
+ * Pool of Transport workers with semaphore-based concurrency control.
75
+ *
76
+ * Features:
77
+ * - Lazy worker creation (workers created on demand)
78
+ * - Configurable concurrency per worker
79
+ * - Wait queue with timeout for callers when pool is at capacity
80
+ * - Automatic cleanup of timers and workers on disposal
81
+ *
82
+ * @example
83
+ * ```typescript
84
+ * const pool = new WorkerPool({
85
+ * createTransport: () => new ProcessIO({ pythonPath: 'python3' }),
86
+ * maxWorkers: 4,
87
+ * maxConcurrentPerWorker: 2,
88
+ * queueTimeoutMs: 5000,
89
+ * });
90
+ *
91
+ * await pool.init();
92
+ *
93
+ * // Use withWorker for automatic acquire/release
94
+ * const result = await pool.withWorker(async (worker) => {
95
+ * return worker.transport.send(message, timeout);
96
+ * });
97
+ *
98
+ * await pool.dispose();
99
+ * ```
100
+ */
101
+ export class WorkerPool extends BoundedContext {
102
+ private readonly options: Omit<Required<WorkerPoolOptions>, 'onWorkerReady'> & {
103
+ onWorkerReady?: (worker: PooledWorker) => Promise<void>;
104
+ };
105
+ private readonly workers: PooledWorker[] = [];
106
+ private readonly waitQueue: QueuedWaiter[] = [];
107
+ /** Tracks workers being created to prevent race condition in acquire() */
108
+ private pendingCreations = 0;
109
+
110
+ /**
111
+ * Create a new WorkerPool.
112
+ *
113
+ * @param options - Pool configuration options
114
+ */
115
+ constructor(options: WorkerPoolOptions) {
116
+ super();
117
+
118
+ // Validate required options
119
+ if (typeof options.createTransport !== 'function') {
120
+ throw new BridgeExecutionError('createTransport must be a function');
121
+ }
122
+ if (typeof options.maxWorkers !== 'number' || options.maxWorkers < 1) {
123
+ throw new BridgeExecutionError('maxWorkers must be a positive number');
124
+ }
125
+
126
+ const minWorkers = options.minWorkers ?? 0;
127
+ if (minWorkers > options.maxWorkers) {
128
+ throw new BridgeExecutionError('minWorkers cannot exceed maxWorkers');
129
+ }
130
+
131
+ this.options = {
132
+ createTransport: options.createTransport,
133
+ maxWorkers: options.maxWorkers,
134
+ minWorkers,
135
+ queueTimeoutMs: options.queueTimeoutMs ?? 30000,
136
+ maxConcurrentPerWorker: options.maxConcurrentPerWorker ?? 1,
137
+ onWorkerReady: options.onWorkerReady,
138
+ };
139
+ }
140
+
141
+ // ===========================================================================
142
+ // LIFECYCLE
143
+ // ===========================================================================
144
+
145
+ /**
146
+ * Initialize the pool.
147
+ *
148
+ * If minWorkers > 0, pre-spawns workers during initialization.
149
+ * Otherwise, workers are created lazily on demand.
150
+ */
151
+ protected async doInit(): Promise<void> {
152
+ // Pre-spawn minimum workers if configured
153
+ if (this.options.minWorkers > 0) {
154
+ const spawns: Promise<PooledWorker>[] = [];
155
+ for (let i = 0; i < this.options.minWorkers; i++) {
156
+ spawns.push(this.createWorker());
157
+ }
158
+ await Promise.all(spawns);
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Dispose the pool and all workers.
164
+ *
165
+ * - Rejects all waiters in the queue
166
+ * - Disposes all transport instances
167
+ * - Clears internal state
168
+ */
169
+ protected async doDispose(): Promise<void> {
170
+ // Reject all waiters in the queue
171
+ for (const waiter of this.waitQueue) {
172
+ clearTimeout(waiter.timer);
173
+ waiter.reject(new BridgeExecutionError('Pool disposed'));
174
+ }
175
+ this.waitQueue.length = 0;
176
+
177
+ // Dispose all workers
178
+ const errors: Error[] = [];
179
+ for (const worker of this.workers) {
180
+ try {
181
+ await worker.transport.dispose();
182
+ } catch (e) {
183
+ errors.push(e instanceof Error ? e : new Error(String(e)));
184
+ }
185
+ }
186
+ this.workers.length = 0;
187
+
188
+ // Report errors if any
189
+ if (errors.length === 1) {
190
+ throw errors[0];
191
+ }
192
+ if (errors.length > 1) {
193
+ throw new AggregateError(errors, 'Multiple errors during worker disposal');
194
+ }
195
+ }
196
+
197
+ // ===========================================================================
198
+ // WORKER MANAGEMENT
199
+ // ===========================================================================
200
+
201
+ /**
202
+ * Acquire a worker from the pool.
203
+ *
204
+ * This method:
205
+ * - Returns an available worker if one exists (inFlightCount < maxConcurrentPerWorker)
206
+ * - Creates a new worker if under the maxWorkers limit
207
+ * - Waits in queue if all workers are at capacity
208
+ *
209
+ * @returns Promise resolving to a pooled worker
210
+ * @throws BridgeTimeoutError if queue timeout expires
211
+ * @throws BridgeExecutionError if pool is disposed while waiting
212
+ */
213
+ async acquire(): Promise<PooledWorker> {
214
+ // Check for disposed state
215
+ if (this.isDisposed) {
216
+ throw new BridgeExecutionError('Pool has been disposed');
217
+ }
218
+
219
+ // Find an available worker (one with capacity)
220
+ const availableWorker = this.findAvailableWorker();
221
+ if (availableWorker) {
222
+ availableWorker.inFlightCount++;
223
+ return availableWorker;
224
+ }
225
+
226
+ // Create a new worker if under the limit
227
+ // Include pendingCreations to prevent race condition where multiple
228
+ // concurrent acquire() calls all pass the length check before any
229
+ // worker is actually added to the array
230
+ if (this.workers.length + this.pendingCreations < this.options.maxWorkers) {
231
+ this.pendingCreations++;
232
+ try {
233
+ const newWorker = await this.createWorker();
234
+ newWorker.inFlightCount++;
235
+ return newWorker;
236
+ } finally {
237
+ this.pendingCreations--;
238
+ }
239
+ }
240
+
241
+ // All workers at capacity - wait in queue
242
+ return this.waitForWorker();
243
+ }
244
+
245
+ /**
246
+ * Release a worker back to the pool.
247
+ *
248
+ * Decrements the worker's in-flight count and notifies any waiters
249
+ * that a worker may be available.
250
+ *
251
+ * @param worker - The worker to release
252
+ */
253
+ release(worker: PooledWorker): void {
254
+ // Validate the worker belongs to this pool
255
+ if (!this.workers.includes(worker)) {
256
+ return;
257
+ }
258
+
259
+ // Decrement in-flight count (minimum 0)
260
+ worker.inFlightCount = Math.max(0, worker.inFlightCount - 1);
261
+
262
+ // If there are waiters and this worker has capacity, fulfill the first waiter
263
+ if (this.waitQueue.length > 0 && worker.inFlightCount < this.options.maxConcurrentPerWorker) {
264
+ const waiter = this.waitQueue.shift();
265
+ if (waiter) {
266
+ clearTimeout(waiter.timer);
267
+ worker.inFlightCount++;
268
+ waiter.resolve(worker);
269
+ }
270
+ }
271
+ }
272
+
273
+ /**
274
+ * Execute a function with an acquired worker, automatically releasing afterward.
275
+ *
276
+ * This is the recommended way to use the pool, as it ensures proper cleanup
277
+ * even if the function throws an error.
278
+ *
279
+ * @param fn - Async function to execute with the worker
280
+ * @returns Promise resolving to the function's return value
281
+ *
282
+ * @example
283
+ * ```typescript
284
+ * const result = await pool.withWorker(async (worker) => {
285
+ * return worker.transport.send(message, timeout);
286
+ * });
287
+ * ```
288
+ */
289
+ async withWorker<T>(fn: (worker: PooledWorker) => Promise<T>): Promise<T> {
290
+ const worker = await this.acquire();
291
+ let workerRemoved = false;
292
+
293
+ try {
294
+ return await fn(worker);
295
+ } catch (error) {
296
+ // If this is a fatal error indicating the worker is dead, remove it from the pool
297
+ if (this.isFatalWorkerError(error)) {
298
+ this.removeWorker(worker);
299
+ workerRemoved = true;
300
+ }
301
+ throw error;
302
+ } finally {
303
+ // Only release if worker wasn't removed due to fatal error
304
+ if (!workerRemoved) {
305
+ this.release(worker);
306
+ }
307
+ }
308
+ }
309
+
310
+ // ===========================================================================
311
+ // WORKER HEALTH
312
+ // ===========================================================================
313
+
314
+ /**
315
+ * Check if an error indicates the worker is dead and should be removed.
316
+ *
317
+ * Fatal errors include:
318
+ * - Process not running
319
+ * - Process exited unexpectedly
320
+ * - Pipe errors (EPIPE)
321
+ * - Connection reset errors (ECONNRESET)
322
+ */
323
+ private isFatalWorkerError(error: unknown): boolean {
324
+ if (error instanceof BridgeProtocolError) {
325
+ const msg = error.message.toLowerCase();
326
+ return (
327
+ msg.includes('not running') ||
328
+ msg.includes('process exited') ||
329
+ msg.includes('epipe') ||
330
+ msg.includes('econnreset')
331
+ );
332
+ }
333
+ return false;
334
+ }
335
+
336
+ /**
337
+ * Remove a worker from the pool.
338
+ *
339
+ * This is called when a worker is detected as dead (crashed, pipe error, etc.).
340
+ * The worker's transport is disposed in the background.
341
+ */
342
+ private removeWorker(worker: PooledWorker): void {
343
+ const index = this.workers.indexOf(worker);
344
+ if (index !== -1) {
345
+ this.workers.splice(index, 1);
346
+ // Dispose transport in background - don't await to avoid blocking
347
+ worker.transport.dispose().catch(() => {
348
+ // Ignore disposal errors for dead workers
349
+ });
350
+ }
351
+ }
352
+
353
+ // ===========================================================================
354
+ // POOL STATISTICS
355
+ // ===========================================================================
356
+
357
+ /**
358
+ * Current number of workers in the pool.
359
+ */
360
+ get workerCount(): number {
361
+ return this.workers.length;
362
+ }
363
+
364
+ /**
365
+ * Number of callers waiting in the queue.
366
+ */
367
+ get queueLength(): number {
368
+ return this.waitQueue.length;
369
+ }
370
+
371
+ /**
372
+ * Total number of in-flight requests across all workers.
373
+ */
374
+ get totalInFlight(): number {
375
+ return this.workers.reduce((sum, w) => sum + w.inFlightCount, 0);
376
+ }
377
+
378
+ // ===========================================================================
379
+ // PRIVATE HELPERS
380
+ // ===========================================================================
381
+
382
+ /**
383
+ * Find an available worker with capacity for another request.
384
+ */
385
+ private findAvailableWorker(): PooledWorker | undefined {
386
+ return this.workers.find(w => w.inFlightCount < this.options.maxConcurrentPerWorker);
387
+ }
388
+
389
+ /**
390
+ * Create a new worker and add it to the pool.
391
+ *
392
+ * If onWorkerReady is configured, calls it after the transport is initialized.
393
+ * This is useful for per-worker warmup (importing modules, running setup).
394
+ */
395
+ private async createWorker(): Promise<PooledWorker> {
396
+ const transport = this.options.createTransport();
397
+
398
+ // Initialize the transport
399
+ await transport.init();
400
+
401
+ const worker: PooledWorker = {
402
+ transport,
403
+ inFlightCount: 0,
404
+ };
405
+
406
+ this.workers.push(worker);
407
+
408
+ // Call onWorkerReady callback if provided
409
+ if (this.options.onWorkerReady) {
410
+ await this.options.onWorkerReady(worker);
411
+ }
412
+
413
+ return worker;
414
+ }
415
+
416
+ /**
417
+ * Wait in queue for a worker to become available.
418
+ */
419
+ private waitForWorker(): Promise<PooledWorker> {
420
+ return new Promise<PooledWorker>((resolve, reject) => {
421
+ const timer = setTimeout(() => {
422
+ // Remove this waiter from the queue
423
+ const index = this.waitQueue.findIndex(w => w.timer === timer);
424
+ if (index !== -1) {
425
+ this.waitQueue.splice(index, 1);
426
+ }
427
+ reject(
428
+ new BridgeTimeoutError(
429
+ `Timed out waiting for available worker after ${this.options.queueTimeoutMs}ms`
430
+ )
431
+ );
432
+ }, this.options.queueTimeoutMs);
433
+
434
+ // Unref the timer so it doesn't keep the Node.js process alive
435
+ if (typeof timer.unref === 'function') {
436
+ timer.unref();
437
+ }
438
+
439
+ this.waitQueue.push({ resolve, reject, timer });
440
+ });
441
+ }
442
+
443
+ // ===========================================================================
444
+ // RUNTIME EXECUTION (Not implemented - WorkerPool is just for worker management)
445
+ // ===========================================================================
446
+
447
+ /**
448
+ * Not implemented - WorkerPool does not execute Python calls directly.
449
+ * Use the BridgeProtocol layer with a pooled worker's transport.
450
+ */
451
+ async call<T = unknown>(
452
+ _module: string,
453
+ _functionName: string,
454
+ _args: unknown[],
455
+ _kwargs?: Record<string, unknown>
456
+ ): Promise<T> {
457
+ throw new BridgeExecutionError(
458
+ 'WorkerPool does not implement call() - use withWorker() to get a transport'
459
+ );
460
+ }
461
+
462
+ /**
463
+ * Not implemented - WorkerPool does not execute Python calls directly.
464
+ */
465
+ async instantiate<T = unknown>(
466
+ _module: string,
467
+ _className: string,
468
+ _args: unknown[],
469
+ _kwargs?: Record<string, unknown>
470
+ ): Promise<T> {
471
+ throw new BridgeExecutionError(
472
+ 'WorkerPool does not implement instantiate() - use withWorker() to get a transport'
473
+ );
474
+ }
475
+
476
+ /**
477
+ * Not implemented - WorkerPool does not execute Python calls directly.
478
+ */
479
+ async callMethod<T = unknown>(
480
+ _handle: string,
481
+ _methodName: string,
482
+ _args: unknown[],
483
+ _kwargs?: Record<string, unknown>
484
+ ): Promise<T> {
485
+ throw new BridgeExecutionError(
486
+ 'WorkerPool does not implement callMethod() - use withWorker() to get a transport'
487
+ );
488
+ }
489
+
490
+ /**
491
+ * Not implemented - WorkerPool does not execute Python calls directly.
492
+ */
493
+ async disposeInstance(_handle: string): Promise<void> {
494
+ throw new BridgeExecutionError(
495
+ 'WorkerPool does not implement disposeInstance() - use withWorker() to get a transport'
496
+ );
497
+ }
498
+ }
@@ -243,6 +243,101 @@ function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
243
243
  );
244
244
  }
245
245
 
246
+ /**
247
+ * Convert a typed array (Int32Array, Float64Array, BigInt64Array, etc.) to a plain JS array.
248
+ *
249
+ * Why: Arrow's column.toArray() returns typed arrays, but we need plain arrays for
250
+ * JSON-compatible output and proper nested array reshaping.
251
+ *
252
+ * @param arr - Typed array or plain array
253
+ * @returns Plain JavaScript array with values converted (BigInt → Number where safe)
254
+ */
255
+ function typedArrayToPlain(arr: unknown): unknown[] {
256
+ if (Array.isArray(arr)) {
257
+ return arr;
258
+ }
259
+ // Handle typed arrays (Int32Array, Float64Array, BigInt64Array, etc.)
260
+ if (ArrayBuffer.isView(arr) && 'length' in arr) {
261
+ const typedArr = arr as unknown as { length: number; [index: number]: unknown };
262
+ const result: unknown[] = [];
263
+ for (let i = 0; i < typedArr.length; i++) {
264
+ const val = typedArr[i];
265
+ // Convert BigInt to Number if within safe integer range
266
+ if (typeof val === 'bigint') {
267
+ if (val >= BigInt(Number.MIN_SAFE_INTEGER) && val <= BigInt(Number.MAX_SAFE_INTEGER)) {
268
+ result.push(Number(val));
269
+ } else {
270
+ result.push(val); // Keep as BigInt if too large
271
+ }
272
+ } else {
273
+ result.push(val);
274
+ }
275
+ }
276
+ return result;
277
+ }
278
+ // Fallback: check if iterable before converting
279
+ if (arr !== null && arr !== undefined && typeof arr === 'object' && Symbol.iterator in arr) {
280
+ return Array.from(arr as Iterable<unknown>);
281
+ }
282
+ // Non-iterable: return empty array (shouldn't happen with valid Arrow data)
283
+ return [];
284
+ }
285
+
286
+ /**
287
+ * Extract values from an Arrow table as a plain JavaScript array.
288
+ *
289
+ * Why: Arrow decoding returns Table objects, not raw arrays. We need to extract
290
+ * the column values and convert any typed arrays to plain arrays.
291
+ */
292
+ function extractArrowValues(data: unknown): unknown[] | null {
293
+ if (Array.isArray(data)) {
294
+ return data;
295
+ }
296
+ // Arrow table - extract values from first column
297
+ const table = data as ArrowTable & { getChildAt?: (i: number) => { toArray?: () => unknown } };
298
+ if (typeof table.getChildAt === 'function') {
299
+ const column = table.getChildAt(0);
300
+ if (column && typeof column.toArray === 'function') {
301
+ return typedArrayToPlain(column.toArray());
302
+ }
303
+ }
304
+ return null;
305
+ }
306
+
307
+ /**
308
+ * Reshape a flat array into a multi-dimensional nested array.
309
+ *
310
+ * Why: PyArrow's pa.array() only handles 1D arrays, so we flatten multi-dimensional
311
+ * arrays before Arrow encoding and reshape after decoding. This maintains Arrow's
312
+ * binary efficiency while working with current arrow-js (which doesn't yet support
313
+ * FixedShapeTensorArray). See: https://github.com/apache/arrow-js/issues/115
314
+ *
315
+ * @param flat - Flat array of values (must be a plain array, not typed array)
316
+ * @param shape - Target shape, e.g., [2, 3] for a 2x3 matrix
317
+ * @returns Nested array with the specified shape
318
+ */
319
+ function reshapeArray(flat: unknown[], shape: readonly number[]): unknown {
320
+ if (shape.length === 0) {
321
+ return flat[0];
322
+ }
323
+ if (shape.length === 1) {
324
+ return flat;
325
+ }
326
+
327
+ // shape.length >= 2, so first is always defined
328
+ const first = shape[0]!;
329
+ const rest = shape.slice(1);
330
+ const chunkSize = rest.reduce((a, b) => a * b, 1);
331
+ const result: unknown[] = [];
332
+
333
+ for (let i = 0; i < first; i++) {
334
+ const chunk = flat.slice(i * chunkSize, (i + 1) * chunkSize);
335
+ result.push(reshapeArray(chunk, rest));
336
+ }
337
+
338
+ return result;
339
+ }
340
+
246
341
  // Why: decoding needs to reject incompatible envelopes before we attempt to interpret payloads.
247
342
  const CODEC_VERSION = 1;
248
343
 
@@ -326,13 +421,43 @@ function decodeEnvelopeCore<T>(
326
421
 
327
422
  if (marker === 'ndarray') {
328
423
  const encoding = (value as { encoding?: unknown }).encoding;
424
+ const shapeValue = (value as { shape?: unknown }).shape;
425
+ const shape = isNumberArray(shapeValue) ? shapeValue : undefined;
426
+
329
427
  if (encoding === 'arrow') {
330
428
  const b64 = (value as { b64?: unknown }).b64;
331
429
  if (typeof b64 !== 'string') {
332
430
  throw new Error('Invalid ndarray envelope: missing b64');
333
431
  }
334
432
  const bytes = fromBase64(b64);
335
- return decodeArrow(bytes);
433
+ const decoded = decodeArrow(bytes);
434
+
435
+ // Extract values from Arrow table and reshape if needed
436
+ // Arrow only handles 1D arrays, so we flatten on encode and reshape here
437
+ // Reshape for: scalars (shape.length === 0) and multi-dim (shape.length > 1)
438
+ // Skip reshape for: 1D arrays (shape.length === 1) - return as-is
439
+ if (isPromiseLike(decoded)) {
440
+ return decoded.then(data => {
441
+ const values = extractArrowValues(data);
442
+ if (!values) {
443
+ return data; // Fallback: return raw data if extraction fails
444
+ }
445
+ // Reshape scalars and multi-dimensional arrays, but not 1D
446
+ if (shape && shape.length !== 1) {
447
+ return reshapeArray(values, shape);
448
+ }
449
+ return values;
450
+ });
451
+ }
452
+ const values = extractArrowValues(decoded);
453
+ if (!values) {
454
+ return decoded; // Fallback: return raw data if extraction fails
455
+ }
456
+ // Reshape scalars and multi-dimensional arrays, but not 1D
457
+ if (shape && shape.length !== 1) {
458
+ return reshapeArray(values, shape);
459
+ }
460
+ return values;
336
461
  }
337
462
  if (encoding === 'json') {
338
463
  if (!('data' in (value as object))) {