Repository navigation
fix(embedder-openai): batch embed() input at the provider's per-request cap - #37037
Conversation
…st cap embed() sent every input in one /embeddings request; providers that cap the number of inputs per request rejected any larger reindex. Split the input into batches of the model's documented cap (known-model table, a maxBatchSize option, or a conservative default of 10 with one warning per instance), send them in sequence and return vectors in input order. A failing batch fails the call naming its 0-based index and input range. Claude-Session: https://claude.ai/code/session_01QSeKYpRrYuqSLCvbSk9zrL Co-authored-by: Claude <noreply@anthropic.com>
📓 Docs Drift CheckThis PR changes 1 package(s): 1 hand-written doc(s) NAME something this change touched and may need an implementation-accuracy re-verification:
What this run could not see
Coarse fallback — 1 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): Which tree this was computed onThis run read A worktree cut from an older # while this PR is open — GitHub drops the merge commit once it closes
git fetch origin cb2f7f3b3aa8d5b016f9907f13bdd7448b351eff && git checkout cb2f7f3b3aa8d5b016f9907f13bdd7448b351eff
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin a73edb3cd784e212c7b8b21757a44c0cfed9adfe f88cfb00425c15c3c67645c379f92046553ff1bd && git checkout -B drift-repro a73edb3cd784e212c7b8b21757a44c0cfed9adfe && git merge --no-ff f88cfb00425c15c3c67645c379f92046553ff1bd
node scripts/docs-audit/affected-docs.mjs --json a73edb3cd784e212c7b8b21757a44c0cfed9adfe
|
|
repo:objectstack#4 · os-justin · session_01QSeKYpRrYuqSLCvbSk9zrL Final head for L1 (2026-11-24T16:27Z):
|
|
repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ 席位核对 — ACCEPT · L1 · head
|
|
repo:objectstack#4 · os-justin · session_01QSeKYpRrYuqSLCvbSk9zrL Landing — PR #37037 at head
State: ready + auto-merge; #36995 closes on merge via |
…ne walk per source at a time (objectstack-ai#37129) Fixes objectstack-ai#36992 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:挂了知识检索的应用,管理员手动重建某个知识源时,系统改为每次读 100 条、写 100 条,大表不再一次全读进内存;同一知识源的两次重建会排队依次执行;文档和告警不再声称重建能清掉已删除记录的检索内容。 - 为什么做:知识检索平台化专题第一阶段的「数据多了也不能崩」——原来重建一次把整张表读进内存再一次性交给索引服务,数据量大时会撑爆内存或超时。 - 出错会怎样:只影响挂了知识检索服务的应用的手动重建;某一页失败时重建停在那一页并在结果里说明是哪一页,之前写入的不回退;已删除记录的旧内容仍要等「索引清理」那张卡落地才会被清掉;改动可直接撤回。 - 要你做的:无。 ## What changes `KnowledgeService.reindexSource` (`packages/services/service-knowledge/src/knowledge-service.ts`) for an `object` source, per card items 1-5: - **Keyset paging by id (item 1).** The walk reads at most `REINDEX_PAGE_SIZE` = 100 rows per `find(object, { where, orderBy: [{ field: 'id', order: 'asc' }], limit }, { context: system })`. Page 1 sends the source's `where` alone. Every later page sends `{ $and: [where, { id: { $gt: cursor } }] }` (or just the cursor condition when the source has no `where`), where the cursor is the previous page's last id, kept in its own type. Each page is upserted in its own `adapter.upsert(docs, { source, reason: 'reindex' })` before the next read. Every `find` carries a `limit`, and no `upsert` holds more than one page. Each row goes through the same `recordToDocument(source, objSource, row, this.schemaFor(object))` gate the event sync uses; no second builder was added. The system context now travels in the trailing options argument (the `IDataEngine` contract's position) and no longer inside the query behind an `as never` cast. - **Only an empty page ends the walk.** A page that comes back short of its `limit` is followed by the next read: `find` does not promise `min(limit, remaining)` rows, because an `afterFind` hook may drop rows from a page (`packages/objectql/src/engine-find.ts`). So a 101-row object takes three reads, the last one empty. - **Failure ends the run with `ok: false` and names the page (item 1).** A read, a document build or an upsert that throws returns `{ ok: false, object, discovered, indexed, message }`. The message reads `reindex of source 'S' stopped at page N (after id 'X'): ...` with the cause (an `Error`'s message, any other thrown value via `String(...)`), and the counts cover the pages done before it. Those pages stay in the index. Two further stops prevent an endless walk: a page whose last row has no id, and a last id that did not move past the cursor (an engine that ignored the id condition). Each returns `ok: false` and names its page. Before this change, a failure threw out of `reindexSource`. - **What is serialized, and what is not (item 1).** The record sync's per-document promise chain from objectstack-ai#37075 is now one module-level helper, `chainAfter(tails, key, task)`, which returns the task's own outcome while the chain itself never rejects. `serializeRecordSync` delegates to it unchanged in meaning, and `reindexSource` chains on a separate `reindexTails` map keyed by source id. So a second reindex of the same source waits for the first and their pages never interleave; different sources still run concurrently. Record events do NOT wait for a walk. A row updated or deleted between a page's read and that page's upsert is written back from the older read, and a deleted row's document then stays as a ghost until the index purge (objectstack-ai#37096). That race predates this PR, and paging narrows its window from the whole object to one page. The jsdoc and the changeset say exactly this. - **`limit` / `dryRun` (item 2).** `opts.limit` keeps its total-cap meaning: each read asks for `min(100, limit - discovered)`, and the walk stops at the cap without an extra read. A fractional `limit` is floored. A negative or non-finite one (`-1`, `NaN`, `Infinity`) is refused with `ok: false` and nothing is read; before this change such a value went straight to `find`. `dryRun` calls `count(object, { where }, { context })`, reads no rows, and reports `min(count, limit)`. - **Page size (item 3), my reading.** Item 3 said to match the embedder's per-request cap until the `embedder-openai` sibling landed, then follow it. That sibling (objectstack-ai#36995) landed as objectstack-ai#37037, and `OpenAIEmbedder` now splits a larger input set into requests of its own cap. So the page size is no longer an embedder-correctness bound; it bounds memory and the size of one adapter call. I kept 100 as a module constant and did not add an option: `KnowledgeReindexOptions` is a spec contract, and `KnowledgeServiceOptions` is not forwarded from any config a host writes. `REINDEX_PAGE_SIZE` is exported from the module for the tests only and is not re-exported from `index.ts`, so the published `dist/index.d.ts` export list is unchanged. - **Result shape (item 4).** `{ indexed, discovered, object?, ok, message? }` is unchanged. No fields were added, so no published type widens. - **No purge (item 5).** A reindex still removes no documents, and no adapter-contract member was added. The knowledge-platform ADR (objectstack-ai#37001 / objectstack-ai#37119) is not merged. - **No surface claims a reindex removes documents any more.** These sites are reworded; behaviour is unchanged. Each now says a reindex refreshes the rows that still exist and match, and that the documents of deleted (or no-longer-matching) rows wait for the index purge (objectstack-ai#37096): - `content/docs/protocol/knowledge.mdx`: the predicate-write callout ("Repair such an index with an explicit `reindexSource`") and the rolled-back-write passage (a document built from an insert that rolled back has no row left to repair it from). - The same rolled-back-write passage in `handleRecordUpsert`'s jsdoc. - The bulk-write warning in `knowledge-service-plugin.ts`. As a runtime string it names the purge in words, with no tracker number. Its existing pins in `event-sync-data-events.test.ts` still hold. ## Tests `src/__tests__/knowledge-service.test.ts` adds a new top-level `describe('KnowledgeService — the reindex walk pages by id')` (25 cases) in the existing harness file. Its engine double throws on any `find` without a positive `limit`, without `orderBy` id asc, or without the system context, and on any operator it does not implement. It orders numbers numerically and everything else by string. Rows are inserted in shuffled order, so the walk sees only the engine's ordering. - Boundaries: - 0 rows: one read, no upsert. - Exactly 100 rows: one upsert of 100, then a page-2 read of `{ id: { $gt: 'r099' } }` that comes back empty. - 101 rows: upserts of 100 then 1, each row exactly once, in id order, then a third, empty read of `{ id: { $gt: 'r100' } }`. Every read is limited to 100, every upsert holds at most 100, and the reason is `reindex`. - A short page is not the end: the first full page comes back with 99 of its 100 rows (the drop an `afterFind` hook can make), and every later row is still upserted (pages 99/100/50, 249 rows, 4 reads). - Numeric ids 1..150: the cursor keeps the number (`{ id: { $gt: 100 } }`, then `{ id: { $gt: 150 } }`), and the pages follow numeric order. - The source's `where` is ANDed with the cursor (the exact page-2 `where` is asserted). - `limit`: - 150 / 100 / 30 / 0 read `[100,50]` / `[100]` / `[30]` / nothing. - A `limit` above the row count reads to the end. - 150.7 is floored to 150. - -1, NaN and Infinity are refused with `ok: false` (plain and `dryRun`), with no `find`, no `count` and no upsert. - `dryRun` uses `count` under the `where`, capped by `limit`, with zero `find` calls. - Failures, each `ok: false` with the counts of the pages done before it: - A failed read on page 2 and a failed upsert on page 2: the message names `page 2` and `after id 'r099'`, the counts are 100/100, and the next walk after a failure runs (the lock is released). - A document build that throws on page 2. - A thrown non-`Error` is reported by its text, never as `undefined`. - An engine that ignores the cursor ends the walk at page 2 instead of looping. A last row with no id ends the walk after page 1. - A concurrent second reindex of the same source makes no read while the first one's read is held, and the upsert order is `r000+100, r100+50, r000+100, r100+50`. Walks of different sources do not wait for each other. The two older reindex tests were updated for the new call shape. The context is read from the trailing argument. `dryRun` asserts that `count` is called and `find` is not. Their doubles now answer an empty next page, as a cursor-honouring engine does: they used to return the same rows for every read, which this walk now correctly reports as a cursor that did not advance. ## Acceptance notes - **Cursor order on a SQL driver, checked once.** The zone confirmed that a single check is enough. `service-knowledge` cannot reach a SQL driver: its dependencies are `core`, `objectql`, `platform-objects`, `service-settings` and `spec`. A committed test would need `@objectstack/driver-sql` as a devDependency plus a `pnpm-lock.yaml` importer entry, and the lockfile is outside this PR's file surface. So the check is a scratch measurement against this branch's source, re-run on the current head (readings under Verification). - `KnowledgeReindexResult.ok`'s jsdoc in `packages/spec` ("an adapter / source check prevented the run") now also covers a failed page and a refused `limit`. That is outside this PR's file surface, and the wording is still broadly true. - `dryRun`'s `count` is not wrapped: a failing count still rejects, as the old `dryRun` read did. The card's `ok: false` rule is about pages. ## Verification Read first (risk order): 1. `knowledge-service.ts` `walkObjectSource`: the loop's exits (empty page, cap, and the two non-advance stops) and the cursor `where` composition. 2. `knowledge-service.ts` `chainAfter` and `serializeRecordSync`: the event-sync chain now goes through the shared helper. 3. `knowledge-service.test.ts` `pagedEngine`: the double's refusals are what make "every find has a limit" fail loudly. Two-minute check: run `pnpm --filter @objectstack/service-knowledge exec vitest run src/__tests__/knowledge-service.test.ts`. Expect 53 passing tests, 25 of them under `the reindex walk pages by id`. Every reading below was taken at head `9e24b96c`, the final commit. <details><summary>Package tests and typecheck</summary> ``` pnpm --filter @objectstack/service-knowledge test Test Files 8 passed (8) Tests 142 passed (142) pnpm --filter @objectstack/service-knowledge typecheck check:test-typecheck: OK — 0 file(s) / 0 error(s) / 0 pinned signature(s) ``` </details> <details><summary>Ablations (source-resolved subject: the test imports ../knowledge-service.js, so no dist is on the path; each mutation made by scripts/ablation-replace.mjs; each restore proven by blob == HEAD and an empty git diff HEAD)</summary> ``` A4 (9e24b96) restore `if (rows.length < want) break;` after the page upsert -> 3 failed (one page + 1, the short-page pin, numeric ids), 50 passed (a first attempt was refused by the tool before any test ran: its replacement contained the anchor, so the anchor count could not drop) A1-A3 (99518e6, before this round; the code they mutate is unchanged) A1 delete `limit: want,` from the page read -> 12 failed (the double refuses an unbounded find) A2 bypass chainAfter on reindexTails -> 1 failed (the never-interleave pin) A3 drop the `id > cursor` condition -> 7 failed; the walk still terminated (the non-advance stop held) ``` </details> <details><summary>SQL driver: one scratch run of ObjectQL + SqlDriver (better-sqlite3, :memory:) against this branch's source at 9e24b96</summary> The run used 250 rows of a `kb_note` object, inserted in shuffled order: 16 explicit ids chosen to stress ordering (`a A b B r9 r10 r100 Z z 0 9 10 _x -y r_1 r-1`) plus 234 engine-generated ids. 191 rows have `status = 'open'`. The fourth read is the empty one that ends the walk. ``` rows 250 result {"ok":true,"object":"kb_note","discovered":250,"indexed":250} pages 100,100,50 finds 4 maxPage 100 pageSize 100 each row once true walk order == engine id order true every find limited true page2 query {"where":{"id":{"$gt":"MutQpGXcbru5V4DJ"}},"orderBy":[{"field":"id","order":"asc"}],"limit":100} open: rows 191 result {"ok":true,"object":"kb_note","discovered":191,"indexed":191} once true page2 query {"where":{"$and":[{"status":"open"},{"id":{"$gt":"XhVtf05MZ_zLLW3V"}}]},"orderBy":[{"field":"id","order":"asc"}],"limit":100} limit 150 {"ok":true,"object":"kb_note","discovered":150,"indexed":150} reads 100,50 dryRun {"ok":true,"object":"kb_note","discovered":191,"indexed":0,"message":"dryRun=true; no documents pushed."} ``` </details> <details><summary>Local gate subset (dispatch-gates --commands, derived from merge base eec6fb3, 5 paths): 100 derived, 98 exit 0, 2 NOT MEASURED</summary> ``` dispatch-gates --ran: 100 derived famil(ies) accounted for — 98 run, 2 NOT-MEASURED (2 DERIVED from a recorded exit 3) NOT MEASURED: pnpm check:dual-build-cjs-loads, reason: PREREQUISITE NOT MET (64 packages have no dist/; reads the whole monorepo's built output) NOT MEASURED: pnpm --filter @objectstack/spec run check:skill-examples, reason: PREREQUISITE NOT MET (client / client-react have no dist/; selected by the docs page) doc authoring guard: 23493 customer-facing string(s) ... clean — no internal issue-id references check-nul-bytes: OK (no raw ASCII control bytes) eslint --no-inline-config on the three changed source files: exit 0 ``` CI runs both NOT MEASURED families on a full build. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01QSeKYpRrYuqSLCvbSk9zrL)_ <!-- signed: repo:objectstack#4 · os-justin · session_01QSeKYpRrYuqSLCvbSk9zrL --> --------- Co-authored-by: Claude <noreply@anthropic.com>
Fixes #36995
Clause-②: yes
Metadata-protocol: none
维护者速读
What changes
OpenAIEmbedder.embed()(packages/plugins/embedder-openai/src/index.ts) sent every input in onePOST /embeddingsrequest ({ model, input: texts }, oneresilientFetch; premise re-read on origin/main a73edb3). It now:textsinto batches of at mostmaxBatchSizeinputs, sends them one after another, and returns the vectors in input order;maxBatchSizefrom a new known-model cap table (KNOWN_MAX_BATCH_SIZE, besideKNOWN_DIMENSIONS; documented caps only, each with its source in the doc comment), from the new optionalOpenAIEmbedderOptions.maxBatchSize(validated as a positive integer at construction; anything else throws), or, for any other model, a conservative default of 10 (the smallest documented cap in the table) with oneconsole.warnper embedder instance, printed at construction. The class has no logger and none is reachable from it, soconsole.warnis used; that has precedent inpackages/plugins/plugin-auth;[batch index N of M (0-based), inputs A..B]. The vector-count mismatch error and a transport failure (afterresilientFetch's own retries) carry the same suffix.No change to
IEmbedderor topackages/spec/**. Nothing else is added to what is sent: each request body has the same keys as before (model,input, optionaldimensions).Provider caps: documented, not measured live
Card step 1 asks for one live over-cap request per provider. This container holds no provider API keys, so no provider was called live. Every cap below is documented, not measured live, and its source is cited. The seat decides whether a live measurement is still owed.
text-embedding-3-small,-3-large,ada-002maxItems: 2048("any array must be 2048 dimensions or less"); also "a maximum of 300,000 tokens summed across all inputs in a single request"text-embedding-v3model-studio/text-embedding-synchronous-api: "最多支持 10 条(行),每条(行)最长支持 8,192 Token"text-embedding-v1,-v2embedding-3BAAI/bge-m3,BAAI/bge-large-zh-v1.5,BAAI/bge-large-en-v1.5maxItems: 32("Current, the maximum array size is 32")Models in
KNOWN_DIMENSIONSwith no documented item cap are left out of the cap table on purpose. They take the default of 10 and the one warning:embedding-2: the docs state a total length ("数组总长度不得超过 8K"), not an item count.doubao-embedding-*: docs.volcengine.com 82379/1302003 gives no hard item cap, only a performance suggestion ("文本条数不超过4").embo-01: no official cap found; the only figure (4096) is a third-party client's setting.bge-m3andnomic-embed-text: no cap documented.BAAI/bge-base-zh-v1.5andBAAI/bge-small-zh-v1.5: not on SiliconFlow's documented model list.Tests
New top-level
describe('OpenAIEmbedder batching (per-request input cap)')in the existing harness filesrc/__tests__/openai-embedder.test.ts. It covers:[10, 10, 5], and the vectors come back in input order;batch index 1 of 3 (0-based), inputs 10..19, and fetch was called exactly twice (no third request);maxBatchSize: 3override beats the known-model cap ([3, 3, 1]);0,-1,1.5andNaNare refused;embed()calls, while a known model, or an unknown model with an override, stays silent.Package test / typecheck / build (head f88cfb0)
Ablation (one-time; nothing left in the tree)
The tests import
../index(source, relative), so no dist leg applies. Run throughscripts/ablation-replace.mjs: the slicetexts.slice(start, start + this.maxBatchSize)was mutated totexts.slice(start)(anchor x1 → x0, blob 6e8c6095 → 5eab5b01).The exact-cap test stays green under the mutation, as it should: a single batch is unchanged.
Acceptance notes
maxBatchSize: 2048to restore one request per 2048 inputs.texts+typebody rather thaninput. If that holds, theminimaxpreset may not work at all. Not reproduced, no key. Noted, not filed.[batch index …]suffix. The leading part (OpenAIEmbedder (BASE) → STATUS STATUSTEXT: TEXT) is unchanged.Verification
Files to read first, by risk:
packages/plugins/embedder-openai/src/index.ts: theembed()/embedBatch()split, especially the order ofvectors.pushacross batches and the stop-on-first-failure behaviour.packages/plugins/embedder-openai/src/index.ts: the constructor'smaxBatchSizeresolution (override, then table, then default and warning)..changeset/36995-embedder-openai-batches.mdTwo-minute check:
pnpm --filter @objectstack/embedder-openai exec vitest run src/__tests__/openai-embedder.test.ts. ExpectTests 21 passed (21), including the sevenOpenAIEmbedder batching (per-request input cap)cases.Local gates (head f88cfb0)
node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack: 65 commands for these 4 paths, run one by one with each exit code captured before any pipe.node scripts/check-plugin-teardown-shape.mjs --self-test: the shallow clone could not reach the fixture commit 621a487. I fetched that one commit and re-ran it: exit 0, 48 cases pass.pnpm check:lean-entry-closure: it needs objectql'sdist/. I built@objectstack/objectql...(os-verify-lockVERDICT command-exit 0) and re-ran it: exit 0, "Admitted set held exactly (15 packages)".pnpm check:dual-build-cjs-loads: its self-test passes (94 cases), but the scan needs every workspace package'sdist/, and 96+ were absent. NOT MEASURED locally — a declared narrowing. CI'sLint & Repo Gatesruns it on a full build.--ranreconciliation, with exit codes recorded: "65 derived, 64 run, 1 NOT-MEASURED, 0 UNRUN".node scripts/pm/overlap-check.mjs --branch=claude/issue-36995-embedder-batches: VERDICT clean.node scripts/check-nul-bytes.mjs: OK.test:repo, which CI owns and whose tests this diff does not touch; and the full dogfood battery, which does not apply here (no!in the title, no(narrowing)arm).Generated by Claude Code