Skip to content

Indexing and integration API

For a complete, runnable workflow and its delivery guarantees, see the indexing guide. Imports below are from omnichunk unless a module is specified. Method signatures and defaults are generated from source.

Local chunk store

ChunkStore(path, collection="default") opens a SQLite file at path; use a context manager or call close(). collection names the logical chunk collection. query(filepath) returns stored chunks for that path. index(root, ...) reprocesses matching files; sync(root, ...) skips unchanged files and configurations. Both return SyncResult. root is the directory to scan; glob (default "**/*") selects files, exclude is a sequence of exclusion patterns, include_hidden defaults to False, and encoding defaults to "utf-8". Supply either a configured chunker or chunker keyword options for processing; passing both raises ValueError. A successful scan may remove missing files within its previously owned scope; consult the guide before changing filters.

SyncResult exposes files_scanned, files_skipped, files_updated and files_deleted counts, removed_chunk_ids for downstream deletions, and diffs keyed by filepath. Delete the removed IDs before upserting each diff's added chunks; refresh locations for unchanged chunks when needed. Migration requires separate source and nonexistent destination paths, with an optional collection name. Its MigrationResult reports file/chunk counts, id_map and whether reindexing is required.

omnichunk.store.ChunkStore

SQLite-backed named collection of chunked documents.

Directory deletion is limited to a previously completed scan with the same resolved root, glob, exclusions and hidden-file policy. A partial file scan or a new filter never deletes siblings. Collections are independent.

One explicit transaction covers a complete sync, including deletions. A read/provider/serialization/database failure propagates and preserves the last good state so a subsequent sync retries it. The write lock is held while processing; use separate connections for concurrent readers.

Source code in src/omnichunk/store/chunk_store.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
class ChunkStore:
    """SQLite-backed named collection of chunked documents.

    Directory deletion is limited to a previously completed scan with the same
    resolved root, glob, exclusions and hidden-file policy. A partial file scan
    or a new filter never deletes siblings. Collections are independent.

    One explicit transaction covers a complete sync, including deletions. A
    read/provider/serialization/database failure propagates and preserves the
    last good state so a subsequent sync retries it. The write lock is held
    while processing; use separate connections for concurrent readers.
    """

    def __init__(self, path: str | Path, *, collection: str = "default") -> None:
        if not isinstance(collection, str) or not collection.strip():
            raise ValueError("collection must be a nonempty name")
        self._db_path = Path(path).resolve()
        self.collection = collection
        self._conn = sqlite3.connect(str(self._db_path), isolation_level=None, timeout=30.0)
        self._conn.row_factory = sqlite3.Row
        try:
            tables = self._conn.execute(
                "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'"
            ).fetchall()
            version = self._conn.execute("PRAGMA user_version").fetchone()[0]
            if version not in (0, STORE_SCHEMA_VERSION) or (tables and version == 0):
                raise LegacyStoreError(
                    f"Unsupported store schema {version}; use migrate_legacy_store(old, new) "
                    "with a separate destination or rebuild a new index. "
                    "The old database is unchanged."
                )
            self._conn.execute("PRAGMA foreign_keys = ON")
            if not tables:
                self._conn.executescript(_SCHEMA)
        except BaseException:
            self._conn.close()
            raise

    def close(self) -> None:
        self._conn.close()

    def __enter__(self) -> ChunkStore:
        return self

    def __exit__(self, *exc: object) -> None:
        self.close()

    def query(self, filepath: str) -> list[Chunk]:
        """Return this collection's chunks in byte/index source order."""
        rows = self._conn.execute(
            "SELECT chunk_json FROM chunks WHERE collection = ? AND filepath = ? "
            "ORDER BY byte_start, chunk_index, stable_id",
            (self.collection, _norm_path(filepath)),
        ).fetchall()
        return [chunk_from_dict(json.loads(row["chunk_json"])) for row in rows]

    def index(
        self,
        root: str | Path,
        *,
        glob: str = "**/*",
        exclude: Sequence[str] | None = None,
        include_hidden: bool = False,
        encoding: str = "utf-8",
        chunker: Chunker | None = None,
        **chunker_options: Any,
    ) -> SyncResult:
        """Re-chunk all matching files, with the same deletion safety as sync."""
        return self._sync(
            root,
            glob=glob,
            exclude=exclude,
            include_hidden=include_hidden,
            encoding=encoding,
            chunker=chunker,
            incremental=False,
            chunker_options=chunker_options,
        )

    def sync(
        self,
        root: str | Path,
        *,
        glob: str = "**/*",
        exclude: Sequence[str] | None = None,
        include_hidden: bool = False,
        encoding: str = "utf-8",
        chunker: Chunker | None = None,
        **chunker_options: Any,
    ) -> SyncResult:
        """Skip only files with unchanged content and processing configuration."""
        return self._sync(
            root,
            glob=glob,
            exclude=exclude,
            include_hidden=include_hidden,
            encoding=encoding,
            chunker=chunker,
            incremental=True,
            chunker_options=chunker_options,
        )

    def _sync(
        self,
        root: str | Path,
        *,
        glob: str,
        exclude: Sequence[str] | None,
        include_hidden: bool,
        encoding: str,
        chunker: Chunker | None,
        incremental: bool,
        chunker_options: dict[str, Any],
    ) -> SyncResult:
        root_path = Path(root).resolve()
        if not root_path.exists():
            raise FileNotFoundError(f"Root does not exist: {root}")
        if chunker is not None and chunker_options:
            raise ValueError("Pass a configured chunker or chunker_options, not both")
        ck = chunker or Chunker(**chunker_options)
        reusable = _cache_reusable(ck)
        fingerprint = _hash_json(
            [
                "omnichunk-store-v2",
                ck.config_fingerprint(),
                encoding,
                type(ck).__module__,
                type(ck).__qualname__,
                ck.registry.revision,
                sorted(ck.registry.parsers),
            ]
        )
        scope_key = _hash_json(
            [
                str(root_path),
                glob,
                sorted(exclude or []),
                include_hidden,
                root_path.is_file(),
            ]
        )
        self._conn.execute("BEGIN IMMEDIATE")
        try:
            paths = self._scan_files(root_path, glob, exclude, include_hidden)
            disk_paths = set(paths)
            previous_scope = {
                row[0]
                for row in self._conn.execute(
                    "SELECT filepath FROM scope_members WHERE collection = ? AND scope_key = ?",
                    (self.collection, scope_key),
                )
            }
            removed: list[str] = []
            diffs: dict[str, ChunkDiff] = {}
            skipped = updated = deleted = 0
            # Only remove missing sources previously owned by this exact completed scan.
            # An existing file excluded by a changed filesystem/filter state is retained.
            for stale in sorted(previous_scope - disk_paths):
                try:
                    Path(stale).stat()
                except FileNotFoundError:
                    removed.extend(
                        row[0]
                        for row in self._conn.execute(
                            "SELECT stable_id FROM chunks WHERE collection = ? AND filepath = ?",
                            (self.collection, stale),
                        )
                    )
                    self._conn.execute(
                        "DELETE FROM files WHERE collection = ? AND path = ?",
                        (self.collection, stale),
                    )
                    deleted += 1
            for filepath in sorted(paths):
                path = Path(filepath)
                stat = path.stat()
                sha = _file_sha256(path)
                row = self._conn.execute(
                    "SELECT content_sha256, config_fingerprint FROM files "
                    "WHERE collection = ? AND path = ?",
                    (self.collection, filepath),
                ).fetchone()
                if (
                    incremental
                    and reusable
                    and row is not None
                    and row["content_sha256"] == sha
                    and row["config_fingerprint"] == fingerprint
                ):
                    skipped += 1
                else:
                    previous = self.query(filepath)
                    chunks = ck.chunk_file(filepath, encoding=encoding)
                    after = path.stat()
                    if (
                        after.st_mtime_ns != stat.st_mtime_ns
                        or after.st_size != stat.st_size
                        or _file_sha256(path) != sha
                    ):
                        raise RuntimeError(f"Source changed while indexing: {filepath}; retry sync")
                    diff = diff_chunks(previous, chunks)
                    diffs[filepath] = diff
                    removed.extend(diff.removed_ids)
                    self._write_document(
                        filepath,
                        stat.st_mtime_ns,
                        stat.st_size,
                        sha,
                        fingerprint,
                        chunks,
                    )
                    updated += 1
                self._conn.execute(
                    "INSERT OR IGNORE INTO scope_members (collection, scope_key, filepath) "
                    "VALUES (?, ?, ?)",
                    (self.collection, scope_key, filepath),
                )
            self._conn.execute("COMMIT")
        except BaseException:
            self._conn.execute("ROLLBACK")
            raise
        return SyncResult(len(paths), skipped, updated, deleted, sorted(set(removed)), diffs)

    def _scan_files(
        self,
        root: Path,
        glob: str,
        exclude: Sequence[str] | None,
        include_hidden: bool,
    ) -> list[str]:
        if root.is_file():
            candidates = [root]
        else:

            def fail(error: OSError) -> None:
                raise error

            # pathlib glob can suppress directory I/O errors. Verify traversal first
            # so an unreadable subtree cannot masquerade as a completed deletion scan.
            for _ in os.walk(root, onerror=fail, followlinks=False):
                pass
            candidates = _collect_directory_files(
                root,
                glob_pattern=glob,
                exclude_patterns=list(exclude or []),
                include_hidden=include_hidden,
            )
        own_files = {str(self._db_path) + suffix for suffix in ("", "-wal", "-shm", "-journal")}
        paths: set[str] = set()
        for candidate in candidates:
            resolved = candidate.resolve()
            if not root.is_file() and not resolved.is_relative_to(root):
                raise ValueError(f"Source symlink escapes indexing root: {candidate}")
            if str(resolved) not in own_files:
                paths.add(str(resolved))
        return sorted(paths)

    def _write_document(
        self,
        filepath: str,
        mtime_ns: int,
        size: int,
        sha: str,
        fingerprint: str,
        chunks: Sequence[Chunk],
    ) -> None:
        self._conn.execute(
            "INSERT INTO files (collection, path, mtime_ns, size, content_sha256, "
            "config_fingerprint, last_indexed_at) VALUES (?, ?, ?, ?, ?, ?, ?) "
            "ON CONFLICT(collection, path) DO UPDATE SET mtime_ns=excluded.mtime_ns, "
            "size=excluded.size, content_sha256=excluded.content_sha256, "
            "config_fingerprint=excluded.config_fingerprint, "
            "last_indexed_at=excluded.last_indexed_at",
            (self.collection, filepath, mtime_ns, size, sha, fingerprint, time.time()),
        )
        self._conn.execute(
            "DELETE FROM chunks WHERE collection = ? AND filepath = ?",
            (self.collection, filepath),
        )
        for chunk in chunks:
            self._conn.execute(
                "INSERT INTO chunks (collection, stable_id, filepath, byte_start, chunk_index, "
                "chunk_json) VALUES (?, ?, ?, ?, ?, ?)",
                (
                    self.collection,
                    stable_chunk_id(chunk),
                    filepath,
                    chunk.byte_range.start,
                    chunk.index,
                    json.dumps(
                        chunk_to_dict(chunk), ensure_ascii=False, sort_keys=True, allow_nan=False
                    ),
                ),
            )

query(filepath)

Return this collection's chunks in byte/index source order.

Source code in src/omnichunk/store/chunk_store.py
188
189
190
191
192
193
194
195
def query(self, filepath: str) -> list[Chunk]:
    """Return this collection's chunks in byte/index source order."""
    rows = self._conn.execute(
        "SELECT chunk_json FROM chunks WHERE collection = ? AND filepath = ? "
        "ORDER BY byte_start, chunk_index, stable_id",
        (self.collection, _norm_path(filepath)),
    ).fetchall()
    return [chunk_from_dict(json.loads(row["chunk_json"])) for row in rows]

index(root, *, glob='**/*', exclude=None, include_hidden=False, encoding='utf-8', chunker=None, **chunker_options)

Re-chunk all matching files, with the same deletion safety as sync.

Source code in src/omnichunk/store/chunk_store.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def index(
    self,
    root: str | Path,
    *,
    glob: str = "**/*",
    exclude: Sequence[str] | None = None,
    include_hidden: bool = False,
    encoding: str = "utf-8",
    chunker: Chunker | None = None,
    **chunker_options: Any,
) -> SyncResult:
    """Re-chunk all matching files, with the same deletion safety as sync."""
    return self._sync(
        root,
        glob=glob,
        exclude=exclude,
        include_hidden=include_hidden,
        encoding=encoding,
        chunker=chunker,
        incremental=False,
        chunker_options=chunker_options,
    )

sync(root, *, glob='**/*', exclude=None, include_hidden=False, encoding='utf-8', chunker=None, **chunker_options)

Skip only files with unchanged content and processing configuration.

Source code in src/omnichunk/store/chunk_store.py
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
def sync(
    self,
    root: str | Path,
    *,
    glob: str = "**/*",
    exclude: Sequence[str] | None = None,
    include_hidden: bool = False,
    encoding: str = "utf-8",
    chunker: Chunker | None = None,
    **chunker_options: Any,
) -> SyncResult:
    """Skip only files with unchanged content and processing configuration."""
    return self._sync(
        root,
        glob=glob,
        exclude=exclude,
        include_hidden=include_hidden,
        encoding=encoding,
        chunker=chunker,
        incremental=True,
        chunker_options=chunker_options,
    )

omnichunk.store.SyncResult dataclass

A committed scan. Exceptions return no success result and roll back the scan.

Apply removed_chunk_ids before upserting each diff's added chunks. Same-ID payload changes are included in both for compatibility. Unchanged chunks may have moved: refresh their location metadata without re-embedding.

Source code in src/omnichunk/store/chunk_store.py
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
@dataclass(frozen=True)
class SyncResult:
    """A committed scan. Exceptions return no success result and roll back the scan.

    Apply ``removed_chunk_ids`` before upserting each diff's ``added`` chunks.
    Same-ID payload changes are included in both for compatibility. Unchanged
    chunks may have moved: refresh their location metadata without re-embedding.
    """

    files_scanned: int
    files_skipped: int
    files_updated: int
    files_deleted: int
    removed_chunk_ids: list[str]
    diffs: dict[str, ChunkDiff]

omnichunk.store.migrate_legacy_store(source, destination, *, collection='default')

Copy a v1 database to a new v2 path without modifying the old database.

The destination must not exist. Complete metadata present in old JSON is retained; already-lost metadata cannot be recreated. Converted records have no scan ownership and an empty configuration fingerprint, forcing reindexing on the next sync. Missing-source records remain recoverable until an explicit new index is built. The returned ID map supports a separate vector rebuild.

Source code in src/omnichunk/store/chunk_store.py
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
def migrate_legacy_store(
    source: str | Path,
    destination: str | Path,
    *,
    collection: str = "default",
) -> MigrationResult:
    """Copy a v1 database to a new v2 path without modifying the old database.

    The destination must not exist. Complete metadata present in old JSON is
    retained; already-lost metadata cannot be recreated. Converted records have
    no scan ownership and an empty configuration fingerprint, forcing reindexing
    on the next sync. Missing-source records remain recoverable until an explicit
    new index is built. The returned ID map supports a separate vector rebuild.
    """
    src, dst = Path(source).resolve(), Path(destination).resolve()
    if src == dst or dst.exists():
        raise ValueError("Migration requires a separate, nonexistent destination")
    old = sqlite3.connect(src.as_uri() + "?mode=ro", uri=True)
    old.row_factory = sqlite3.Row
    created = False
    try:
        version = old.execute("PRAGMA user_version").fetchone()[0]
        if version not in (0, 1):
            raise LegacyStoreError(f"Expected legacy store schema 0 or 1, got {version}")
        old.execute("BEGIN")
        old_files = old.execute("SELECT * FROM files ORDER BY path").fetchall()
        with dst.open("xb"):
            pass
        created = True
        id_map: dict[str, str] = {}
        count = 0
        with ChunkStore(dst, collection=collection) as new:
            new._conn.execute("BEGIN IMMEDIATE")
            try:
                for row in old_files:
                    filepath = _norm_path(row["path"])
                    entries = old.execute(
                        "SELECT stable_id, chunk_json FROM chunks WHERE filepath = ?",
                        (row["path"],),
                    ).fetchall()
                    pairs = [
                        (entry["stable_id"], chunk_from_dict(json.loads(entry["chunk_json"])))
                        for entry in entries
                    ]
                    pairs.sort(key=lambda pair: (pair[1].byte_range.start, pair[1].index, pair[0]))
                    occurrences: dict[str, int] = {}
                    chunks: list[Chunk] = []
                    for old_id, chunk in pairs:
                        occurrence = occurrences.get(chunk.text, 0)
                        occurrences[chunk.text] = occurrence + 1
                        converted = replace(
                            chunk,
                            source=SourceDescriptor(
                                source_id=filepath,
                                revision=row["content_sha256"],
                                normalization="legacy-unknown",
                                format_name="legacy",
                            ),
                            occurrence=occurrence,
                            config_fingerprint="",
                        )
                        chunks.append(converted)
                        id_map[old_id] = stable_chunk_id(converted)
                    new._write_document(
                        filepath,
                        row["mtime_ns"],
                        row["size"],
                        row["content_sha256"],
                        "",
                        chunks,
                    )
                    count += len(chunks)
                new._conn.execute("COMMIT")
            except BaseException:
                new._conn.execute("ROLLBACK")
                raise
        return MigrationResult(str(dst), len(old_files), count, id_map)
    except BaseException:
        if created:
            dst.unlink(missing_ok=True)
        raise
    finally:
        old.close()

omnichunk.store.MigrationResult dataclass

Offline copy result; rebuild embeddings for the new occurrence IDs.

Source code in src/omnichunk/store/chunk_store.py
 94
 95
 96
 97
 98
 99
100
101
102
@dataclass(frozen=True)
class MigrationResult:
    """Offline copy result; rebuild embeddings for the new occurrence IDs."""

    destination: str
    files_copied: int
    chunks_copied: int
    id_map: dict[str, str]
    reindex_required: bool = True

omnichunk.store.LegacyStoreError

Bases: ValueError

An old or unknown database must not be mutated by the v2 store.

Source code in src/omnichunk/store/chunk_store.py
90
91
class LegacyStoreError(ValueError):
    """An old or unknown database must not be mutated by the v2 store."""

Journal and delivery

IndexJournal(path) uses its own SQLite file, separate from ChunkStore. plan(sources, *, target_id, model_revision, ...) produces an IndexPlan without writing to a vector backend. Each IndexSource has a stable source_id, source revision, a tuple of chunks, and optional JSON-compatible metadata. collection defaults to "default"; target_id identifies the backend target; model_revision is required and preprocessing_revision defaults to "identity-v1"; together they identify embedding behavior. use_contextualized_text=True selects the contextualized embedding payload; set it to False for raw chunk text. Set scope and complete_scope=True only for a complete scan; delete_sources explicitly removes the specified source IDs. Enqueue the plan before delivery.

deliver(sink, embed, *, collection="default", batch_size=64, max_batches=None, retry_failed=False) sends bounded batches. embed accepts a sequence of texts and returns corresponding vectors; it can be omitted when no uncached embeddings are needed. max_batches limits work per call; retry_failed permits retry of previously permanent or unclassified failures. The sink's target_id must match the plan. DeliveryResult reports completed and pending work; status() reports the journal's current state. Delivery is at least once, so sinks must be idempotent.

For IndexPlan, base_generation is the collection generation used to create the plan; upserts contains IndexRecord values to write, while removed_ids lists IDs to delete. added_ids, metadata_update_ids, embedding_invalidations and unchanged_ids classify the comparison with the previous state. plan_id identifies the plan and schema_version versions its JSON representation. DeliveryBatch contains the collection, target, idempotency key, vector upserts, deletes and operation IDs. A custom IndexSink.apply(batch) must return a DeliveryReceipt with the matching key and exactly those operation IDs. DeliveryResult counts acknowledged and pending operations, model calls and reused embeddings; completed indicates whether delivery finished. IndexStatus contains the current generation, pending plan and operation counts, last error, and whether that error is retryable.

omnichunk.indexing.IndexJournal

A separate delivery database; existing ChunkStore databases are untouched.

A collection is bound to one caller-owned target identity and vector dimension. One pending plan serializes each collection. External calls occur under a SQLite write transaction; use independent connections for workers, never a reentrant journal callback. A sink must make every operation idempotent.

Source code in src/omnichunk/indexing/journal.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
class IndexJournal:
    """A separate delivery database; existing ChunkStore databases are untouched.

    A collection is bound to one caller-owned target identity and vector dimension.
    One pending plan serializes each collection. External calls occur under a
    SQLite write transaction; use independent connections for workers, never a
    reentrant journal callback. A sink must make every operation idempotent.
    """

    def __init__(self, path: str | Path) -> None:
        self._conn = sqlite3.connect(str(path), isolation_level=None, timeout=30.0)
        self._conn.row_factory = sqlite3.Row
        try:
            # Existing journals can open while another worker delivers under a
            # write lock. Read all schema fields from one consistent snapshot.
            with self._transaction():
                fresh = self._check_schema()
            if fresh:
                with self._transaction(write=True):
                    # Another constructor may have initialized the database
                    # while this connection was waiting for the writer lock.
                    if self._check_schema():
                        for statement in _SCHEMA.split(";"):
                            if statement.strip():
                                # executescript() would commit our lock before
                                # executing the schema. These are static DDL and
                                # PRAGMA statements with no embedded semicolons.
                                self._conn.execute(statement)
        except BaseException:
            self._conn.close()
            raise

    def _check_schema(self) -> bool:
        """Inspect one transaction snapshot; return True for a fresh database."""
        tables = {
            row[0]
            for row in self._conn.execute(
                "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"
            )
        }
        version = self._conn.execute("PRAGMA user_version").fetchone()[0]
        application = self._conn.execute("PRAGMA application_id").fetchone()[0]
        required = {
            "collections",
            "sources",
            "records",
            "scopes",
            "plans",
            "operations",
            "embeddings",
        }
        if not tables and version == 0 and application == 0:
            return True
        if version != 1 or application != _APPLICATION_ID or tables != required:
            raise JournalSchemaError(
                "Unsupported journal database; use a new journal and reconcile the target"
            )
        return False

    def close(self) -> None:
        self._conn.close()

    def __enter__(self) -> IndexJournal:
        return self

    def __exit__(self, *exc: object) -> None:
        self.close()

    @contextmanager
    def _transaction(self, *, write: bool = False) -> Iterator[None]:
        self._conn.execute("BEGIN IMMEDIATE" if write else "BEGIN")
        try:
            yield
            self._conn.execute("COMMIT")
        except BaseException:
            self._conn.execute("ROLLBACK")
            raise

    def records(self, *, collection: str = "default") -> tuple[IndexRecord, ...]:
        """Return the last fully acknowledged generation, including source metadata."""
        return tuple(
            _record(row[0])
            for row in self._conn.execute(
                "SELECT body FROM records WHERE collection=? ORDER BY source_id,id",
                (name(collection, "collection"),),
            )
        )

    def status(self, *, collection: str = "default") -> IndexStatus:
        name(collection, "collection")
        with self._transaction():
            row = self._conn.execute(
                "SELECT generation FROM collections WHERE name=?", (collection,)
            ).fetchone()
            pending = self._conn.execute(
                "SELECT * FROM plans WHERE collection=? AND done=0", (collection,)
            ).fetchone()
            if pending is None:
                return IndexStatus(collection, row[0] if row else 0, None, 0, 0, None, True)
            count = self._conn.execute(
                "SELECT COUNT(*),COALESCE(SUM(acked),0) FROM operations WHERE plan_id=?",
                (pending["id"],),
            ).fetchone()
            return IndexStatus(
                collection,
                row[0],
                pending["id"],
                count[0] - count[1],
                count[1],
                pending["error"],
                bool(pending["retryable"]),
            )

    def plan(
        self,
        sources: Iterable[IndexSource],
        *,
        collection: str = "default",
        target_id: str,
        model_revision: str,
        preprocessing_revision: str = "identity-v1",
        use_contextualized_text: bool = True,
        scope: str | None = None,
        complete_scope: bool = False,
        delete_sources: Iterable[str] = (),
    ) -> IndexPlan:
        """Build a dry-run plan without committing source state or calling a model.

        Exhaust the supplied scan before planning. ``complete_scope`` removes only
        missing members of that named scope with no other scope owner. An explicit
        deletion removes all ownership. A failed/incomplete iterator cannot delete.
        """
        name(collection, "collection")
        name(target_id, "target_id")
        name(model_revision, "model_revision")
        name(preprocessing_revision, "preprocessing_revision")
        if type(use_contextualized_text) is not bool or type(complete_scope) is not bool:
            raise ValueError("Index policies must be booleans")
        if scope is not None:
            name(scope, "scope")
        elif complete_scope:
            raise ValueError("complete_scope requires an explicit scope")
        desired: dict[str, IndexSource] = {}
        new_records: dict[str, IndexRecord] = {}
        for source in sources:
            if not isinstance(source, IndexSource) or source.source_id in desired:
                raise ValueError("Expected unique IndexSource objects")
            rows = _source_records(
                source, model_revision, preprocessing_revision, use_contextualized_text
            )
            desired[source.source_id] = source
            for record in rows:
                if record.id in new_records:
                    raise ValueError("Duplicate record ID")
                new_records[record.id] = record
        if isinstance(delete_sources, (str, bytes)):
            raise ValueError("delete_sources must be an iterable of source IDs, not a string")
        deleted = {name(source_id, "deleted source_id") for source_id in delete_sources}
        if deleted & set(desired):
            raise ValueError("A source cannot be updated and deleted together")
        with self._transaction():
            current = self._conn.execute(
                "SELECT * FROM collections WHERE name=?", (collection,)
            ).fetchone()
            if self._conn.execute(
                "SELECT 1 FROM plans WHERE collection=? AND done=0", (collection,)
            ).fetchone():
                raise IndexConflictError(
                    "Deliver the pending collection plan before planning another"
                )
            if current and current["target_id"] != target_id:
                raise IndexConflictError("Collection is bound to a different target_id")
            previous = {row.id: row for row in self.records(collection=collection)}
            known_sources = {
                row[0]
                for row in self._conn.execute(
                    "SELECT source_id FROM sources WHERE collection=?", (collection,)
                )
            }
            if scope is not None and complete_scope:
                old_members = {
                    row[0]
                    for row in self._conn.execute(
                        "SELECT source_id FROM scopes WHERE collection=? AND scope=?",
                        (collection, scope),
                    )
                }
                other_members = {
                    row[0]
                    for row in self._conn.execute(
                        "SELECT source_id FROM scopes WHERE collection=? AND scope<>?",
                        (collection, scope),
                    )
                }
                deleted.update(old_members - set(desired) - other_members)
            if (
                current
                and (
                    current["model"],
                    current["preprocessing"],
                    bool(current["contextualized"]),
                )
                != (model_revision, preprocessing_revision, use_contextualized_text)
                and known_sources - set(desired) - deleted
            ):
                raise IndexConflictError(
                    "Policy changes require all existing sources or a new collection"
                )
            affected = set(desired) | deleted
            removed = tuple(
                sorted(
                    identifier
                    for identifier, record in previous.items()
                    if record.source_id in affected and identifier not in new_records
                )
            )
            added, metadata, invalidated, unchanged = [], [], [], []
            upserts = []
            for identifier, record in sorted(new_records.items()):
                old = previous.get(identifier)
                if old is None:
                    added.append(identifier)
                elif old.embedding_key != record.embedding_key:
                    invalidated.append(identifier)
                elif old != record:
                    metadata.append(identifier)
                else:
                    unchanged.append(identifier)
                    continue
                upserts.append(record)
            result = IndexPlan(
                collection,
                target_id,
                current["generation"] if current else 0,
                model_revision,
                preprocessing_revision,
                use_contextualized_text,
                tuple(sorted((key, value.revision) for key, value in desired.items())),
                tuple(sorted(deleted)),
                tuple(upserts),
                removed,
                tuple(added),
                tuple(metadata),
                tuple(invalidated),
                tuple(unchanged),
                scope,
                complete_scope,
                tuple(sorted(desired)) if scope else (),
            )
            result = replace(result, plan_id=digest(result._body()))
            return IndexPlan.from_json(result.to_json())

    def _validate_transition(self, plan: IndexPlan) -> None:
        """Validate source ownership and action semantics against the CAS snapshot."""
        previous = {record.id: record for record in self.records(collection=plan.collection)}
        sources = dict(plan.source_revisions)
        affected = set(sources) | set(plan.deleted_sources)
        upserts = {record.id: record for record in plan.upserts}
        removed = set(plan.removed_ids)
        unchanged = set(plan.unchanged_ids)
        expected_old = {key for key, record in previous.items() if record.source_id in affected}
        if expected_old != (removed | unchanged | (set(upserts) & set(previous))):
            raise ValueError("Plan does not account for every record in its affected sources")
        for identifier in removed | unchanged:
            if identifier not in previous or previous[identifier].source_id not in affected:
                raise ValueError("Plan record does not belong to an affected source")
        for identifier in unchanged:
            record = previous[identifier]
            if sources.get(
                record.source_id
            ) != record.source_revision or record.embedding_key != embedding_key(
                record.text, plan.model_revision, plan.preprocessing_revision
            ):
                raise ValueError("Unchanged record has stale source/model metadata")
        for record in (*plan.upserts, *(previous[key] for key in unchanged)):
            raw = record.metadata.get("omnichunk")
            if not isinstance(raw, dict):
                raise ValueError("Index record requires canonical chunk provenance")
            chunk = chunk_from_dict(raw)
            extra = {key: value for key, value in record.metadata.items() if key != "omnichunk"}
            expected = _source_records(
                IndexSource(record.source_id, record.source_revision, (chunk,), extra),
                plan.model_revision,
                plan.preprocessing_revision,
                plan.use_contextualized_text,
            )
            if expected != (record,):
                raise ValueError("Index record differs from its canonical chunk provenance")
            if record.id in unchanged:
                continue
            old = previous.get(record.id)
            if old is not None and old.source_id != record.source_id:
                raise ValueError("An index ID cannot change source ownership")
            category = (
                plan.added_ids
                if old is None
                else (
                    plan.embedding_invalidations
                    if old.embedding_key != record.embedding_key
                    else plan.metadata_update_ids
                )
            )
            if record.id not in category or old == record:
                raise ValueError("Plan upsert classification differs from acknowledged state")
        # Imported plans must satisfy the same collective source checks as
        # plan(). Validating each upsert alone cannot detect conflicting spans
        # between siblings, including siblings retained as unchanged records.
        resulting: dict[str, list[IndexRecord]] = {source_id: [] for source_id in sources}
        for record in (*plan.upserts, *(previous[key] for key in unchanged)):
            resulting[record.source_id].append(record)
        for source_id, records in resulting.items():
            _source_records(
                IndexSource(
                    source_id,
                    sources[source_id],
                    tuple(chunk_from_dict(record.metadata["omnichunk"]) for record in records),
                ),
                plan.model_revision,
                plan.preprocessing_revision,
                plan.use_contextualized_text,
            )
        if plan.complete_scope:
            members = {
                row[0]
                for row in self._conn.execute(
                    "SELECT source_id FROM scopes WHERE collection=? AND scope=?",
                    (plan.collection, plan.scope),
                )
            }
            other_owners = {
                row[0]
                for row in self._conn.execute(
                    "SELECT source_id FROM scopes WHERE collection=? AND scope<>?",
                    (plan.collection, plan.scope),
                )
            }
            required_deletions = members - set(sources) - other_owners
            if required_deletions - set(plan.deleted_sources):
                raise ValueError("Complete scope plan omits required stale source deletions")
        current = self._conn.execute(
            "SELECT * FROM collections WHERE name=?", (plan.collection,)
        ).fetchone()
        if current and (
            current["model"],
            current["preprocessing"],
            bool(current["contextualized"]),
        ) != (plan.model_revision, plan.preprocessing_revision, plan.use_contextualized_text):
            known = {
                row[0]
                for row in self._conn.execute(
                    "SELECT source_id FROM sources WHERE collection=?", (plan.collection,)
                )
            }
            if known - affected:
                raise IndexConflictError("Policy changes require every existing source")

    def enqueue(self, plan: IndexPlan) -> str:
        """Persist a validated plan and its outbox atomically; safe to retry."""
        body = plan.to_json()
        plan = IndexPlan.from_json(body)
        with self._transaction(write=True):
            existing = self._conn.execute(
                "SELECT body FROM plans WHERE id=?", (plan.plan_id,)
            ).fetchone()
            if existing:
                if existing[0] != body:
                    raise IndexConflictError("Plan ID already exists with different contents")
                return plan.plan_id
            current = self._conn.execute(
                "SELECT * FROM collections WHERE name=?", (plan.collection,)
            ).fetchone()
            if (current["generation"] if current else 0) != plan.base_generation:
                raise IndexConflictError("Stale plan generation; create a new plan")
            if current and current["target_id"] != plan.target_id:
                raise IndexConflictError("Collection is bound to a different target_id")
            if self._conn.execute(
                "SELECT 1 FROM plans WHERE collection=? AND done=0", (plan.collection,)
            ).fetchone():
                raise IndexConflictError("A collection plan is already pending")
            self._validate_transition(plan)
            if not current:
                self._conn.execute(
                    "INSERT INTO collections(name,target_id,model,preprocessing,contextualized) "
                    "VALUES(?,?,?,?,?)",
                    (
                        plan.collection,
                        plan.target_id,
                        plan.model_revision,
                        plan.preprocessing_revision,
                        int(plan.use_contextualized_text),
                    ),
                )
            self._conn.execute(
                "INSERT INTO plans(id,collection,body) VALUES(?,?,?)",
                (plan.plan_id, plan.collection, body),
            )
            operations: list[tuple[str, str, str | None]] = [
                ("delete", identifier, None) for identifier in plan.removed_ids
            ]
            operations.extend(
                ("upsert", record.id, canonical_json(asdict(record))) for record in plan.upserts
            )
            for sequence, (kind, identifier, record_body) in enumerate(operations):
                self._conn.execute(
                    "INSERT INTO operations(plan_id,sequence,operation_id,kind,record_id,body) "
                    "VALUES(?,?,?,?,?,?)",
                    (
                        plan.plan_id,
                        sequence,
                        digest([plan.plan_id, kind, identifier]),
                        kind,
                        identifier,
                        record_body,
                    ),
                )
            if not operations:
                self._finish(plan)
        return plan.plan_id

    def _finish(self, plan: IndexPlan) -> None:
        for identifier in plan.removed_ids:
            self._conn.execute(
                "DELETE FROM records WHERE collection=? AND id=?", (plan.collection, identifier)
            )
        for record in plan.upserts:
            self._conn.execute(
                "INSERT OR REPLACE INTO records(collection,id,source_id,body) VALUES(?,?,?,?)",
                (plan.collection, record.id, record.source_id, canonical_json(asdict(record))),
            )
        for source_id in plan.deleted_sources:
            self._conn.execute(
                "DELETE FROM sources WHERE collection=? AND source_id=?",
                (plan.collection, source_id),
            )
            self._conn.execute(
                "DELETE FROM scopes WHERE collection=? AND source_id=?",
                (plan.collection, source_id),
            )
        for source_id, revision in plan.source_revisions:
            self._conn.execute(
                "INSERT OR REPLACE INTO sources(collection,source_id,revision) VALUES(?,?,?)",
                (plan.collection, source_id, revision),
            )
        if plan.scope is not None:
            if plan.complete_scope:
                self._conn.execute(
                    "DELETE FROM scopes WHERE collection=? AND scope=?",
                    (plan.collection, plan.scope),
                )
            for source_id in plan.scope_source_ids:
                self._conn.execute(
                    "INSERT OR IGNORE INTO scopes(collection,scope,source_id) VALUES(?,?,?)",
                    (plan.collection, plan.scope, source_id),
                )
        self._conn.execute(
            "UPDATE collections SET generation=?,model=?,preprocessing=?,contextualized=? "
            "WHERE name=?",
            (
                plan.base_generation + 1,
                plan.model_revision,
                plan.preprocessing_revision,
                int(plan.use_contextualized_text),
                plan.collection,
            ),
        )
        self._conn.execute("UPDATE plans SET done=1,error=NULL WHERE id=?", (plan.plan_id,))

    def deliver(
        self,
        sink: IndexSink,
        embed: Callable[[Sequence[str]], Sequence[Sequence[float]]] | None = None,
        *,
        collection: str = "default",
        batch_size: int = 64,
        max_batches: int | None = None,
        retry_failed: bool = False,
    ) -> DeliveryResult:
        """Deliver bounded batches; exact acknowledgements checkpoint durable work.

        A remote success followed by a crash is replayed. Prepared vectors were
        committed before remote I/O, so recovery reuses them. Unknown failures
        require explicit ``retry_failed=True``; retryable failures remain eligible.
        This method does not sleep or promise distributed exactly-once delivery.
        """
        name(collection, "collection")
        name(sink.target_id, "sink.target_id")
        if (
            type(batch_size) is not int
            or batch_size <= 0
            or (max_batches is not None and (type(max_batches) is not int or max_batches <= 0))
            or type(retry_failed) is not bool
        ):
            raise ValueError("Invalid delivery batch/retry limits")
        acknowledged = calls = reused = batches = 0
        active_id: str | None = None
        fresh: set[str] = set()
        while max_batches is None or batches < max_batches:
            failed: Exception | None = None
            with self._transaction(write=True):
                state = self._conn.execute(
                    "SELECT * FROM collections WHERE name=?", (collection,)
                ).fetchone()
                if state and state["target_id"] != sink.target_id:
                    raise IndexConflictError("Sink target_id differs from the collection binding")
                pending = self._conn.execute(
                    "SELECT * FROM plans WHERE collection=? AND done=0", (collection,)
                ).fetchone()
                if pending is None:
                    return DeliveryResult(active_id, acknowledged, 0, True, calls, reused)
                active_id = pending["id"]
                if pending["error"] and not pending["retryable"] and not retry_failed:
                    raise PermanentSinkError(
                        f"Pending delivery requires retry_failed=True: {pending['error']}"
                    )
                plan = IndexPlan.from_json(pending["body"])
                operations = self._conn.execute(
                    "SELECT * FROM operations WHERE plan_id=? AND acked=0 "
                    "ORDER BY sequence LIMIT ?",
                    (active_id, batch_size),
                ).fetchall()
                records = [_record(row["body"]) for row in operations if row["kind"] == "upsert"]
                cached: dict[str, tuple[float, ...]] = {}
                missing: dict[str, str] = {}
                self._conn.execute("SAVEPOINT delivery_batch")
                try:
                    for record in records:
                        row = self._conn.execute(
                            "SELECT vector FROM embeddings WHERE collection=? AND fingerprint=?",
                            (collection, record.embedding_key),
                        ).fetchone()
                        if row:
                            cached[record.embedding_key] = vector_values(
                                json.loads(row[0]), state["dimension"]
                            )
                        else:
                            missing[record.embedding_key] = record.text
                    if missing:
                        if embed is None:
                            raise ValueError(
                                "An embedding callback is required for uncached payloads"
                            )
                        calls += 1
                        values = list(embed(list(missing.values())))
                        if len(values) != len(missing):
                            raise ValueError(
                                "Embedding callback returned the wrong number of vectors"
                            )
                        vectors = []
                        dimension = state["dimension"]
                        for value in values:
                            vector = vector_values(value, dimension)
                            dimension = dimension or len(vector)
                            vectors.append(vector)
                        for fingerprint, vector in zip(missing, vectors):
                            self._conn.execute(
                                "INSERT OR REPLACE INTO embeddings(collection,fingerprint,vector) "
                                "VALUES(?,?,?)",
                                (collection, fingerprint, canonical_json(vector)),
                            )
                            fresh.add(fingerprint)
                        self._conn.execute(
                            "UPDATE collections SET dimension=? WHERE name=?",
                            (dimension, collection),
                        )
                        # Commit preparation before a separate transaction reselects
                        # pending work. Another worker may already deliver it.
                        continue
                    operation_ids = tuple(row["operation_id"] for row in operations)
                    batch = DeliveryBatch(
                        collection,
                        sink.target_id,
                        digest([active_id, operation_ids]),
                        tuple(
                            VectorRecord(
                                record.id,
                                record.source_id,
                                record.source_revision,
                                record.text,
                                record.metadata,
                                cached[record.embedding_key],
                            )
                            for record in records
                        ),
                        tuple(row["record_id"] for row in operations if row["kind"] == "delete"),
                        operation_ids,
                    )
                    receipt = sink.apply(batch)
                    if (
                        not isinstance(receipt, DeliveryReceipt)
                        or receipt.idempotency_key != batch.idempotency_key
                        or receipt.operation_ids != operation_ids
                    ):
                        raise AcknowledgementError(
                            "Sink receipt must match the submitted operation IDs and key"
                        )
                    self._conn.executemany(
                        "UPDATE operations SET acked=1 WHERE plan_id=? AND operation_id=?",
                        [(active_id, key) for key in operation_ids],
                    )
                    self._conn.execute(
                        "UPDATE plans SET error=NULL,retryable=1 WHERE id=?", (active_id,)
                    )
                    acknowledged += len(operations)
                    reused += sum(record.embedding_key not in fresh for record in records)
                    batches += 1
                    remaining = self._conn.execute(
                        "SELECT COUNT(*) FROM operations WHERE plan_id=? AND acked=0", (active_id,)
                    ).fetchone()[0]
                    if not remaining:
                        self._finish(plan)
                        return DeliveryResult(active_id, acknowledged, 0, True, calls, reused)
                except Exception as exc:
                    self._conn.execute("ROLLBACK TO delivery_batch")
                    self._conn.execute("RELEASE delivery_batch")
                    self._conn.execute(
                        "UPDATE plans SET error=?,retryable=? WHERE id=?",
                        (
                            f"{type(exc).__name__}: {exc}",
                            int(isinstance(exc, RetryableSinkError)),
                            active_id,
                        ),
                    )
                    failed = exc
            if failed is not None:
                raise failed
        status = self.status(collection=collection)
        return DeliveryResult(
            active_id,
            acknowledged,
            status.pending_operations,
            status.pending_plan_id is None,
            calls,
            reused,
        )

    def prune_embeddings(self, *, collection: str = "default") -> int:
        """Remove vectors unused by acknowledged records; reject pending plans."""
        name(collection, "collection")
        with self._transaction(write=True):
            if self._conn.execute(
                "SELECT 1 FROM plans WHERE collection=? AND done=0", (collection,)
            ).fetchone():
                raise IndexConflictError("Cannot prune embeddings while delivery is pending")
            keep = {record.embedding_key for record in self.records(collection=collection)}
            stale = [
                row[0]
                for row in self._conn.execute(
                    "SELECT fingerprint FROM embeddings WHERE collection=?", (collection,)
                )
                if row[0] not in keep
            ]
            self._conn.executemany(
                "DELETE FROM embeddings WHERE collection=? AND fingerprint=?",
                [(collection, key) for key in stale],
            )
            return len(stale)

records(*, collection='default')

Return the last fully acknowledged generation, including source metadata.

Source code in src/omnichunk/indexing/journal.py
213
214
215
216
217
218
219
220
221
def records(self, *, collection: str = "default") -> tuple[IndexRecord, ...]:
    """Return the last fully acknowledged generation, including source metadata."""
    return tuple(
        _record(row[0])
        for row in self._conn.execute(
            "SELECT body FROM records WHERE collection=? ORDER BY source_id,id",
            (name(collection, "collection"),),
        )
    )

plan(sources, *, collection='default', target_id, model_revision, preprocessing_revision='identity-v1', use_contextualized_text=True, scope=None, complete_scope=False, delete_sources=())

Build a dry-run plan without committing source state or calling a model.

Exhaust the supplied scan before planning. complete_scope removes only missing members of that named scope with no other scope owner. An explicit deletion removes all ownership. A failed/incomplete iterator cannot delete.

Source code in src/omnichunk/indexing/journal.py
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
def plan(
    self,
    sources: Iterable[IndexSource],
    *,
    collection: str = "default",
    target_id: str,
    model_revision: str,
    preprocessing_revision: str = "identity-v1",
    use_contextualized_text: bool = True,
    scope: str | None = None,
    complete_scope: bool = False,
    delete_sources: Iterable[str] = (),
) -> IndexPlan:
    """Build a dry-run plan without committing source state or calling a model.

    Exhaust the supplied scan before planning. ``complete_scope`` removes only
    missing members of that named scope with no other scope owner. An explicit
    deletion removes all ownership. A failed/incomplete iterator cannot delete.
    """
    name(collection, "collection")
    name(target_id, "target_id")
    name(model_revision, "model_revision")
    name(preprocessing_revision, "preprocessing_revision")
    if type(use_contextualized_text) is not bool or type(complete_scope) is not bool:
        raise ValueError("Index policies must be booleans")
    if scope is not None:
        name(scope, "scope")
    elif complete_scope:
        raise ValueError("complete_scope requires an explicit scope")
    desired: dict[str, IndexSource] = {}
    new_records: dict[str, IndexRecord] = {}
    for source in sources:
        if not isinstance(source, IndexSource) or source.source_id in desired:
            raise ValueError("Expected unique IndexSource objects")
        rows = _source_records(
            source, model_revision, preprocessing_revision, use_contextualized_text
        )
        desired[source.source_id] = source
        for record in rows:
            if record.id in new_records:
                raise ValueError("Duplicate record ID")
            new_records[record.id] = record
    if isinstance(delete_sources, (str, bytes)):
        raise ValueError("delete_sources must be an iterable of source IDs, not a string")
    deleted = {name(source_id, "deleted source_id") for source_id in delete_sources}
    if deleted & set(desired):
        raise ValueError("A source cannot be updated and deleted together")
    with self._transaction():
        current = self._conn.execute(
            "SELECT * FROM collections WHERE name=?", (collection,)
        ).fetchone()
        if self._conn.execute(
            "SELECT 1 FROM plans WHERE collection=? AND done=0", (collection,)
        ).fetchone():
            raise IndexConflictError(
                "Deliver the pending collection plan before planning another"
            )
        if current and current["target_id"] != target_id:
            raise IndexConflictError("Collection is bound to a different target_id")
        previous = {row.id: row for row in self.records(collection=collection)}
        known_sources = {
            row[0]
            for row in self._conn.execute(
                "SELECT source_id FROM sources WHERE collection=?", (collection,)
            )
        }
        if scope is not None and complete_scope:
            old_members = {
                row[0]
                for row in self._conn.execute(
                    "SELECT source_id FROM scopes WHERE collection=? AND scope=?",
                    (collection, scope),
                )
            }
            other_members = {
                row[0]
                for row in self._conn.execute(
                    "SELECT source_id FROM scopes WHERE collection=? AND scope<>?",
                    (collection, scope),
                )
            }
            deleted.update(old_members - set(desired) - other_members)
        if (
            current
            and (
                current["model"],
                current["preprocessing"],
                bool(current["contextualized"]),
            )
            != (model_revision, preprocessing_revision, use_contextualized_text)
            and known_sources - set(desired) - deleted
        ):
            raise IndexConflictError(
                "Policy changes require all existing sources or a new collection"
            )
        affected = set(desired) | deleted
        removed = tuple(
            sorted(
                identifier
                for identifier, record in previous.items()
                if record.source_id in affected and identifier not in new_records
            )
        )
        added, metadata, invalidated, unchanged = [], [], [], []
        upserts = []
        for identifier, record in sorted(new_records.items()):
            old = previous.get(identifier)
            if old is None:
                added.append(identifier)
            elif old.embedding_key != record.embedding_key:
                invalidated.append(identifier)
            elif old != record:
                metadata.append(identifier)
            else:
                unchanged.append(identifier)
                continue
            upserts.append(record)
        result = IndexPlan(
            collection,
            target_id,
            current["generation"] if current else 0,
            model_revision,
            preprocessing_revision,
            use_contextualized_text,
            tuple(sorted((key, value.revision) for key, value in desired.items())),
            tuple(sorted(deleted)),
            tuple(upserts),
            removed,
            tuple(added),
            tuple(metadata),
            tuple(invalidated),
            tuple(unchanged),
            scope,
            complete_scope,
            tuple(sorted(desired)) if scope else (),
        )
        result = replace(result, plan_id=digest(result._body()))
        return IndexPlan.from_json(result.to_json())

enqueue(plan)

Persist a validated plan and its outbox atomically; safe to retry.

Source code in src/omnichunk/indexing/journal.py
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
def enqueue(self, plan: IndexPlan) -> str:
    """Persist a validated plan and its outbox atomically; safe to retry."""
    body = plan.to_json()
    plan = IndexPlan.from_json(body)
    with self._transaction(write=True):
        existing = self._conn.execute(
            "SELECT body FROM plans WHERE id=?", (plan.plan_id,)
        ).fetchone()
        if existing:
            if existing[0] != body:
                raise IndexConflictError("Plan ID already exists with different contents")
            return plan.plan_id
        current = self._conn.execute(
            "SELECT * FROM collections WHERE name=?", (plan.collection,)
        ).fetchone()
        if (current["generation"] if current else 0) != plan.base_generation:
            raise IndexConflictError("Stale plan generation; create a new plan")
        if current and current["target_id"] != plan.target_id:
            raise IndexConflictError("Collection is bound to a different target_id")
        if self._conn.execute(
            "SELECT 1 FROM plans WHERE collection=? AND done=0", (plan.collection,)
        ).fetchone():
            raise IndexConflictError("A collection plan is already pending")
        self._validate_transition(plan)
        if not current:
            self._conn.execute(
                "INSERT INTO collections(name,target_id,model,preprocessing,contextualized) "
                "VALUES(?,?,?,?,?)",
                (
                    plan.collection,
                    plan.target_id,
                    plan.model_revision,
                    plan.preprocessing_revision,
                    int(plan.use_contextualized_text),
                ),
            )
        self._conn.execute(
            "INSERT INTO plans(id,collection,body) VALUES(?,?,?)",
            (plan.plan_id, plan.collection, body),
        )
        operations: list[tuple[str, str, str | None]] = [
            ("delete", identifier, None) for identifier in plan.removed_ids
        ]
        operations.extend(
            ("upsert", record.id, canonical_json(asdict(record))) for record in plan.upserts
        )
        for sequence, (kind, identifier, record_body) in enumerate(operations):
            self._conn.execute(
                "INSERT INTO operations(plan_id,sequence,operation_id,kind,record_id,body) "
                "VALUES(?,?,?,?,?,?)",
                (
                    plan.plan_id,
                    sequence,
                    digest([plan.plan_id, kind, identifier]),
                    kind,
                    identifier,
                    record_body,
                ),
            )
        if not operations:
            self._finish(plan)
    return plan.plan_id

deliver(sink, embed=None, *, collection='default', batch_size=64, max_batches=None, retry_failed=False)

Deliver bounded batches; exact acknowledgements checkpoint durable work.

A remote success followed by a crash is replayed. Prepared vectors were committed before remote I/O, so recovery reuses them. Unknown failures require explicit retry_failed=True; retryable failures remain eligible. This method does not sleep or promise distributed exactly-once delivery.

Source code in src/omnichunk/indexing/journal.py
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
def deliver(
    self,
    sink: IndexSink,
    embed: Callable[[Sequence[str]], Sequence[Sequence[float]]] | None = None,
    *,
    collection: str = "default",
    batch_size: int = 64,
    max_batches: int | None = None,
    retry_failed: bool = False,
) -> DeliveryResult:
    """Deliver bounded batches; exact acknowledgements checkpoint durable work.

    A remote success followed by a crash is replayed. Prepared vectors were
    committed before remote I/O, so recovery reuses them. Unknown failures
    require explicit ``retry_failed=True``; retryable failures remain eligible.
    This method does not sleep or promise distributed exactly-once delivery.
    """
    name(collection, "collection")
    name(sink.target_id, "sink.target_id")
    if (
        type(batch_size) is not int
        or batch_size <= 0
        or (max_batches is not None and (type(max_batches) is not int or max_batches <= 0))
        or type(retry_failed) is not bool
    ):
        raise ValueError("Invalid delivery batch/retry limits")
    acknowledged = calls = reused = batches = 0
    active_id: str | None = None
    fresh: set[str] = set()
    while max_batches is None or batches < max_batches:
        failed: Exception | None = None
        with self._transaction(write=True):
            state = self._conn.execute(
                "SELECT * FROM collections WHERE name=?", (collection,)
            ).fetchone()
            if state and state["target_id"] != sink.target_id:
                raise IndexConflictError("Sink target_id differs from the collection binding")
            pending = self._conn.execute(
                "SELECT * FROM plans WHERE collection=? AND done=0", (collection,)
            ).fetchone()
            if pending is None:
                return DeliveryResult(active_id, acknowledged, 0, True, calls, reused)
            active_id = pending["id"]
            if pending["error"] and not pending["retryable"] and not retry_failed:
                raise PermanentSinkError(
                    f"Pending delivery requires retry_failed=True: {pending['error']}"
                )
            plan = IndexPlan.from_json(pending["body"])
            operations = self._conn.execute(
                "SELECT * FROM operations WHERE plan_id=? AND acked=0 "
                "ORDER BY sequence LIMIT ?",
                (active_id, batch_size),
            ).fetchall()
            records = [_record(row["body"]) for row in operations if row["kind"] == "upsert"]
            cached: dict[str, tuple[float, ...]] = {}
            missing: dict[str, str] = {}
            self._conn.execute("SAVEPOINT delivery_batch")
            try:
                for record in records:
                    row = self._conn.execute(
                        "SELECT vector FROM embeddings WHERE collection=? AND fingerprint=?",
                        (collection, record.embedding_key),
                    ).fetchone()
                    if row:
                        cached[record.embedding_key] = vector_values(
                            json.loads(row[0]), state["dimension"]
                        )
                    else:
                        missing[record.embedding_key] = record.text
                if missing:
                    if embed is None:
                        raise ValueError(
                            "An embedding callback is required for uncached payloads"
                        )
                    calls += 1
                    values = list(embed(list(missing.values())))
                    if len(values) != len(missing):
                        raise ValueError(
                            "Embedding callback returned the wrong number of vectors"
                        )
                    vectors = []
                    dimension = state["dimension"]
                    for value in values:
                        vector = vector_values(value, dimension)
                        dimension = dimension or len(vector)
                        vectors.append(vector)
                    for fingerprint, vector in zip(missing, vectors):
                        self._conn.execute(
                            "INSERT OR REPLACE INTO embeddings(collection,fingerprint,vector) "
                            "VALUES(?,?,?)",
                            (collection, fingerprint, canonical_json(vector)),
                        )
                        fresh.add(fingerprint)
                    self._conn.execute(
                        "UPDATE collections SET dimension=? WHERE name=?",
                        (dimension, collection),
                    )
                    # Commit preparation before a separate transaction reselects
                    # pending work. Another worker may already deliver it.
                    continue
                operation_ids = tuple(row["operation_id"] for row in operations)
                batch = DeliveryBatch(
                    collection,
                    sink.target_id,
                    digest([active_id, operation_ids]),
                    tuple(
                        VectorRecord(
                            record.id,
                            record.source_id,
                            record.source_revision,
                            record.text,
                            record.metadata,
                            cached[record.embedding_key],
                        )
                        for record in records
                    ),
                    tuple(row["record_id"] for row in operations if row["kind"] == "delete"),
                    operation_ids,
                )
                receipt = sink.apply(batch)
                if (
                    not isinstance(receipt, DeliveryReceipt)
                    or receipt.idempotency_key != batch.idempotency_key
                    or receipt.operation_ids != operation_ids
                ):
                    raise AcknowledgementError(
                        "Sink receipt must match the submitted operation IDs and key"
                    )
                self._conn.executemany(
                    "UPDATE operations SET acked=1 WHERE plan_id=? AND operation_id=?",
                    [(active_id, key) for key in operation_ids],
                )
                self._conn.execute(
                    "UPDATE plans SET error=NULL,retryable=1 WHERE id=?", (active_id,)
                )
                acknowledged += len(operations)
                reused += sum(record.embedding_key not in fresh for record in records)
                batches += 1
                remaining = self._conn.execute(
                    "SELECT COUNT(*) FROM operations WHERE plan_id=? AND acked=0", (active_id,)
                ).fetchone()[0]
                if not remaining:
                    self._finish(plan)
                    return DeliveryResult(active_id, acknowledged, 0, True, calls, reused)
            except Exception as exc:
                self._conn.execute("ROLLBACK TO delivery_batch")
                self._conn.execute("RELEASE delivery_batch")
                self._conn.execute(
                    "UPDATE plans SET error=?,retryable=? WHERE id=?",
                    (
                        f"{type(exc).__name__}: {exc}",
                        int(isinstance(exc, RetryableSinkError)),
                        active_id,
                    ),
                )
                failed = exc
        if failed is not None:
            raise failed
    status = self.status(collection=collection)
    return DeliveryResult(
        active_id,
        acknowledged,
        status.pending_operations,
        status.pending_plan_id is None,
        calls,
        reused,
    )

prune_embeddings(*, collection='default')

Remove vectors unused by acknowledged records; reject pending plans.

Source code in src/omnichunk/indexing/journal.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
def prune_embeddings(self, *, collection: str = "default") -> int:
    """Remove vectors unused by acknowledged records; reject pending plans."""
    name(collection, "collection")
    with self._transaction(write=True):
        if self._conn.execute(
            "SELECT 1 FROM plans WHERE collection=? AND done=0", (collection,)
        ).fetchone():
            raise IndexConflictError("Cannot prune embeddings while delivery is pending")
        keep = {record.embedding_key for record in self.records(collection=collection)}
        stale = [
            row[0]
            for row in self._conn.execute(
                "SELECT fingerprint FROM embeddings WHERE collection=?", (collection,)
            )
            if row[0] not in keep
        ]
        self._conn.executemany(
            "DELETE FROM embeddings WHERE collection=? AND fingerprint=?",
            [(collection, key) for key in stale],
        )
        return len(stale)

omnichunk.indexing.IndexSource dataclass

Source code in src/omnichunk/indexing/models.py
 98
 99
100
101
102
103
@dataclass(frozen=True)
class IndexSource:
    source_id: str
    revision: str
    chunks: tuple[Chunk, ...]
    metadata: dict[str, Any] = field(default_factory=dict)

omnichunk.indexing.IndexPlan dataclass

Source code in src/omnichunk/indexing/models.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
@dataclass(frozen=True)
class IndexPlan:
    collection: str
    target_id: str
    base_generation: int
    model_revision: str
    preprocessing_revision: str
    use_contextualized_text: bool
    source_revisions: tuple[tuple[str, str], ...]
    deleted_sources: tuple[str, ...]
    upserts: tuple[IndexRecord, ...]
    removed_ids: tuple[str, ...]
    added_ids: tuple[str, ...]
    metadata_update_ids: tuple[str, ...]
    embedding_invalidations: tuple[str, ...]
    unchanged_ids: tuple[str, ...]
    scope: str | None = None
    complete_scope: bool = False
    scope_source_ids: tuple[str, ...] = ()
    plan_id: str = ""
    schema_version: int = 1

    def _body(self) -> dict[str, Any]:
        result = asdict(self)
        result.pop("plan_id")
        return result

    def to_json(self) -> str:
        """Serialize an integrity-checked plan; post-creation mutation is rejected."""
        value = {**self._body(), "plan_id": self.plan_id}
        self.from_dict(value)
        return canonical_json(value)

    @classmethod
    def from_json(cls, value: str) -> IndexPlan:
        def pairs(items: list[tuple[str, Any]]) -> dict[str, Any]:
            result: dict[str, Any] = {}
            for key, item in items:
                if key in result:
                    raise ValueError("Duplicate plan JSON key")
                result[key] = item
            return result

        return cls.from_dict(json.loads(value, object_pairs_hook=pairs))

    @classmethod
    def from_dict(cls, value: Any) -> IndexPlan:
        value = json_value(value)
        if not isinstance(value, dict) or set(value) != set(cls.__dataclass_fields__):
            raise ValueError("Invalid index plan fields")
        if type(value["schema_version"]) is not int or value["schema_version"] != 1:
            raise ValueError("Unsupported index plan schema")
        for key in (
            "collection",
            "target_id",
            "model_revision",
            "preprocessing_revision",
            "plan_id",
        ):
            name(value[key], key)
        if type(value["base_generation"]) is not int or value["base_generation"] < 0:
            raise ValueError("Invalid plan generation")
        for key in ("use_contextualized_text", "complete_scope"):
            if type(value[key]) is not bool:
                raise ValueError(f"{key} must be a boolean")
        if value["scope"] is not None:
            name(value["scope"], "scope")
        elif value["complete_scope"] or value["scope_source_ids"]:
            raise ValueError("Scope membership requires a scope")
        source_revisions = value["source_revisions"]
        if not isinstance(source_revisions, list):
            raise ValueError("Invalid source revisions")
        sources: dict[str, str] = {}
        for pair in source_revisions:
            if not isinstance(pair, list) or len(pair) != 2:
                raise ValueError("Invalid source revision pair")
            source, revision = name(pair[0], "source_id"), name(pair[1], "revision")
            if source in sources:
                raise ValueError("Duplicate source ID")
            sources[source] = revision
        tuple_fields = (
            "deleted_sources",
            "removed_ids",
            "added_ids",
            "metadata_update_ids",
            "embedding_invalidations",
            "unchanged_ids",
            "scope_source_ids",
        )
        for key in tuple_fields:
            items = value[key]
            if (
                not isinstance(items, list)
                or any(not isinstance(item, str) or not item.strip() for item in items)
                or len(set(items)) != len(items)
            ):
                raise ValueError(f"Invalid or duplicate {key}")
            value[key] = tuple(items)
        if set(sources) & set(value["deleted_sources"]):
            raise ValueError("A source cannot be updated and deleted in one plan")
        if set(value["scope_source_ids"]) != (set(sources) if value["scope"] else set()):
            raise ValueError("Scope source membership differs from updated sources")
        records = []
        if not isinstance(value["upserts"], list):
            raise ValueError("Invalid upserts")
        ids: set[str] = set()
        for raw in value["upserts"]:
            if not isinstance(raw, dict) or set(raw) != set(IndexRecord.__dataclass_fields__):
                raise ValueError("Invalid index record fields")
            for key in ("id", "source_id", "source_revision", "embedding_key"):
                name(raw[key], key)
            if not isinstance(raw["text"], str) or not isinstance(raw["metadata"], dict):
                raise ValueError("Invalid index record payload")
            if raw["id"] in ids or sources.get(raw["source_id"]) != raw["source_revision"]:
                raise ValueError("Duplicate record or mismatched source ownership")
            if raw["embedding_key"] != embedding_key(
                raw["text"], value["model_revision"], value["preprocessing_revision"]
            ):
                raise ValueError("Embedding fingerprint does not match the payload")
            ids.add(raw["id"])
            records.append(IndexRecord(**raw))
        categories = [
            set(value[key])
            for key in ("added_ids", "metadata_update_ids", "embedding_invalidations")
        ]
        if set().union(*categories) != ids or sum(map(len, categories)) != len(ids):
            raise ValueError("Upsert classifications must partition the upserts")
        if (ids & (set(value["removed_ids"]) | set(value["unchanged_ids"]))) or (
            set(value["removed_ids"]) & set(value["unchanged_ids"])
        ):
            raise ValueError("Record actions overlap")
        plan_id = value.pop("plan_id")
        if digest(value) != plan_id:
            raise ValueError("Index plan digest does not match its contents")
        value["upserts"] = tuple(records)
        value["source_revisions"] = tuple(tuple(pair) for pair in source_revisions)
        return cls(**value, plan_id=plan_id)

to_json()

Serialize an integrity-checked plan; post-creation mutation is rejected.

Source code in src/omnichunk/indexing/models.py
196
197
198
199
200
def to_json(self) -> str:
    """Serialize an integrity-checked plan; post-creation mutation is rejected."""
    value = {**self._body(), "plan_id": self.plan_id}
    self.from_dict(value)
    return canonical_json(value)

omnichunk.indexing.IndexRecord dataclass

Source code in src/omnichunk/indexing/models.py
106
107
108
109
110
111
112
113
@dataclass(frozen=True)
class IndexRecord:
    id: str
    source_id: str
    source_revision: str
    text: str
    metadata: dict[str, Any]
    embedding_key: str

omnichunk.indexing.VectorRecord dataclass

Source code in src/omnichunk/indexing/models.py
116
117
118
119
120
121
122
123
@dataclass(frozen=True)
class VectorRecord:
    id: str
    source_id: str
    source_revision: str
    text: str
    metadata: dict[str, Any]
    embedding: tuple[float, ...]

omnichunk.indexing.DeliveryBatch dataclass

Source code in src/omnichunk/indexing/models.py
126
127
128
129
130
131
132
133
@dataclass(frozen=True)
class DeliveryBatch:
    collection: str
    target_id: str
    idempotency_key: str
    upserts: tuple[VectorRecord, ...]
    deletes: tuple[str, ...]
    operation_ids: tuple[str, ...]

omnichunk.indexing.DeliveryReceipt dataclass

Source code in src/omnichunk/indexing/models.py
136
137
138
139
@dataclass(frozen=True)
class DeliveryReceipt:
    idempotency_key: str
    operation_ids: tuple[str, ...]

omnichunk.indexing.DeliveryResult dataclass

Source code in src/omnichunk/indexing/models.py
159
160
161
162
163
164
165
166
@dataclass(frozen=True)
class DeliveryResult:
    plan_id: str | None
    acknowledged: int
    pending: int
    completed: bool
    embedding_calls: int
    reused_embeddings: int

omnichunk.indexing.IndexStatus dataclass

Source code in src/omnichunk/indexing/models.py
148
149
150
151
152
153
154
155
156
@dataclass(frozen=True)
class IndexStatus:
    collection: str
    generation: int
    pending_plan_id: str | None
    pending_operations: int
    acknowledged_operations: int
    last_error: str | None
    retryable: bool

omnichunk.indexing.IndexSink

Bases: Protocol

Source code in src/omnichunk/indexing/models.py
142
143
144
145
class IndexSink(Protocol):
    target_id: str

    def apply(self, batch: DeliveryBatch) -> DeliveryReceipt: ...

omnichunk.indexing.IndexConflictError

Bases: ValueError

A plan no longer matches the collection generation or pending delivery.

Source code in src/omnichunk/indexing/models.py
16
17
class IndexConflictError(ValueError):
    """A plan no longer matches the collection generation or pending delivery."""

omnichunk.indexing.JournalSchemaError

Bases: ValueError

The database is not a supported indexing journal.

Source code in src/omnichunk/indexing/models.py
20
21
class JournalSchemaError(ValueError):
    """The database is not a supported indexing journal."""

omnichunk.indexing.RetryableSinkError

Bases: RuntimeError

Delivery failed transiently and can be retried by the next deliver call.

Source code in src/omnichunk/indexing/models.py
24
25
class RetryableSinkError(RuntimeError):
    """Delivery failed transiently and can be retried by the next deliver call."""

omnichunk.indexing.PermanentSinkError

Bases: RuntimeError

Delivery needs intervention before an explicit retry_failed=True call.

Source code in src/omnichunk/indexing/models.py
28
29
class PermanentSinkError(RuntimeError):
    """Delivery needs intervention before an explicit retry_failed=True call."""

omnichunk.indexing.AcknowledgementError

Bases: PermanentSinkError

A sink did not acknowledge exactly the submitted batch.

Source code in src/omnichunk/indexing/models.py
32
33
class AcknowledgementError(PermanentSinkError):
    """A sink did not acknowledge exactly the submitted batch."""

Backend and framework adapters

QdrantSink(client, *, target_id, collection_name, dimensions) uses a caller-configured Qdrant client and an existing physical collection. PgvectorSink accepts a caller-owned connection, target_id, dimensions and optional SQL table (default "omnichunk_vectors"); call initialize() explicitly with an idle connection and sufficient database privileges. Both require a positive vector dimension. Qdrant retrieval should filter by logical collection and application-owned access metadata. The guide includes setup recipes.

omnichunk.indexing.sinks.QdrantSink

Write to a caller-provisioned Qdrant collection using qdrant-client 1.x.

The collection must have a single unnamed dense vector of dimensions. Logical index collections share the physical collection safely through UUID mapping. Retrieval must filter both collection and caller-owned access attributes, for example metadata.acl. target_id must permanently identify this endpoint and physical collection in the application's journal. If one ID occurs in both deletes and upserts, deletion precedes replacement.

Source code in src/omnichunk/indexing/sinks.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
class QdrantSink:
    """Write to a caller-provisioned Qdrant collection using qdrant-client 1.x.

    The collection must have a single unnamed dense vector of ``dimensions``.
    Logical index collections share the physical collection safely through UUID
    mapping. Retrieval must filter both ``collection`` and caller-owned access
    attributes, for example ``metadata.acl``. ``target_id`` must permanently
    identify this endpoint and physical collection in the application's journal.
    If one ID occurs in both deletes and upserts, deletion precedes replacement.
    """

    def __init__(
        self, client: Any, *, target_id: str, collection_name: str, dimensions: int
    ) -> None:
        self.client = client
        self.target_id = _name(target_id, "target_id")
        self.collection_name = _name(collection_name, "collection_name")
        self.dimensions = _dimension(dimensions)

    def apply(self, batch: DeliveryBatch) -> DeliveryReceipt:
        _validate_batch(batch, self.target_id, self.dimensions)
        models = importlib.import_module("qdrant_client.models")
        # Validate/construct every point before any deletion is sent.
        points = [
            models.PointStruct(
                id=qdrant_point_id(batch.collection, record.id),
                vector=[float(value) for value in record.embedding],
                payload={
                    "collection": batch.collection,
                    "record_id": record.id,
                    "source_id": record.source_id,
                    "source_revision": record.source_revision,
                    "text": record.text,
                    "metadata": _json_copy(record.metadata),
                },
            )
            for record in batch.upserts
        ]
        try:
            if batch.deletes:
                result = self.client.delete(
                    collection_name=self.collection_name,
                    points_selector=models.PointIdsList(
                        points=[qdrant_point_id(batch.collection, key) for key in batch.deletes]
                    ),
                    wait=True,
                )
                self._require_completed(result)
            if points:
                result = self.client.upsert(
                    collection_name=self.collection_name, points=points, wait=True
                )
                self._require_completed(result)
        except Exception as exc:
            if isinstance(exc, (RetryableSinkError, PermanentSinkError)):
                raise
            raise _delivery_error(exc, "Qdrant") from exc
        return DeliveryReceipt(batch.idempotency_key, batch.operation_ids)

    @staticmethod
    def _require_completed(result: Any) -> None:
        status = getattr(result, "status", None)
        if getattr(status, "value", status) != "completed":
            raise RetryableSinkError("Qdrant did not confirm completed durable operations")

omnichunk.indexing.sinks.PgvectorSink

Commit collection-scoped writes through a caller-owned psycopg 3 connection.

Call initialize() explicitly to create the vector extension and table. The connection must be idle at entry so a receipt cannot precede an outer transaction's commit. Use autocommit connections for application reads. target_id must identify the database/schema/table in the journal.

Source code in src/omnichunk/indexing/sinks.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
class PgvectorSink:
    """Commit collection-scoped writes through a caller-owned psycopg 3 connection.

    Call ``initialize()`` explicitly to create the vector extension and table.
    The connection must be idle at entry so a receipt cannot precede an outer
    transaction's commit. Use autocommit connections for application reads.
    ``target_id`` must identify the database/schema/table in the journal.
    """

    def __init__(
        self,
        connection: Any,
        *,
        target_id: str,
        dimensions: int,
        table: str = "omnichunk_vectors",
    ) -> None:
        self.connection = connection
        self.target_id = _name(target_id, "target_id")
        self.dimensions = _dimension(dimensions)
        if not isinstance(table, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]{0,62}", table):
            raise ValueError("table must be an unqualified SQL identifier of at most 63 characters")
        self.table = table

    def _require_idle(self) -> None:
        # psycopg.pq.TransactionStatus.IDLE has value zero.
        if self.connection.info.transaction_status != 0:
            raise PermanentSinkError("Pgvector delivery requires an idle connection")

    def initialize(self) -> None:
        """Explicitly provision the extension/table; requires database privileges."""
        self._require_idle()
        sql = importlib.import_module("psycopg.sql")
        with self.connection.transaction():
            self.connection.execute("CREATE EXTENSION IF NOT EXISTS vector")
            self.connection.execute(
                sql.SQL(
                    "CREATE TABLE IF NOT EXISTS {} ("
                    "collection TEXT NOT NULL, id TEXT NOT NULL, source_id TEXT NOT NULL, "
                    "source_revision TEXT NOT NULL, text TEXT NOT NULL, metadata JSONB NOT NULL, "
                    "embedding vector({}) NOT NULL, PRIMARY KEY (collection, id))"
                ).format(sql.Identifier(self.table), sql.Literal(self.dimensions))
            )

    def apply(self, batch: DeliveryBatch) -> DeliveryReceipt:
        _validate_batch(batch, self.target_id, self.dimensions)
        self._require_idle()
        sql = importlib.import_module("psycopg.sql")
        # Build JSON/vector parameters before opening the remote transaction.
        rows = [
            (
                batch.collection,
                record.id,
                record.source_id,
                record.source_revision,
                record.text,
                json.dumps(_json_copy(record.metadata), ensure_ascii=False, allow_nan=False),
                "[" + ",".join(str(float(value)) for value in record.embedding) + "]",
            )
            for record in batch.upserts
        ]
        try:
            with self.connection.transaction():
                if batch.deletes:
                    self.connection.execute(
                        sql.SQL("DELETE FROM {} WHERE collection = %s AND id = ANY(%s)").format(
                            sql.Identifier(self.table)
                        ),
                        (batch.collection, list(batch.deletes)),
                    )
                if rows:
                    with self.connection.cursor() as cursor:
                        cursor.executemany(
                            sql.SQL(
                                "INSERT INTO {} (collection,id,source_id,source_revision,text,"
                                "metadata,embedding) VALUES (%s,%s,%s,%s,%s,%s::jsonb,%s::vector) "
                                "ON CONFLICT (collection,id) DO UPDATE SET "
                                "source_id=EXCLUDED.source_id,source_revision=EXCLUDED.source_revision,"
                                "text=EXCLUDED.text,metadata=EXCLUDED.metadata,embedding=EXCLUDED.embedding"
                            ).format(sql.Identifier(self.table)),
                            rows,
                        )
        except Exception as exc:
            raise _delivery_error(exc, "pgvector") from exc
        return DeliveryReceipt(batch.idempotency_key, batch.operation_ids)

initialize()

Explicitly provision the extension/table; requires database privileges.

Source code in src/omnichunk/indexing/sinks.py
221
222
223
224
225
226
227
228
229
230
231
232
233
234
def initialize(self) -> None:
    """Explicitly provision the extension/table; requires database privileges."""
    self._require_idle()
    sql = importlib.import_module("psycopg.sql")
    with self.connection.transaction():
        self.connection.execute("CREATE EXTENSION IF NOT EXISTS vector")
        self.connection.execute(
            sql.SQL(
                "CREATE TABLE IF NOT EXISTS {} ("
                "collection TEXT NOT NULL, id TEXT NOT NULL, source_id TEXT NOT NULL, "
                "source_revision TEXT NOT NULL, text TEXT NOT NULL, metadata JSONB NOT NULL, "
                "embedding vector({}) NOT NULL, PRIMARY KEY (collection, id))"
            ).format(sql.Identifier(self.table), sql.Literal(self.dimensions))
        )

omnichunk.indexing.sinks.qdrant_point_id(collection, record_id)

Map a logical collection/record pair to the UUID used for writes/deletes.

Source code in src/omnichunk/indexing/sinks.py
24
25
26
def qdrant_point_id(collection: str, record_id: str) -> str:
    """Map a logical collection/record pair to the UUID used for writes/deletes."""
    return str(uuid5(NAMESPACE_URL, json.dumps(["omnichunk-index-v1", collection, record_id])))

Framework adapters require their respective optional dependencies. OmniChunkTextSplitter and OmniChunkNodeParser accept an options mapping with the same chunk options, filepath="document.txt", optional levels for hierarchical output, and use_contextualized_text=False to select raw text by default. The LlamaIndex parser requires JSON-serializable options and does not support id_func. OmniChunkIngestionPipeline accepts LlamaIndex pipeline arguments and requires OmniChunkNodeParser as its first transformation; it creates one by default. See the framework guide for document identities, caching and complete examples.

omnichunk.integrations.langchain.OmniChunkTextSplitter

Bases: TextSplitter

Split source documents once while preserving IDs, metadata and citations.

options are ordinary Chunker options. levels optionally emits all hierarchy levels with links in reserved metadata['omnichunk']. Supply document IDs or per-document source_id metadata for identity across edits. Without them, inline text uses a content-hash identity. Raw text is the default; contextualized output is explicit and its source ranges still address raw text.

Source code in src/omnichunk/integrations/langchain.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
class OmniChunkTextSplitter(TextSplitter):
    """Split source documents once while preserving IDs, metadata and citations.

    ``options`` are ordinary Chunker options. ``levels`` optionally emits all
    hierarchy levels with links in reserved ``metadata['omnichunk']``. Supply
    document IDs or per-document ``source_id`` metadata for identity across edits.
    Without them, inline text uses a content-hash identity. Raw text is the default;
    contextualized output is explicit and its source ranges still address raw text.
    """

    def __init__(
        self,
        *,
        options: dict[str, Any] | None = None,
        filepath: str = "document.txt",
        use_contextualized_text: bool = False,
        levels: list[int] | None = None,
    ) -> None:
        super().__init__(chunk_overlap=0, strip_whitespace=False)
        # Tokenizer/model callbacks remain caller-owned, as with Chunker itself.
        self.options = dict(options or {})
        self.filepath = filepath
        self.use_contextualized_text = use_contextualized_text
        self.levels = list(levels) if levels is not None else None

    def split_text(self, text: str) -> list[str]:
        return [doc.page_content for doc in self.create_documents([text])]

    def create_documents(
        self, texts: list[str], metadatas: list[dict[Any, Any]] | None = None
    ) -> list[Document]:
        if metadatas is not None and len(texts) != len(metadatas):
            raise ValueError("texts and metadatas must have equal lengths")
        return self.split_documents(
            Document(page_content=text, metadata=metadatas[i] if metadatas is not None else {})
            for i, text in enumerate(texts)
        )

    def split_documents(self, documents: Iterable[Document]) -> list[Document]:
        result = []
        for document in documents:
            items = split_source(
                document.page_content,
                document.metadata,
                document.id,
                options=self.options,
                filepath=self.filepath,
                levels=self.levels,
            )
            for item in items:
                content = (
                    item.chunk.contextualized_text
                    if self.use_contextualized_text
                    else item.chunk.text
                )
                result.append(
                    Document(id=item.node_id, page_content=content, metadata=item.metadata)
                )
        return result

omnichunk.integrations.llamaindex.OmniChunkNodeParser

Bases: NodeParser

Cacheable native parser with exact citations and optional hierarchy.

Options must be JSON serializable for ingestion cache identity. Use named tokenizers rather than callbacks. Metadata remains available to filtering but is excluded from model rendering; embedding input is exactly the selected raw/contextualized payload. Metadata storage does not enforce authorization.

Source code in src/omnichunk/integrations/llamaindex.py
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
class OmniChunkNodeParser(NodeParser):
    """Cacheable native parser with exact citations and optional hierarchy.

    Options must be JSON serializable for ingestion cache identity. Use named
    tokenizers rather than callbacks. Metadata remains available to filtering but
    is excluded from model rendering; embedding input is exactly the selected
    raw/contextualized payload. Metadata storage does not enforce authorization.
    """

    options: dict[str, Any] = Field(default_factory=dict)
    filepath: str = "document.txt"
    use_contextualized_text: bool = False
    levels: list[int] | None = None
    adapter_revision: str = "omnichunk-native-v1"

    def __init__(self, **data: Any) -> None:
        if "id_func" in data:
            raise ValueError("OmniChunk manages stable node IDs; id_func is not supported")
        options = data.get("options", {})
        try:
            json.dumps(options, allow_nan=False)
        except (TypeError, ValueError) as exc:
            raise ValueError(
                "Parser options must be JSON serializable for ingestion caching"
            ) from exc
        super().__init__(**data)

    @classmethod
    def class_name(cls) -> str:
        return "OmniChunkNodeParser"

    def to_dict(self, **kwargs: Any) -> dict[str, Any]:
        # Configuration can be mutated through Pydantic fields after construction.
        # Revalidate before constructing the ingestion cache's transform key.
        try:
            json.dumps(self.options, allow_nan=False)
        except (TypeError, ValueError) as exc:
            raise ValueError(
                "Parser options must be JSON serializable for ingestion caching"
            ) from exc
        data = super().to_dict(**kwargs)
        # IDs are produced from source/chunk identity, not NodeParser.id_func.
        # Its default callable does not round-trip across LlamaIndex versions.
        data.pop("id_func", None)
        return data

    def _parse_nodes(
        self, nodes: Sequence[BaseNode], show_progress: bool = False, **kwargs: Any
    ) -> list[BaseNode]:
        result: list[BaseNode] = []
        for source in nodes:
            identity = source.metadata.get(_INGESTION_IDENTITY)
            if _INGESTION_IDENTITY in source.metadata and (
                not isinstance(identity, dict)
                or set(identity) != {"fingerprint", "source_hash"}
                or not all(isinstance(value, str) for value in identity.values())
            ):
                raise ValueError(f"Reserved ingestion metadata key: {_INGESTION_IDENTITY}")
            source_metadata = {
                key: value for key, value in source.metadata.items() if key != _INGESTION_IDENTITY
            }
            items = split_source(
                source.get_content(metadata_mode=MetadataMode.NONE),
                source_metadata,
                source.node_id,
                options=self.options,
                filepath=self.filepath,
                levels=self.levels,
            )
            groups: dict[int, list[TextNode]] = {}
            for item in items:
                payload = (
                    item.chunk.contextualized_text
                    if self.use_contextualized_text
                    else item.chunk.text
                )
                # SOURCE points to the original framework document. Logical
                # OmniChunk source_id may be independently caller-selected.
                source_info = deepcopy(source.as_related_node_info())
                source_info.metadata.pop(_INGESTION_IDENTITY, None)
                if isinstance(identity, dict):
                    source_info.hash = identity["source_hash"]
                relationships: dict[NodeRelationship, RelatedNodeInfo | list[RelatedNodeInfo]] = {
                    NodeRelationship.SOURCE: source_info
                }
                if item.parent_id is not None:
                    relationships[NodeRelationship.PARENT] = RelatedNodeInfo(node_id=item.parent_id)
                if item.children:
                    relationships[NodeRelationship.CHILD] = [
                        RelatedNodeInfo(node_id=x) for x in item.children
                    ]
                metadata = (
                    item.metadata
                    if self.include_metadata
                    else {"omnichunk": item.metadata["omnichunk"]}
                )
                node = TextNode(
                    id_=item.node_id,
                    text=payload,
                    metadata=metadata,
                    relationships=relationships,
                    start_char_idx=item.char_start,
                    end_char_idx=item.char_end,
                    excluded_embed_metadata_keys=list(metadata),
                    excluded_llm_metadata_keys=list(metadata),
                )
                groups.setdefault(item.level, []).append(node)
                result.append(node)
            if self.include_prev_next_rel:
                for group in groups.values():
                    for i, node in enumerate(group):
                        if i:
                            node.relationships[NodeRelationship.PREVIOUS] = RelatedNodeInfo(
                                node_id=group[i - 1].node_id
                            )
                        if i + 1 < len(group):
                            node.relationships[NodeRelationship.NEXT] = RelatedNodeInfo(
                                node_id=group[i + 1].node_id
                            )
        return result

    def _postprocess_parsed_nodes(
        self, nodes: list[BaseNode], parent_doc_map: dict[str, Document]
    ) -> list[BaseNode]:
        # The base implementation searches rendered text in the source and adds
        # cross-level adjacency. Exact source indices/relationships are set above.
        return nodes

omnichunk.integrations.llamaindex.OmniChunkIngestionPipeline

Bases: IngestionPipeline

Native pipeline whose cache distinguishes identical text from different sources.

LlamaIndex's ordinary cache key excludes document IDs and can return another document's cached citations. This pipeline copies inputs and fingerprints their complete JSON source records before cache lookup. Its first transform must be :class:OmniChunkNodeParser; subsequent transforms remain caller-owned. Internal identity metadata is removed by the parser and never embedded.

Source code in src/omnichunk/integrations/llamaindex.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
class OmniChunkIngestionPipeline(IngestionPipeline):
    """Native pipeline whose cache distinguishes identical text from different sources.

    LlamaIndex's ordinary cache key excludes document IDs and can return another
    document's cached citations. This pipeline copies inputs and fingerprints
    their complete JSON source records before cache lookup. Its first transform
    must be :class:`OmniChunkNodeParser`; subsequent transforms remain caller-owned.
    Internal identity metadata is removed by the parser and never embedded.
    """

    def __init__(self, **data: Any) -> None:
        if "transformations" not in data:
            data["transformations"] = [OmniChunkNodeParser()]
        super().__init__(**data)
        if not self.transformations or not isinstance(self.transformations[0], OmniChunkNodeParser):
            raise ValueError("OmniChunkIngestionPipeline requires OmniChunkNodeParser first")

    def _prepare_inputs(
        self, documents: Sequence[Document] | None, nodes: Sequence[BaseNode] | None
    ) -> list[BaseNode]:
        # Both run() and arun() call this before deduplication and cache lookup.
        if not self.transformations or not isinstance(self.transformations[0], OmniChunkNodeParser):
            raise ValueError("OmniChunkIngestionPipeline requires OmniChunkNodeParser first")
        result = []
        for source in super()._prepare_inputs(documents, nodes):
            if _INGESTION_IDENTITY in source.metadata:
                raise ValueError(f"Reserved ingestion metadata key: {_INGESTION_IDENTITY}")
            try:
                raw = json.dumps(
                    {"node": source.to_dict(), "native_hash": source.hash},
                    sort_keys=True,
                    separators=(",", ":"),
                    allow_nan=False,
                )
            except (TypeError, ValueError) as exc:
                raise ValueError("Ingestion source records must be finite JSON values") from exc
            copied = deepcopy(source)
            fingerprint = sha256(raw.encode("utf-8")).hexdigest()
            copied.metadata[_INGESTION_IDENTITY] = {
                "fingerprint": fingerprint,
                "source_hash": source.hash,
            }
            # A source may hide metadata with a custom text/metadata template.
            # Normalize only the private copy; raw source text remains unchanged.
            copied.metadata_template = "{key}: {value}"
            if hasattr(copied, "metadata_separator"):
                copied.metadata_separator = "\n"
            else:
                # The declared minimum LlamaIndex version uses this spelling.
                cast(Any, copied).metadata_seperator = "\n"
            if hasattr(copied, "text_template"):
                copied.text_template = "{metadata_str}\n\n{content}"
            if fingerprint not in copied.get_content(MetadataMode.ALL):
                raise ValueError("Ingestion source must expose identity metadata to the cache")
            result.append(copied)
        return result