briefcase-python 2.4.1

Python bindings for Briefcase AI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
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
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
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
"""
Versioned embedding pipeline with atomic manifests.

An EmbeddingManifest captures the complete state of an embedding index:
  - Which documents were embedded (IDs + content hashes)
  - Which model + version produced the embeddings
  - The lakeFS commit the documents came from
  - Whether the index is stale (documents or model changed)
"""

import hashlib
import json
from dataclasses import dataclass, field, asdict
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional
import logging

try:
    from opentelemetry import trace
    HAS_OTEL = True
except ImportError:
    HAS_OTEL = False

import briefcase.semantic_conventions.rag as rag_conventions  # noqa: F401

logger = logging.getLogger(__name__)


# ---------------------------------------------------------------------------
# Data classes
# ---------------------------------------------------------------------------

@dataclass
class Document:
    """Document for embedding."""
    id: str
    content: str
    metadata: dict = field(default_factory=dict)
    path: str = ""  # lakeFS path

    @property
    def content_hash(self) -> str:
        """SHA-256 of document content."""
        return hashlib.sha256(self.content.encode()).hexdigest()


@dataclass
class EmbeddingRecord:
    """Single document's embedding with provenance."""
    document_id: str
    document_hash: str  # SHA-256 of content at embed time
    embedding: List[float]
    model: str
    model_version: str
    created_at: str  # ISO-8601


@dataclass
class EmbeddingBatch:
    """Batch of embeddings."""
    batch_id: str
    model: str
    model_version: str
    dimensions: int
    embeddings: List[List[float]]
    document_ids: List[str]
    document_hashes: List[str]
    created_at: datetime
    source_commit: str

    def to_dict(self) -> Dict[str, Any]:
        d = asdict(self)
        d["created_at"] = self.created_at.isoformat()
        # Don't serialize full embeddings to JSON (too large)
        d.pop("embeddings", None)
        return d


class ManifestStatus(Enum):
    """Status of an embedding manifest."""
    CURRENT = "current"
    STALE_DOCUMENTS = "stale_documents"
    STALE_MODEL = "stale_model"
    STALE_BOTH = "stale_both"
    REBUILDING = "rebuilding"


@dataclass
class EmbeddingManifest:
    """
    Atomic manifest capturing the complete state of an embedding index.

    This is the core versioning artifact: it records exactly which documents
    were embedded, with which model, at which lakeFS commit.
    """
    manifest_id: str
    index_name: str
    model: str
    model_version: str
    dimensions: int
    source_commit: str  # lakeFS commit SHA documents came from
    document_count: int
    document_hashes: Dict[str, str]  # doc_id -> content_hash at embed time
    batch_ids: List[str]
    created_at: str  # ISO-8601
    status: str = ManifestStatus.CURRENT.value
    parent_manifest_id: Optional[str] = None
    metadata: Dict[str, Any] = field(default_factory=dict)

    def to_dict(self) -> Dict[str, Any]:
        return asdict(self)

    def to_json(self) -> str:
        return json.dumps(self.to_dict(), sort_keys=True, indent=2)

    @classmethod
    def from_dict(cls, d: Dict[str, Any]) -> "EmbeddingManifest":
        return cls(**{k: v for k, v in d.items() if k in cls.__dataclass_fields__})

    @classmethod
    def from_json(cls, s: str) -> "EmbeddingManifest":
        return cls.from_dict(json.loads(s))

    @property
    def manifest_hash(self) -> str:
        """Deterministic hash of manifest content (for integrity checking)."""
        content = json.dumps({
            "index_name": self.index_name,
            "model": self.model,
            "model_version": self.model_version,
            "source_commit": self.source_commit,
            "document_hashes": self.document_hashes,
        }, sort_keys=True)
        return hashlib.sha256(content.encode()).hexdigest()


@dataclass
class InvalidationReport:
    """Report describing why an embedding index is stale."""
    manifest_id: str
    index_name: str
    is_valid: bool
    status: str  # ManifestStatus value
    added_documents: List[str] = field(default_factory=list)
    removed_documents: List[str] = field(default_factory=list)
    changed_documents: List[str] = field(default_factory=list)
    model_changed: bool = False
    old_model: Optional[str] = None
    new_model: Optional[str] = None
    old_model_version: Optional[str] = None
    new_model_version: Optional[str] = None
    timestamp: str = field(default_factory=lambda: datetime.utcnow().isoformat())

    def to_dict(self) -> Dict[str, Any]:
        return {k: v for k, v in asdict(self).items() if v is not None}


# ---------------------------------------------------------------------------
# Pipeline
# ---------------------------------------------------------------------------

class VersionedEmbeddingPipeline:
    """
    Pipeline that creates embeddings from documents and stores them
    with atomic manifests for full version tracking.

    Usage:
        pipeline = VersionedEmbeddingPipeline(embedding_model=model)
        batch = pipeline.create_embedding_batch(documents)
        manifest = pipeline.create_manifest("my_index", [batch])
        report = pipeline.check_invalidation("my_index", current_docs)
    """

    def __init__(
        self,
        embedding_model: Any = None,
        lakefs_client: Any = None,
        repository: Optional[str] = None,
        branch: str = "main",
    ):
        self.model = embedding_model
        self.lakefs = lakefs_client
        self.repository = repository
        self.branch = branch

        # index_name -> list of EmbeddingManifest (most recent last)
        self._manifests: Dict[str, List[EmbeddingManifest]] = {}

        # batch_id -> EmbeddingBatch
        self._batches: Dict[str, EmbeddingBatch] = {}

    # ------------------------------------------------------------------
    # Embedding creation
    # ------------------------------------------------------------------

    def create_embedding_batch(
        self,
        documents: List[Document],
        batch_id: Optional[str] = None,
        source_commit: Optional[str] = None,
    ) -> EmbeddingBatch:
        """
        Create embeddings for a batch of documents.

        If self.model has an `embed(texts)` method, uses it.
        Otherwise falls back to mock embeddings.
        """
        if batch_id is None:
            batch_id = f"batch_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}"

        if source_commit is None:
            if self.lakefs and hasattr(self.lakefs, 'get_commit'):
                try:
                    source_commit = self.lakefs.get_commit()
                except Exception:
                    source_commit = "unknown"
            else:
                source_commit = "unknown"

        model_name = getattr(self.model, 'name', 'mock-model') if self.model else 'mock-model'
        model_version = getattr(self.model, 'version', '1.0') if self.model else '1.0'

        # Generate embeddings
        texts = [doc.content for doc in documents]
        if self.model and hasattr(self.model, 'embed'):
            try:
                raw_embeddings = self.model.embed(texts)
                embeddings = [list(e) for e in raw_embeddings]
            except Exception as e:
                logger.warning(f"Embedding model failed, using mock: {e}")
                embeddings = self._mock_embeddings(len(texts))
        else:
            embeddings = self._mock_embeddings(len(texts))

        dimensions = len(embeddings[0]) if embeddings else 0
        document_ids = [doc.id for doc in documents]
        document_hashes = [doc.content_hash for doc in documents]

        batch = EmbeddingBatch(
            batch_id=batch_id,
            model=model_name,
            model_version=model_version,
            dimensions=dimensions,
            embeddings=embeddings,
            document_ids=document_ids,
            document_hashes=document_hashes,
            created_at=datetime.utcnow(),
            source_commit=source_commit,
        )

        self._batches[batch_id] = batch
        logger.info(f"Created embedding batch {batch_id}: {len(documents)} docs, {dimensions}d")

        return batch

    # ------------------------------------------------------------------
    # Manifest management
    # ------------------------------------------------------------------

    def create_manifest(
        self,
        index_name: str,
        batches: List[EmbeddingBatch],
        metadata: Optional[Dict[str, Any]] = None,
    ) -> EmbeddingManifest:
        """
        Create an atomic manifest from one or more embedding batches.

        The manifest captures the full state of the index at this point.
        """
        if not batches:
            raise ValueError("At least one batch is required to create a manifest")

        # Aggregate document hashes across batches
        doc_hashes: Dict[str, str] = {}
        batch_ids = []
        total_docs = 0

        for batch in batches:
            batch_ids.append(batch.batch_id)
            for doc_id, doc_hash in zip(batch.document_ids, batch.document_hashes):
                doc_hashes[doc_id] = doc_hash
                total_docs += 1

        # Use first batch for model info (all batches should use same model)
        first = batches[0]
        source_commit = first.source_commit

        parent = self.get_latest_manifest(index_name)
        manifest_id = f"{index_name}_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}_{first.source_commit[:8]}"

        manifest = EmbeddingManifest(
            manifest_id=manifest_id,
            index_name=index_name,
            model=first.model,
            model_version=first.model_version,
            dimensions=first.dimensions,
            source_commit=source_commit,
            document_count=len(doc_hashes),
            document_hashes=doc_hashes,
            batch_ids=batch_ids,
            created_at=datetime.utcnow().isoformat(),
            status=ManifestStatus.CURRENT.value,
            parent_manifest_id=parent.manifest_id if parent else None,
            metadata=metadata or {},
        )

        self._manifests.setdefault(index_name, []).append(manifest)

        # Store to lakeFS if available
        if self.lakefs and self.repository:
            path = f"manifests/{index_name}/{manifest_id}.json"
            try:
                self.lakefs.upload_object(
                    self.repository, self.branch, path, manifest.to_json()
                )
            except Exception as e:
                logger.warning(f"Failed to upload manifest to lakeFS: {e}")

        logger.info(
            f"Created manifest {manifest_id}: {len(doc_hashes)} docs, "
            f"model={first.model}@{first.model_version}"
        )

        return manifest

    def get_latest_manifest(self, index_name: str) -> Optional[EmbeddingManifest]:
        """Get the most recent manifest for an index."""
        manifests = self._manifests.get(index_name, [])
        return manifests[-1] if manifests else None

    def get_manifests(
        self,
        index_name: str,
        limit: Optional[int] = None,
    ) -> List[EmbeddingManifest]:
        """Get manifests for an index, optionally limited."""
        manifests = self._manifests.get(index_name, [])
        if limit:
            manifests = manifests[-limit:]
        return manifests

    def get_all_index_names(self) -> List[str]:
        """List all tracked index names."""
        return list(self._manifests.keys())

    # ------------------------------------------------------------------
    # Invalidation detection
    # ------------------------------------------------------------------

    def check_invalidation(
        self,
        index_name: str,
        current_documents: List[Document],
        current_model: Optional[str] = None,
        current_model_version: Optional[str] = None,
    ) -> InvalidationReport:
        """
        Check whether an embedding index is stale.

        Compares the latest manifest against current documents and model.
        Returns an InvalidationReport describing what changed.
        """
        manifest = self.get_latest_manifest(index_name)

        if manifest is None:
            # No manifest → nothing to invalidate, but also nothing to validate
            return InvalidationReport(
                manifest_id="none",
                index_name=index_name,
                is_valid=False,
                status=ManifestStatus.STALE_DOCUMENTS.value,
                added_documents=[doc.id for doc in current_documents],
            )

        # Build current doc hash map
        current_hashes = {doc.id: doc.content_hash for doc in current_documents}
        manifest_hashes = manifest.document_hashes

        # Detect document changes
        current_ids = set(current_hashes.keys())
        manifest_ids = set(manifest_hashes.keys())

        added = sorted(current_ids - manifest_ids)
        removed = sorted(manifest_ids - current_ids)
        changed = sorted([
            doc_id for doc_id in current_ids & manifest_ids
            if current_hashes[doc_id] != manifest_hashes[doc_id]
        ])

        docs_changed = bool(added or removed or changed)

        # Detect model changes
        model_changed = False
        effective_model = current_model or (
            getattr(self.model, 'name', None) if self.model else None
        )
        effective_version = current_model_version or (
            getattr(self.model, 'version', None) if self.model else None
        )

        if effective_model and effective_model != manifest.model:
            model_changed = True
        if effective_version and effective_version != manifest.model_version:
            model_changed = True

        # Determine status
        if docs_changed and model_changed:
            status = ManifestStatus.STALE_BOTH
        elif docs_changed:
            status = ManifestStatus.STALE_DOCUMENTS
        elif model_changed:
            status = ManifestStatus.STALE_MODEL
        else:
            status = ManifestStatus.CURRENT

        is_valid = status == ManifestStatus.CURRENT

        # Update manifest status
        if not is_valid:
            manifest.status = status.value

        return InvalidationReport(
            manifest_id=manifest.manifest_id,
            index_name=index_name,
            is_valid=is_valid,
            status=status.value,
            added_documents=added,
            removed_documents=removed,
            changed_documents=changed,
            model_changed=model_changed,
            old_model=manifest.model if model_changed else None,
            new_model=effective_model if model_changed else None,
            old_model_version=manifest.model_version if model_changed else None,
            new_model_version=effective_version if model_changed else None,
        )

    def rebuild_index(
        self,
        index_name: str,
        documents: List[Document],
        source_commit: Optional[str] = None,
        batch_id: Optional[str] = None,
    ) -> EmbeddingManifest:
        """
        Rebuild an embedding index: create new embeddings and a new manifest.

        Convenience method that chains create_embedding_batch + create_manifest.
        """
        batch = self.create_embedding_batch(
            documents, batch_id=batch_id, source_commit=source_commit
        )
        manifest = self.create_manifest(index_name, [batch])
        return manifest

    # ------------------------------------------------------------------
    # Helpers
    # ------------------------------------------------------------------

    @staticmethod
    def _mock_embeddings(count: int, dimensions: int = 128) -> List[List[float]]:
        """Create mock embeddings for testing."""
        return [[0.0] * dimensions for _ in range(count)]