@exulu/backend 5.5.1 → 5.7.0

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.
@@ -0,0 +1,27 @@
1
+ import { queues as ExuluQueues, global_queues } from "./queues";
2
+ import type { ExuluQueueConfig } from "@EXULU_TYPES/queue-config";
3
+
4
+ /**
5
+ * Server-side bulk import (CSV -> items): one job at a time, one context's
6
+ * import running per worker slot -- a bulk import already runs its own
7
+ * bounded concurrency pool internally (src/exulu/import/run-import.ts), so
8
+ * the queue just serializes whole import runs. The 6 h timeout covers a large
9
+ * file streamed + chunk-processed end to end.
10
+ *
11
+ * Both callers (ExuluApp's boot-time registration in src/exulu/app/index.ts
12
+ * and the StartImport/CancelImport resolvers' `getImportQueue()`) go through
13
+ * this one helper so the parameters cannot drift apart -- `register` is
14
+ * idempotent per queue name, so calling it from both is safe.
15
+ */
16
+ export const IMPORT_QUEUE_CONCURRENCY = { worker: 1, queue: 1 };
17
+ export const IMPORT_QUEUE_RATELIMIT = 1;
18
+ export const IMPORT_QUEUE_TIMEOUT_SECONDS = 6 * 3600;
19
+
20
+ export function registerImportQueue(): { use: () => Promise<ExuluQueueConfig> } {
21
+ return ExuluQueues.register(
22
+ global_queues.import,
23
+ IMPORT_QUEUE_CONCURRENCY,
24
+ IMPORT_QUEUE_RATELIMIT,
25
+ IMPORT_QUEUE_TIMEOUT_SECONDS,
26
+ );
27
+ }
@@ -21,14 +21,21 @@ describe("maybePruneJobResults", () => {
21
21
  whereInCalls.push(args);
22
22
  return builder;
23
23
  },
24
+ whereNot: () => builder,
25
+ whereRaw: () => builder,
26
+ orWhereNull: () => builder,
24
27
  orderBy: () => builder,
25
28
  offset: () => builder,
26
29
  limit: () => builder,
27
30
  first: async () => undefined, // under cap: nothing to delete
28
- where: () => builder,
31
+ where: (arg: any) => {
32
+ if (typeof arg === "function") arg.call(builder);
33
+ return builder;
34
+ },
29
35
  del: async () => 0,
30
36
  };
31
37
  const db: any = jest.fn(() => builder);
38
+ db.client = { config: { client: "pg" } };
32
39
 
33
40
  // The module-level counter only reaches the prune body every 100th call.
34
41
  for (let i = 0; i < 100; i++) {
@@ -39,3 +46,100 @@ describe("maybePruneJobResults", () => {
39
46
  expect(whereInCalls[0]).toEqual(["state", TERMINAL_JOB_STATES]);
40
47
  });
41
48
  });
49
+
50
+ /**
51
+ * Review Focus 7: import rows get their own, smaller, per-context retention
52
+ * instead of sharing the generic MAX_TERMINAL rolling window -- a tenant
53
+ * running frequent imports in one context should not crowd out every other
54
+ * context's/job type's terminal rows. Fake-db pattern: chainable builder
55
+ * recording every call per method name (as in
56
+ * src/exulu/email-inbound/intake.test.ts), so each assertion checks the
57
+ * actual knex calls the module made rather than its return value.
58
+ */
59
+ describe("maybePruneJobResults -- import retention exemption", () => {
60
+ function fakeDb(opts: { dialect?: string; boundaryCreatedAt?: string } = {}) {
61
+ const calls: Record<string, any[][]> = {};
62
+ const builder: any = {};
63
+ const record =
64
+ (name: string) =>
65
+ (...args: any[]) => {
66
+ (calls[name] ||= []).push(args);
67
+ return builder;
68
+ };
69
+ builder.whereIn = record("whereIn");
70
+ builder.whereNot = record("whereNot");
71
+ builder.orWhereNull = record("orWhereNull");
72
+ // Grouped predicate: `.where((b) => b.whereNot(...).orWhereNull(...))`.
73
+ // Knex invokes the callback with `this` bound to a sub-builder -- record
74
+ // the call itself, then run the callback against this same builder so
75
+ // its whereNot/orWhereNull calls land in the same `calls` map (matching
76
+ // how the production code's grouped predicate is actually built).
77
+ builder.where = (...args: any[]) => {
78
+ (calls["where"] ||= []).push(args);
79
+ if (typeof args[0] === "function") args[0].call(builder);
80
+ return builder;
81
+ };
82
+ builder.whereRaw = record("whereRaw");
83
+ builder.orderBy = record("orderBy");
84
+ builder.offset = record("offset");
85
+ builder.limit = record("limit");
86
+ builder.first = jest.fn(async () =>
87
+ opts.boundaryCreatedAt ? { createdAt: opts.boundaryCreatedAt } : undefined,
88
+ );
89
+ builder.del = jest.fn(async () => 0);
90
+ const db: any = jest.fn(() => builder);
91
+ db.client = { config: { client: opts.dialect ?? "pg" } };
92
+ return { db, calls, del: builder.del as jest.Mock };
93
+ }
94
+
95
+ it("excludes import rows from both the generic boundary query and its delete, via a grouped predicate", async () => {
96
+ const { db, calls } = fakeDb({ boundaryCreatedAt: "2026-01-01T00:00:00.000Z" });
97
+ for (let i = 0; i < 100; i++) await maybePruneJobResults(db);
98
+
99
+ // Both queries build the predicate as `.where((b) => b.whereNot({type:
100
+ // "import"}).orWhereNull("type"))` -- a plain top-level `.whereNot({type:
101
+ // "import"})` compiles to `not type = 'import'`, which SQL evaluates to
102
+ // NULL/false for a row with `type IS NULL`, making such rows unprunable
103
+ // forever (D-Fix F2). The grouped `orWhereNull` closes that gap.
104
+ expect((calls["where"] ?? []).length).toBeGreaterThanOrEqual(2);
105
+ const whereNotCalls = calls["whereNot"] ?? [];
106
+ expect(whereNotCalls.length).toBeGreaterThanOrEqual(2);
107
+ for (const args of whereNotCalls) {
108
+ expect(args[0]).toEqual({ type: "import" });
109
+ }
110
+ const orWhereNullCalls = calls["orWhereNull"] ?? [];
111
+ expect(orWhereNullCalls.length).toBeGreaterThanOrEqual(2);
112
+ for (const args of orWhereNullCalls) {
113
+ expect(args).toEqual(["type"]);
114
+ }
115
+ });
116
+
117
+ it("runs its own per-context cap query and delete for import rows (Postgres)", async () => {
118
+ // No boundaryCreatedAt: the generic cap's own delete never fires (under
119
+ // cap), isolating this assertion to the import cap's independent delete.
120
+ const { db, calls, del } = fakeDb();
121
+ for (let i = 0; i < 100; i++) await maybePruneJobResults(db);
122
+
123
+ const whereRawCalls = calls["whereRaw"] ?? [];
124
+ expect(whereRawCalls.length).toBeGreaterThanOrEqual(1);
125
+ const [sql, bindings] = whereRawCalls[0]!;
126
+ expect(sql).toMatch(/row_number\(\)/i);
127
+ expect(sql).toMatch(/partition by context/i);
128
+ expect(bindings).toContain(200);
129
+
130
+ // Scoped to type = "import", and runs its own delete independent of the
131
+ // generic cap's boundary check above.
132
+ const typeWhereCalls = (calls["where"] ?? []).filter(
133
+ (args) => JSON.stringify(args[0]) === JSON.stringify({ type: "import" }),
134
+ );
135
+ expect(typeWhereCalls.length).toBeGreaterThanOrEqual(1);
136
+ expect(del).toHaveBeenCalledTimes(1);
137
+ });
138
+
139
+ it("skips the per-context import cap on a non-Postgres dialect", async () => {
140
+ const { db, calls } = fakeDb({ dialect: "mysql" });
141
+ for (let i = 0; i < 100; i++) await maybePruneJobResults(db);
142
+
143
+ expect(calls["whereRaw"]).toBeUndefined();
144
+ });
145
+ });
@@ -17,6 +17,15 @@ import { TERMINAL_JOB_STATES } from "@EXULU_TYPES/enums/jobs";
17
17
 
18
18
  const MAX_TERMINAL = 10_000;
19
19
  const PRUNE_EVERY = 100;
20
+ /**
21
+ * Import runs (server-side bulk import) get their own, smaller, per-context
22
+ * cap instead of sharing the generic MAX_TERMINAL rolling window below -- a
23
+ * tenant running frequent imports in one context should not crowd out every
24
+ * other context's or job type's terminal rows, and 200 per context is plenty
25
+ * to review (older ones are still available in the context's own audit trail
26
+ * via the item rows they created/updated).
27
+ */
28
+ const MAX_IMPORT_PER_CONTEXT = 200;
20
29
 
21
30
  let sinceLastPrune = 0;
22
31
  let pruning = false;
@@ -27,19 +36,50 @@ export async function maybePruneJobResults(db: any): Promise<void> {
27
36
  sinceLastPrune = 0;
28
37
  pruning = true;
29
38
  try {
30
- // The (MAX_TERMINAL+1)-th newest terminal row marks the boundary; delete it
31
- // and everything older. Dialect-agnostic (knex offset/limit) so it works on
32
- // both Postgres and MySQL.
33
- const boundary = await db("job_results")
34
- .whereIn("state", TERMINAL_JOB_STATES)
39
+ await pruneGenericJobResults(db);
40
+ await pruneImportJobResults(db);
41
+ } finally {
42
+ pruning = false;
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Excludes import rows from the generic cap, on either a SELECT or a
48
+ * DELETE: a plain top-level `.whereNot({ type: "import" })` compiles to
49
+ * `not (type = 'import')`, and SQL's three-valued logic evaluates that to
50
+ * NULL (neither true nor false, so excluded from the result) for any row
51
+ * whose `type` is NULL -- making every untyped job_results row permanently
52
+ * unprunable (D-Fix F2). The grouped `orWhereNull("type")` catches those
53
+ * rows back into the generic cap, where they belong (they were never
54
+ * exempted on purpose -- `type` is just nullable on the column).
55
+ */
56
+ function excludeImportType(builder: any): any {
57
+ return builder.where(function (this: any) {
58
+ this.whereNot({ type: "import" }).orWhereNull("type");
59
+ });
60
+ }
61
+
62
+ /**
63
+ * The (MAX_TERMINAL+1)-th newest terminal row marks the boundary; delete it
64
+ * and everything older. Dialect-agnostic (knex offset/limit) so it works on
65
+ * both Postgres and MySQL. Import rows are excluded here (see
66
+ * excludeImportType) -- they get their own, smaller, per-context cap in
67
+ * pruneImportJobResults instead.
68
+ */
69
+ async function pruneGenericJobResults(db: any): Promise<void> {
70
+ try {
71
+ const boundary = await excludeImportType(
72
+ db("job_results").whereIn("state", TERMINAL_JOB_STATES),
73
+ )
35
74
  .orderBy("createdAt", "desc")
36
75
  .offset(MAX_TERMINAL)
37
76
  .limit(1)
38
77
  .first();
39
78
 
40
79
  if (boundary?.createdAt) {
41
- const deleted = await db("job_results")
42
- .whereIn("state", TERMINAL_JOB_STATES)
80
+ const deleted = await excludeImportType(
81
+ db("job_results").whereIn("state", TERMINAL_JOB_STATES),
82
+ )
43
83
  .where("createdAt", "<=", boundary.createdAt)
44
84
  .del();
45
85
  if (deleted) {
@@ -50,7 +90,43 @@ export async function maybePruneJobResults(db: any): Promise<void> {
50
90
  }
51
91
  } catch (err) {
52
92
  console.error("[EXULU] job_results prune failed", err);
53
- } finally {
54
- pruning = false;
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Per-context cap for import job_results rows: keeps only the newest
98
+ * MAX_IMPORT_PER_CONTEXT terminal rows per context, independent of the
99
+ * generic MAX_TERMINAL window above. Needs a Postgres window function
100
+ * (row_number() over (partition by context ...)), so this step is skipped
101
+ * entirely on any other knex dialect -- the generic cap above still bounds
102
+ * the table's overall size regardless, and this codebase only ever connects
103
+ * with the "pg" client (src/postgres/client.ts), so the guard is defensive
104
+ * rather than a real supported-dialect split.
105
+ */
106
+ async function pruneImportJobResults(db: any): Promise<void> {
107
+ if (db.client?.config?.client !== "pg") return;
108
+ try {
109
+ const statePlaceholders = TERMINAL_JOB_STATES.map(() => "?").join(", ");
110
+ const deleted = await db("job_results")
111
+ .where({ type: "import" })
112
+ .whereRaw(
113
+ `id in (
114
+ select id from (
115
+ select id, row_number() over (partition by context order by "createdAt" desc) as rn
116
+ from job_results
117
+ where type = 'import' and state in (${statePlaceholders})
118
+ ) ranked
119
+ where rn > ?
120
+ )`,
121
+ [...TERMINAL_JOB_STATES, MAX_IMPORT_PER_CONTEXT],
122
+ )
123
+ .del();
124
+ if (deleted) {
125
+ console.log(
126
+ `[EXULU] pruned ${deleted} terminal import job_results rows (cap ${MAX_IMPORT_PER_CONTEXT}/context).`,
127
+ );
128
+ }
129
+ } catch (err) {
130
+ console.error("[EXULU] import job_results prune failed", err);
55
131
  }
56
132
  }
@@ -16,6 +16,7 @@ import { checkLicense } from "@EE/entitlements";
16
16
  export const global_queues = {
17
17
  eval_runs: "eval_runs",
18
18
  email_intake: "email_intake",
19
+ import: "import",
19
20
  };
20
21
 
21
22
  // Used for workflows and embedders
@@ -0,0 +1,178 @@
1
+ /**
2
+ * The defect under test: tiktoken's `load()` has no cache of its own
3
+ * (node_modules/tiktoken/load.cjs) — it is a bare `fetch(url).then(r =>
4
+ * r.text())` — and `ExuluTokenizer` used to call it on every `create()`. Since
5
+ * `createAndUpsertEmbeddings` builds a chunker per item, embedding N items
6
+ * meant N downloads of the ~1.6MB BPE ranks from a third-party host.
7
+ *
8
+ * Spec: docs/superpowers/specs/2026-10-27-chunking-library-defects-design.md §3
9
+ */
10
+ import type { ExuluTokenizer as ExuluTokenizerType } from "./tokenizer";
11
+
12
+ /** A tiny but valid "<base64 token> <rank>" ranks file. */
13
+ const RANKS = ["IQ== 0", "Ig== 1", "Iw== 2", "aGVsbG8= 3"].join("\n") + "\n";
14
+
15
+ const realFetch = globalThis.fetch;
16
+
17
+ /** A fresh module instance, so the module-level ranks cache starts empty. */
18
+ const freshTokenizer = (): typeof ExuluTokenizerType => {
19
+ let ctor: typeof ExuluTokenizerType | undefined;
20
+ jest.isolateModules(() => {
21
+ ctor = (require("./tokenizer") as typeof import("./tokenizer")).ExuluTokenizer;
22
+ });
23
+ return ctor!;
24
+ };
25
+
26
+ const stubFetch = () => {
27
+ const mock = jest.fn(async () => ({ text: async () => RANKS }));
28
+ globalThis.fetch = mock as unknown as typeof fetch;
29
+ return mock;
30
+ };
31
+
32
+ afterEach(() => {
33
+ globalThis.fetch = realFetch;
34
+ });
35
+
36
+ describe("ExuluTokenizer BPE loading", () => {
37
+ it("downloads the ranks once no matter how many tokenizers are built", async () => {
38
+ const ExuluTokenizer = freshTokenizer();
39
+ const fetchMock = stubFetch();
40
+
41
+ for (let i = 0; i < 3; i++) {
42
+ const tokenizer = new ExuluTokenizer();
43
+ await tokenizer.create("gpt-3.5-turbo");
44
+ }
45
+
46
+ expect(fetchMock).toHaveBeenCalledTimes(1);
47
+ });
48
+
49
+ it("shares one download between models that use the same encoding", async () => {
50
+ const ExuluTokenizer = freshTokenizer();
51
+ const fetchMock = stubFetch();
52
+
53
+ // Both map to cl100k_base, so keying the cache by encoding (not by model)
54
+ // is what makes this one download instead of two.
55
+ await new ExuluTokenizer().create("gpt-3.5-turbo");
56
+ await new ExuluTokenizer().create("gpt-4");
57
+
58
+ expect(fetchMock).toHaveBeenCalledTimes(1);
59
+ });
60
+
61
+ it("collapses concurrent creations into a single download", async () => {
62
+ const ExuluTokenizer = freshTokenizer();
63
+ const fetchMock = stubFetch();
64
+
65
+ // Embedding runs chunk items concurrently; without caching the in-flight
66
+ // promise this is one download per caller.
67
+ await Promise.all(
68
+ Array.from({ length: 5 }, () => new ExuluTokenizer().create("gpt-3.5-turbo")),
69
+ );
70
+
71
+ expect(fetchMock).toHaveBeenCalledTimes(1);
72
+ });
73
+
74
+ it("does not cache a failed download, so a transient outage is retryable", async () => {
75
+ const ExuluTokenizer = freshTokenizer();
76
+ const mock = jest
77
+ .fn()
78
+ .mockRejectedValueOnce(new Error("ConnectTimeoutError"))
79
+ .mockResolvedValue({ text: async () => RANKS });
80
+ globalThis.fetch = mock as unknown as typeof fetch;
81
+
82
+ await expect(new ExuluTokenizer().create("gpt-3.5-turbo")).rejects.toThrow();
83
+
84
+ // A poisoned cache entry would make every later create() fail for the
85
+ // lifetime of the process.
86
+ const tokenizer = new ExuluTokenizer();
87
+ await tokenizer.create("gpt-3.5-turbo");
88
+ expect(tokenizer.countTokens("hello")).toBe(1);
89
+ expect(mock).toHaveBeenCalledTimes(2);
90
+ });
91
+
92
+ it("gives every tokenizer its own encoder, so freeing one leaves others usable", async () => {
93
+ const ExuluTokenizer = freshTokenizer();
94
+ stubFetch();
95
+
96
+ const first = new ExuluTokenizer();
97
+ const second = new ExuluTokenizer();
98
+ await first.create("gpt-3.5-turbo");
99
+ await second.create("gpt-3.5-turbo");
100
+
101
+ // Caching the ranks must not become caching one shared WASM encoder:
102
+ // both chunkers call free() at the end of every chunk().
103
+ await first.free();
104
+
105
+ expect(second.countTokens("hello")).toBe(1);
106
+ });
107
+
108
+ it("still memoizes within a single instance", async () => {
109
+ const ExuluTokenizer = freshTokenizer();
110
+ const fetchMock = stubFetch();
111
+
112
+ const tokenizer = new ExuluTokenizer();
113
+ const a = await tokenizer.create("gpt-3.5-turbo");
114
+ const b = await tokenizer.create("gpt-3.5-turbo");
115
+
116
+ expect(a).toBe(b);
117
+ expect(fetchMock).toHaveBeenCalledTimes(1);
118
+ });
119
+ });
120
+
121
+ describe("ExuluTokenizer encoder lifecycle", () => {
122
+ it("drops the handle when freed, so a dangling pointer is unreachable", async () => {
123
+ const ExuluTokenizer = freshTokenizer();
124
+ stubFetch();
125
+
126
+ const tokenizer = new ExuluTokenizer();
127
+ await tokenizer.create("gpt-3.5-turbo");
128
+ await tokenizer.free();
129
+
130
+ // Leaving the freed Tiktoken in place is what produced "null pointer
131
+ // passed to rust" on the next call.
132
+ expect(tokenizer.encoder).toBeNull();
133
+ expect(() => tokenizer.countTokens("hello")).toThrow("Tokenizer not initialized");
134
+ });
135
+
136
+ it("rebuilds a freed encoder without downloading the ranks again", async () => {
137
+ const ExuluTokenizer = freshTokenizer();
138
+ const fetchMock = stubFetch();
139
+
140
+ const tokenizer = new ExuluTokenizer();
141
+ await tokenizer.create("gpt-3.5-turbo");
142
+ await tokenizer.free();
143
+ await tokenizer.ensure();
144
+
145
+ expect(tokenizer.countTokens("hello")).toBe(1);
146
+ expect(fetchMock).toHaveBeenCalledTimes(1);
147
+ });
148
+
149
+ it("is a no-op when the encoder is still alive", async () => {
150
+ const ExuluTokenizer = freshTokenizer();
151
+ stubFetch();
152
+
153
+ const tokenizer = new ExuluTokenizer();
154
+ const created = await tokenizer.create("gpt-3.5-turbo");
155
+
156
+ expect(await tokenizer.ensure()).toBe(created);
157
+ });
158
+
159
+ it("refuses to ensure a tokenizer that was never created", async () => {
160
+ const ExuluTokenizer = freshTokenizer();
161
+ stubFetch();
162
+
163
+ await expect(new ExuluTokenizer().ensure()).rejects.toThrow("Tokenizer not initialized");
164
+ });
165
+
166
+ it("tolerates being freed twice", async () => {
167
+ const ExuluTokenizer = freshTokenizer();
168
+ stubFetch();
169
+
170
+ const tokenizer = new ExuluTokenizer();
171
+ await tokenizer.create("gpt-3.5-turbo");
172
+ await tokenizer.free();
173
+
174
+ // A double free on a live pointer is what crashes WASM; the null guard
175
+ // has to hold.
176
+ await expect(tokenizer.free()).resolves.toBeUndefined();
177
+ });
178
+ });
package/ee/tokenizer.ts CHANGED
@@ -5,25 +5,93 @@ import models from "tiktoken/model_to_encoding.json" with { type: "json" };
5
5
 
6
6
  export type TokenizerModelName = keyof typeof models;
7
7
 
8
+ type TiktokenBPE = Awaited<ReturnType<typeof load>>;
9
+
10
+ /**
11
+ * The BPE ranks, cached for the lifetime of the process and keyed by ENCODING
12
+ * rather than by model — most model names share one encoding (every current
13
+ * gpt-3.5/gpt-4 name maps to cl100k_base), so keying by model would re-download
14
+ * the same bytes.
15
+ *
16
+ * Why this cache has to exist: tiktoken's `load()` holds no cache of its own
17
+ * (node_modules/tiktoken/load.cjs — a bare `fetch(url).then(r => r.text())`),
18
+ * and the ranks for cl100k_base are ~1.6MB fetched from
19
+ * openaipublic.blob.core.windows.net. `createAndUpsertEmbeddings` builds a
20
+ * chunker per item, so without this, embedding N items meant N downloads from
21
+ * a third-party host — the dominant cost of a bulk re-embed, and an undeclared
22
+ * hard dependency on that host being reachable.
23
+ *
24
+ * The PROMISE is cached, not just the result, so concurrent callers share one
25
+ * in-flight download instead of racing to start their own.
26
+ */
27
+ const ranksByEncoding = new Map<string, Promise<TiktokenBPE>>();
28
+
29
+ const loadRanks = (encoding: string): Promise<TiktokenBPE> => {
30
+ const cached = ranksByEncoding.get(encoding);
31
+ if (cached) return cached;
32
+
33
+ const time = performance.now();
34
+ console.log("[EXULU] Loading tokenizer ranks.", encoding);
35
+ const pending = load(registry[encoding as keyof typeof registry])
36
+ .then((ranks): TiktokenBPE => {
37
+ console.log("[EXULU] Loaded tokenizer ranks.", encoding, performance.now() - time);
38
+ return ranks;
39
+ })
40
+ .catch((error: unknown) => {
41
+ // Never leave a rejected promise in the cache: a single transient
42
+ // timeout would otherwise fail every embed for the life of the process.
43
+ ranksByEncoding.delete(encoding);
44
+ throw error;
45
+ });
46
+
47
+ ranksByEncoding.set(encoding, pending);
48
+ return pending;
49
+ };
50
+
8
51
  export class ExuluTokenizer {
9
52
  constructor() {}
10
53
 
11
54
  public encoder: Tiktoken | null = null;
12
55
 
56
+ /** Remembered so `ensure()` can rebuild an encoder that `free()` released. */
57
+ private modelName: TokenizerModelName | null = null;
58
+
13
59
  async create(modelName: TokenizerModelName): Promise<Tiktoken> {
60
+ this.modelName = modelName;
14
61
  if (this.encoder) {
15
62
  return this.encoder;
16
63
  }
17
- const time = performance.now();
18
- console.log("[EXULU] Loading tokenizer.", modelName);
19
- const model = await load(registry[models[modelName] as keyof typeof registry]);
20
- console.log("[EXULU] Loaded tokenizer.", modelName, performance.now() - time);
21
- const encoder = new Tiktoken(model.bpe_ranks, model.special_tokens, model.pat_str);
22
- console.log("[EXULU] Set encoder.");
64
+ // A Tiktoken per instance, built from the shared ranks. Deliberately NOT a
65
+ // shared encoder: both chunkers call `tokenizer.free()` at the end of every
66
+ // chunk() (sentence.ts, recursive.ts), which would free a shared one out
67
+ // from under every other caller. Construction from cached ranks is the
68
+ // cheap half — the download was the expensive part.
69
+ const ranks = await loadRanks(models[modelName]);
70
+ const encoder = new Tiktoken(ranks.bpe_ranks, ranks.special_tokens, ranks.pat_str);
71
+ console.log("[EXULU] Set encoder.", modelName);
23
72
  this.encoder = encoder;
24
73
  return encoder;
25
74
  }
26
75
 
76
+ /**
77
+ * The encoder, rebuilt if a previous `chunk()` freed it.
78
+ *
79
+ * Both chunkers free their tokenizer at the end of every `chunk()`, so an
80
+ * instance that is used twice — directly, or via `chunkBatch`, which calls
81
+ * `chunk()` once per text — needs its encoder back. Rebuilding is cheap:
82
+ * the ranks are already cached process-wide, so this costs a `Tiktoken`
83
+ * construction and no network.
84
+ */
85
+ async ensure(): Promise<Tiktoken> {
86
+ if (this.encoder) {
87
+ return this.encoder;
88
+ }
89
+ if (!this.modelName) {
90
+ throw new Error("Tokenizer not initialized");
91
+ }
92
+ return this.create(this.modelName);
93
+ }
94
+
27
95
  async decode(tokens: Uint32Array): Promise<string> {
28
96
  if (!this.encoder) {
29
97
  throw new Error("Tokenizer not initialized");
@@ -75,6 +143,12 @@ export class ExuluTokenizer {
75
143
  console.log("[EXULU] Freeing tokenizer.");
76
144
  if (this.encoder) {
77
145
  this.encoder.free();
146
+ // Drop the handle along with the allocation. A freed Tiktoken is a
147
+ // dangling pointer into WASM memory, and both chunkers free after EVERY
148
+ // chunk(), so leaving it set made the next call on the same instance
149
+ // crash with "null pointer passed to rust". Null means `ensure()`
150
+ // rebuilds instead.
151
+ this.encoder = null;
78
152
  }
79
153
  }
80
154
  }