Skip to content

Commit 7480906

Browse files
yvonneyxbanxuan.zyxgemini-code-assist[bot]hustcc
authored
feat: 支持以只读模式打开已有 zvec (#12)
* feat: 支持以只读模式打开已有 zvec * Update test/storage/store.test.ts Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> * Update test/storage/store.test.ts Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> * feat: use readOnly option of zvec * chore: 0.1.1 --------- Co-authored-by: banxuan.zyx <banxuan.zyx@antgroup.com> Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> Co-authored-by: hustcc <i@hust.cc>
1 parent c792560 commit 7480906

7 files changed

Lines changed: 146 additions & 9 deletions

File tree

‎README.md‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ await ctx.close();
5757
| Parameter | Type | Default | Description |
5858
|-----------|------|---------|-------------|
5959
| `vectorsDir` | `string` | `.context/vectors` | Directory to store vector files |
60+
| `readOnly` | `boolean` | `false` | Open existing `.zvec` files only. In read-only mode, missing libraries are not created and `load()` writes throw. |
6061
| `basePath` | `string` | `process.cwd()` | Base path for resolving document IDs. Set for cross-machine consistent IDs. |
6162
| `onProgress` | `(phase, detail) => void` | — | Progress callback for `load()` phases: `'load'` → `'embed'` → `'insert'`. |
6263
| queryExpansion | QueryExpansionOptions | false | false | Query expansion with user-provided synonym map. false disables. Without synonyms, expansion is a no-op. |
@@ -98,6 +99,21 @@ const ctxNoExpand = await Context.create({
9899
});
99100
```
100101
102+
#### Read-only zvec Example
103+
104+
Use `readOnly: true` when `.zvec` files are prepared elsewhere and the current process should only query them:
105+
106+
```typescript
107+
const ctx = await Context.create({
108+
vectorsDir: '.context/vectors',
109+
readOnly: true,
110+
});
111+
112+
const results = await ctx.query('How to configure a line chart', { library: 'g2' });
113+
```
114+
115+
In read-only mode, `Context` opens existing `${library}.zvec` files with `ZVecOpen`. It does not create missing stores, and `load()` will throw because it would mutate the zvec file.
116+
101117
### `ctx.load(library, pattern)`
102118
103119
Load files into a specified library with automatic batch vectorization. Documents are embedded in batches and inserted into the vector store. A content-hash change detection mechanism re-embeds files whose content has changed since the last load.
@@ -219,4 +235,4 @@ await ctx.close();
219235
220236
## License
221237
222-
MIT
238+
MIT

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@antv/context",
3-
"version": "0.1.0",
3+
"version": "0.1.1",
44
"description": "A local context retrieval library that enables semantic search over your documentation. It loads documents (Markdown, JSON, Text), vectorizes them using [Transformers.js](https://huggingface.co/transformers.js), and stores vectors locally in `.zvec` files for fast semantic querying. ",
55
"main": "dist/index.js",
66
"types": "dist/index.d.ts",

‎src/context.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ export class Context {
3333
this.options = {
3434
basePath: process.cwd(),
3535
vectorsDir: '.context/vectors',
36+
readOnly: false,
3637
...options,
3738
};
3839
this.embedder = embedder;
@@ -164,4 +165,4 @@ export class Context {
164165
async close(): Promise<void> {
165166
this.store.close();
166167
}
167-
}
168+
}

‎src/storage/store.ts‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,16 @@ const FTS_FIELDS = ['content'];
2323
export class Store {
2424
private vectorsDir: string;
2525
private embedder: Embedder;
26-
private options?: ContextOptions;
26+
private options: ContextOptions;
2727
private zvecs: Map<string, ZVecCollection> = new Map();
2828

2929
constructor(vectorsDir: string, embedder: Embedder, options?: ContextOptions) {
3030
this.vectorsDir = vectorsDir;
3131
this.embedder = embedder;
32-
this.options = options;
32+
this.options = {
33+
readOnly: false,
34+
...options,
35+
};
3336
}
3437

3538
/** Get or create zvec instance. tokenizerName configures tokenizer on first creation. */
@@ -41,10 +44,10 @@ export class Store {
4144
let collection: ZVecCollection;
4245

4346
if (fs.existsSync(filePath)) {
44-
collection = ZVecOpen(filePath);
47+
collection = ZVecOpen(filePath, { readOnly: this.options.readOnly });
4548
} else {
4649
const schema = buildZvecSchema(this.embedder.dimensions, tokenizerName);
47-
collection = ZVecCreateAndOpen(filePath, schema);
50+
collection = ZVecCreateAndOpen(filePath, schema, { readOnly: this.options.readOnly });
4851
}
4952

5053
this.zvecs.set(library, collection);
@@ -166,4 +169,4 @@ export class Store {
166169
fields: r.fields ?? {},
167170
}));
168171
}
169-
}
172+
}

‎src/types.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,16 @@ export interface ContextOptions {
4848
* Defaults to `'.context/vectors'`.
4949
*/
5050
vectorsDir?: string;
51+
/**
52+
* Open existing vector files without creating or mutating zvec stores.
53+
*
54+
* When enabled, `query()` can read from existing `${library}.zvec` files,
55+
* while `load()` and any write path will throw. Missing zvec files are
56+
* reported as errors instead of being created.
57+
*
58+
* Defaults to `false`.
59+
*/
60+
readOnly?: boolean;
5161
/**
5262
* Base path for resolving document IDs.
5363
*

‎test/context.test.ts‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,4 +310,92 @@ describe('Context with weight configuration', () => {
310310

311311
await ctx.close();
312312
});
313+
});
314+
315+
describe('Context two-phase separation', () => {
316+
const twoPhaseDir = TEST_DIR + '-two-phase';
317+
const multiPhaseDir = TEST_DIR + '-multi-phase';
318+
319+
afterAll(() => {
320+
if (fs.existsSync(twoPhaseDir)) {
321+
fs.rmSync(twoPhaseDir, { recursive: true, force: true });
322+
}
323+
if (fs.existsSync(multiPhaseDir)) {
324+
fs.rmSync(multiPhaseDir, { recursive: true, force: true });
325+
}
326+
});
327+
328+
it('should load files in first phase and query in second phase with new instance', async () => {
329+
// Phase 1: Create Context and load files
330+
const ctxPhase1 = await Context.create({
331+
vectorsDir: twoPhaseDir,
332+
});
333+
334+
await ctxPhase1.load('two-phase-lib', path.join(FIXTURES_DIR, 'getting-started.md'));
335+
336+
// Query in phase 1 to verify data was loaded
337+
const phase1Results = await ctxPhase1.query('install', { library: 'two-phase-lib', topK: 3 });
338+
expect(phase1Results.length).toBeGreaterThan(0);
339+
const phase1Contents = phase1Results.map((r) => r.content).join(' ');
340+
expect(phase1Contents).toContain('npm');
341+
342+
// Close first phase context
343+
await ctxPhase1.close();
344+
345+
// Phase 2: Create new Context instance with the same vectorsDir
346+
const ctxPhase2 = await Context.create({
347+
vectorsDir: twoPhaseDir,
348+
});
349+
350+
// Query without calling load - should use the persisted vector files
351+
const phase2Results = await ctxPhase2.query('install', { library: 'two-phase-lib', topK: 3 });
352+
expect(phase2Results.length).toBeGreaterThan(0);
353+
const phase2Contents = phase2Results.map((r) => r.content).join(' ');
354+
expect(phase2Contents).toContain('npm');
355+
356+
// Verify the results are similar (same documents found)
357+
const phase1Ids = phase1Results.map((r) => r.id).sort();
358+
const phase2Ids = phase2Results.map((r) => r.id).sort();
359+
expect(phase1Ids).toEqual(phase2Ids);
360+
361+
await ctxPhase2.close();
362+
});
363+
364+
it('should handle multiple load phases in different instances', async () => {
365+
// Phase 1: Load first file
366+
const ctx1 = await Context.create({
367+
vectorsDir: multiPhaseDir,
368+
});
369+
await ctx1.load('multi-lib-1', path.join(FIXTURES_DIR, 'getting-started.md'));
370+
await ctx1.close();
371+
372+
// Phase 2: Load second file with same context
373+
const ctx2 = await Context.create({
374+
vectorsDir: multiPhaseDir,
375+
});
376+
await ctx2.load('multi-lib-2', path.join(FIXTURES_DIR, 'line-chart-guide.md'));
377+
378+
// Query both libraries
379+
const results1 = await ctx2.query('npm', { library: 'multi-lib-1', topK: 1 });
380+
const results2 = await ctx2.query('tooltip', { library: 'multi-lib-2', topK: 1 });
381+
382+
expect(results1.length).toBeGreaterThan(0);
383+
expect(results2.length).toBeGreaterThan(0);
384+
385+
await ctx2.close();
386+
387+
// Phase 3: New instance should still have both libraries
388+
const ctx3 = await Context.create({
389+
vectorsDir: multiPhaseDir,
390+
readOnly: true, // Open in read-only mode to ensure no writes
391+
});
392+
393+
const results1Again = await ctx3.query('install', { library: 'multi-lib-1', topK: 1 });
394+
const results2Again = await ctx3.query('chart', { library: 'multi-lib-2', topK: 1 });
395+
396+
expect(results1Again.length).toBeGreaterThan(0);
397+
expect(results2Again.length).toBeGreaterThan(0);
398+
399+
await ctx3.close();
400+
});
313401
});

‎test/storage/store.test.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,16 @@ describe('Store', () => {
4343
const zvec2 = store.acquireZvec('test-lib', 'jieba');
4444
expect(zvec1).toBe(zvec2);
4545
});
46+
47+
it('should not create missing zvec in read-only mode', () => {
48+
const readOnlyStore = new Store(path.join(__dirname, '.test-vectors-not-exist'), embedder, { readOnly: true });
49+
try {
50+
expect(() => readOnlyStore.acquireZvec('missing-lib', 'jieba')).toThrow(/read-only mode/);
51+
expect(fs.existsSync(path.join(__dirname, '.test-vectors-not-exist', 'missing-lib.zvec'))).toBe(false);
52+
} finally {
53+
readOnlyStore.close();
54+
}
55+
});
4656
});
4757

4858
describe('addDoc', () => {
@@ -60,6 +70,15 @@ describe('Store', () => {
6070
it('should not throw for empty docs array', () => {
6171
expect(() => store.addDoc('test-lib', [])).not.toThrow();
6272
});
73+
74+
it('should reject writes in read-only mode', () => {
75+
const readOnlyStore = new Store(testDir, embedder, { readOnly: true });
76+
try {
77+
expect(() => readOnlyStore.addDoc('test-lib', [])).toThrow(/read-only mode/);
78+
} finally {
79+
readOnlyStore.close();
80+
}
81+
});
6382
});
6483

6584
describe('fetchDocs', () => {
@@ -110,4 +129,4 @@ describe('Store', () => {
110129
expect(() => store.close()).not.toThrow();
111130
});
112131
});
113-
});
132+
});

0 commit comments

Comments
 (0)