@esankhan3/anvil-knowledge-core 0.3.6 → 0.3.8
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.
- package/dist/chunker.d.ts +2 -2
- package/dist/chunker.d.ts.map +1 -1
- package/dist/chunker.js +20 -4
- package/dist/chunker.js.map +1 -1
- package/dist/chunks-io.d.ts +9 -0
- package/dist/chunks-io.d.ts.map +1 -1
- package/dist/chunks-io.js +23 -0
- package/dist/chunks-io.js.map +1 -1
- package/dist/index-pool.d.ts +43 -0
- package/dist/index-pool.d.ts.map +1 -0
- package/dist/index-pool.js +145 -0
- package/dist/index-pool.js.map +1 -0
- package/dist/index-worker.d.ts +8 -0
- package/dist/index-worker.d.ts.map +1 -0
- package/dist/index-worker.js +21 -0
- package/dist/index-worker.js.map +1 -0
- package/dist/indexer.d.ts.map +1 -1
- package/dist/indexer.js +205 -179
- package/dist/indexer.js.map +1 -1
- package/dist/project-graph-builder-core.d.ts.map +1 -1
- package/dist/project-graph-builder-core.js +11 -0
- package/dist/project-graph-builder-core.js.map +1 -1
- package/dist/repo-pipeline.d.ts +51 -0
- package/dist/repo-pipeline.d.ts.map +1 -0
- package/dist/repo-pipeline.js +114 -0
- package/dist/repo-pipeline.js.map +1 -0
- package/dist/retriever.d.ts.map +1 -1
- package/dist/retriever.js +25 -7
- package/dist/retriever.js.map +1 -1
- package/dist/vector-store.d.ts +1 -1
- package/dist/vector-store.d.ts.map +1 -1
- package/dist/vector-store.js +7 -5
- package/dist/vector-store.js.map +1 -1
- package/package.json +1 -1
package/dist/indexer.js
CHANGED
|
@@ -1,46 +1,63 @@
|
|
|
1
|
-
import { existsSync, readFileSync, mkdirSync, writeFileSync, readdirSync, statSync } from 'node:fs';
|
|
2
|
-
import { execSync } from 'node:child_process';
|
|
1
|
+
import { existsSync, readFileSync, mkdirSync, writeFileSync, readdirSync, statSync, rmSync } from 'node:fs';
|
|
3
2
|
import { join, basename } from 'node:path';
|
|
4
|
-
import { chunkRepo, chunkChangedFiles } from '@esankhan3/anvil-knowledge-core';
|
|
5
|
-
import { buildAstGraph, generateGraphReport, incrementalGraphUpdate } from '@esankhan3/anvil-knowledge-core';
|
|
6
|
-
import { getAllChanges, getChangedFilesList, getDeletedFilesList } from '@esankhan3/anvil-knowledge-core';
|
|
7
3
|
import { createEmbeddingProvider } from '@esankhan3/anvil-knowledge-core';
|
|
8
4
|
import { VectorStore } from '@esankhan3/anvil-knowledge-core';
|
|
9
5
|
import { ProjectGraphBuilder } from '@esankhan3/anvil-knowledge-core';
|
|
10
6
|
import { detectCrossRepoEdges } from '@esankhan3/anvil-knowledge-core';
|
|
11
|
-
import { detectWorkspace } from '@esankhan3/anvil-knowledge-core';
|
|
12
7
|
import { HybridRetriever } from './retriever.js';
|
|
13
8
|
import { loadKnowledgeConfig, getKnowledgeBasePath } from '@esankhan3/anvil-knowledge-core';
|
|
14
9
|
import { profileProject, loadAllProfiles } from '@esankhan3/anvil-knowledge-core';
|
|
15
10
|
import { inferServiceMesh } from '@esankhan3/anvil-knowledge-core';
|
|
16
|
-
import {
|
|
11
|
+
import { computeStructuralHash } from '@esankhan3/anvil-knowledge-core';
|
|
17
12
|
import { createQueryRouter } from '@esankhan3/anvil-knowledge-core';
|
|
18
|
-
import {
|
|
13
|
+
import { createChunkWriter, iterateChunksFile } from './chunks-io.js';
|
|
19
14
|
import { writeSystemGraphSqlite } from './graph-store.js';
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
}
|
|
28
|
-
function readRepoIndexMeta(basePath, repoName) {
|
|
29
|
-
const metaPath = join(basePath, repoName, 'index_meta.json');
|
|
30
|
-
if (!existsSync(metaPath))
|
|
31
|
-
return null;
|
|
32
|
-
try {
|
|
33
|
-
return JSON.parse(readFileSync(metaPath, 'utf-8'));
|
|
34
|
-
}
|
|
35
|
-
catch {
|
|
36
|
-
return null;
|
|
37
|
-
}
|
|
38
|
-
}
|
|
15
|
+
import { resolveIndexConcurrency, runReposPooled } from './index-pool.js';
|
|
16
|
+
import { processRepoPipeline, getRepoSha, readRepoIndexMeta } from './repo-pipeline.js';
|
|
17
|
+
// ---------------------------------------------------------------------------
|
|
18
|
+
// SHA-based staleness detection
|
|
19
|
+
// ---------------------------------------------------------------------------
|
|
20
|
+
// RepoIndexMeta, getRepoSha, readRepoIndexMeta moved to repo-pipeline.ts (shared
|
|
21
|
+
// with the worker). writeRepoIndexMeta stays here — only buildKB writes meta.
|
|
39
22
|
function writeRepoIndexMeta(basePath, repoName, meta) {
|
|
40
23
|
const dir = join(basePath, repoName);
|
|
41
24
|
mkdirSync(dir, { recursive: true });
|
|
42
25
|
writeFileSync(join(dir, 'index_meta.json'), JSON.stringify(meta, null, 2), 'utf-8');
|
|
43
26
|
}
|
|
27
|
+
/**
|
|
28
|
+
* Structural dedup, streaming: read each per-repo shard line-by-line, keep the
|
|
29
|
+
* first chunk per structural hash, write survivors to chunks.json. Bounded
|
|
30
|
+
* memory — a Set of hashes + one chunk at a time, never the whole corpus (this
|
|
31
|
+
* replaces the in-RAM deduplicateByStructure(allChunks) that OOM'd at org scale).
|
|
32
|
+
* Keeps first-seen per hash (repo order) rather than smallest-id, but the
|
|
33
|
+
* survivors are structurally identical, so dedup is functionally equivalent.
|
|
34
|
+
*/
|
|
35
|
+
async function dedupShardsToChunks(shardPaths, chunksPath) {
|
|
36
|
+
const seen = new Set();
|
|
37
|
+
const writer = createChunkWriter(chunksPath);
|
|
38
|
+
let kept = 0, dropped = 0, tokens = 0;
|
|
39
|
+
try {
|
|
40
|
+
for (const sp of shardPaths) {
|
|
41
|
+
if (!existsSync(sp))
|
|
42
|
+
continue;
|
|
43
|
+
for await (const c of iterateChunksFile(sp)) {
|
|
44
|
+
const h = computeStructuralHash(c.content, c.language).hash;
|
|
45
|
+
if (seen.has(h)) {
|
|
46
|
+
dropped++;
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
seen.add(h);
|
|
50
|
+
writer.write(c);
|
|
51
|
+
kept++;
|
|
52
|
+
tokens += c.tokens;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
finally {
|
|
57
|
+
writer.close();
|
|
58
|
+
}
|
|
59
|
+
return { kept, dropped, tokens };
|
|
60
|
+
}
|
|
44
61
|
export class KnowledgeIndexer {
|
|
45
62
|
// ---------------------------------------------------------------------------
|
|
46
63
|
// BUILD KB — fast, static, no embedding. Profiles + chunks + graphs + edges.
|
|
@@ -102,101 +119,81 @@ export class KnowledgeIndexer {
|
|
|
102
119
|
// 3. Chunk repos — use git diff for incremental detection
|
|
103
120
|
report({ phase: 'chunking', message: `Chunking ${reposToIndex.length} repos...`, percent: 10, etaSeconds: -1, reposTotal: repos.length, reposProcessed: skippedRepos.length, skippedRepos });
|
|
104
121
|
log(`Chunking ${reposToIndex.length} repos (${skippedRepos.length} skipped — unchanged)...`);
|
|
105
|
-
|
|
122
|
+
// Process each repo (chunk + AST graph + workspace) through a persistent
|
|
123
|
+
// worker pool across cores — the CPU-bound bottleneck. Each repo streams its
|
|
124
|
+
// chunks to a per-repo shard on disk and returns only its (small) graph +
|
|
125
|
+
// metadata, so the main thread never accumulates the whole corpus (bounded
|
|
126
|
+
// memory). Concurrency is adaptive; a worker failure falls back to in-thread.
|
|
106
127
|
const repoStats = [];
|
|
107
128
|
const repoChunkResults = new Map();
|
|
108
|
-
const
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
129
|
+
const workspaceMaps = new Map();
|
|
130
|
+
const shardPaths = [];
|
|
131
|
+
const graphBuilder = new ProjectGraphBuilder();
|
|
132
|
+
await graphBuilder.init();
|
|
133
|
+
const toIndex = new Set(reposToIndex.map((r) => r.name));
|
|
134
|
+
const jobs = repos.map((r) => ({
|
|
135
|
+
repoName: r.name,
|
|
136
|
+
repoPath: r.path,
|
|
137
|
+
language: r.language,
|
|
138
|
+
basePath,
|
|
139
|
+
project,
|
|
140
|
+
chunking: config.chunking,
|
|
141
|
+
doChunk: toIndex.has(r.name),
|
|
142
|
+
force: !!opts?.force,
|
|
143
|
+
}));
|
|
144
|
+
const concurrency = resolveIndexConcurrency(jobs.length);
|
|
145
|
+
const workerUrl = concurrency > 1 ? new URL('./index-worker.js', import.meta.url) : null;
|
|
146
|
+
log(`Processing ${jobs.length} repos (chunk + AST) — concurrency ${concurrency}${workerUrl ? ' (workers)' : ' (in-thread)'}, ${skippedRepos.length} skipped`);
|
|
147
|
+
report({ phase: 'chunking', message: `Chunking + graphing ${jobs.length} repos (×${concurrency})...`, percent: 15, etaSeconds: -1, reposTotal: repos.length, reposProcessed: 0, skippedRepos });
|
|
148
|
+
let processed = 0;
|
|
149
|
+
await runReposPooled(jobs, {
|
|
150
|
+
concurrency,
|
|
151
|
+
workerUrl,
|
|
152
|
+
log,
|
|
153
|
+
inThread: (job) => processRepoPipeline(job),
|
|
154
|
+
toMessage: (job) => job,
|
|
155
|
+
onResult: (res) => {
|
|
156
|
+
if (res.graph) {
|
|
157
|
+
try {
|
|
158
|
+
graphBuilder.addRepoGraph(res.repoName, res.graph);
|
|
159
|
+
}
|
|
160
|
+
catch (e) {
|
|
161
|
+
log(`Warning: addRepoGraph failed for ${res.repoName}: ${e}`);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
if (res.workspaceMap && res.workspaceMap.packages.length > 0)
|
|
165
|
+
workspaceMaps.set(res.repoName, res.workspaceMap);
|
|
166
|
+
repoStats.push({ name: res.repoName, chunkCount: res.chunkCount, language: res.language });
|
|
167
|
+
if (res.chunked) {
|
|
168
|
+
repoChunkResults.set(res.repoName, { changedFiles: res.changedFiles, deletedFiles: res.deletedFiles, fileIndex: res.fileIndex ?? {} });
|
|
169
|
+
if (res.shardPath)
|
|
170
|
+
shardPaths.push(res.shardPath);
|
|
171
|
+
}
|
|
172
|
+
processed++;
|
|
173
|
+
if (processed % 10 === 0 || processed === jobs.length) {
|
|
174
|
+
report({ phase: 'graphing', message: `Processed ${processed}/${jobs.length} repos`, percent: Math.round(15 + (processed / jobs.length) * 50), etaSeconds: -1 });
|
|
175
|
+
}
|
|
176
|
+
},
|
|
177
|
+
});
|
|
131
178
|
for (const name of skippedRepos) {
|
|
132
179
|
const meta = readRepoIndexMeta(basePath, name);
|
|
133
180
|
repoStats.push({ name, chunkCount: meta?.chunkCount ?? 0, language: '' });
|
|
134
181
|
}
|
|
135
|
-
|
|
136
|
-
//
|
|
137
|
-
report({ phase: 'dedup', message: 'Deduplicating chunks
|
|
138
|
-
const dedupResult = deduplicateByStructure(allChunks);
|
|
139
|
-
const uniqueChunks = dedupResult.unique;
|
|
140
|
-
if (dedupResult.savings.chunks > 0) {
|
|
141
|
-
log(`Structural dedup: ${dedupResult.savings.chunks} duplicates removed`);
|
|
142
|
-
}
|
|
143
|
-
// Persist chunks NOW — BEFORE building the graph — and free the in-memory
|
|
144
|
-
// chunk arrays. Otherwise ~810k chunk objects (content + contextualized
|
|
145
|
-
// source, multi-GB) stay resident alongside the ~900k-node graphology graph
|
|
146
|
-
// (also multi-GB); their SUM OOMs even a 16GB heap. Writing + freeing here
|
|
147
|
-
// makes the chunk and graph phases sequential — peak ≈ max(chunks, graph),
|
|
148
|
-
// not their sum.
|
|
182
|
+
// Structural dedup — streaming over the per-repo shards into chunks.json
|
|
183
|
+
// (bounded memory; replaces the in-RAM dedup that OOM'd at org scale).
|
|
184
|
+
report({ phase: 'dedup', message: 'Deduplicating chunks (streaming)...', percent: 68, etaSeconds: -1 });
|
|
149
185
|
const chunksPath = join(basePath, 'chunks.json');
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
const
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
// 5. Detect workspace structures
|
|
158
|
-
const workspaceMaps = new Map();
|
|
159
|
-
for (const repo of repos) {
|
|
186
|
+
const dedup = await dedupShardsToChunks(shardPaths, chunksPath);
|
|
187
|
+
const dedupedChunkCount = dedup.kept;
|
|
188
|
+
const dedupedTokenSum = dedup.tokens;
|
|
189
|
+
if (dedup.dropped > 0)
|
|
190
|
+
log(`Structural dedup: ${dedup.dropped} duplicates removed`);
|
|
191
|
+
log(`Saved ${dedupedChunkCount} chunks to ${chunksPath}`);
|
|
192
|
+
for (const sp of shardPaths) {
|
|
160
193
|
try {
|
|
161
|
-
|
|
162
|
-
if (wsMap.packages.length > 0) {
|
|
163
|
-
workspaceMaps.set(repo.name, wsMap);
|
|
164
|
-
log(`Detected workspace in ${repo.name}: ${wsMap.packages.length} packages`);
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
catch (err) {
|
|
168
|
-
log(`Warning: Workspace detection failed for ${repo.name}: ${err}`);
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
// 6. Build AST graphs — incremental when possible via git diff
|
|
172
|
-
report({ phase: 'graphing', message: 'Building AST graphs...', percent: 40, etaSeconds: -1 });
|
|
173
|
-
const graphBuilder = new ProjectGraphBuilder();
|
|
174
|
-
await graphBuilder.init();
|
|
175
|
-
for (const repo of repos) {
|
|
176
|
-
try {
|
|
177
|
-
const repoKbDir = join(basePath, repo.name);
|
|
178
|
-
mkdirSync(repoKbDir, { recursive: true });
|
|
179
|
-
const existingGraphPath = join(repoKbDir, 'graph.json');
|
|
180
|
-
const diff = repoDiffs.get(repo.name);
|
|
181
|
-
let graph;
|
|
182
|
-
if (diff && !diff.fallbackToFull && existsSync(existingGraphPath)) {
|
|
183
|
-
// Incremental graph update — only re-parse changed files
|
|
184
|
-
const existingGraph = JSON.parse(readFileSync(existingGraphPath, 'utf-8'));
|
|
185
|
-
graph = await incrementalGraphUpdate(existingGraph, getChangedFilesList(diff), getDeletedFilesList(diff), repo.path, { workspaceMap: workspaceMaps.get(repo.name) });
|
|
186
|
-
log(`Updated AST graph for ${repo.name} incrementally (${diff.added.length + diff.modified.length} files changed)`);
|
|
187
|
-
}
|
|
188
|
-
else {
|
|
189
|
-
// Full rebuild
|
|
190
|
-
graph = await buildAstGraph(repo.path, { workspaceMap: workspaceMaps.get(repo.name) });
|
|
191
|
-
log(`Built AST graph for ${repo.name} (${graph.nodes.length} nodes, ${graph.links.length} edges)`);
|
|
192
|
-
}
|
|
193
|
-
graphBuilder.addRepoGraph(repo.name, graph);
|
|
194
|
-
writeFileSync(join(repoKbDir, 'graph.json'), JSON.stringify(graph));
|
|
195
|
-
writeFileSync(join(repoKbDir, 'GRAPH_REPORT.md'), generateGraphReport(repo.name, graph));
|
|
196
|
-
}
|
|
197
|
-
catch (err) {
|
|
198
|
-
log(`Warning: AST graph build failed for ${repo.name}: ${err}`);
|
|
194
|
+
rmSync(sp, { force: true });
|
|
199
195
|
}
|
|
196
|
+
catch { /* ok */ }
|
|
200
197
|
}
|
|
201
198
|
// 7. Detect cross-repo edges (14 strategies)
|
|
202
199
|
report({ phase: 'graphing', message: 'Detecting cross-repo edges...', percent: 70, etaSeconds: -1 });
|
|
@@ -320,34 +317,50 @@ export class KnowledgeIndexer {
|
|
|
320
317
|
const report = opts?.onDetailedProgress ?? (() => { });
|
|
321
318
|
const startTime = Date.now();
|
|
322
319
|
const basePath = getKnowledgeBasePath(project);
|
|
323
|
-
// Load chunks from disk (only new/changed chunks from buildKB)
|
|
324
320
|
const chunksPath = join(basePath, 'chunks.json');
|
|
325
321
|
if (!existsSync(chunksPath)) {
|
|
326
322
|
throw new Error(`No chunks found — run Build KB first. Expected: ${chunksPath}`);
|
|
327
323
|
}
|
|
328
|
-
const chunks = await readChunksFile(chunksPath);
|
|
329
|
-
log(`Loaded ${chunks.length} chunks from ${chunksPath}`);
|
|
330
324
|
// Open vector store. healCorrupt: this is the write/rebuild path, so if a
|
|
331
325
|
// prior run left the table corrupt (killed mid-write → 0-byte fragment),
|
|
332
326
|
// drop it and rebuild from chunks.json rather than failing every reindex.
|
|
333
327
|
const dbPath = join(basePath, 'lancedb');
|
|
334
328
|
const vectorStore = new VectorStore(dbPath);
|
|
335
329
|
await vectorStore.init({ healCorrupt: true });
|
|
336
|
-
//
|
|
330
|
+
// Which chunks are already embedded (id-set diff). Bounded: holds only the
|
|
331
|
+
// id strings, never the chunk bodies.
|
|
337
332
|
const existingIds = new Set();
|
|
338
333
|
try {
|
|
339
334
|
const stats = await vectorStore.getStats();
|
|
340
335
|
if (stats && stats.rowCount > 0) {
|
|
341
|
-
// Load existing chunk IDs from the store
|
|
342
336
|
const existingChunks = await vectorStore.getChunkIds(project);
|
|
343
337
|
for (const id of existingChunks)
|
|
344
338
|
existingIds.add(id);
|
|
345
339
|
}
|
|
346
340
|
}
|
|
347
341
|
catch { /* first run — no existing data */ }
|
|
348
|
-
const newChunks = chunks.filter((c) => !existingIds.has(c.id));
|
|
349
342
|
const deletedFiles = this.getDeletedFiles(basePath);
|
|
350
|
-
|
|
343
|
+
// Pass 1 — stream chunks.json to tally totals + how many need embedding,
|
|
344
|
+
// WITHOUT ever holding all chunks in memory. At org scale (~810k chunks,
|
|
345
|
+
// each carrying full source + contextualized text) the old
|
|
346
|
+
// `readChunksFile()` array was multi-GB and OOM'd the embed step (the
|
|
347
|
+
// crash surfaced during "Removing stale chunks", but the array — loaded
|
|
348
|
+
// here, before deletion — was the resident hog). Streaming bounds memory
|
|
349
|
+
// to the id-set + one in-flight batch (see pass 2 below).
|
|
350
|
+
let totalChunks = 0;
|
|
351
|
+
let totalTokens = 0;
|
|
352
|
+
let newChunkCount = 0;
|
|
353
|
+
const repoChunkCounts = new Map();
|
|
354
|
+
for await (const c of iterateChunksFile(chunksPath)) {
|
|
355
|
+
totalChunks++;
|
|
356
|
+
totalTokens += c.tokens;
|
|
357
|
+
repoChunkCounts.set(c.repoName, (repoChunkCounts.get(c.repoName) ?? 0) + 1);
|
|
358
|
+
if (!existingIds.has(c.id))
|
|
359
|
+
newChunkCount++;
|
|
360
|
+
}
|
|
361
|
+
log(`Loaded ${totalChunks} chunks from ${chunksPath}`);
|
|
362
|
+
const repoNames = [...repoChunkCounts.keys()];
|
|
363
|
+
if (newChunkCount === 0 && deletedFiles.length === 0) {
|
|
351
364
|
// All vectors already present, so DON'T re-embed. But still (re)build the
|
|
352
365
|
// full-text (BM25) index over the existing rows: a prior run that wrote
|
|
353
366
|
// vectors then aborted before the post-loop FTS build (e.g. killed/aborted
|
|
@@ -356,12 +369,11 @@ export class KnowledgeIndexer {
|
|
|
356
369
|
log('All chunks already embedded — ensuring full-text index is built (no re-embed).');
|
|
357
370
|
await vectorStore.ensureFtsIndex();
|
|
358
371
|
report({ phase: 'done', message: 'All chunks already embedded', percent: 100, etaSeconds: 0 });
|
|
359
|
-
const repoNames = [...new Set(chunks.map((c) => c.repoName))];
|
|
360
372
|
return {
|
|
361
373
|
project,
|
|
362
|
-
repos: repoNames.map((n) => ({ name: n, chunkCount:
|
|
363
|
-
totalChunks
|
|
364
|
-
totalTokens
|
|
374
|
+
repos: repoNames.map((n) => ({ name: n, chunkCount: repoChunkCounts.get(n) ?? 0, language: '' })),
|
|
375
|
+
totalChunks,
|
|
376
|
+
totalTokens,
|
|
365
377
|
embeddingProvider: 'cached',
|
|
366
378
|
embeddingDimensions: 0,
|
|
367
379
|
crossRepoEdges: 0,
|
|
@@ -399,80 +411,94 @@ export class KnowledgeIndexer {
|
|
|
399
411
|
};
|
|
400
412
|
const batchSize = envInt('CODE_SEARCH_EMBEDDING_BATCH_SIZE', isOllama ? 10 : 128);
|
|
401
413
|
const concurrency = isOllama ? 1 : envInt('CODE_SEARCH_EMBEDDING_CONCURRENCY', 8);
|
|
402
|
-
log(`Embedding ${
|
|
403
|
-
//
|
|
404
|
-
//
|
|
405
|
-
//
|
|
406
|
-
//
|
|
407
|
-
//
|
|
408
|
-
//
|
|
409
|
-
//
|
|
410
|
-
//
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
414
|
+
log(`Embedding ${newChunkCount} new chunks with ${embedder.name} (${totalChunks - newChunkCount} cached, batch ${batchSize} × concurrency ${concurrency})...`);
|
|
415
|
+
// Stream chunks.json a second time and embed only the new ones, in batches.
|
|
416
|
+
// Up to `concurrency` batches are in flight at once; each is written to
|
|
417
|
+
// LanceDB the instant its embeddings return (writes serialized via
|
|
418
|
+
// writeChain — LanceDB's add must not run concurrently on one table).
|
|
419
|
+
// Crucially we NEVER materialize the full chunk set nor a pre-sliced
|
|
420
|
+
// `batches[][]`: the producer reads one chunk at a time, fills a batch,
|
|
421
|
+
// dispatches it, then blocks until an in-flight slot frees. Memory stays
|
|
422
|
+
// bounded to the id-set + ~concurrency batches regardless of corpus size.
|
|
423
|
+
// The run stays resumable: new chunks are diffed against ids already in the
|
|
424
|
+
// store, so a crash loses only the few in-flight batches and a re-run
|
|
425
|
+
// continues from there. FTS is built once after the loop (skipIndex defers
|
|
426
|
+
// the per-batch rebuild).
|
|
427
|
+
const totalBatches = Math.max(1, Math.ceil(newChunkCount / batchSize));
|
|
415
428
|
let batchesDone = 0;
|
|
416
429
|
let stored = 0;
|
|
417
|
-
let cursor = 0;
|
|
418
430
|
const embedStartTime = Date.now();
|
|
419
431
|
let writeChain = Promise.resolve();
|
|
420
|
-
// When any
|
|
421
|
-
// after all
|
|
422
|
-
// while its siblings keep embedding + mutating progress in the
|
|
423
|
-
// ("zombie" workers), so the run reads as failed yet the count
|
|
432
|
+
// When any batch fails, signal the producer + siblings to stop and surface
|
|
433
|
+
// the error after all in-flight batches settle — otherwise a failed batch
|
|
434
|
+
// rejects while its siblings keep embedding + mutating progress in the
|
|
435
|
+
// background ("zombie" workers), so the run reads as failed yet the count
|
|
436
|
+
// keeps rising.
|
|
424
437
|
let aborted = null;
|
|
425
|
-
const
|
|
426
|
-
|
|
438
|
+
const inFlight = new Set();
|
|
439
|
+
const dispatch = (batchChunks) => {
|
|
440
|
+
const task = (async () => {
|
|
427
441
|
if (aborted)
|
|
428
442
|
return;
|
|
429
|
-
const idx = cursor++;
|
|
430
|
-
if (idx >= totalBatches)
|
|
431
|
-
return;
|
|
432
|
-
const batchChunks = batches[idx];
|
|
433
|
-
let batchRows;
|
|
434
443
|
try {
|
|
435
444
|
const batchEmbeddings = await embedder.embed(batchChunks.map((c) => c.contextualizedContent));
|
|
436
|
-
batchRows = batchChunks.map((chunk, j) => ({ ...chunk, embedding: batchEmbeddings[j] }));
|
|
445
|
+
const batchRows = batchChunks.map((chunk, j) => ({ ...chunk, embedding: batchEmbeddings[j] }));
|
|
437
446
|
// Serialize the LanceDB write by chaining onto the previous one, and
|
|
438
447
|
// await only the promise we just appended.
|
|
439
448
|
const myWrite = (writeChain = writeChain.then(() => vectorStore.addChunks(batchRows, { skipIndex: true })));
|
|
440
449
|
await myWrite;
|
|
450
|
+
if (aborted)
|
|
451
|
+
return;
|
|
452
|
+
stored += batchRows.length;
|
|
453
|
+
batchesDone++;
|
|
454
|
+
const elapsed = Date.now() - embedStartTime;
|
|
455
|
+
const msPerBatch = elapsed / batchesDone;
|
|
456
|
+
const etaSeconds = Math.ceil((msPerBatch * (totalBatches - batchesDone)) / 1000);
|
|
457
|
+
const percent = Math.round(5 + (batchesDone / totalBatches) * 85);
|
|
458
|
+
report({
|
|
459
|
+
phase: 'embedding',
|
|
460
|
+
message: `Embedding: ${stored}/${newChunkCount} new (~${etaSeconds}s remaining)`,
|
|
461
|
+
percent, etaSeconds,
|
|
462
|
+
chunksTotal: newChunkCount, chunksProcessed: stored,
|
|
463
|
+
});
|
|
464
|
+
if (batchesDone % 10 === 0 || batchesDone === totalBatches) {
|
|
465
|
+
log(` Embedded ${stored}/${newChunkCount} (ETA: ${formatEta(etaSeconds)})`);
|
|
466
|
+
}
|
|
441
467
|
}
|
|
442
468
|
catch (err) {
|
|
443
|
-
aborted = err; // stop siblings; rethrown after
|
|
444
|
-
return;
|
|
469
|
+
aborted = err; // stop producer + siblings; rethrown after all settle
|
|
445
470
|
}
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
batchesDone++;
|
|
450
|
-
const elapsed = Date.now() - embedStartTime;
|
|
451
|
-
const msPerBatch = elapsed / batchesDone;
|
|
452
|
-
const etaSeconds = Math.ceil((msPerBatch * (totalBatches - batchesDone)) / 1000);
|
|
453
|
-
const percent = Math.round(5 + (batchesDone / totalBatches) * 85);
|
|
454
|
-
report({
|
|
455
|
-
phase: 'embedding',
|
|
456
|
-
message: `Embedding: ${stored}/${newChunks.length} new (~${etaSeconds}s remaining)`,
|
|
457
|
-
percent, etaSeconds,
|
|
458
|
-
chunksTotal: newChunks.length, chunksProcessed: stored,
|
|
459
|
-
});
|
|
460
|
-
if (batchesDone % 10 === 0 || batchesDone === totalBatches) {
|
|
461
|
-
log(` Embedded ${stored}/${newChunks.length} (ETA: ${formatEta(etaSeconds)})`);
|
|
462
|
-
}
|
|
463
|
-
}
|
|
471
|
+
})();
|
|
472
|
+
inFlight.add(task);
|
|
473
|
+
void task.finally(() => inFlight.delete(task));
|
|
464
474
|
};
|
|
465
|
-
|
|
475
|
+
let batch = [];
|
|
476
|
+
for await (const c of iterateChunksFile(chunksPath)) {
|
|
477
|
+
if (aborted)
|
|
478
|
+
break;
|
|
479
|
+
if (existingIds.has(c.id))
|
|
480
|
+
continue;
|
|
481
|
+
batch.push(c);
|
|
482
|
+
if (batch.length >= batchSize) {
|
|
483
|
+
dispatch(batch);
|
|
484
|
+
batch = [];
|
|
485
|
+
// Back-pressure: never let more than `concurrency` batches be resident.
|
|
486
|
+
while (inFlight.size >= concurrency && !aborted)
|
|
487
|
+
await Promise.race(inFlight);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
if (batch.length > 0 && !aborted)
|
|
491
|
+
dispatch(batch);
|
|
492
|
+
await Promise.all(inFlight);
|
|
466
493
|
if (aborted)
|
|
467
494
|
throw aborted; // no zombies left running; fail the run cleanly
|
|
468
495
|
// Build the full-text index once, after all batches are inserted.
|
|
469
496
|
report({ phase: 'storing', message: 'Building full-text index...', percent: 92, etaSeconds: -1 });
|
|
470
|
-
if (
|
|
497
|
+
if (newChunkCount > 0) {
|
|
471
498
|
await vectorStore.ensureFtsIndex();
|
|
472
499
|
}
|
|
473
|
-
log(`Stored ${
|
|
474
|
-
// Update metadata
|
|
475
|
-
const repoNames = [...new Set(chunks.map((c) => c.repoName))];
|
|
500
|
+
log(`Stored ${newChunkCount} new chunks in LanceDB (${deletedFiles.length} removed)`);
|
|
501
|
+
// Update metadata (repoNames was computed during pass 1).
|
|
476
502
|
for (const repoName of repoNames) {
|
|
477
503
|
const metaPath = join(basePath, repoName, 'index_meta.json');
|
|
478
504
|
if (existsSync(metaPath)) {
|
|
@@ -486,12 +512,12 @@ export class KnowledgeIndexer {
|
|
|
486
512
|
}
|
|
487
513
|
}
|
|
488
514
|
const durationMs = Date.now() - startTime;
|
|
489
|
-
report({ phase: 'done', message: `Embedded ${
|
|
515
|
+
report({ phase: 'done', message: `Embedded ${newChunkCount} new chunks (${deletedFiles.length} removed) in ${formatEta(Math.ceil(durationMs / 1000))}`, percent: 100, etaSeconds: 0 });
|
|
490
516
|
return {
|
|
491
517
|
project,
|
|
492
|
-
repos: repoNames.map((n) => ({ name: n, chunkCount:
|
|
493
|
-
totalChunks
|
|
494
|
-
totalTokens
|
|
518
|
+
repos: repoNames.map((n) => ({ name: n, chunkCount: repoChunkCounts.get(n) ?? 0, language: '' })),
|
|
519
|
+
totalChunks,
|
|
520
|
+
totalTokens,
|
|
495
521
|
embeddingProvider: embedder.name,
|
|
496
522
|
embeddingDimensions: embedder.dimensions,
|
|
497
523
|
crossRepoEdges: 0,
|