Source code for multistorageclient.providers.manifest_metadata
1# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2# SPDX-License-Identifier: Apache-2.0
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16from __future__ import annotations # Enables forward references in type hints
17
18import json
19import logging
20import os
21import posixpath
22from collections.abc import Iterator
23from dataclasses import asdict, dataclass
24from datetime import UTC, datetime
25from typing import Any
26
27from ..types import (
28 AWARE_DATETIME_MIN,
29 MAX_SYMLINK_DEPTH,
30 MetadataProvider,
31 ObjectMetadata,
32 ResolvedPath,
33 ResolvedPathState,
34 StorageProvider,
35)
36from ..utils import _decode_buffer, create_attribute_filter_evaluator, glob, matches_attribute_filter_expression
37from .manifest_formats import ManifestFormat, get_format_handler
38from .manifest_object_metadata import ManifestObjectMetadata
39
40logger = logging.getLogger(__name__)
41
42
43DEFAULT_MANIFEST_BASE_DIR = ".msc_manifests"
44MANIFEST_INDEX_FILENAME = "msc_manifest_index.json"
45MANIFEST_PARTS_CHILD_DIR = "parts"
46MANIFEST_PART_PREFIX = "msc_manifest_part"
47SEQUENCE_PADDING = 6 # Define padding for the sequence number (e.g., 6 for "000001")
48
49
[docs]
50@dataclass
51class ManifestPartReference:
52 """
53 A data class representing a reference to dataset manifest part.
54 """
55
56 #: The path of the manifest part relative to the main manifest.
57 path: str
58
[docs]
59 @staticmethod
60 def from_dict(data: dict[str, Any]) -> ManifestPartReference:
61 """
62 Creates a ManifestPartReference instance from a dictionary.
63 """
64 # Validate that the required 'path' field is present
65 if "path" not in data:
66 raise ValueError("Missing required field: 'path'")
67
68 return ManifestPartReference(path=data["path"])
69
[docs]
70 def to_dict(self) -> dict:
71 """
72 Converts ManifestPartReference instance to a dictionary.
73 """
74 return {
75 "path": self.path,
76 }
77
78
[docs]
79@dataclass
80class Manifest:
81 """
82 A data class representing a dataset manifest.
83 """
84
85 #: Defines the version of the manifest schema.
86 version: str
87 #: References to manifest parts.
88 parts: list[ManifestPartReference]
89 #: Format of manifest parts (jsonl or parquet).
90 format: str = "jsonl"
91
[docs]
92 @staticmethod
93 def from_dict(data: dict) -> Manifest:
94 """
95 Creates a Manifest instance from a dictionary (parsed from JSON).
96 """
97 try:
98 version = data["version"]
99 parts = [ManifestPartReference.from_dict(part) for part in data["parts"]]
100 format = data.get("format", "jsonl")
101 except KeyError as e:
102 raise ValueError("Invalid manifest data: Missing required field") from e
103
104 return Manifest(version=version, parts=parts, format=format)
105
[docs]
106 def to_json(self) -> str:
107 data = asdict(self)
108 data["parts"] = [part.to_dict() for part in self.parts]
109 return json.dumps(data)
110
111
[docs]
112class ManifestMetadataProvider(MetadataProvider):
113 _storage_provider: StorageProvider
114 _files: dict[str, ManifestObjectMetadata]
115 _pending_adds: dict[str, ManifestObjectMetadata]
116 _pending_removes: set[str]
117 _manifest_path: str
118 _writable: bool
119 _allow_overwrites: bool
120 _format: ManifestFormat | str
121
122 def __init__(
123 self,
124 storage_provider: StorageProvider,
125 manifest_path: str,
126 writable: bool = False,
127 allow_overwrites: bool = False,
128 manifest_format: ManifestFormat | str = ManifestFormat.JSONL,
129 ) -> None:
130 """
131 Creates a :py:class:`ManifestMetadataProvider`.
132
133 :param storage_provider: Storage provider.
134 :param manifest_path: Main manifest file path.
135 :param writable: If true, allows modifications and new manifests to be written.
136 :param allow_overwrites: If true, allows overwriting existing files without error.
137 :param manifest_format: Format for manifest parts. Defaults to ManifestFormat.JSONL.
138 """
139 self._storage_provider = storage_provider
140 self._files = {}
141 self._pending_adds = {}
142 self._pending_removes = set()
143 self._manifest_path = manifest_path
144 self._writable = writable
145 self._allow_overwrites = allow_overwrites
146 self._format = (
147 manifest_format if isinstance(manifest_format, ManifestFormat) else ManifestFormat(manifest_format)
148 )
149
150 self._load_manifest(storage_provider, self._manifest_path)
151
152 def _load_manifest(self, storage_provider: StorageProvider, manifest_path: str) -> None:
153 """
154 Loads manifest.
155
156 :param storage_provider: Storage provider.
157 :param manifest_path: Main manifest file path
158 """
159
160 def helper_find_manifest_file(manifest_path: str) -> str:
161 if storage_provider.is_file(manifest_path):
162 return manifest_path
163
164 if storage_provider.is_file(os.path.join(manifest_path, MANIFEST_INDEX_FILENAME)):
165 return os.path.join(manifest_path, MANIFEST_INDEX_FILENAME)
166
167 # Now go looking and select newest manifest.
168 if DEFAULT_MANIFEST_BASE_DIR not in manifest_path.split("/"):
169 manifest_path = os.path.join(manifest_path, DEFAULT_MANIFEST_BASE_DIR)
170
171 candidates = storage_provider.glob(os.path.join(manifest_path, "*", MANIFEST_INDEX_FILENAME))
172 candidates = sorted(candidates)
173 return candidates[-1] if candidates else ""
174
175 resolved_manifest_path = helper_find_manifest_file(manifest_path)
176 if not resolved_manifest_path:
177 logger.warning(f"No manifest found at '{manifest_path}'.")
178 return
179
180 file_content = storage_provider.get_object(resolved_manifest_path)
181
182 prefix = os.path.dirname(resolved_manifest_path)
183 _, file_extension = os.path.splitext(resolved_manifest_path)
184 self._load_manifest_file(storage_provider, file_content, prefix, file_extension[1:])
185
186 def _load_manifest_file(
187 self, storage_provider: StorageProvider, file_content: bytes, manifest_base: str, file_type: str
188 ) -> None:
189 """
190 Loads a manifest.
191
192 :param storage_provider: Storage provider.
193 :param file_content: Manifest file content bytes.
194 :param manifest_base: Manifest file base path.
195 :param file_type: Manifest file type.
196 """
197 if file_type == "json":
198 manifest_dict = json.loads(_decode_buffer(file_content))
199 manifest = Manifest.from_dict(manifest_dict)
200
201 # Check manifest version. Not needed once we make the manifest model use sum types/discriminated unions.
202 if manifest.version != "1":
203 raise ValueError(f"Manifest version {manifest.version} is not supported.")
204
205 # Load manifest parts.
206 for manifest_part_reference in manifest.parts:
207 object_metadata_list: list[ManifestObjectMetadata] = self._load_manifest_part_file(
208 storage_provider=storage_provider,
209 manifest_base=manifest_base,
210 manifest_part_reference=manifest_part_reference,
211 manifest_format=manifest.format,
212 )
213
214 for object_metadatum in object_metadata_list:
215 self._files[object_metadatum.key] = object_metadatum
216 else:
217 raise NotImplementedError(f"Manifest file type {file_type} is not supported.")
218
219 def _load_manifest_part_file(
220 self,
221 storage_provider: StorageProvider,
222 manifest_base: str,
223 manifest_part_reference: ManifestPartReference,
224 manifest_format: ManifestFormat | str = ManifestFormat.JSONL,
225 ) -> list[ManifestObjectMetadata]:
226 """
227 Loads a manifest part and converts to ManifestObjectMetadata.
228
229 :param storage_provider: Storage provider.
230 :param manifest_base: Manifest file base path. Prepend to manifest part reference paths.
231 :param manifest_part_reference: Manifest part reference.
232 :param manifest_format: Format of the manifest part (jsonl or parquet).
233 """
234 if not os.path.isabs(manifest_part_reference.path):
235 remote_path = os.path.join(manifest_base, manifest_part_reference.path)
236 else:
237 remote_path = manifest_part_reference.path
238 manifest_part_file_content = storage_provider.get_object(remote_path)
239
240 _, ext = os.path.splitext(remote_path)
241 detected_format = ext[1:] if ext else manifest_format
242
243 format_handler = get_format_handler(detected_format)
244 object_metadata_list = format_handler.read_part(manifest_part_file_content)
245
246 # Convert ObjectMetadata to ManifestObjectMetadata
247 # The format handler returns ObjectMetadata, but may have extra attributes set (like physical_path)
248 return [ManifestObjectMetadata.from_object_metadata(obj) for obj in object_metadata_list]
249
250 def _write_manifest_files(
251 self,
252 storage_provider: StorageProvider,
253 object_metadata: list[ManifestObjectMetadata],
254 manifest_format: ManifestFormat | str = ManifestFormat.JSONL,
255 ) -> None:
256 """
257 Writes the main manifest and its part files.
258
259 Accepts ManifestObjectMetadata which extends ObjectMetadata, so format handlers
260 (which expect ObjectMetadata) can serialize it, preserving all fields including physical_path.
261
262 :param storage_provider: The storage provider to use for writing.
263 :param object_metadata: ManifestObjectMetadata objects to include in manifest.
264 :param manifest_format: Format for manifest parts. Defaults to ManifestFormat.JSONL.
265 """
266 if not object_metadata:
267 return
268
269 base_path = self._manifest_path
270 manifest_base_path = base_path
271
272 base_path_parts = base_path.split(os.sep)
273 if DEFAULT_MANIFEST_BASE_DIR in base_path_parts:
274 manifests_index = base_path_parts.index(DEFAULT_MANIFEST_BASE_DIR)
275 if manifests_index > 0:
276 manifest_base_path = os.path.join(*base_path_parts[:manifests_index])
277 else:
278 manifest_base_path = ""
279 if base_path.startswith(os.sep):
280 manifest_base_path = os.sep + manifest_base_path
281
282 current_time = datetime.now(UTC)
283 current_time_str = current_time.isoformat(timespec="seconds")
284 manifest_folderpath = os.path.join(manifest_base_path, DEFAULT_MANIFEST_BASE_DIR, current_time_str)
285
286 format_handler = get_format_handler(manifest_format)
287 suffix = format_handler.get_file_suffix()
288
289 # We currently write only one part by default.
290 part_sequence_number = 1
291 manifest_part_file_path = os.path.join(
292 MANIFEST_PARTS_CHILD_DIR,
293 f"{MANIFEST_PART_PREFIX}{part_sequence_number:0{SEQUENCE_PADDING}}{suffix}",
294 )
295
296 format_value = manifest_format.value if isinstance(manifest_format, ManifestFormat) else manifest_format
297 manifest = Manifest(
298 version="1", parts=[ManifestPartReference(path=manifest_part_file_path)], format=format_value
299 )
300
301 manifest_part_content = format_handler.write_part(list(object_metadata))
302 storage_provider.put_object(os.path.join(manifest_folderpath, manifest_part_file_path), manifest_part_content)
303
304 manifest_file_path = os.path.join(manifest_folderpath, MANIFEST_INDEX_FILENAME)
305 manifest_content = manifest.to_json()
306 storage_provider.put_object(manifest_file_path, manifest_content.encode("utf-8"))
307
[docs]
308 def list_objects(
309 self,
310 path: str,
311 start_after: str | None = None,
312 end_at: str | None = None,
313 include_directories: bool = False,
314 attribute_filter_expression: str | None = None,
315 show_attributes: bool = False,
316 ) -> Iterator[ObjectMetadata]:
317 """
318 List objects in the manifest.
319
320 :param path: The path to filter objects by.
321 :param start_after: The object to start after.
322 :param end_at: The object to end at.
323 :param include_directories: Whether to include directories.
324 :param attribute_filter_expression: The attribute filter expression to filter objects by.
325 :param show_attributes: This field is not used in this implementation - It will always return attributes. This is present merely to satisfy the interface.
326 """
327
328 if (start_after is not None) and (end_at is not None) and not (start_after < end_at):
329 raise ValueError(f"start_after ({start_after}) must be before end_at ({end_at})!")
330
331 if path and not path.endswith("/"):
332 path = path + "/"
333
334 # create evaluator for attribute filter expression if present
335 evaluator = (
336 create_attribute_filter_evaluator(attribute_filter_expression) if attribute_filter_expression else None
337 )
338
339 if include_directories:
340 # Match delimiter-style providers such as S3: list the immediate child
341 # directories first, then the immediate files. The manifest only stores
342 # object keys, so this view is built on demand for the requested path.
343 directories: dict[str, ObjectMetadata] = {}
344 synthetic_directories: set[str] = set()
345 files: list[ObjectMetadata] = []
346
347 for key, obj_metadata in sorted(self._files.items()):
348 if not key.startswith(path) or (
349 evaluator is not None and not matches_attribute_filter_expression(obj_metadata, evaluator)
350 ):
351 continue
352
353 relative = key[len(path) :].lstrip("/")
354
355 if "/" not in relative:
356 if (start_after is not None and key <= start_after) or (end_at is not None and end_at < key):
357 continue
358
359 if obj_metadata.type == "directory":
360 # Prefer explicit directory entries from the manifest when present.
361 directory_key = obj_metadata.key.rstrip("/")
362 directories[directory_key] = ObjectMetadata(
363 key=directory_key,
364 type="directory",
365 last_modified=obj_metadata.last_modified,
366 content_length=0,
367 content_type=obj_metadata.content_type,
368 etag=obj_metadata.etag,
369 storage_class=obj_metadata.storage_class,
370 metadata=obj_metadata.metadata,
371 symlink_target=obj_metadata.symlink_target,
372 )
373 synthetic_directories.discard(directory_key)
374 else:
375 files.append(obj_metadata)
376 continue
377
378 # Nested files imply an immediate child directory under the listed path.
379 directory_name = f"{path}{relative.split('/', 1)[0]}"
380 directory_key = directory_name.rstrip("/")
381 existing_directory = directories.get(directory_key)
382 if existing_directory is None:
383 directories[directory_key] = ObjectMetadata(
384 key=directory_key,
385 type="directory",
386 last_modified=obj_metadata.last_modified,
387 content_length=0,
388 )
389 synthetic_directories.add(directory_key)
390 else:
391 if directory_key in synthetic_directories:
392 existing_directory.last_modified = max(
393 existing_directory.last_modified, obj_metadata.last_modified
394 )
395
396 yield from (
397 directories[key]
398 for key in sorted(directories)
399 if (start_after is None or start_after < key) and (end_at is None or key <= end_at)
400 )
401 yield from sorted(files, key=lambda obj: obj.key)
402 return
403
404 # Note that this is a generator, not a tuple (there's no tuple comprehension).
405 keys = (
406 key
407 for key, obj_metadata in self._files.items()
408 if key.startswith(path)
409 and obj_metadata.type != "directory"
410 and (start_after is None or start_after < key)
411 and (end_at is None or key <= end_at)
412 and (
413 evaluator is None or matches_attribute_filter_expression(obj_metadata, evaluator)
414 ) # filter by evaluator if present
415 )
416
417 for key in sorted(keys):
418 yield self._files[key]
419
[docs]
420 def get_object_metadata(self, path: str, include_pending: bool = False) -> ObjectMetadata:
421 """Return object or directory metadata; ``""`` and ``"/"`` identify the profile root."""
422 if include_pending:
423 if path in self._pending_removes:
424 raise FileNotFoundError(f"Object {path} does not exist.")
425 if path in self._pending_adds:
426 return self._pending_adds[path]
427 if path in self._files:
428 # Return ManifestObjectMetadata directly (it extends ObjectMetadata)
429 return self._files[path]
430 return self._get_directory_metadata(path, include_pending)
431
432 def _get_directory_metadata(self, path: str, include_pending: bool) -> ObjectMetadata:
433 dir_prefix = path.rstrip("/")
434 if dir_prefix:
435 dir_prefix += "/"
436
437 has_committed = any(
438 k.startswith(dir_prefix) and (not include_pending or k not in self._pending_removes) for k in self._files
439 )
440 has_pending = include_pending and any(k.startswith(dir_prefix) for k in self._pending_adds)
441
442 if not has_committed and not has_pending:
443 raise FileNotFoundError(f"Object {path} does not exist.")
444
445 return ObjectMetadata(
446 key=dir_prefix,
447 type="directory",
448 content_length=0,
449 last_modified=AWARE_DATETIME_MIN,
450 )
451
[docs]
452 def glob(self, pattern: str, attribute_filter_expression: str | None = None) -> list[str]:
453 """
454 List objects in the manifest.
455
456 :param pattern: The pattern to filter objects by.
457 :param attribute_filter_expression: The attribute filter expression to filter objects by.
458 """
459
460 all_objects = [
461 object.key for object in self.list_objects("", attribute_filter_expression=attribute_filter_expression)
462 ]
463 return [key for key in glob(all_objects, pattern)]
464
[docs]
465 def realpath(self, logical_path: str) -> ResolvedPath:
466 """
467 Resolves a logical path to its physical storage path if the object exists.
468 Only checks committed files, not pending changes.
469 Follows ``symlink_target`` chains in the manifest with depth limit and cycle detection.
470
471 :param logical_path: The user-facing logical path
472
473 :return: ResolvedPath with exists=True if found, exists=False otherwise
474 """
475 visited: set[str] = set()
476 current = logical_path
477 for _ in range(MAX_SYMLINK_DEPTH):
478 manifest_obj = self._files.get(current)
479 if not manifest_obj:
480 return ResolvedPath(physical_path=current, state=ResolvedPathState.UNTRACKED, profile=None)
481 if not manifest_obj.symlink_target:
482 if manifest_obj.physical_path is None:
483 raise ValueError(f"Manifest entry for '{current}' has no physical path")
484 return ResolvedPath(
485 physical_path=manifest_obj.physical_path, state=ResolvedPathState.EXISTS, profile=None
486 )
487 if current in visited:
488 raise ValueError(f"Symlink cycle detected at: {current}")
489 visited.add(current)
490 current = ObjectMetadata.resolve_symlink_target(current, manifest_obj.symlink_target)
491 raise ValueError(f"Too many levels of symlinks (>{MAX_SYMLINK_DEPTH}): {logical_path}")
492
[docs]
493 def generate_physical_path(self, logical_path: str, for_overwrite: bool = False) -> ResolvedPath:
494 """
495 Generates a physical storage path for a new object or for overwriting an existing object.
496
497 For now, this simply returns the logical path (no path rewriting).
498 In the future, this could generate unique paths for overwrites.
499
500 :param logical_path: The user-facing logical path
501 :param for_overwrite: When ``True``, generate a path for overwriting an existing object.
502
503 :return: The physical storage path to use for writing
504 """
505 # For now, physical path = logical path
506 # Future enhancement: generate unique paths for overwrites
507 # if for_overwrite and self._allow_overwrites:
508 # return f"{logical_path}-{uuid.uuid4().hex}"
509 return ResolvedPath(physical_path=logical_path, state=ResolvedPathState.UNTRACKED, profile=None)
510
[docs]
511 def add_file(self, path: str, metadata: ObjectMetadata) -> None:
512 """
513 Stages a file for the next manifest commit, preserving its storage class and symlink target.
514
515 :param path: The logical path to register in the manifest.
516 :param metadata: Object metadata whose key is the physical path, or manifest metadata with a matching logical path.
517 """
518 if not self.is_writable():
519 raise RuntimeError(f"Manifest update support not enabled in configuration. Attempted to add {path}.")
520
521 # Check if file already exists in committed state and overwrites are not allowed
522 # Pending files can always be overwritten
523 if not self._allow_overwrites and path in self._files:
524 raise FileExistsError(f"File {path} already exists and overwrites are not allowed.")
525
526 # Handle two cases:
527 # 1. If metadata is already a ManifestObjectMetadata, use it directly
528 # 2. Otherwise, create one assuming metadata.key contains the physical path
529 if isinstance(metadata, ManifestObjectMetadata):
530 # Already has proper logical/physical path separation
531 manifest_metadata = metadata
532 # Ensure the logical path matches what was requested
533 if manifest_metadata.key != path:
534 raise ValueError(f"Logical path mismatch: expected {path}, got {manifest_metadata.key}")
535 else:
536 # For backward compatibility, create a ManifestObjectMetadata from ObjectMetadata
537 symlink_target = metadata.symlink_target
538 if symlink_target and posixpath.dirname(metadata.key) != posixpath.dirname(path):
539 physical_target = ObjectMetadata.resolve_symlink_target(metadata.key, symlink_target)
540 logical_target = next(
541 (
542 key
543 for key, entry in {**self._files, **self._pending_adds}.items()
544 if entry.physical_path == physical_target
545 ),
546 physical_target,
547 )
548 symlink_target = ObjectMetadata.encode_symlink_target(path, logical_target)
549 manifest_metadata = ManifestObjectMetadata(
550 key=path, # Logical path (user-facing)
551 content_length=metadata.content_length,
552 last_modified=metadata.last_modified,
553 content_type=metadata.content_type,
554 etag=metadata.etag,
555 storage_class=metadata.storage_class,
556 metadata=metadata.metadata,
557 type=metadata.type,
558 symlink_target=symlink_target,
559 physical_path=metadata.key, # Physical path (from storage provider)
560 )
561
562 # TODO: Time travel is not supported - we do not rename file paths when overwriting.
563 # When a file is overwritten, the manifest points to the new version of the file at the same location
564 # without maintaining history of previous versions.
565 self._pending_adds[path] = manifest_metadata
566
[docs]
567 def remove_file(self, path: str) -> None:
568 if not self.is_writable():
569 raise RuntimeError(f"Manifest update support not enabled in configuration. Attempted to remove {path}.")
570 if path not in self._files:
571 raise FileNotFoundError(f"Object {path} does not exist.")
572 self._pending_removes.add(path)
573
576
579
582
[docs]
583 def commit_updates(self) -> None:
584 if not self._pending_adds and not self._pending_removes:
585 return
586
587 if self._pending_adds:
588 self._files.update(self._pending_adds)
589 self._pending_adds = {}
590
591 for path in self._pending_removes:
592 self._files.pop(path)
593 self._pending_removes = set()
594
595 # Serialize ManifestObjectMetadata directly
596 # to_dict() will include all fields including physical_path
597 object_metadata = list(self._files.values())
598 self._write_manifest_files(self._storage_provider, object_metadata, manifest_format=self._format)