Skip to content

Commit fc198b2

Browse files
feat(spec): IReranker contract and RERANKER_SERVICE token (#38778)
repo:objectstack#3 · os-steve · session_01ADHkmPDtfMCw4FJfyFfQ7v Fixes #38772 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 用户无感:开发者在规范包的契约入口里多了一个“重排器”接口和它的服务名,运行时行为不变。 - 属于“知识检索重排”专题,先把重排器的契约立住,后续的知识服务重排步骤按它接入。 - 目前没有任何代码读取它,出错也只影响类型声明,整个改动可直接撤回。 - 无 ## What changes - New `packages/spec/src/contracts/reranker.ts`, mirroring `embedder.ts`: `IReranker { readonly id: string; rerank(query: string, documents: string[], opts?: { signal?: AbortSignal }): Promise<Array<{ index: number; score: number }>> }` and `RERANKER_SERVICE = 'reranker' as const`. - The docblock states the ruled contract and no more: the model always comes from the deployment, never from a knowledge source; the knowledge service resolves it per search, as adapters resolve the embedder; one call per search, at most 50 documents; the caller passes an `AbortSignal` for its time limit; each entry names a document by its position in `documents` plus the reranker's score. No order or completeness guarantee is stated (not ruled). - `packages/spec/src/contracts/index.ts`: one `export * from './reranker.js';` line, placed right after `knowledge-service.js` (not after `embedder.js`, where #38744 inserts its own line; `overlap-check.mjs` reads both merges clean). - Regenerated by their generators: `packages/spec/api-surface/contracts.json` and `packages/spec/export-origins/contracts.json` (+2 names each). `gen:declaration-map` wrote nothing. - Changeset `.changeset/38772-reranker-contract.md`: `@objectstack/spec` patch (`Metadata-protocol: none` sets patch). - Not here: no `IReranker.model`, no vendor list, no reader, no `core-service-contracts.ts` entry (the embedder has none either), no runtime change. ## Tests - `packages/spec/src/contracts/reranker.test.ts`: type-level pins (exported `Assert<Eq<…>>` aliases compiled by `check:test-typecheck`) for the member set (`id` | `rerank` only), readonly `id`, the exact parameter tuple, the options bag, optional `opts`, the `Promise<Array<{ index; score }>>` answer, the barrel re-export and the `'reranker'` literal; plus two runtime cases. - Reverse verification: adding `model?: string` and a `topK` option to the interface turned `check:test-typecheck` red with 3 type errors in `reranker.test.ts`; restored from HEAD, clean. ## Acceptance notes - `opts.signal` is typed optional (`{ signal?: AbortSignal }`), as `fetch`'s `RequestInit` spells it; the epic's line writes `opts?: { signal }`. The docblock says the caller passes one. - Returned order and count are not defined by the contract (the ruling says index + score per document only); row 2's service orders by position. ## Verification <details><summary>Local gates</summary> At head `7d0eea72`. `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 90 commands; `--ran` reconciliation: 90 derived, 86 run (exit 0), 4 NOT MEASURED, 0 unrun. - Spec package: `pnpm --filter @objectstack/spec typecheck` (tsc, check:scripts-typecheck, check:test-typecheck) exit 0; `vitest run --project local src/contracts/reranker.test.ts src/contracts/core-service-contracts.test.ts` 2 files, 13 tests passed. - `check:api-surface`, `check:export-origins`, `check:generated`, `check:authorable-surface`, `check:dual-source-exports`, `check:entry-nameability`, `check:exported-any`, `check:spec-docblock-symbol-anchors`, `check:changeset-no-major`, `check:empty-changeset`, `check:nul-bytes`: exit 0 (all within the 86). - NOT MEASURED, to CI: `check:doc-formula-expressions`, `check:dual-build-cjs-loads`, `check:lean-entry-closure` (exit 3, prerequisite: other packages' dist not built here); `check:type-check-debt` (whole-workspace ratchet, not reached within the local time cap). - `node scripts/pm/overlap-check.mjs`: clean against origin/main and #38744. </details> Two-minute check: `pnpm --filter @objectstack/spec exec vitest run --project local src/contracts/reranker.test.ts` prints `2 passed`. Read first: `packages/spec/src/contracts/reranker.ts` (the docblock is the contract text), then `reranker.test.ts`. --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmPDtfMCw4FJfyFfQ7v)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ADHkmPDtfMCw4FJfyFfQ7v <!-- signed: repo:objectstack#3 · os-steve · session_01ADHkmPDtfMCw4FJfyFfQ7v --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 09eea10 commit fc198b2

6 files changed

Lines changed: 141 additions & 0 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/spec': patch
3+
---
4+
5+
feat(spec): `IReranker` and `RERANKER_SERVICE`, the reranker contract in `@objectstack/spec/contracts`
6+
7+
Clause-②: yes (widening)
8+
Metadata-protocol: none
9+
10+
`@objectstack/spec/contracts` now exports `IReranker`, the contract for a provider that scores passages against a query, and its service token `RERANKER_SERVICE = 'reranker'`, mirroring `IEmbedder` and `EMBEDDER_SERVICE`. `IReranker` has a stable `id` and one method, `rerank(query, documents, opts?: { signal })`, which resolves to an array of `{ index, score }`: `index` is the document's position in `documents`, `score` the reranker's score for it. A higher `score` means the document matches the query better. The caller ranks by `score`; the order of the returned array carries no meaning. The model always comes from the deployment, never from a knowledge source; the knowledge service is to resolve the reranker per search, as knowledge adapters resolve the embedder, and that reader lands with `retrieval.rerank` (#38750, row 2); the caller makes one call per search and sends at most 50 documents; the caller passes an `AbortSignal` for its time limit.
11+
12+
Nothing reads the contract yet, and no runtime behaviour changes.

‎packages/spec/api-surface/contracts.json‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,7 @@
222222
"IPubSub (interface)",
223223
"IQueueService (interface)",
224224
"IRealtimeService (interface)",
225+
"IReranker (interface)",
225226
"IRlsMembershipResolver (interface)",
226227
"ISchemaDiffService (interface)",
227228
"ISchemaDriver (interface)",
@@ -332,6 +333,7 @@
332333
"QueueMessage (interface)",
333334
"QueueMessageRecord (interface)",
334335
"QueuePublishOptions (interface)",
336+
"RERANKER_SERVICE (const)",
335337
"RESERVED_RLS_MEMBERSHIP_KEYS (const)",
336338
"RESUME_AUTHORITY_SERVICE (const)",
337339
"RLS_MEMBERSHIP_RESOLVER_SERVICE (const)",

‎packages/spec/export-origins/contracts.json‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,7 @@
222222
"IPubSub": "src/contracts/cluster-service.ts#IPubSub (interface)",
223223
"IQueueService": "src/contracts/queue-service.ts#IQueueService (interface)",
224224
"IRealtimeService": "src/contracts/realtime-service.ts#IRealtimeService (interface)",
225+
"IReranker": "src/contracts/reranker.ts#IReranker (interface)",
225226
"IRlsMembershipResolver": "src/contracts/rls-membership-resolver.ts#IRlsMembershipResolver (interface)",
226227
"ISchemaDiffService": "src/contracts/schema-diff-service.ts#ISchemaDiffService (interface)",
227228
"ISchemaDriver": "src/contracts/schema-driver.ts#ISchemaDriver (interface)",
@@ -332,6 +333,7 @@
332333
"QueueMessage": "src/contracts/queue-service.ts#QueueMessage (interface)",
333334
"QueueMessageRecord": "src/contracts/queue-service.ts#QueueMessageRecord (interface)",
334335
"QueuePublishOptions": "src/contracts/queue-service.ts#QueuePublishOptions (interface)",
336+
"RERANKER_SERVICE": "src/contracts/reranker.ts#RERANKER_SERVICE (const)",
335337
"RESERVED_RLS_MEMBERSHIP_KEYS": "src/contracts/rls-membership-resolver.ts#RESERVED_RLS_MEMBERSHIP_KEYS (const)",
336338
"RESUME_AUTHORITY_SERVICE": "src/contracts/automation-service.ts#RESUME_AUTHORITY_SERVICE (const)",
337339
"RLS_MEMBERSHIP_RESOLVER_SERVICE": "src/contracts/rls-membership-resolver.ts#RLS_MEMBERSHIP_RESOLVER_SERVICE (const)",

‎packages/spec/src/contracts/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ export * from './attachment-doors-service.js';
7777
export * from './print-door-service.js';
7878
export * from './package-service.js';
7979
export * from './knowledge-service.js';
80+
export * from './reranker.js';
8081
export * from './knowledge-adapter.js';
8182
export * from './embedder.js';
8283

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
//
3+
// `IReranker` / `RERANKER_SERVICE`: the reranker contract the knowledge
4+
// service resolves per search. The card asks for a type-level pin of the
5+
// ruled shape: `IReranker { id; rerank(query, documents, opts?: { signal }) }`
6+
// returning an array of `{ index, score }`, and the `'reranker'` service token,
7+
// both reachable from the `contracts` barrel.
8+
//
9+
// Optionality is pinned with `{} extends Pick<…>` aliases, not `expectTypeOf`:
10+
// `toEqualTypeOf` cannot tell an optional member from a REQUIRED one typed
11+
// `T | undefined`. The aliases are exported so TS6196 does not flag them as
12+
// unused; `check:test-typecheck` compiles this file.
13+
14+
import { describe, it, expect } from 'vitest';
15+
import { RERANKER_SERVICE, type IReranker } from './reranker';
16+
import {
17+
RERANKER_SERVICE as RERANKER_SERVICE_FROM_BARREL,
18+
type IReranker as IRerankerFromBarrel,
19+
} from './index';
20+
21+
type Eq<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
22+
type Assert<T extends true> = T;
23+
24+
type Rerank = IReranker['rerank'];
25+
type RerankOpts = NonNullable<Parameters<Rerank>[2]>;
26+
27+
/** Exactly two members: `id` and `rerank` (no `model`, no preset list). */
28+
export type MembersAreIdAndRerank = Assert<Eq<keyof IReranker, 'id' | 'rerank'>>;
29+
30+
/** `id` is a readonly string, as `IEmbedder.id`. */
31+
export type IdIsAString = Assert<Eq<IReranker['id'], string>>;
32+
export type IdIsReadonly = Assert<Eq<Readonly<Pick<IReranker, 'id'>>, Pick<IReranker, 'id'>>>;
33+
34+
/** `rerank(query, documents, opts?)`: a string query, string documents. */
35+
export type RerankTakesQueryDocumentsOpts = Assert<
36+
Eq<Parameters<Rerank>, [query: string, documents: string[], opts?: { signal?: AbortSignal }]>
37+
>;
38+
39+
/** The options bag carries only the caller's `AbortSignal`. */
40+
export type OptsCarryOnlyASignal = Assert<Eq<RerankOpts, { signal?: AbortSignal }>>;
41+
42+
/** `opts` itself is optional: `rerank(query, documents)` is a valid call. */
43+
export type OptsAreOptional = Assert<[string, string[]] extends Parameters<Rerank> ? true : false>;
44+
45+
/** The answer: an array of `{ index, score }`, asynchronously. */
46+
export type RerankAnswersIndexAndScore = Assert<
47+
Eq<ReturnType<Rerank>, Promise<Array<{ index: number; score: number }>>>
48+
>;
49+
50+
/** The barrel (`@objectstack/spec/contracts`) exports this contract, not a look-alike. */
51+
export type BarrelExportsTheContract = Assert<Eq<IRerankerFromBarrel, IReranker>>;
52+
53+
/** The service token is the literal `'reranker'`. */
54+
export type TokenIsTheLiteral = Assert<Eq<typeof RERANKER_SERVICE, 'reranker'>>;
55+
56+
describe('IReranker contract', () => {
57+
it('registers under the `reranker` service token, exported from the contracts barrel', () => {
58+
expect(RERANKER_SERVICE).toBe('reranker');
59+
expect(RERANKER_SERVICE_FROM_BARREL).toBe(RERANKER_SERVICE);
60+
});
61+
62+
it('is satisfied by an implementation that answers index + score per document', async () => {
63+
const reranker: IReranker = {
64+
id: 'fixture',
65+
async rerank(_query, documents) {
66+
return documents.map((_, index) => ({ index, score: 1 / (index + 1) }));
67+
},
68+
};
69+
await expect(reranker.rerank('q', ['a', 'b'])).resolves.toEqual([
70+
{ index: 0, score: 1 },
71+
{ index: 1, score: 0.5 },
72+
]);
73+
});
74+
});
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* `IReranker` — protocol-level contract for providers that score a set of
5+
* passages against a query, so the knowledge service can re-order a search's
6+
* candidates.
7+
*
8+
* Mirrors `IEmbedder` (`./embedder.ts`): a deployment registers one
9+
* implementation under {@link RERANKER_SERVICE}, and the knowledge service
10+
* resolves it per search, as knowledge adapters resolve the embedder. The
11+
* reader lands with `retrieval.rerank` (#38750, row 2); until then nothing
12+
* resolves this service.
13+
*
14+
* Conventions:
15+
* - The model always comes from the deployment, never from a knowledge
16+
* source.
17+
* - The caller makes one call per search and sends at most 50 documents.
18+
* - The caller passes an `AbortSignal` (`opts.signal`) for its time limit.
19+
* - Each returned entry names one document by its position in the
20+
* `documents` input (`index`) and carries the score the reranker gave it.
21+
* - A higher `score` means the document matches the query better. The
22+
* caller ranks by `score`; the order of the returned array carries no
23+
* meaning.
24+
*/
25+
export interface IReranker {
26+
/** Stable id for logs and diagnostics. */
27+
readonly id: string;
28+
/**
29+
* Score `documents` against `query`. Each entry's `index` is the
30+
* document's position in `documents`; `score` is the reranker's score for
31+
* it. A higher `score` means the document matches the query better. The
32+
* caller ranks by `score`; the order of the returned array carries no
33+
* meaning.
34+
*/
35+
rerank(
36+
query: string,
37+
documents: string[],
38+
opts?: { signal?: AbortSignal },
39+
): Promise<Array<{ index: number; score: number }>>;
40+
}
41+
42+
/**
43+
* DI service token for the kernel-registered `IReranker` instance.
44+
*
45+
* The knowledge service is to resolve this service per search, the way
46+
* knowledge adapters resolve `EMBEDDER_SERVICE` (`./embedder.ts`); the
47+
* deployment configures the reranker once, and no knowledge source names one.
48+
* The reader lands with `retrieval.rerank` (#38750, row 2).
49+
*/
50+
export const RERANKER_SERVICE = 'reranker' as const;

0 commit comments

Comments
 (0)