index method

Future<WayfinderIndexResult> index(
  1. ProjectBundle bundle, {
  2. bool force = false,
  3. void onProgress(
    1. IndexProgress progress
    )?,
  4. WayfinderCancellation? cancel,
})

Creates or refreshes bundle's index. A current index returns without opening an encoder; force discards it and re-embeds every passage.

onProgress receives each IndexPhase as the run reaches it, and the embedding count before the first batch and after every batch. A run reports IndexPhase.loading before it opens the encoder, so loading a model is reported as loading. cancel is checked between steps and batches, last right after the IndexPhase.publishing event: a cancelled run writes nothing, leaves the current generation, and throws cancelled.

Searches keep reading the current generation while the run embeds, and read the new one once it is published.

Implementation

Future<WayfinderIndexResult> index(
  ProjectBundle bundle, {
  bool force = false,
  void Function(IndexProgress progress)? onProgress,
  WayfinderCancellation? cancel,
}) => _admit(() async {
  final index = await _namespace(bundle);
  final lock = await _lockWriter(index);
  try {
    await _collectExpired(index);
    return await _encoding((acquire) async {
      final watch = Stopwatch()..start();
      final root = index.root;
      final directory = index.directory;
      throwIfCancelled(cancel);
      onProgress?.call(const IndexProgress(IndexPhase.scanning));
      final files = await _inventory(root);
      final inventory = _inventoryHash(files);
      _Pinned? previous;
      try {
        previous = await _pin(index);
      } on WayfinderException {
        // Indexing replaces an incomplete or incompatible saved generation.
      }
      if (force) {
        previous = null;
      } else if (_assess(index, files, previous?.saved)
          case KnowledgeIndexCurrent(:final warnings)) {
        return WayfinderIndexResult(
          bundle: root,
          index: directory.path,
          embeddedChunks: 0,
          removedChunks: 0,
          writtenChunks: 0,
          elapsedMs: watch.elapsedMilliseconds,
          current: true,
          warnings: warnings,
        );
      }
      onProgress?.call(const IndexProgress(IndexPhase.loading));
      throwIfCancelled(cancel);
      final opened = await acquire();
      throwIfCancelled(cancel);
      final saved = previous?.saved;
      final compatible =
          saved != null &&
          saved.configuration == _configuration &&
          saved.model == _space &&
          saved.source == encoder.identity.source &&
          saved.snapshot.bundleId == root &&
          saved.dimension == opened.embedder.dimension;
      final fitted = compatible && saved.inventory == inventory
          ? saved.snapshot
          : await (await KnowledgeSnapshot.load(
              root,
              bundleId: root,
              idNamespace: _chunkIdNamespace,
              linkFields: wayfinderLinkFields,
            )).fitInputs(
              countTokens: opened.countTokens,
              maxTokens: opened.maxTokens,
              includeContext: true,
            );
      if (_inventoryHash(_savedFiles(fitted)) != inventory) {
        throw const WayfinderException(
          'bundle-changed',
          'Knowledge changed while loading.',
        );
      }
      throwIfCancelled(cancel);
      // The previous generation's passages and vectors, so only changed
      // inputs are embedded.
      final store = compatible ? await _memoryOf(previous!) : MemoryStore();
      final counts =
          await KnowledgeIndex(
            store: store,
            embedder: opened.embedder,
            includeContext: true,
          ).synchronize(
            fitted,
            onEmbedded: onProgress == null
                ? null
                : (embedded, total) => onProgress(
                    IndexProgress(
                      IndexPhase.embedding,
                      completed: embedded,
                      total: total,
                    ),
                  ),
            cancel: cancel,
          );
      if (_inventoryHash(await _inventory(root)) != inventory) {
        throw const WayfinderException(
          'bundle-changed',
          'Knowledge changed while indexing.',
        );
      }
      onProgress?.call(const IndexProgress(IndexPhase.publishing));
      throwIfCancelled(cancel);
      final rows = <List<double>>[];
      final inputs = <String>[];
      for (final chunk in fitted.chunks) {
        final vector = await store.getEmbedding(
          chunk.id,
          source: encoder.identity.source,
          modelName: _space,
        );
        final input =
            (store.chunks[chunk.id]?.metadata['okfEmbeddingInputs']
                as Map?)?[_space];
        if (vector == null || input is! String) {
          throw StateError('Indexing left a passage without its vector.');
        }
        rows.add(vector.vector);
        inputs.add(input);
      }
      final dimension = opened.embedder.dimension;
      final bytes = IndexGeneration.encode(rows, dimension);
      await directory.create(recursive: true);
      final staged = await _stageGeneration(directory);
      var published = false;
      try {
        await File(
          p.join(staged.path, IndexGeneration.vectorsFile),
        ).writeAsBytes(bytes, flush: true);
        final record = {
          'configuration': _configuration,
          'model': _space,
          'source': encoder.identity.source,
          'inventory': inventory,
          'vectors': {
            'file': IndexGeneration.vectorsFile,
            'format': IndexGeneration.format,
            'dimension': dimension,
            'count': rows.length,
            'sha256': IndexGeneration.digest(bytes),
            'inputs': inputs,
          },
          'snapshot': fitted.toMap(),
        };
        await File(
          p.join(staged.path, IndexGeneration.snapshotFile),
        ).writeAsString(jsonEncode(record), flush: true);
        await _publish(index, p.basename(staged.path));
        published = true;
        await _collectGarbage(index, keep: p.basename(staged.path));
        return WayfinderIndexResult(
          bundle: root,
          index: directory.path,
          warnings: fitted.diagnostics,
          embeddedChunks: counts.embeddedChunks,
          removedChunks: counts.removedChunks,
          writtenChunks: counts.writtenChunks,
          elapsedMs: watch.elapsedMilliseconds,
        );
      } finally {
        if (!published && await staged.exists()) {
          await staged.delete(recursive: true);
        }
      }
    });
  } finally {
    await lock.release();
  }
});