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
"""
Wrapped lakeFS client that automatically captures commit SHAs.
"""

from typing import Optional, Dict, Any, Tuple
from datetime import datetime, timezone
import logging
import os

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

from briefcase.semantic_conventions import lakefs as lakefs_attrs

logger = logging.getLogger(__name__)


class VersionedClient:
    """
    Wrapper around lakeFS client that automatically captures version metadata.

    Configuration priority (highest to lowest):
        1. Explicit parameters
        2. Environment variables (LAKEFS_ENDPOINT, LAKEFS_ACCESS_KEY, LAKEFS_SECRET_KEY)
        3. Default endpoint (https://briefcasebrain.us-east-1.lakefscloud.io/api/v1)

    Usage:
        # Using explicit parameters
        client = VersionedClient(
            repository="acme-healthcare",
            branch="main",
            briefcase_client=briefcase_client,
            lakefs_endpoint="https://lakefs.example.com/api/v1",
            lakefs_access_key="key",
            lakefs_secret_key="secret"
        )

        # Using environment variables
        # export LAKEFS_ENDPOINT="https://lakefs.example.com/api/v1"
        # export LAKEFS_ACCESS_KEY="key"
        # export LAKEFS_SECRET_KEY="secret"
        client = VersionedClient(
            repository="acme-healthcare",
            branch="main",
            briefcase_client=briefcase_client
        )

        # All operations automatically tracked
        content = client.read_object("policies/policy.pdf")
    """

    def __init__(
        self,
        repository: str,
        branch: str,
        commit: str = "latest",
        briefcase_client=None,
        lakefs_endpoint: Optional[str] = None,
        lakefs_access_key: Optional[str] = None,
        lakefs_secret_key: Optional[str] = None,
        require_live: bool = False,
    ):
        self.repository = repository
        self.branch = branch
        self.commit = commit
        self.briefcase_client = briefcase_client
        self.require_live = require_live or self._is_truthy(
            os.getenv("BRIEFCASE_LAKEFS_REQUIRE_LIVE")
        )

        # Resolve configuration with priority: param > env var > default
        resolved_endpoint = (
            lakefs_endpoint or
            os.getenv("LAKEFS_ENDPOINT") or
            "https://briefcasebrain.us-east-1.lakefscloud.io/api/v1"
        )
        self._endpoint = self._normalize_endpoint(resolved_endpoint)
        resolved_access_key = lakefs_access_key or os.getenv("LAKEFS_ACCESS_KEY")
        resolved_secret_key = lakefs_secret_key or os.getenv("LAKEFS_SECRET_KEY")

        # Initialize underlying lakeFS client
        self._lakefs = None
        self._lakefs_client = None
        self._has_lakefs = False
        try:
            import lakefs
            self._lakefs = lakefs
            if not resolved_access_key or not resolved_secret_key:
                raise ValueError(
                    "missing credentials (set LAKEFS_ACCESS_KEY and LAKEFS_SECRET_KEY)"
                )
            self._lakefs_client = lakefs.Client(
                host=self._endpoint,
                username=resolved_access_key,
                password=resolved_secret_key,
            )
            self._has_lakefs = True
        except (ImportError, Exception) as e:
            if self.require_live:
                raise RuntimeError(
                    "Failed to initialize live lakeFS client in strict mode. "
                    "Install `lakefs>=0.14.0` and provide valid lakeFS credentials."
                ) from e
            logger.warning(f"lakeFS client not available: {e}. Using mock mode.")

        # Resolve commit SHA if "latest" requested
        if self.commit == "latest":
            self.commit = self._resolve_latest_commit()

        # Cache commit metadata
        self._commit_metadata = self._fetch_commit_metadata()

    def _resolve_latest_commit(self) -> str:
        """Resolve 'latest' to actual commit SHA."""
        if not self._has_lakefs or not self._lakefs_client:
            # Mock mode: return fake SHA
            return "abc123def456789012345678901234567890abcd"

        try:
            branch_ref = self._repository().branch(self.branch)
            return branch_ref.get_commit().id
        except Exception as e:
            if self.require_live:
                raise RuntimeError(
                    f"Failed to resolve latest commit for {self.repository}/{self.branch}"
                ) from e
            logger.error(f"Failed to resolve latest commit: {e}")
            # Return mock SHA on error
            return "abc123def456789012345678901234567890abcd"

    def _fetch_commit_metadata(self) -> Dict[str, Any]:
        """Fetch and cache commit metadata."""
        if not self._has_lakefs or not self._lakefs_client:
            # Mock mode: return fake metadata
            return {
                "sha": self.commit,
                "message": "Mock commit message",
                "author": "mock-author",
                "timestamp": datetime.now().isoformat(),
                "metadata": {}
            }

        try:
            commit = self._repository().ref(self.commit).get_commit()
            return {
                "sha": commit.id,
                "message": commit.message,
                "author": commit.committer,
                "timestamp": self._format_timestamp(commit.creation_date),
                "metadata": commit.metadata or {}
            }
        except Exception as e:
            if self.require_live:
                raise RuntimeError(
                    f"Failed to fetch commit metadata for {self.repository}@{self.commit}"
                ) from e
            logger.error(f"Failed to fetch commit metadata: {e}")
            # Return mock metadata on error
            return {
                "sha": self.commit,
                "message": "Error fetching commit",
                "author": "unknown",
                "timestamp": datetime.now().isoformat(),
                "metadata": {}
            }

    def read_object(
        self,
        path: str,
        return_metadata: bool = False
    ) -> bytes | Tuple[bytes, Dict]:
        """
        Read an object from lakeFS with automatic instrumentation.

        Args:
            path: Object path (e.g., "policies/policy.pdf")
            return_metadata: If True, return (content, metadata) tuple

        Returns:
            Object content as bytes, optionally with metadata dict
        """
        start_time = datetime.now()

        if not self._has_lakefs or not self._lakefs_client:
            # Mock mode: return fake content
            content = b"Mock file content for " + path.encode()
            etag = "mock-etag-12345"
            content_type = "application/octet-stream"
            last_modified = None
        else:
            try:
                # Read from lakeFS using repository/ref/object model
                ref = self._repository().ref(self.commit)
                obj = ref.object(path)
                with obj.reader("rb") as reader:
                    content = reader.read()

                stats = obj.stat()
                etag = stats.checksum
                content_type = stats.content_type or "application/octet-stream"
                last_modified = self._format_timestamp(stats.mtime)
            except Exception as e:
                if self.require_live:
                    raise RuntimeError(
                        f"Failed to read object {path} from {self.repository}@{self.commit}"
                    ) from e
                logger.error(f"Failed to read object {path}: {e}")
                # Return mock content on error
                content = b"Error reading file"
                etag = "error-etag"
                content_type = "application/octet-stream"
                last_modified = None

        # Build metadata
        metadata = {
            "path": path,
            "size": len(content),
            "content_type": content_type,
            "etag": etag,
            "last_modified": last_modified,
            "commit_sha": self._commit_metadata.get("sha", self.commit),
            "commit_metadata": self._commit_metadata
        }

        # Instrument if Briefcase client available
        if self.briefcase_client:
            self._record_access(path, metadata, start_time)

        if return_metadata:
            return content, metadata
        return content

    def _record_access(
        self,
        path: str,
        metadata: Dict,
        start_time: datetime
    ):
        """Record file access in current Briefcase span."""
        if not HAS_OTEL:
            logger.warning("OpenTelemetry not available, skipping instrumentation")
            return

        try:
            current_span = trace.get_current_span()
            if not current_span or not current_span.is_recording():
                return

            # Set commit-level attributes (once per span)
            current_span.set_attribute(
                lakefs_attrs.LAKEFS_COMMIT_SHA,
                self._commit_metadata["sha"]
            )
            current_span.set_attribute(
                lakefs_attrs.LAKEFS_COMMIT_BRANCH,
                self.branch
            )
            current_span.set_attribute(
                lakefs_attrs.LAKEFS_COMMIT_TIMESTAMP,
                self._commit_metadata["timestamp"]
            )
            current_span.set_attribute(
                lakefs_attrs.LAKEFS_REPOSITORY,
                self.repository
            )

            # Record file access event
            current_span.add_event(
                "lakefs.file_accessed",
                attributes={
                    lakefs_attrs.LAKEFS_FILE_PATH: path,
                    lakefs_attrs.LAKEFS_FILE_SIZE: metadata["size"],
                    lakefs_attrs.LAKEFS_FILE_MODIFIED: metadata["last_modified"] or "unknown",
                    lakefs_attrs.LAKEFS_FILE_HASH: metadata["etag"],
                    lakefs_attrs.LAKEFS_ACCESS_TIME: datetime.now().isoformat(),
                    "duration_ms": (datetime.now() - start_time).total_seconds() * 1000
                }
            )

            # Set per-artifact attribute for this specific file
            artifact_attr = f"{lakefs_attrs.LAKEFS_ARTIFACT_PREFIX}{path}"
            current_span.set_attribute(artifact_attr, self.commit)
        except Exception as e:
            logger.error(f"Failed to record access: {e}")

    def list_objects(self, prefix: str = "") -> list:
        """List objects in lakeFS with optional prefix filter."""
        if not self._has_lakefs or not self._lakefs_client:
            # Mock mode: return fake list
            mock_results = [{"path": f"{prefix}file1.txt"}, {"path": f"{prefix}file2.txt"}]
            # Still emit OTel events in mock mode for testing
            if self.briefcase_client and HAS_OTEL:
                try:
                    current_span = trace.get_current_span()
                    if current_span and current_span.is_recording():
                        current_span.add_event(
                            "lakefs.objects_listed",
                            attributes={
                                "prefix": prefix,
                                "count": len(mock_results),
                                lakefs_attrs.LAKEFS_COMMIT_SHA: self.commit
                            }
                        )
                except Exception:
                    pass
            return mock_results

        try:
            results = []
            for obj in self._repository().ref(self.commit).objects(prefix=prefix):
                path = getattr(obj, "path", None)
                if not path:
                    continue
                entry = {"path": path}
                size = getattr(obj, "size_bytes", None)
                checksum = getattr(obj, "checksum", None)
                if size is not None:
                    entry["size_bytes"] = size
                if checksum:
                    entry["checksum"] = checksum
                results.append(entry)
        except Exception as e:
            if self.require_live:
                raise RuntimeError(
                    f"Failed to list objects from {self.repository}@{self.commit}"
                ) from e
            logger.error(f"Failed to list objects: {e}")
            # Return mock list on error
            return [{"path": f"{prefix}error.txt"}]

        # Instrument listing operation
        if self.briefcase_client and HAS_OTEL:
            try:
                current_span = trace.get_current_span()
                if current_span and current_span.is_recording():
                    current_span.add_event(
                        "lakefs.objects_listed",
                        attributes={
                            "prefix": prefix,
                            "count": len(results),
                            lakefs_attrs.LAKEFS_COMMIT_SHA: self.commit
                        }
                    )
            except Exception as e:
                logger.error(f"Failed to instrument list operation: {e}")

        return results

    def get_commit(self) -> str:
        """Get the current commit SHA."""
        return self._commit_metadata.get("sha", self.commit)

    def object_exists(self, path: str) -> bool:
        """Check if an object exists in lakeFS."""
        if not self._has_lakefs or not self._lakefs_client:
            # Mock mode: always return True
            return True

        try:
            return self._repository().ref(self.commit).object(path).exists()
        except Exception as e:
            if self.require_live:
                raise RuntimeError(
                    f"Failed object existence check for {path} on {self.repository}@{self.commit}"
                ) from e
            return False

    def upload_object(
        self,
        path: str,
        data: bytes,
        content_type: str = "application/octet-stream"
    ):
        """Upload an object to lakeFS."""
        if not self._has_lakefs or not self._lakefs_client:
            logger.info(f"Mock mode: Would upload {len(data)} bytes to {path}")
            return

        try:
            obj = self._repository().branch(self.branch).object(path)
            with obj.writer(mode="wb", content_type=content_type) as writer:
                writer.write(data)
        except Exception as e:
            logger.error(f"Failed to upload object {path}: {e}")
            if self.require_live:
                raise RuntimeError(
                    f"Failed to upload object {path} to {self.repository}/{self.branch}"
                ) from e
            raise

    @staticmethod
    def _is_truthy(value: Optional[str]) -> bool:
        return str(value).strip().lower() in {"1", "true", "yes", "on"}

    @staticmethod
    def _normalize_endpoint(endpoint: str) -> str:
        normalized = endpoint.rstrip("/")
        if normalized.endswith("/api/v1"):
            normalized = normalized[:-7]
        return normalized

    @staticmethod
    def _format_timestamp(value: Any) -> str:
        if isinstance(value, (int, float)):
            # lakeFS SDK emits mtime/creation dates as epoch milliseconds
            return datetime.fromtimestamp(float(value) / 1000.0, tz=timezone.utc).isoformat()
        if isinstance(value, datetime):
            if value.tzinfo is None:
                value = value.replace(tzinfo=timezone.utc)
            return value.isoformat()
        if value is None:
            return datetime.now(tz=timezone.utc).isoformat()
        return str(value)

    def _repository(self):
        if not self._has_lakefs or not self._lakefs_client or not self._lakefs:
            raise RuntimeError("lakeFS client is not initialized")
        return self._lakefs.Repository(self.repository, client=self._lakefs_client)


# Backwards compatibility alias
InstrumentedLakeFSClient = VersionedClient