Skip to content

fix(embedder-openai): batch embed() input at the provider's per-request cap - #37037

Merged
objectstack-fleet[bot] merged 1 commit into
mainfrom
claude/issue-36995-embedder-batches
Nov 24, 2026
Merged

objectstack-fleet[bot] merged 1 commit into
mainfrom
claude/issue-36995-embedder-batches

Conversation

@objectstack-fleet

Copy link
Copy Markdown
Contributor

Fixes #36995

Clause-②: yes
Metadata-protocol: none

维护者速读

  • 用户能看到什么变化:部署方接入有单次条数上限的向量服务(通义、智谱、硅基流动等)后,知识库重建不再因为一次塞进太多文本而整批失败;界面无变化。
  • 为什么做:属于「知识检索平台化」专题,替接入国内向量服务的部署方解决重建失败。
  • 出错会怎样:最坏是重建请求次数变多、变慢;某一批失败时整次调用失败并指出是第几批,改动可直接撤回。
  • 要你做什么:无。

What changes

OpenAIEmbedder.embed() (packages/plugins/embedder-openai/src/index.ts) sent every input in one POST /embeddings request ({ model, input: texts }, one resilientFetch; premise re-read on origin/main a73edb3). It now:

  • splits texts into batches of at most maxBatchSize inputs, sends them one after another, and returns the vectors in input order;
  • takes maxBatchSize from a new known-model cap table (KNOWN_MAX_BATCH_SIZE, beside KNOWN_DIMENSIONS; documented caps only, each with its source in the doc comment), from the new optional OpenAIEmbedderOptions.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 one console.warn per embedder instance, printed at construction. The class has no logger and none is reachable from it, so console.warn is used; that has precedent in packages/plugins/plugin-auth;
  • fails the whole call on a failing batch and sends no later batch. The error keeps the provider's status and response text exactly as before and appends [batch index N of M (0-based), inputs A..B]. The vector-count mismatch error and a transport failure (after resilientFetch's own retries) carry the same suffix.

No change to IEmbedder or to packages/spec/**. Nothing else is added to what is sent: each request body has the same keys as before (model, input, optional dimensions).

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.

Provider Model(s) in the table Cap used Source (read 2026-11-24)
OpenAI text-embedding-3-small, -3-large, ada-002 2048 developers.openai.com API reference, embeddings create: array maxItems: 2048 ("any array must be 2048 dimensions or less"); also "a maximum of 300,000 tokens summed across all inputs in a single request"
阿里通义 DashScope text-embedding-v3 10 help.aliyun.com model-studio/text-embedding-synchronous-api: "最多支持 10 条(行),每条(行)最长支持 8,192 Token"
阿里通义 DashScope text-embedding-v1, -v2 25 same page: "最多支持 25 条(行),每条(行)最长支持 2,048 Token"
智谱 BigModel embedding-3 64 docs.bigmodel.cn API reference 文本嵌入 and the embedding-3 model page: "数组最大不得超过 64 条"
硅基流动 SiliconFlow BAAI/bge-m3, BAAI/bge-large-zh-v1.5, BAAI/bge-large-en-v1.5 32 docs.siliconflow.com create-embeddings: array maxItems: 32 ("Current, the maximum array size is 32")

Models in KNOWN_DIMENSIONS with 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 doubao-embedding-*: docs.volcengine.com 82379/1302003 gives no hard item cap, only a performance suggestion ("文本条数不超过4").
  • MiniMax embo-01: no official cap found; the only figure (4096) is a third-party client's setting.
  • Ollama bge-m3 and nomic-embed-text: no cap documented.
  • BAAI/bge-base-zh-v1.5 and BAAI/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 file src/__tests__/openai-embedder.test.ts. It covers:

  • 25 inputs on a cap-10 model are sent as [10, 10, 5], and the vectors come back in input order;
  • exactly the cap is one request;
  • cap + 1 is two requests;
  • a failing second batch rejects with the provider text and batch index 1 of 3 (0-based), inputs 10..19, and fetch was called exactly twice (no third request);
  • a maxBatchSize: 3 override beats the known-model cap ([3, 3, 1]);
  • 0, -1, 1.5 and NaN are refused;
  • an unknown model is batched at 10 and warns exactly once across two embed() calls, while a known model, or an unknown model with an override, stays silent.
Package test / typecheck / build (head f88cfb0)
pnpm --filter @objectstack/embedder-openai test       → Test Files 1 passed (1) · Tests 21 passed (21)
pnpm --filter @objectstack/embedder-openai typecheck  → exit 0; check:test-typecheck: OK — 0 file(s) / 0 error(s)
pnpm --filter @objectstack/embedder-openai build      → exit 0; check-dts-emitted: 2/2 declared declaration file(s) present
os-verify-lock: VERDICT command-exit 0
Ablation (one-time; nothing left in the tree)

The tests import ../index (source, relative), so no dist leg applies. Run through scripts/ablation-replace.mjs: the slice texts.slice(start, start + this.maxBatchSize) was mutated to texts.slice(start) (anchor x1 → x0, blob 6e8c6095 → 5eab5b01).

× splits input above the cap and preserves input order
× sends cap + 1 inputs as two requests
× fails the call on a failing batch, naming its index, and sends no later batch
× honours an explicit maxBatchSize over the known-model cap
× batches an unknown model at the conservative default and warns once per instance
Tests  5 failed | 16 passed (21)
ablation-replace: ok restored: blob == HEAD (6e8c60954841) and `git diff HEAD` is empty

The exact-cap test stays green under the mutation, as it should: a single batch is unchanged.

Acceptance notes

  • The token total per request is not batched on. OpenAI also caps a request at 300,000 tokens summed across its inputs. Batching by item count does not bound that, so 2048 long inputs can still exceed it. This is read from the docs only, not reproduced. It belongs with the input-size work the card leaves to the epic (over-long inputs and chunking). Noted, not filed.
  • Azure OpenAI deployments are named by deployment, not by model, so they always take the default of 10 and the warning. An Azure user sets maxBatchSize: 2048 to restore one request per 2048 inputs.
  • MiniMax request shape, unverified. The only description of MiniMax's own embeddings endpoint I found is a third-party snippet, which shows a texts + type body rather than input. If that holds, the minimax preset may not work at all. Not reproduced, no key. Noted, not filed.
  • Error text. Every embedder error now ends with the [batch index …] suffix. The leading part (OpenAIEmbedder (BASE) → STATUS STATUSTEXT: TEXT) is unchanged.

Verification

Files to read first, by risk:

  1. packages/plugins/embedder-openai/src/index.ts: the embed() / embedBatch() split, especially the order of vectors.push across batches and the stop-on-first-failure behaviour.
  2. packages/plugins/embedder-openai/src/index.ts: the constructor's maxBatchSize resolution (override, then table, then default and warning).
  3. .changeset/36995-embedder-openai-batches.md

Two-minute check: pnpm --filter @objectstack/embedder-openai exec vitest run src/__tests__/openai-embedder.test.ts. Expect Tests 21 passed (21), including the seven OpenAIEmbedder batching (per-request input cap) cases.

Local gates (head f88cfb0)
  • Derived with 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.
  • First pass: 62 exited 0. The other 3 exited 3 with "prerequisite not met", which is not a verdict:
    • 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's dist/. I built @objectstack/objectql... (os-verify-lock VERDICT 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's dist/, and 96+ were absent. NOT MEASURED locally — a declared narrowing. CI's Lint & Repo Gates runs it on a full build.
  • --ran reconciliation, 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.
  • Not run locally: 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

…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>
@github-actions

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

This PR changes 1 package(s): @objectstack/embedder-openai, touching 6 documentable anchor(s). ⚠️ 1 changed file(s) yielded no anchor (packages/plugins/embedder-openai/README.md), so the pages documenting them are NOT COVERED by this run — this is not a clean bill of health for those files.

1 hand-written doc(s) NAME something this change touched and may need an implementation-accuracy re-verification:

  • content/docs/permissions/record-view-auditing.mdx (via maxBatchSize (symbol, a field of class OpenAIEmbedder; a field of interface OpenAIEmbedderOptions))
What this run could not see
  • 1 changed file(s) yielded no anchor (packages/plugins/embedder-openai/README.md) — pages documenting those are invisible to this run
  • 2 name(s) were too generic to anchor anything (single lowercase words)
  • the SDK route bridge reached 69 of 252 client-bound route-ledger rows — the other 183 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 183: 0 are remediable by widening that discovery convention (an in-repo file declares the path; the convention did not scan it); 59 are structural — on a ledger where NOT ONE row is declared in-repo, so no discovery change reaches them at any price; 124 are undecided (no in-repo declaration, on a ledger that has other in-repo registrars — absence and an unreadable spelling are not distinguishable here). The rows themselves: node scripts/docs-audit/affected-docs.mjs --bridge-coverage
  • a page that states a rule by its inputs shares no identifier with the emitter that implements the rule, so an emitter-only diff cannot list it — not on this run and not on any run. Measured on fix(driver-sql): emit varchar(maxLength) for a text field a declared index keys on #11430: content/docs/protocol/objectql/types.mdx documents the text-family column mapping by the ObjectQL type names it maps FROM (text / textarea / html) while the diff changed createColumn; it went unlisted, and it was the page that diff falsified, in four places. No shared token exists to detect this on, so a rule your change carries has to be re-read by hand in the pages that restate it.
  • a key NAME is not a key, so the hand re-read the line above prescribes can land on the wrong schema. The same spelling is authorable on one governed type and a [REMOVED] tombstone on another for each of active, aria, joins, objects, template, tools and version (censused on [finding] tools is a key on BOTH AgentSchema (tombstoned, dead) and SkillSchema (live, cloud-attested), so a name-based search attributes skill examples to the agent key — it produced a false stop-the-line alarm on PR #19059 #19093 over the liveness ledger's governed types, top-level keys); nothing in a search result distinguishes the two, so a grep hit on a LIVE example reads as evidence about the DEAD key. Measured on fix(spec): the agent.tools liveness row says dead — it claimed live on a key the schema tombstoned #19059: content/docs/ai/agents.mdx was reported as contradicting the agent.tools tombstone over its tools: example at :161, which is inside the defineSkill({ block opened at :155 — the page was already correct. Settle ownership by PARSING the value against both schemas, never by the name: that literal PASSES SkillSchema, and as an AgentSchema it FAILS at tools with the tombstone prescription. ⛔ These names are not the whole class — a key retired through a .strict() guidance map leaves no tombstone in the walked shape and none of them here (tool.category, live as AIToolDefinition.category).

Coarse fallback — 1 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): node scripts/docs-audit/affected-docs.mjs --json a73edb3cd784e212c7b8b21757a44c0cfed9adfe → packageMentionDocs.

Which tree this was computed on

This run read content/docs from cb2f7f3b3aa8d5b016f9907f13bdd7448b351eff — the merge of head f88cfb00425c15c3c67645c379f92046553ff1bd into base a73edb3cd784e212c7b8b21757a44c0cfed9adfe, which is what actions/checkout gives a pull_request run. Not the PR head.

A worktree cut from an older main holds a different content/docs, so re-deriving there can legitimately return a different list — that is a different tree, not a wrong row. To answer on the same tree:

# 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

⚠️ That checkout carried uncommitted changes, so the commit above does not fully identify what was read.

Advisory only, and a precision-first one (#9192): a page is listed because it names a
symbol, wire route or SDK method this diff touched — not because it mentions a changed
package. Each row says which anchor put it there, so a wrong row is reportable rather than
merely annoying. To re-verify, run the docs-accuracy-audit workflow scoped to these files:
node scripts/docs-audit/affected-docs.mjs a73edb3cd784e212c7b8b21757a44c0cfed9adfe → pass the list as
args.docs, on the commit named under Which tree this was computed on.

@github-actions github-actions Bot added documentation Improvements or additions to documentation tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface labels Nov 24, 2026
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-justin · session_01QSeKYpRrYuqSLCvbSk9zrL

Final head for L1 (2026-11-24T16:27Z): f88cfb00425c15c3c67645c379f92046553ff1bd — check-runs on it: 33 success, 16 skipped, 0 failure, 0 pending; mergeable state clean. Area: a4-K.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ

席位核对 — ACCEPT · L1 · head f88cfb00425c15c3c67645c379f92046553ff1bd · 2026-11-24T16:28Z

Requested by zone a4-K for card #36995 (epic #37000 phase 1); the seat session reviews.

  • Shape. 4 files, all under packages/plugins/embedder-openai/ plus one changeset (+217/−11); no governed path. Clause-②: yes (a new public option, maxBatchSize, widens what a caller may pass) with no arm, Metadata-protocol: none: AGENTS.md's Post-Task Checklist step 3 — a non-protocol change ships patch, which the changeset carries. The Clause-②: yes declaration alone owes this lane review at the default tier; no contract face is touched.
  • Acceptance, as ruled. Card embedder-openai: embed() sends every input in one request; providers with a per-request cap reject a reindex #36995's acceptance was changed by the maintainer's ruling 7137388978 (option A): documented caps cited with their source, measured later where a key exists. The code cites each source beside KNOWN_MAX_BATCH_SIZE (OpenAI 2048; DashScope v3 10, v1/v2 25; Zhipu embedding-3 64; SiliconFlow BGE 32); the PR body says "documented, not measured live".
  • Behaviour, read against the code. embed() slices into batches of maxBatchSize, sends them in sequence and concatenates in input order; an explicit maxBatchSize wins, then the known-model table, then 10 with one console.warn per instance; a non-positive-integer override throws at construction. A failing batch — transport throw, non-2xx, or a vector count that does not match the batch — fails the whole call with [batch index i of n (0-based), inputs a..b] and sends no later batch. Nothing is dropped silently. An unknown model that was sent unbatched before now takes more requests of 10: slower, never rejected for count; stated in the changeset.
  • Tests. Seven new cases in openai-embedder.test.ts: split and order, exactly-cap, cap+1, failing batch (index named, no later request), explicit override over the table, invalid override refused, unknown model default with one warning. They cover each branch above.
  • Changeset sentence read. Every bullet matches the code.
  • Gates. Check-runs at this head: 33 success, 16 skipped, 0 failed, 0 pending (zone's reading, announced on the PR, 7137698499).
  • Out of scope, judged by the zone at the filing gate: OpenAI's per-request total-token cap belongs to the epic's splitter work (专题:知识检索平台化(应用写一份知识源配置就有可用的检索:开源、托管、企业版都能用) #37000 phase 2, row 6), not a separate card; the minimax preset's request shape is an unverified inference with no reproduction, not filed. Agreed.
  • Nit (no push for it): the transport-failure branch wraps the error without { cause: err }, so the original stack is lost; carry it in the next change to this file.
  • No must-fix, no should-fix. The zone lands it (not governed, under 3000 lines).

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-justin · session_01QSeKYpRrYuqSLCvbSk9zrL

Landing — PR #37037 at head f88cfb00425c15c3c67645c379f92046553ff1bd (2026-11-24T16:29Z), on ACCEPT 7137733635. Area: a4-K.

Probe Reading
check-governed-merges.mjs --pr 37037 NOT governed, 0 of 4 paths; 228 changed lines ≤ 3000
landing-k.mjs --pr 37037 K = 5 < 15; locale leg none; shared-budget leg none

State: ready + auto-merge; #36995 closes on merge via Fixes.

@objectstack-fleet
objectstack-fleet Bot marked this pull request as ready for review November 24, 2026 16:30
@objectstack-fleet
objectstack-fleet Bot added this pull request to the merge queue Nov 24, 2026
Merged via the queue into main with commit 5ff858b Nov 24, 2026
50 checks passed
@objectstack-fleet
objectstack-fleet Bot deleted the claude/issue-36995-embedder-batches branch November 24, 2026 17:02
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation size/m tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

Development

Successfully merging this pull request may close these issues.

embedder-openai: embed() sends every input in one request; providers with a per-request cap reject a reindex

2 participants