-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.js
More file actions
945 lines (799 loc) · 30.7 KB
/
test.js
File metadata and controls
945 lines (799 loc) · 30.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
import { describe, it } from "node:test";
import assert from "node:assert/strict";
import { Readable } from "node:stream";
import { EventEmitter } from "node:events";
import { filterUnindexed, dedup, postProcessResults, isOurServer, isIndexable, userPort, BASE_PORT, MIN_SCORE, createHandler } from "./lib.js";
import { createEmbedPool } from "./embed-pool.js";
// --- Mock helpers for handler tests ---
function mockReq(method, url, body = {}) {
const data = JSON.stringify(body);
const stream = Readable.from([Buffer.from(data)]);
stream.method = method;
stream.url = url;
return stream;
}
function mockRes() {
const res = {
statusCode: null,
headers: {},
body: null,
writeHead(code, headers) { res.statusCode = code; res.headers = headers || {}; },
end(data) { res.body = data ? JSON.parse(data) : null; res._ended = true; },
_ended: false,
};
return res;
}
function makeDeps(overrides = {}) {
let _isIndexing = false;
const closedDbs = [];
return {
openVectorDb: () => ({
close() { closedDbs.push("vec"); },
exec() {},
prepare: () => ({ all: () => [] }),
}),
openSessionStore: () => ({
close() { closedDbs.push("session"); },
prepare: () => ({ all: () => [] }),
}),
getUnindexedContent: () => [],
indexContent: async () => 0,
search: async (_db, _q, _l) => [{ score: "0.5000", session_id: "s1", source_type: "turn", snippet: "test" }],
runMaintenance: () => {},
getIsIndexing: () => _isIndexing,
setIsIndexing: (v) => { _isIndexing = v; },
_closedDbs: closedDbs,
_setIsIndexing: (v) => { _isIndexing = v; },
...overrides,
};
}
describe("userPort", () => {
it("returns a number within the expected range", () => {
const port = userPort("testuser");
assert.ok(port >= BASE_PORT, `port ${port} should be >= ${BASE_PORT}`);
assert.ok(port <= BASE_PORT + 0xFFF, `port ${port} should be <= ${BASE_PORT + 0xFFF}`);
});
it("is deterministic for the same username", () => {
assert.equal(userPort("alice"), userPort("alice"));
});
it("is case-insensitive", () => {
assert.equal(userPort("Alice"), userPort("alice"));
});
it("returns different ports for different usernames", () => {
// Not guaranteed for all pairs, but statistically overwhelmingly likely
assert.notEqual(userPort("alice"), userPort("bob"));
});
});
describe("filterUnindexed", () => {
it("returns items not in the existing index", () => {
const all = [
{ session_id: "s1", source_type: "turn", source_id: "1", content: "hello" },
{ session_id: "s1", source_type: "turn", source_id: "2", content: "world" },
{ session_id: "s2", source_type: "checkpoint", source_id: "1", content: "foo" },
];
const existing = [
{ session_id: "s1", source_type: "turn", source_id: "1" },
];
const result = filterUnindexed(all, existing);
assert.equal(result.length, 2);
assert.equal(result[0].content, "world");
assert.equal(result[1].content, "foo");
});
it("returns all items when index is empty", () => {
const all = [
{ session_id: "s1", source_type: "turn", source_id: "1", content: "a" },
];
const result = filterUnindexed(all, []);
assert.equal(result.length, 1);
});
it("returns empty when everything is indexed", () => {
const all = [
{ session_id: "s1", source_type: "turn", source_id: "1", content: "a" },
];
const existing = [
{ session_id: "s1", source_type: "turn", source_id: "1" },
];
const result = filterUnindexed(all, existing);
assert.equal(result.length, 0);
});
it("handles null source_id correctly", () => {
const all = [
{ session_id: "s1", source_type: "turn", source_id: null, content: "a" },
{ session_id: "s1", source_type: "turn", source_id: null, content: "b" },
];
const existing = [
{ session_id: "s1", source_type: "turn", source_id: null },
];
// Both map to same key, so both filtered
const result = filterUnindexed(all, existing);
assert.equal(result.length, 0);
});
});
describe("dedup", () => {
it("removes duplicate content", () => {
const results = [
{ content: "hello", distance: 0.1 },
{ content: "hello", distance: 0.2 },
{ content: "world", distance: 0.3 },
];
const result = dedup(results);
assert.equal(result.length, 2);
assert.equal(result[0].distance, 0.1); // keeps first occurrence
});
it("preserves order of first occurrences", () => {
const results = [
{ content: "a", distance: 0.1 },
{ content: "b", distance: 0.2 },
{ content: "a", distance: 0.3 },
{ content: "c", distance: 0.4 },
];
const result = dedup(results);
assert.deepEqual(result.map(r => r.content), ["a", "b", "c"]);
});
it("returns empty for empty input", () => {
assert.equal(dedup([]).length, 0);
});
});
describe("postProcessResults", () => {
it("filters results below score floor", () => {
const results = [
{ distance: 0.5, session_id: "s1", source_type: "turn", content: "good" }, // score 0.5 ✓
{ distance: 0.9, session_id: "s1", source_type: "turn", content: "bad" }, // score 0.1 ✗
];
const processed = postProcessResults(results, 10);
assert.equal(processed.length, 1);
assert.equal(processed[0].score, "0.5000");
});
it("respects limit", () => {
const results = Array.from({ length: 20 }, (_, i) => ({
distance: 0.3 + i * 0.01,
session_id: "s1",
source_type: "turn",
content: `item ${i}`,
}));
const processed = postProcessResults(results, 5);
assert.equal(processed.length, 5);
});
it("truncates long content to 500 chars with ellipsis", () => {
const longContent = "x".repeat(600);
const results = [
{ distance: 0.3, session_id: "s1", source_type: "turn", content: longContent },
];
const processed = postProcessResults(results, 10);
assert.equal(processed[0].snippet.length, 503); // 500 + "..."
assert.ok(processed[0].snippet.endsWith("..."));
});
it("reports true score, not jittered", () => {
const results = [
{ distance: 0.4, session_id: "s1", source_type: "turn", content: "test" },
];
const processed = postProcessResults(results, 10);
assert.equal(processed[0].score, "0.6000");
});
it("returns empty for all-garbage input", () => {
const results = [
{ distance: 0.95, session_id: "s1", source_type: "turn", content: "noise" },
];
const processed = postProcessResults(results, 10);
assert.equal(processed.length, 0);
});
it("score floor is exactly MIN_SCORE", () => {
const exactlyAtFloor = [
{ distance: 1 - MIN_SCORE, session_id: "s1", source_type: "turn", content: "borderline" },
];
const processed = postProcessResults(exactlyAtFloor, 10);
assert.equal(processed.length, 1);
});
});
describe("isOurServer", () => {
it("matches our server", () => {
assert.ok(isOurServer({
Name: "node.exe",
CommandLine: '"C:\\nvm4w\\nodejs\\node.exe" vector-memory-server.js',
}));
});
it("rejects different process", () => {
assert.ok(!isOurServer({
Name: "python.exe",
CommandLine: "python server.py",
}));
});
it("rejects node running different script", () => {
assert.ok(!isOurServer({
Name: "node.exe",
CommandLine: '"node" app.js',
}));
});
it("rejects null/undefined info", () => {
assert.ok(!isOurServer(null));
assert.ok(!isOurServer(undefined));
assert.ok(!isOurServer({}));
});
it("rejects missing CommandLine", () => {
assert.ok(!isOurServer({ Name: "node.exe" }));
});
});
describe("isIndexable", () => {
it("accepts content >= 10 chars", () => {
assert.ok(isIndexable({ content: "hello world" }));
});
it("rejects short content", () => {
assert.ok(!isIndexable({ content: "hi" }));
});
it("rejects empty content", () => {
assert.ok(!isIndexable({ content: "" }));
});
it("rejects null/undefined content", () => {
assert.ok(!isIndexable({ content: null }));
assert.ok(!isIndexable({}));
});
it("trims whitespace before checking length", () => {
assert.ok(!isIndexable({ content: " hi " }));
assert.ok(isIndexable({ content: " hello world " }));
});
});
// --- Handler tests (DI) ---
describe("handleRequest - /ping", () => {
it("returns { ok: true }", async () => {
const handler = createHandler(makeDeps());
const res = mockRes();
await handler(mockReq("POST", "/ping"), res);
assert.equal(res.statusCode, 200);
assert.deepEqual(res.body, { ok: true });
});
it("includes identity when getIdentity is provided", async () => {
const deps = makeDeps({
getIdentity: () => ({ user: "testuser", version: "1.0.0" }),
});
const handler = createHandler(deps);
const res = mockRes();
await handler(mockReq("POST", "/ping"), res);
assert.equal(res.statusCode, 200);
assert.equal(res.body.ok, true);
assert.equal(res.body.user, "testuser");
assert.equal(res.body.version, "1.0.0");
});
});
describe("handleRequest - routing", () => {
it("returns 404 for GET requests", async () => {
const handler = createHandler(makeDeps());
const res = mockRes();
await handler(mockReq("GET", "/ping"), res);
assert.equal(res.statusCode, 404);
});
it("returns 404 for unknown POST paths", async () => {
const handler = createHandler(makeDeps());
const res = mockRes();
await handler(mockReq("POST", "/unknown"), res);
assert.equal(res.statusCode, 404);
});
});
describe("handleRequest - /search", () => {
it("returns search results", async () => {
const deps = makeDeps();
const handler = createHandler(deps);
const res = mockRes();
await handler(mockReq("POST", "/search", { query: "test", limit: 5 }), res);
assert.equal(res.statusCode, 200);
assert.ok(Array.isArray(res.body));
assert.equal(res.body[0].score, "0.5000");
});
it("defaults limit to 10", async () => {
let capturedLimit;
const deps = makeDeps({
search: async (_db, _q, limit) => { capturedLimit = limit; return []; },
});
const handler = createHandler(deps);
await handler(mockReq("POST", "/search", { query: "test" }), mockRes());
assert.equal(capturedLimit, 10);
});
it("skips inline indexing when isIndexing is true", async () => {
let indexCalled = false;
const deps = makeDeps({
indexContent: async () => { indexCalled = true; return 1; },
getUnindexedContent: () => [{ content: "something here!" }],
});
deps._setIsIndexing(true);
const handler = createHandler(deps);
await handler(mockReq("POST", "/search", { query: "test" }), mockRes());
assert.ok(!indexCalled, "indexContent should not be called when isIndexing is true");
});
it("does inline indexing when isIndexing is false and there is unindexed content", async () => {
let indexCalled = false;
const deps = makeDeps({
indexContent: async () => { indexCalled = true; return 1; },
getUnindexedContent: () => [{ content: "something here!" }],
});
const handler = createHandler(deps);
await handler(mockReq("POST", "/search", { query: "test" }), mockRes());
assert.ok(indexCalled);
});
it("resets isIndexing after inline indexing completes", async () => {
const deps = makeDeps({
getUnindexedContent: () => [{ content: "something here!" }],
indexContent: async () => 1,
});
const handler = createHandler(deps);
await handler(mockReq("POST", "/search", { query: "test" }), mockRes());
assert.equal(deps.getIsIndexing(), false);
});
it("resets isIndexing even if indexContent throws", async () => {
const deps = makeDeps({
getUnindexedContent: () => [{ content: "something here!" }],
indexContent: async () => { throw new Error("boom"); },
});
const handler = createHandler(deps);
const res = mockRes();
await handler(mockReq("POST", "/search", { query: "test" }), res);
assert.equal(deps.getIsIndexing(), false);
assert.equal(res.statusCode, 500);
});
it("closes vecDb even on error", async () => {
const deps = makeDeps({
search: async () => { throw new Error("search failed"); },
});
const handler = createHandler(deps);
await handler(mockReq("POST", "/search", { query: "test" }), mockRes());
assert.ok(deps._closedDbs.includes("vec"));
});
it("skips indexing when sessionStore is null", async () => {
let indexCalled = false;
const deps = makeDeps({
openSessionStore: () => null,
indexContent: async () => { indexCalled = true; return 1; },
});
const handler = createHandler(deps);
const res = mockRes();
await handler(mockReq("POST", "/search", { query: "test" }), res);
assert.equal(res.statusCode, 200);
assert.ok(!indexCalled, "indexContent should not be called when sessionStore is null");
});
});
describe("handleRequest - /reindex", () => {
it("rejects when isIndexing is true", async () => {
const deps = makeDeps();
deps._setIsIndexing(true);
const handler = createHandler(deps);
const res = mockRes();
await handler(mockReq("POST", "/reindex"), res);
assert.equal(res.statusCode, 200);
assert.equal(res.body.error, "Indexing already in progress. Try again shortly.");
});
it("returns count on success", async () => {
const deps = makeDeps({
openSessionStore: () => ({
close() {},
prepare: () => ({ all: () => [{ content: "x", session_id: "s", source_type: "t", source_id: "1" }] }),
}),
indexContent: async () => 42,
});
const handler = createHandler(deps);
const res = mockRes();
await handler(mockReq("POST", "/reindex"), res);
assert.equal(res.body.count, 42);
});
it("returns error when session store not found", async () => {
const deps = makeDeps({ openSessionStore: () => null });
const handler = createHandler(deps);
const res = mockRes();
await handler(mockReq("POST", "/reindex"), res);
assert.equal(res.body.error, "Session store not found.");
});
it("resets isIndexing after reindex completes", async () => {
const deps = makeDeps();
const handler = createHandler(deps);
await handler(mockReq("POST", "/reindex"), mockRes());
assert.equal(deps.getIsIndexing(), false);
});
it("resets isIndexing even on error", async () => {
const deps = makeDeps({
openVectorDb: () => ({
close() {},
exec() { throw new Error("db exploded"); },
}),
});
const handler = createHandler(deps);
const res = mockRes();
await handler(mockReq("POST", "/reindex"), res);
assert.equal(deps.getIsIndexing(), false);
assert.equal(res.statusCode, 500);
});
});
// --- MockWorker for embed pool tests ---
class MockWorker extends EventEmitter {
constructor() {
super();
this.messages = [];
this.terminated = false;
}
postMessage(msg) {
this.messages.push(msg);
}
terminate() {
this.terminated = true;
}
}
function mockWorkerFactory() {
const workers = [];
const factory = () => {
const w = new MockWorker();
workers.push(w);
return w;
};
factory.workers = workers;
return factory;
}
// --- Embed pool tests ---
describe("createEmbedPool", () => {
it("embeds text through the worker (happy path)", async () => {
const factory = mockWorkerFactory();
const pool = createEmbedPool(factory);
pool.initWorker();
const p = pool.embed("hello");
const msg = factory.workers[0].messages[0];
factory.workers[0].emit("message", { id: msg.id, embedding: Buffer.from([1, 2, 3]) });
const result = await p;
assert.deepEqual(result, Buffer.from([1, 2, 3]));
pool.shutdown();
});
it("rejects embed when worker was never started", async () => {
const pool = createEmbedPool(() => new MockWorker());
await assert.rejects(() => pool.embed("hello"), /Embed worker is not running/);
});
it("rejects pending embeds on worker error", async () => {
const factory = mockWorkerFactory();
const pool = createEmbedPool(factory);
pool.initWorker();
const p = pool.embed("hello");
factory.workers[0].emit("error", new Error("segfault"));
await assert.rejects(() => p, /Worker crashed/);
pool.shutdown();
});
it("restarts worker on non-zero exit", async () => {
const factory = mockWorkerFactory();
const pool = createEmbedPool(factory, { restartDelay: 50 });
pool.initWorker();
factory.workers[0].emit("exit", 1);
await new Promise(r => setTimeout(r, 100));
assert.equal(factory.workers.length, 2, "worker should have been recreated");
assert.equal(pool.isAlive(), true);
pool.shutdown();
});
// === BUG TESTS: these demonstrate the issues we're fixing ===
it("restarts worker on code-0 exit (bug: currently does not)", async () => {
const factory = mockWorkerFactory();
const pool = createEmbedPool(factory, { restartDelay: 50 });
pool.initWorker();
factory.workers[0].emit("exit", 0);
await new Promise(r => setTimeout(r, 100));
assert.equal(factory.workers.length, 2, "worker should restart even on clean exit");
assert.equal(pool.isAlive(), true, "pool should be alive after code-0 restart");
pool.shutdown();
});
it("waits for worker restart instead of rejecting immediately (bug: currently rejects)", async () => {
const factory = mockWorkerFactory();
const pool = createEmbedPool(factory, { restartDelay: 50, workerReadyTimeout: 5000 });
pool.initWorker();
// Crash the worker
factory.workers[0].emit("exit", 1);
// Immediately try to embed — should wait for restart, not reject
let rejected = false;
let error = null;
const embedPromise = pool.embed("test text")
.catch(e => { rejected = true; error = e; });
// Give microtasks a chance to settle (synchronous rejection would be caught here)
await new Promise(r => setTimeout(r, 10));
assert.equal(rejected, false,
`embed() rejected immediately with "${error?.message}" instead of waiting for worker restart`);
// Let restart happen
await new Promise(r => setTimeout(r, 100));
// Respond from new worker
assert.equal(factory.workers.length, 2, "worker should have restarted");
const msg = factory.workers[1].messages[0];
factory.workers[1].emit("message", { id: msg.id, embedding: Buffer.from([4, 5, 6]) });
await embedPromise;
assert.equal(rejected, false);
pool.shutdown();
});
it("does not restart after explicit shutdown", async () => {
const factory = mockWorkerFactory();
const pool = createEmbedPool(factory, { restartDelay: 50 });
pool.initWorker();
pool.shutdown();
factory.workers[0].emit("exit", 1);
await new Promise(r => setTimeout(r, 100));
assert.equal(factory.workers.length, 1, "should not restart after shutdown");
});
it("times out if worker restart takes too long", async () => {
const factory = mockWorkerFactory();
const pool = createEmbedPool(factory, { restartDelay: 10000, workerReadyTimeout: 50 });
pool.initWorker();
factory.workers[0].emit("exit", 1);
await assert.rejects(() => pool.embed("test"), /restart timed out/i);
pool.shutdown();
});
it("handles worker 'error' message type (model error)", async () => {
const factory = mockWorkerFactory();
const pool = createEmbedPool(factory);
pool.initWorker();
// Send an error-type message (model failed to load, etc.)
factory.workers[0].emit("message", { type: "error", message: "ONNX load failed" });
// Pool should still be alive — this is a non-fatal model error, not a crash
assert.equal(pool.isAlive(), true);
pool.shutdown();
});
it("times out embed when worker never responds", async () => {
const factory = mockWorkerFactory();
const pool = createEmbedPool(factory, { embedTimeout: 50 });
pool.initWorker();
// Send an embed but never respond from the mock worker
await assert.rejects(() => pool.embed("hello"), /timed out after 50ms/);
pool.shutdown();
});
it("rejects embed when postMessage throws", async () => {
const factory = mockWorkerFactory();
const pool = createEmbedPool(factory);
pool.initWorker();
// Make postMessage throw (simulates worker in bad state)
factory.workers[0].postMessage = () => { throw new Error("DataCloneError"); };
await assert.rejects(() => pool.embed("hello"), /DataCloneError/);
pool.shutdown();
});
it("ignores 'ready' message type without affecting pending embeds", async () => {
const factory = mockWorkerFactory();
const pool = createEmbedPool(factory);
pool.initWorker();
const p = pool.embed("hello");
// Send a ready message — should be ignored, embed still pending
factory.workers[0].emit("message", { type: "ready" });
// Now send the real response
const msg = factory.workers[0].messages[0];
factory.workers[0].emit("message", { id: msg.id, embedding: Buffer.from([9]) });
const result = await p;
assert.deepEqual(result, Buffer.from([9]));
pool.shutdown();
});
it("ignores response for unknown embed id", async () => {
const factory = mockWorkerFactory();
const pool = createEmbedPool(factory);
pool.initWorker();
// Send a response for an ID that was never requested — should not throw
factory.workers[0].emit("message", { id: 99999, embedding: Buffer.from([1]) });
pool.shutdown();
});
it("shutdown is idempotent when no worker was started", () => {
const pool = createEmbedPool(() => new MockWorker());
// Should not throw
pool.shutdown();
pool.shutdown();
});
it("BUG: workerFactory() throwing in scheduleRestart retries with backoff", async () => {
let callCount = 0;
const workers = [];
const factory = () => {
callCount++;
if (callCount === 2) throw new Error("Worker constructor exploded");
const w = new MockWorker();
workers.push(w);
return w;
};
const pool = createEmbedPool(factory, { restartDelay: 50, workerReadyTimeout: 2000, maxRestartDelay: 200 });
pool.initWorker();
// Worker exits cleanly — first restart throws, second should succeed via backoff
workers[0].emit("exit", 0);
// Wait for retry
await new Promise(r => setTimeout(r, 500));
assert.ok(callCount >= 3, `Expected at least 3 factory calls, got ${callCount}`);
assert.equal(pool.isAlive(), true, "pool should recover via backoff retry");
pool.shutdown();
});
it("BUG: shutdown during restart delay still spawns zombie worker", async () => {
const factory = mockWorkerFactory();
const pool = createEmbedPool(factory, { restartDelay: 50 });
pool.initWorker();
// Worker exits — restart is scheduled with 50ms delay
factory.workers[0].emit("exit", 1);
// Shutdown immediately (before the 50ms restart fires)
pool.shutdown();
// Wait for the restart timer to fire (guard should catch it)
await new Promise(r => setTimeout(r, 150));
// Should NOT have created a second worker — guard prevents it
assert.equal(factory.workers.length, 1,
`Expected 1 worker but got ${factory.workers.length} — zombie worker spawned after shutdown`);
});
it("shutdown resolves pending restart waiters", async () => {
const factory = mockWorkerFactory();
const pool = createEmbedPool(factory, { restartDelay: 10000, workerReadyTimeout: 5000 });
pool.initWorker();
// Trigger exit — restart is scheduled but slow
factory.workers[0].emit("exit", 1);
// Start an embed — it will wait for the restart
const embedPromise = pool.embed("hello").catch(e => e);
// Shutdown while it's waiting
pool.shutdown();
const result = await embedPromise;
assert.ok(result instanceof Error);
assert.match(result.message, /not running|shutting down/i);
});
// === BUG: code-0 exit orphans in-flight embeds ===
it("BUG: code-0 exit rejects in-flight embeds (not orphaned for 60s)", async () => {
const factory = mockWorkerFactory();
const pool = createEmbedPool(factory, { embedTimeout: 5000, restartDelay: 50 });
pool.initWorker();
// Start an embed (worker won't respond)
const embedPromise = pool.embed("hello").catch(e => e);
await new Promise(r => setTimeout(r, 10));
// Worker exits cleanly — in-flight embed should be rejected promptly
const start = Date.now();
factory.workers[0].emit("exit", 0);
const result = await embedPromise;
const elapsed = Date.now() - start;
assert.ok(result instanceof Error, "in-flight embed should have been rejected");
assert.ok(elapsed < 1000,
`embed took ${elapsed}ms to reject — orphaned until embedTimeout instead of rejected on exit`);
pool.shutdown();
});
// === BUG: failed restart = permanent death (no retry) ===
it("BUG: failed restart retries with backoff instead of dying permanently", async () => {
let callCount = 0;
const workers = [];
const factory = () => {
callCount++;
// Fail on attempts 2 and 3, succeed on attempt 4
if (callCount >= 2 && callCount <= 3) throw new Error("ONNX load failed");
const w = new MockWorker();
workers.push(w);
return w;
};
const pool = createEmbedPool(factory, {
restartDelay: 30,
workerReadyTimeout: 5000,
maxRestartDelay: 200,
});
pool.initWorker();
// Worker exits — first restart attempt will fail, second will fail, third should succeed
workers[0].emit("exit", 0);
// Wait for backoff retries to play out
await new Promise(r => setTimeout(r, 1500));
assert.ok(callCount >= 4,
`Expected at least 4 factory calls (1 init + 2 failures + 1 success), got ${callCount}`);
assert.equal(pool.isAlive(), true, "pool should have recovered after transient failures");
pool.shutdown();
});
it("POSITIVE: backoff delay increases on consecutive failures", async () => {
let callCount = 0;
const timestamps = [];
const workers = [];
const factory = () => {
callCount++;
timestamps.push(Date.now());
if (callCount >= 2) throw new Error("still broken");
const w = new MockWorker();
workers.push(w);
return w;
};
const pool = createEmbedPool(factory, {
restartDelay: 50,
workerReadyTimeout: 5000,
maxRestartDelay: 400,
});
pool.initWorker();
workers[0].emit("exit", 0);
// Wait for several backoff attempts
await new Promise(r => setTimeout(r, 2000));
// Should have multiple attempts with increasing gaps
assert.ok(callCount >= 4, `Expected at least 4 attempts, got ${callCount}`);
// Verify delays are increasing (backoff)
for (let i = 2; i < timestamps.length - 1; i++) {
const gap1 = timestamps[i] - timestamps[i - 1];
const gap2 = timestamps[i + 1] - timestamps[i];
assert.ok(gap2 >= gap1 * 0.8, // allow 20% timing jitter
`Expected increasing delays but gap ${i}: ${gap1}ms, gap ${i+1}: ${gap2}ms`);
}
pool.shutdown();
});
it("POSITIVE: backoff resets after a successful restart", async () => {
let callCount = 0;
const workers = [];
const factory = () => {
callCount++;
// Fail on second call, succeed on all others
if (callCount === 2) throw new Error("transient failure");
const w = new MockWorker();
workers.push(w);
return w;
};
const pool = createEmbedPool(factory, {
restartDelay: 30,
workerReadyTimeout: 5000,
maxRestartDelay: 500,
});
pool.initWorker();
// First exit → restart fails → retries → succeeds
workers[0].emit("exit", 0);
await new Promise(r => setTimeout(r, 500));
assert.equal(pool.isAlive(), true, "pool should have recovered");
const secondWorkerIdx = workers.length - 1;
// Second exit → should restart with initial delay (not backoff from previous failure)
workers[secondWorkerIdx].emit("exit", 0);
await new Promise(r => setTimeout(r, 200));
assert.equal(pool.isAlive(), true, "pool should restart at base delay after prior success");
pool.shutdown();
});
it("POSITIVE: backoff caps at maxRestartDelay", async () => {
let callCount = 0;
const timestamps = [];
const workers = [];
const factory = () => {
callCount++;
timestamps.push(Date.now());
if (callCount >= 2) throw new Error("permanently broken");
const w = new MockWorker();
workers.push(w);
return w;
};
const pool = createEmbedPool(factory, {
restartDelay: 50,
maxRestartDelay: 150,
});
pool.initWorker();
workers[0].emit("exit", 0);
await new Promise(r => setTimeout(r, 2000));
// All gaps after the first few should be capped at ~150ms
const gaps = [];
for (let i = 1; i < timestamps.length; i++) {
gaps.push(timestamps[i] - timestamps[i - 1]);
}
// The last few gaps should all be ≤ maxRestartDelay + jitter
const lastGaps = gaps.slice(-3);
for (const gap of lastGaps) {
assert.ok(gap <= 250,
`Gap ${gap}ms exceeds maxRestartDelay (150ms) + reasonable jitter`);
}
pool.shutdown();
});
it("shutdown cancels pending restart timer", async () => {
const factory = mockWorkerFactory();
const pool = createEmbedPool(factory, { restartDelay: 50 });
pool.initWorker();
// Trigger exit — restart timer starts
factory.workers[0].emit("exit", 1);
// Shutdown immediately — should cancel the restart
pool.shutdown();
// Wait for timer that would have fired
await new Promise(r => setTimeout(r, 100));
// Should NOT have created a second worker
assert.equal(factory.workers.length, 1, "shutdown should cancel pending restart");
});
it("belt-and-suspenders: shuttingDown guard catches callback when clearTimeout fails", async () => {
const factory = mockWorkerFactory();
const pool = createEmbedPool(factory, { restartDelay: 50 });
pool.initWorker();
// Worker exits — restart timer is scheduled
factory.workers[0].emit("exit", 1);
// Monkeypatch clearTimeout to a no-op, simulating a race where
// the timer callback is already queued when shutdown tries to cancel it
const realClearTimeout = globalThis.clearTimeout;
globalThis.clearTimeout = () => {};
try {
pool.shutdown();
} finally {
globalThis.clearTimeout = realClearTimeout;
}
// Timer fires because clearTimeout was neutered — the shuttingDown guard catches it
await new Promise(r => setTimeout(r, 150));
// No zombie worker spawned — guard did its job
assert.equal(factory.workers.length, 1,
"shuttingDown guard should prevent zombie worker when clearTimeout fails");
});
it("uses default options when none provided", async () => {
const factory = mockWorkerFactory();
const pool = createEmbedPool(factory);
pool.initWorker();
const p = pool.embed("test");
const msg = factory.workers[0].messages[0];
factory.workers[0].emit("message", { id: msg.id, embedding: Buffer.from([1]) });
await p;
pool.shutdown();
});
});