Coverage for python / lsst / daf / butler / direct_butler / _direct_butler.py: 10%

941 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-01-20 01:25 -0800

1# This file is part of daf_butler. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

5# (http://www.lsst.org). 

6# See the COPYRIGHT file at the top-level directory of this distribution 

7# for details of code ownership. 

8# 

9# This software is dual licensed under the GNU General Public License and also 

10# under a 3-clause BSD license. Recipients may choose which of these licenses 

11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt, 

12# respectively. If you choose the GPL option then the following text applies 

13# (but note that there is still no warranty even if you opt for BSD instead): 

14# 

15# This program is free software: you can redistribute it and/or modify 

16# it under the terms of the GNU General Public License as published by 

17# the Free Software Foundation, either version 3 of the License, or 

18# (at your option) any later version. 

19# 

20# This program is distributed in the hope that it will be useful, 

21# but WITHOUT ANY WARRANTY; without even the implied warranty of 

22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

23# GNU General Public License for more details. 

24# 

25# You should have received a copy of the GNU General Public License 

26# along with this program. If not, see <http://www.gnu.org/licenses/>. 

27 

28"""Butler top level classes.""" 

29 

30from __future__ import annotations 

31 

32__all__ = ( 

33 "ButlerValidationError", 

34 "DirectButler", 

35) 

36 

37import collections.abc 

38import contextlib 

39import io 

40import itertools 

41import math 

42import numbers 

43import os 

44import uuid 

45import warnings 

46from collections import Counter, defaultdict 

47from collections.abc import Collection, Iterable, Iterator, MutableMapping, Sequence 

48from functools import partial 

49from types import EllipsisType 

50from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple, TextIO, cast 

51 

52from deprecated.sphinx import deprecated 

53from sqlalchemy.exc import IntegrityError 

54 

55from lsst.resources import ResourcePath, ResourcePathExpression 

56from lsst.utils.introspection import find_outside_stacklevel, get_class_of 

57from lsst.utils.iteration import chunk_iterable 

58from lsst.utils.logging import VERBOSE, getLogger 

59from lsst.utils.timer import time_this 

60 

61from .._butler import Butler, _DeprecatedDefault 

62from .._butler_config import ButlerConfig 

63from .._butler_instance_options import ButlerInstanceOptions 

64from .._butler_metrics import ButlerMetrics 

65from .._collection_type import CollectionType 

66from .._dataset_existence import DatasetExistence 

67from .._dataset_ref import DatasetRef 

68from .._dataset_type import DatasetType 

69from .._deferredDatasetHandle import DeferredDatasetHandle 

70from .._exceptions import DatasetNotFoundError, DimensionValueError, EmptyQueryResultError, ValidationError 

71from .._file_dataset import FileDataset 

72from .._limited_butler import LimitedButler 

73from .._query_all_datasets import QueryAllDatasetsParameters, query_all_datasets 

74from .._registry_shim import RegistryShim 

75from .._storage_class import StorageClass, StorageClassFactory 

76from .._timespan import Timespan 

77from ..datastore import Datastore, NullDatastore 

78from ..datastores.file_datastore.retrieve_artifacts import ZipIndex, retrieve_and_zip 

79from ..datastores.file_datastore.transfer import retrieve_file_transfer_records 

80from ..dimensions import DataCoordinate, Dimension, DimensionGroup 

81from ..direct_query_driver import DirectQueryDriver 

82from ..progress import Progress 

83from ..queries import Query 

84from ..registry import ( 

85 ConflictingDefinitionError, 

86 DataIdError, 

87 MissingDatasetTypeError, 

88 RegistryDefaults, 

89 _RegistryFactory, 

90) 

91from ..registry.sql_registry import SqlRegistry 

92from ..transfers import RepoExportContext 

93from ..utils import transactional 

94from ._direct_butler_collections import DirectButlerCollections 

95 

96if TYPE_CHECKING: 

97 from lsst.resources import ResourceHandleProtocol 

98 

99 from .._dataset_provenance import DatasetProvenance 

100 from .._dataset_ref import DatasetId 

101 from ..datastore import DatasetRefURIs 

102 from ..dimensions import DataId, DataIdValue, DimensionElement, DimensionRecord, DimensionUniverse 

103 from ..registry import CollectionArgType, Registry 

104 from ..transfers import RepoImportBackend 

105 

106_LOG = getLogger(__name__) 

107 

108 

109class ButlerValidationError(ValidationError): 

110 """There is a problem with the Butler configuration.""" 

111 

112 pass 

113 

114 

115class DirectButler(Butler): # numpydoc ignore=PR02 

116 """Main entry point for the data access system. 

117 

118 Parameters 

119 ---------- 

120 config : `ButlerConfig` 

121 The configuration for this Butler instance. 

122 registry : `SqlRegistry` 

123 The object that manages dataset metadata and relationships. 

124 datastore : Datastore 

125 The object that manages actual dataset storage. 

126 storageClasses : StorageClassFactory 

127 An object that maps known storage class names to objects that fully 

128 describe them. 

129 

130 Notes 

131 ----- 

132 Most users should call the top-level `Butler`.``from_config`` instead of 

133 using this constructor directly. 

134 """ 

135 

136 # This is __new__ instead of __init__ because we have to support 

137 # instantiation via the legacy constructor Butler.__new__(), which 

138 # reads the configuration and selects which subclass to instantiate. The 

139 # interaction between __new__ and __init__ is kind of wacky in Python. If 

140 # we were using __init__ here, __init__ would be called twice (once when 

141 # the DirectButler instance is constructed inside Butler.from_config(), and 

142 # a second time with the original arguments to Butler() when the instance 

143 # is returned from Butler.__new__() 

144 def __new__( 

145 cls, 

146 *, 

147 config: ButlerConfig, 

148 registry: SqlRegistry, 

149 datastore: Datastore, 

150 storageClasses: StorageClassFactory, 

151 metrics: ButlerMetrics | None = None, 

152 ) -> DirectButler: 

153 self = cast(DirectButler, super().__new__(cls)) 

154 self._config = config 

155 self._registry = registry 

156 self._datastore = datastore 

157 self.storageClasses = storageClasses 

158 self._metrics = metrics if metrics is not None else ButlerMetrics() 

159 

160 # For execution butler the datastore needs a special 

161 # dependency-inversion trick. This is not used by regular butler, 

162 # but we do not have a way to distinguish regular butler from execution 

163 # butler. 

164 self._datastore.set_retrieve_dataset_type_method(partial(_retrieve_dataset_type, registry)) 

165 

166 self._closed = False 

167 

168 return self 

169 

170 @classmethod 

171 def create_from_config( 

172 cls, 

173 config: ButlerConfig, 

174 *, 

175 options: ButlerInstanceOptions, 

176 without_datastore: bool = False, 

177 ) -> DirectButler: 

178 """Construct a Butler instance from a configuration file. 

179 

180 Parameters 

181 ---------- 

182 config : `ButlerConfig` 

183 The configuration for this Butler instance. 

184 options : `ButlerInstanceOptions` 

185 Default values and other settings for the Butler instance. 

186 without_datastore : `bool`, optional 

187 If `True` do not attach a datastore to this butler. Any attempts 

188 to use a datastore will fail. 

189 

190 Notes 

191 ----- 

192 Most users should call the top-level `Butler`.``from_config`` 

193 instead of using this function directly. 

194 """ 

195 if "run" in config or "collection" in config: 

196 raise ValueError("Passing a run or collection via configuration is no longer supported.") 

197 

198 defaults = RegistryDefaults.from_butler_instance_options(options) 

199 try: 

200 butlerRoot = config.get("root", config.configDir) 

201 writeable = options.writeable 

202 if writeable is None: 

203 writeable = options.run is not None 

204 registry = _RegistryFactory(config).from_config( 

205 butlerRoot=butlerRoot, writeable=writeable, defaults=defaults 

206 ) 

207 if without_datastore: 

208 datastore: Datastore = NullDatastore(None, None) 

209 else: 

210 datastore = Datastore.fromConfig( 

211 config, registry.getDatastoreBridgeManager(), butlerRoot=butlerRoot 

212 ) 

213 # TODO: Once datastore drops dependency on registry we can 

214 # construct datastore first and pass opaque tables to registry 

215 # constructor. 

216 registry.make_datastore_tables(datastore.get_opaque_table_definitions()) 

217 storageClasses = StorageClassFactory() 

218 storageClasses.addFromConfig(config) 

219 

220 return DirectButler( 

221 config=config, 

222 registry=registry, 

223 datastore=datastore, 

224 storageClasses=storageClasses, 

225 metrics=options.metrics, 

226 ) 

227 except Exception: 

228 # Failures here usually mean that configuration is incomplete, 

229 # just issue an error message which includes config file URI. 

230 _LOG.error(f"Failed to instantiate Butler from config {config.configFile}.") 

231 raise 

232 

233 def clone( 

234 self, 

235 *, 

236 collections: CollectionArgType | None | EllipsisType = ..., 

237 run: str | None | EllipsisType = ..., 

238 inferDefaults: bool | EllipsisType = ..., 

239 dataId: dict[str, str] | EllipsisType = ..., 

240 metrics: ButlerMetrics | None = None, 

241 ) -> DirectButler: 

242 # Docstring inherited 

243 defaults = self._registry.defaults.clone(collections, run, inferDefaults, dataId) 

244 registry = self._registry.copy(defaults) 

245 

246 return DirectButler( 

247 registry=registry, 

248 config=self._config, 

249 datastore=self._datastore.clone(registry.getDatastoreBridgeManager()), 

250 storageClasses=self.storageClasses, 

251 metrics=metrics, 

252 ) 

253 

254 def close(self) -> None: 

255 if not self._closed: 

256 self._closed = True 

257 self._registry.close() 

258 # Cause exceptions to be raised if a user attempts to use the 

259 # instance after closing it. Without this, Butler would still 

260 # work after being closed because of implementation details 

261 # of SqlAlchemy, but this may not continue to be the case in the 

262 # future and we don't want users to get in the habit of doing this. 

263 self._registry = _BUTLER_CLOSED_INSTANCE 

264 self._datastore = _BUTLER_CLOSED_INSTANCE 

265 

266 GENERATION: ClassVar[int] = 3 

267 """This is a Generation 3 Butler. 

268 

269 This attribute may be removed in the future, once the Generation 2 Butler 

270 interface has been fully retired; it should only be used in transitional 

271 code. 

272 """ 

273 

274 @classmethod 

275 def _unpickle( 

276 cls, 

277 config: ButlerConfig, 

278 collections: tuple[str, ...] | None, 

279 run: str | None, 

280 defaultDataId: dict[str, str], 

281 writeable: bool, 

282 ) -> DirectButler: 

283 """Callable used to unpickle a Butler. 

284 

285 We prefer not to use ``Butler.__init__`` directly so we can force some 

286 of its many arguments to be keyword-only (note that ``__reduce__`` 

287 can only invoke callables with positional arguments). 

288 

289 Parameters 

290 ---------- 

291 config : `ButlerConfig` 

292 Butler configuration, already coerced into a true `ButlerConfig` 

293 instance (and hence after any search paths for overrides have been 

294 utilized). 

295 collections : `tuple` [ `str` ] 

296 Names of the default collections to read from. 

297 run : `str`, optional 

298 Name of the default `~CollectionType.RUN` collection to write to. 

299 defaultDataId : `dict` [ `str`, `str` ] 

300 Default data ID values. 

301 writeable : `bool` 

302 Whether the Butler should support write operations. 

303 

304 Returns 

305 ------- 

306 butler : `Butler` 

307 A new `Butler` instance. 

308 """ 

309 return cls.create_from_config( 

310 config=config, 

311 options=ButlerInstanceOptions( 

312 collections=collections, run=run, writeable=writeable, kwargs=defaultDataId 

313 ), 

314 ) 

315 

316 def __reduce__(self) -> tuple: 

317 """Support pickling.""" 

318 return ( 

319 DirectButler._unpickle, 

320 ( 

321 self._config, 

322 self.collections.defaults, 

323 self.run, 

324 dict(self._registry.defaults.dataId.required), 

325 self._registry.isWriteable(), 

326 ), 

327 ) 

328 

329 def __str__(self) -> str: 

330 return ( 

331 f"Butler(collections={self.collections}, run={self.run}, " 

332 f"datastore='{self._datastore}', registry='{self._registry}')" 

333 ) 

334 

335 def isWriteable(self) -> bool: 

336 # Docstring inherited. 

337 return self._registry.isWriteable() 

338 

339 def _caching_context(self) -> contextlib.AbstractContextManager[None]: 

340 """Context manager that enables caching.""" 

341 return self._registry.caching_context() 

342 

343 @contextlib.contextmanager 

344 def transaction(self) -> Iterator[None]: 

345 """Context manager supporting `Butler` transactions. 

346 

347 Transactions can be nested. 

348 """ 

349 with self._registry.transaction(), self._datastore.transaction(): 

350 yield 

351 

352 def _standardizeArgs( 

353 self, 

354 datasetRefOrType: DatasetRef | DatasetType | str, 

355 dataId: DataId | None = None, 

356 for_put: bool = True, 

357 **kwargs: Any, 

358 ) -> tuple[DatasetType, DataId | None]: 

359 """Standardize the arguments passed to several Butler APIs. 

360 

361 Parameters 

362 ---------- 

363 datasetRefOrType : `DatasetRef`, `DatasetType`, or `str` 

364 When `DatasetRef` the `dataId` should be `None`. 

365 Otherwise the `DatasetType` or name thereof. 

366 dataId : `dict` or `DataCoordinate` 

367 A `dict` of `Dimension` link name, value pairs that label the 

368 `DatasetRef` within a Collection. When `None`, a `DatasetRef` 

369 should be provided as the second argument. 

370 for_put : `bool`, optional 

371 If `True` this call is invoked as part of a `Butler.put()`. 

372 Otherwise it is assumed to be part of a `Butler.get()`. This 

373 parameter is only relevant if there is dataset type 

374 inconsistency. 

375 **kwargs 

376 Additional keyword arguments used to augment or construct a 

377 `DataCoordinate`. See `DataCoordinate.standardize` 

378 parameters. 

379 

380 Returns 

381 ------- 

382 datasetType : `DatasetType` 

383 A `DatasetType` instance extracted from ``datasetRefOrType``. 

384 dataId : `dict` or `DataId`, optional 

385 Argument that can be used (along with ``kwargs``) to construct a 

386 `DataId`. 

387 

388 Notes 

389 ----- 

390 Butler APIs that conceptually need a DatasetRef also allow passing a 

391 `DatasetType` (or the name of one) and a `DataId` (or a dict and 

392 keyword arguments that can be used to construct one) separately. This 

393 method accepts those arguments and always returns a true `DatasetType` 

394 and a `DataId` or `dict`. 

395 

396 Standardization of `dict` vs `DataId` is best handled by passing the 

397 returned ``dataId`` (and ``kwargs``) to `Registry` APIs, which are 

398 generally similarly flexible. 

399 """ 

400 externalDatasetType: DatasetType | None = None 

401 internalDatasetType: DatasetType | None = None 

402 if isinstance(datasetRefOrType, DatasetRef): 

403 if dataId is not None or kwargs: 

404 raise ValueError("DatasetRef given, cannot use dataId as well") 

405 externalDatasetType = datasetRefOrType.datasetType 

406 dataId = datasetRefOrType.dataId 

407 else: 

408 # Don't check whether DataId is provided, because Registry APIs 

409 # can usually construct a better error message when it wasn't. 

410 if isinstance(datasetRefOrType, DatasetType): 

411 externalDatasetType = datasetRefOrType 

412 else: 

413 internalDatasetType = self.get_dataset_type(datasetRefOrType) 

414 

415 # Check that they are self-consistent 

416 if externalDatasetType is not None: 

417 internalDatasetType = self.get_dataset_type(externalDatasetType.name) 

418 if externalDatasetType != internalDatasetType: 

419 # We can allow differences if they are compatible, depending 

420 # on whether this is a get or a put. A get requires that 

421 # the python type associated with the datastore can be 

422 # converted to the user type. A put requires that the user 

423 # supplied python type can be converted to the internal 

424 # type expected by registry. 

425 relevantDatasetType = internalDatasetType 

426 if for_put: 

427 is_compatible = internalDatasetType.is_compatible_with(externalDatasetType) 

428 else: 

429 is_compatible = externalDatasetType.is_compatible_with(internalDatasetType) 

430 relevantDatasetType = externalDatasetType 

431 if not is_compatible: 

432 raise ValueError( 

433 f"Supplied dataset type ({externalDatasetType}) inconsistent with " 

434 f"registry definition ({internalDatasetType})" 

435 ) 

436 # Override the internal definition. 

437 internalDatasetType = relevantDatasetType 

438 

439 assert internalDatasetType is not None 

440 return internalDatasetType, dataId 

441 

442 def _rewrite_data_id( 

443 self, dataId: DataId | None, datasetType: DatasetType, **kwargs: Any 

444 ) -> tuple[DataId | None, dict[str, Any]]: 

445 """Rewrite a data ID taking into account dimension records. 

446 

447 Take a Data ID and keyword args and rewrite it if necessary to 

448 allow the user to specify dimension records rather than dimension 

449 primary values. 

450 

451 This allows a user to include a dataId dict with keys of 

452 ``exposure.day_obs`` and ``exposure.seq_num`` instead of giving 

453 the integer exposure ID. It also allows a string to be given 

454 for a dimension value rather than the integer ID if that is more 

455 convenient. For example, rather than having to specifying the 

456 detector with ``detector.full_name``, a string given for ``detector`` 

457 will be interpreted as the full name and converted to the integer 

458 value. 

459 

460 Keyword arguments can also use strings for dimensions like detector 

461 and exposure but python does not allow them to include ``.`` and 

462 so the ``exposure.day_obs`` syntax can not be used in a keyword 

463 argument. 

464 

465 Parameters 

466 ---------- 

467 dataId : `dict` or `DataCoordinate` 

468 A `dict` of `Dimension` link name, value pairs that will label the 

469 `DatasetRef` within a Collection. 

470 datasetType : `DatasetType` 

471 The dataset type associated with this dataId. Required to 

472 determine the relevant dimensions. 

473 **kwargs 

474 Additional keyword arguments used to augment or construct a 

475 `DataId`. See `DataId` parameters. 

476 

477 Returns 

478 ------- 

479 dataId : `dict` or `DataCoordinate` 

480 The, possibly rewritten, dataId. If given a `DataCoordinate` and 

481 no keyword arguments, the original dataId will be returned 

482 unchanged. 

483 **kwargs : `dict` 

484 Any unused keyword arguments (would normally be empty dict). 

485 """ 

486 # Process dimension records that are using record information 

487 # rather than ids 

488 newDataId: dict[str, DataIdValue] = {} 

489 byRecord: dict[str, dict[str, Any]] = defaultdict(dict) 

490 

491 if isinstance(dataId, DataCoordinate): 

492 # Do nothing if we have a DataCoordinate and no kwargs. 

493 if not kwargs: 

494 return dataId, kwargs 

495 # If we have a DataCoordinate with kwargs, we know the 

496 # DataCoordinate only has values for real dimensions. 

497 newDataId.update(dataId.mapping) 

498 elif dataId: 

499 # The data is mapping, which means it might have keys like 

500 # "exposure.obs_id" (unlike kwargs, because a "." is not allowed in 

501 # a keyword parameter). 

502 for k, v in dataId.items(): 

503 if isinstance(k, str) and "." in k: 

504 # Someone is using a more human-readable dataId 

505 dimensionName, record = k.split(".", 1) 

506 byRecord[dimensionName][record] = v 

507 else: 

508 newDataId[k] = v 

509 

510 # Go through the updated dataId and check the type in case someone is 

511 # using an alternate key. We have already filtered out the compound 

512 # keys dimensions.record format. 

513 not_dimensions = {} 

514 

515 # Will need to look in the dataId and the keyword arguments 

516 # and will remove them if they need to be fixed or are unrecognized. 

517 for dataIdDict in (newDataId, kwargs): 

518 # Use a list so we can adjust the dict safely in the loop 

519 for dimensionName in list(dataIdDict): 

520 value = dataIdDict[dimensionName] 

521 try: 

522 dimension = self.dimensions.dimensions[dimensionName] 

523 except KeyError: 

524 # This is not a real dimension 

525 not_dimensions[dimensionName] = value 

526 del dataIdDict[dimensionName] 

527 continue 

528 

529 # Convert an integral type to an explicit int to simplify 

530 # comparisons here 

531 if isinstance(value, numbers.Integral): 

532 value = int(value) 

533 

534 if not isinstance(value, dimension.primaryKey.getPythonType()): 

535 for alternate in dimension.alternateKeys: 

536 if isinstance(value, alternate.getPythonType()): 

537 byRecord[dimensionName][alternate.name] = value 

538 del dataIdDict[dimensionName] 

539 _LOG.debug( 

540 "Converting dimension %s to %s.%s=%s", 

541 dimensionName, 

542 dimensionName, 

543 alternate.name, 

544 value, 

545 ) 

546 break 

547 else: 

548 _LOG.warning( 

549 "Type mismatch found for value '%r' provided for dimension %s. " 

550 "Could not find matching alternative (primary key has type %s) " 

551 "so attempting to use as-is.", 

552 value, 

553 dimensionName, 

554 dimension.primaryKey.getPythonType(), 

555 ) 

556 

557 # By this point kwargs and newDataId should only include valid 

558 # dimensions. Merge kwargs in to the new dataId and log if there 

559 # are dimensions in both (rather than calling update). 

560 for k, v in kwargs.items(): 

561 if k in newDataId and newDataId[k] != v: 

562 _LOG.debug( 

563 "Keyword arg %s overriding explicit value in dataId of %s with %s", k, newDataId[k], v 

564 ) 

565 newDataId[k] = v 

566 # No need to retain any values in kwargs now. 

567 kwargs = {} 

568 

569 # If we have some unrecognized dimensions we have to try to connect 

570 # them to records in other dimensions. This is made more complicated 

571 # by some dimensions having records with clashing names. A mitigation 

572 # is that we can tell by this point which dimensions are missing 

573 # for the DatasetType but this does not work for calibrations 

574 # where additional dimensions can be used to constrain the temporal 

575 # axis. 

576 if not_dimensions: 

577 # Search for all dimensions even if we have been given a value 

578 # explicitly. In some cases records are given as well as the 

579 # actually dimension and this should not be an error if they 

580 # match. 

581 mandatoryDimensions = datasetType.dimensions.names # - provided 

582 

583 candidateDimensions: set[str] = set() 

584 candidateDimensions.update(mandatoryDimensions) 

585 

586 # For calibrations we may well be needing temporal dimensions 

587 # so rather than always including all dimensions in the scan 

588 # restrict things a little. It is still possible for there 

589 # to be confusion over day_obs in visit vs exposure for example. 

590 # If we are not searching calibration collections things may 

591 # fail but they are going to fail anyway because of the 

592 # ambiguousness of the dataId... 

593 if datasetType.isCalibration(): 

594 for dim in self.dimensions.dimensions: 

595 if dim.temporal: 

596 candidateDimensions.add(str(dim)) 

597 

598 # Look up table for the first association with a dimension 

599 guessedAssociation: dict[str, dict[str, Any]] = defaultdict(dict) 

600 

601 # Keep track of whether an item is associated with multiple 

602 # dimensions. 

603 counter: Counter[str] = Counter() 

604 assigned: dict[str, set[str]] = defaultdict(set) 

605 

606 # Go through the missing dimensions and associate the 

607 # given names with records within those dimensions 

608 matched_dims = set() 

609 for dimensionName in candidateDimensions: 

610 dimension = self.dimensions.dimensions[dimensionName] 

611 fields = dimension.metadata.names | dimension.uniqueKeys.names 

612 for field in not_dimensions: 

613 if field in fields: 

614 guessedAssociation[dimensionName][field] = not_dimensions[field] 

615 counter[dimensionName] += 1 

616 assigned[field].add(dimensionName) 

617 matched_dims.add(field) 

618 

619 # Calculate the fields that matched nothing. 

620 never_found = set(not_dimensions) - matched_dims 

621 

622 if never_found: 

623 raise DimensionValueError(f"Unrecognized keyword args given: {never_found}") 

624 

625 # There is a chance we have allocated a single dataId item 

626 # to multiple dimensions. Need to decide which should be retained. 

627 # For now assume that the most popular alternative wins. 

628 # This means that day_obs with seq_num will result in 

629 # exposure.day_obs and not visit.day_obs 

630 # Also prefer an explicitly missing dimension over an inferred 

631 # temporal dimension. 

632 for fieldName, assignedDimensions in assigned.items(): 

633 if len(assignedDimensions) > 1: 

634 # Pick the most popular (preferring mandatory dimensions) 

635 requiredButMissing = assignedDimensions.intersection(mandatoryDimensions) 

636 if requiredButMissing: 

637 candidateDimensions = requiredButMissing 

638 else: 

639 candidateDimensions = assignedDimensions 

640 

641 # If this is a choice between visit and exposure and 

642 # neither was a required part of the dataset type, 

643 # (hence in this branch) always prefer exposure over 

644 # visit since exposures are always defined and visits 

645 # are defined from exposures. 

646 if candidateDimensions == {"exposure", "visit"}: 

647 candidateDimensions = {"exposure"} 

648 

649 # Select the relevant items and get a new restricted 

650 # counter. 

651 theseCounts = {k: v for k, v in counter.items() if k in candidateDimensions} 

652 duplicatesCounter: Counter[str] = Counter() 

653 duplicatesCounter.update(theseCounts) 

654 

655 # Choose the most common. If they are equally common 

656 # we will pick the one that was found first. 

657 # Returns a list of tuples 

658 selected = duplicatesCounter.most_common(1)[0][0] 

659 

660 _LOG.debug( 

661 "Ambiguous dataId entry '%s' associated with multiple dimensions: %s." 

662 " Removed ambiguity by choosing dimension %s.", 

663 fieldName, 

664 ", ".join(assignedDimensions), 

665 selected, 

666 ) 

667 

668 for candidateDimension in assignedDimensions: 

669 if candidateDimension != selected: 

670 del guessedAssociation[candidateDimension][fieldName] 

671 

672 # Update the record look up dict with the new associations 

673 for dimensionName, values in guessedAssociation.items(): 

674 if values: # A dict might now be empty 

675 _LOG.debug( 

676 "Assigned non-dimension dataId keys to dimension %s: %s", dimensionName, values 

677 ) 

678 byRecord[dimensionName].update(values) 

679 

680 if byRecord: 

681 # Some record specifiers were found so we need to convert 

682 # them to the Id form 

683 for dimensionName, values in byRecord.items(): 

684 if dimensionName in newDataId: 

685 _LOG.debug( 

686 "DataId specified explicit %s dimension value of %s in addition to" 

687 " general record specifiers for it of %s. Checking for self-consistency.", 

688 dimensionName, 

689 newDataId[dimensionName], 

690 str(values), 

691 ) 

692 # Get the actual record and compare with these values. 

693 # Only query with relevant data ID values. 

694 filtered_data_id = { 

695 k: v for k, v in newDataId.items() if k in self.dimensions[dimensionName].required 

696 } 

697 try: 

698 recs = self.query_dimension_records( 

699 dimensionName, 

700 data_id=filtered_data_id, 

701 ) 

702 except (DataIdError, EmptyQueryResultError): 

703 raise DimensionValueError( 

704 f"Could not find dimension '{dimensionName}'" 

705 f" with dataId {filtered_data_id} as part of comparing with" 

706 f" record values {byRecord[dimensionName]}" 

707 ) from None 

708 if len(recs) == 1: 

709 errmsg: list[str] = [] 

710 for k, v in values.items(): 

711 if (recval := getattr(recs[0], k)) != v: 

712 errmsg.append(f"{k} ({recval} != {v})") 

713 if errmsg: 

714 raise DimensionValueError( 

715 f"Dimension {dimensionName} in dataId has explicit value" 

716 f" {newDataId[dimensionName]} inconsistent with" 

717 f" {dimensionName} dimension record: " + ", ".join(errmsg) 

718 ) 

719 else: 

720 # Multiple matches for an explicit dimension 

721 # should never happen but let downstream complain. 

722 pass 

723 continue 

724 

725 # Do not use data ID keys in query that aren't relevant. 

726 # Otherwise we can have detector queries being constrained 

727 # by an exposure ID that doesn't exist and return no matches 

728 # for a detector even though it's a good detector name. 

729 filtered_data_id = { 

730 k: v 

731 for k, v in newDataId.items() 

732 if k in self.dimensions[dimensionName].minimal_group.names 

733 } 

734 

735 def _get_attr(obj: Any, attr: str) -> Any: 

736 # Used to implement x.exposure.seq_num when given 

737 # x and "exposure.seq_num". 

738 for component in attr.split("."): 

739 obj = getattr(obj, component) 

740 return obj 

741 

742 with self.query() as q: 

743 x = q.expression_factory 

744 # Build up a WHERE expression. 

745 predicates = tuple(_get_attr(x, f"{dimensionName}.{k}") == v for k, v in values.items()) 

746 extra_args: dict[str, Any] = {} # For mypy. 

747 extra_args.update(filtered_data_id) 

748 extra_args.update(kwargs) 

749 q = q.where(x.all(*predicates), **extra_args) 

750 records = set(q.dimension_records(dimensionName)) 

751 

752 if len(records) != 1: 

753 if len(records) > 1: 

754 # visit can have an ambiguous answer without involving 

755 # visit_system. The default visit_system is defined 

756 # by the instrument. 

757 if ( 

758 dimensionName == "visit" 

759 and "visit_system_membership" in self.dimensions 

760 and "visit_system" in self.dimensions["instrument"].metadata 

761 ): 

762 instrument_records = self.query_dimension_records( 

763 "instrument", 

764 data_id=newDataId, 

765 explain=False, 

766 **kwargs, 

767 ) 

768 if len(instrument_records) == 1: 

769 visit_system = instrument_records[0].visit_system 

770 if visit_system is None: 

771 # Set to a value that will never match. 

772 visit_system = -1 

773 

774 # Look up each visit in the 

775 # visit_system_membership records. 

776 for rec in records: 

777 membership = self.query_dimension_records( 

778 # Use bind to allow zero results. 

779 # This is a fully-specified query. 

780 "visit_system_membership", 

781 instrument=instrument_records[0].name, 

782 visit_system=visit_system, 

783 visit=rec.id, 

784 explain=False, 

785 ) 

786 if membership: 

787 # This record is the right answer. 

788 records = {rec} 

789 break 

790 

791 # The ambiguity may have been resolved so check again. 

792 if len(records) > 1: 

793 _LOG.debug( 

794 "Received %d records from constraints of %s", len(records), str(values) 

795 ) 

796 for r in records: 

797 _LOG.debug("- %s", str(r)) 

798 raise DimensionValueError( 

799 f"DataId specification for dimension {dimensionName} is not" 

800 f" uniquely constrained to a single dataset by {values}." 

801 f" Got {len(records)} results." 

802 ) 

803 else: 

804 raise DimensionValueError( 

805 f"DataId specification for dimension {dimensionName} matched no" 

806 f" records when constrained by {values}" 

807 ) 

808 

809 # Get the primary key from the real dimension object 

810 dimension = self.dimensions.dimensions[dimensionName] 

811 if not isinstance(dimension, Dimension): 

812 raise RuntimeError( 

813 f"{dimension.name} is not a true dimension, and cannot be used in data IDs." 

814 ) 

815 newDataId[dimensionName] = getattr(records.pop(), dimension.primaryKey.name) 

816 

817 return newDataId, kwargs 

818 

819 def _findDatasetRef( 

820 self, 

821 datasetRefOrType: DatasetRef | DatasetType | str, 

822 dataId: DataId | None = None, 

823 *, 

824 collections: Any = None, 

825 predict: bool = False, 

826 run: str | None = None, 

827 datastore_records: bool = False, 

828 timespan: Timespan | None = None, 

829 **kwargs: Any, 

830 ) -> DatasetRef: 

831 """Shared logic for methods that start with a search for a dataset in 

832 the registry. 

833 

834 Parameters 

835 ---------- 

836 datasetRefOrType : `DatasetRef`, `DatasetType`, or `str` 

837 When `DatasetRef` the `dataId` should be `None`. 

838 Otherwise the `DatasetType` or name thereof. 

839 dataId : `dict` or `DataCoordinate`, optional 

840 A `dict` of `Dimension` link name, value pairs that label the 

841 `DatasetRef` within a Collection. When `None`, a `DatasetRef` 

842 should be provided as the first argument. 

843 collections : Any, optional 

844 Collections to be searched, overriding ``self.collections``. 

845 Can be any of the types supported by the ``collections`` argument 

846 to butler construction. 

847 predict : `bool`, optional 

848 If `True`, return a newly created `DatasetRef` with a unique 

849 dataset ID if finding a reference in the `Registry` fails. 

850 Defaults to `False`. 

851 run : `str`, optional 

852 Run collection name to use for creating `DatasetRef` for predicted 

853 datasets. Only used if ``predict`` is `True`. 

854 datastore_records : `bool`, optional 

855 If `True` add datastore records to returned `DatasetRef`. 

856 timespan : `Timespan` or `None`, optional 

857 A timespan that the validity range of the dataset must overlap. 

858 If not provided and this is a calibration dataset type, an attempt 

859 will be made to find the timespan from any temporal coordinate 

860 in the data ID. 

861 **kwargs 

862 Additional keyword arguments used to augment or construct a 

863 `DataId`. See `DataId` parameters. 

864 

865 Returns 

866 ------- 

867 ref : `DatasetRef` 

868 A reference to the dataset identified by the given arguments. 

869 This can be the same dataset reference as given if it was 

870 resolved. 

871 

872 Raises 

873 ------ 

874 LookupError 

875 Raised if no matching dataset exists in the `Registry` (and 

876 ``predict`` is `False`). 

877 ValueError 

878 Raised if a resolved `DatasetRef` was passed as an input, but it 

879 differs from the one found in the registry. 

880 TypeError 

881 Raised if no collections were provided. 

882 """ 

883 datasetType, dataId = self._standardizeArgs(datasetRefOrType, dataId, for_put=False, **kwargs) 

884 if isinstance(datasetRefOrType, DatasetRef): 

885 if collections is not None: 

886 warnings.warn("Collections should not be specified with DatasetRef", stacklevel=3) 

887 # May need to retrieve datastore records if requested. 

888 if datastore_records and datasetRefOrType._datastore_records is None: 

889 datasetRefOrType = self._registry.get_datastore_records(datasetRefOrType) 

890 return datasetRefOrType 

891 

892 dataId, kwargs = self._rewrite_data_id(dataId, datasetType, **kwargs) 

893 

894 if datasetType.isCalibration(): 

895 # Because this is a calibration dataset, first try to make a 

896 # standardize the data ID without restricting the dimensions to 

897 # those of the dataset type requested, because there may be extra 

898 # dimensions that provide temporal information for a validity-range 

899 # lookup. 

900 dataId = DataCoordinate.standardize( 

901 dataId, universe=self.dimensions, defaults=self._registry.defaults.dataId, **kwargs 

902 ) 

903 if timespan is None: 

904 if dataId.dimensions.temporal: 

905 dataId = self._registry.expandDataId(dataId) 

906 # Use the timespan from the data ID to constrain the 

907 # calibration lookup, but only if the caller has not 

908 # specified an explicit timespan. 

909 timespan = dataId.timespan 

910 else: 

911 # Try an arbitrary timespan. Downstream will fail if this 

912 # results in more than one matching dataset. 

913 timespan = Timespan(None, None) 

914 else: 

915 # Standardize the data ID to just the dimensions of the dataset 

916 # type instead of letting registry.findDataset do it, so we get the 

917 # result even if no dataset is found. 

918 dataId = DataCoordinate.standardize( 

919 dataId, 

920 dimensions=datasetType.dimensions, 

921 defaults=self._registry.defaults.dataId, 

922 **kwargs, 

923 ) 

924 # Always lookup the DatasetRef, even if one is given, to ensure it is 

925 # present in the current collection. 

926 ref = self.find_dataset( 

927 datasetType, 

928 dataId, 

929 collections=collections, 

930 timespan=timespan, 

931 datastore_records=datastore_records, 

932 ) 

933 if ref is None: 

934 if predict: 

935 if run is None: 

936 run = self.run 

937 if run is None: 

938 raise TypeError("Cannot predict dataset ID/location with run=None.") 

939 return DatasetRef(datasetType, dataId, run=run) 

940 else: 

941 if collections is None: 

942 collections = self._registry.defaults.collections 

943 raise DatasetNotFoundError( 

944 f"Dataset {datasetType.name} with data ID {dataId} " 

945 f"could not be found in collections {collections}." 

946 ) 

947 if datasetType != ref.datasetType: 

948 # If they differ it is because the user explicitly specified 

949 # a compatible dataset type to this call rather than using the 

950 # registry definition. The DatasetRef must therefore be recreated 

951 # using the user definition such that the expected type is 

952 # returned. 

953 ref = DatasetRef( 

954 datasetType, ref.dataId, run=ref.run, id=ref.id, datastore_records=ref._datastore_records 

955 ) 

956 

957 return ref 

958 

959 @transactional 

960 def put( 

961 self, 

962 obj: Any, 

963 datasetRefOrType: DatasetRef | DatasetType | str, 

964 /, 

965 dataId: DataId | None = None, 

966 *, 

967 run: str | None = None, 

968 provenance: DatasetProvenance | None = None, 

969 **kwargs: Any, 

970 ) -> DatasetRef: 

971 """Store and register a dataset. 

972 

973 Parameters 

974 ---------- 

975 obj : `object` 

976 The dataset. 

977 datasetRefOrType : `DatasetRef`, `DatasetType`, or `str` 

978 When `DatasetRef` is provided, ``dataId`` should be `None`. 

979 Otherwise the `DatasetType` or name thereof. If a fully resolved 

980 `DatasetRef` is given the run and ID are used directly. 

981 dataId : `dict` or `DataCoordinate` 

982 A `dict` of `Dimension` link name, value pairs that label the 

983 `DatasetRef` within a Collection. When `None`, a `DatasetRef` 

984 should be provided as the second argument. 

985 run : `str`, optional 

986 The name of the run the dataset should be added to, overriding 

987 ``self.run``. Not used if a resolved `DatasetRef` is provided. 

988 provenance : `DatasetProvenance` or `None`, optional 

989 Any provenance that should be attached to the serialized dataset. 

990 Not supported by all serialization mechanisms. 

991 **kwargs 

992 Additional keyword arguments used to augment or construct a 

993 `DataCoordinate`. See `DataCoordinate.standardize` 

994 parameters. Not used if a resolve `DatasetRef` is provided. 

995 

996 Returns 

997 ------- 

998 ref : `DatasetRef` 

999 A reference to the stored dataset, updated with the correct id if 

1000 given. 

1001 

1002 Raises 

1003 ------ 

1004 TypeError 

1005 Raised if the butler is read-only or if no run has been provided. 

1006 """ 

1007 if isinstance(datasetRefOrType, DatasetRef): 

1008 # This is a direct put of predefined DatasetRef. 

1009 _LOG.debug("Butler put direct: %s", datasetRefOrType) 

1010 if run is not None: 

1011 warnings.warn("Run collection is not used for DatasetRef", stacklevel=3) 

1012 

1013 with self._metrics.instrument_put(_LOG, msg="Dataset put direct"): 

1014 # If registry already has a dataset with the same dataset ID, 

1015 # dataset type and DataId, then _importDatasets will do 

1016 # nothing and just return an original ref. We have to raise in 

1017 # this case, there is a datastore check below for that. 

1018 self._registry._importDatasets([datasetRefOrType], expand=True) 

1019 # Before trying to write to the datastore check that it does 

1020 # not know this dataset. This is prone to races, of course. 

1021 if self._datastore.knows(datasetRefOrType): 

1022 raise ConflictingDefinitionError( 

1023 f"Datastore already contains dataset: {datasetRefOrType}" 

1024 ) 

1025 # Try to write dataset to the datastore, if it fails due to a 

1026 # race with another write, the content of stored data may be 

1027 # unpredictable. 

1028 try: 

1029 self._datastore.put(obj, datasetRefOrType, provenance=provenance) 

1030 except IntegrityError as e: 

1031 raise ConflictingDefinitionError(f"Datastore already contains dataset: {e}") from e 

1032 

1033 return datasetRefOrType 

1034 

1035 _LOG.debug("Butler put: %s, dataId=%s, run=%s", datasetRefOrType, dataId, run) 

1036 if not self.isWriteable(): 

1037 raise TypeError("Butler is read-only.") 

1038 

1039 with self._metrics.instrument_put(_LOG, msg="Dataset put with dataID"): 

1040 datasetType, dataId = self._standardizeArgs(datasetRefOrType, dataId, **kwargs) 

1041 

1042 # Handle dimension records in dataId 

1043 dataId, kwargs = self._rewrite_data_id(dataId, datasetType, **kwargs) 

1044 

1045 # Add Registry Dataset entry. 

1046 dataId = self._registry.expandDataId(dataId, dimensions=datasetType.dimensions, **kwargs) 

1047 (ref,) = self._registry.insertDatasets(datasetType, run=run, dataIds=[dataId]) 

1048 self._datastore.put(obj, ref, provenance=provenance) 

1049 

1050 return ref 

1051 

1052 def getDeferred( 

1053 self, 

1054 datasetRefOrType: DatasetRef | DatasetType | str, 

1055 /, 

1056 dataId: DataId | None = None, 

1057 *, 

1058 parameters: dict | None = None, 

1059 collections: Any = None, 

1060 storageClass: str | StorageClass | None = None, 

1061 timespan: Timespan | None = None, 

1062 **kwargs: Any, 

1063 ) -> DeferredDatasetHandle: 

1064 """Create a `DeferredDatasetHandle` which can later retrieve a dataset, 

1065 after an immediate registry lookup. 

1066 

1067 Parameters 

1068 ---------- 

1069 datasetRefOrType : `DatasetRef`, `DatasetType`, or `str` 

1070 When `DatasetRef` the `dataId` should be `None`. 

1071 Otherwise the `DatasetType` or name thereof. 

1072 dataId : `dict` or `DataCoordinate`, optional 

1073 A `dict` of `Dimension` link name, value pairs that label the 

1074 `DatasetRef` within a Collection. When `None`, a `DatasetRef` 

1075 should be provided as the first argument. 

1076 parameters : `dict` 

1077 Additional StorageClass-defined options to control reading, 

1078 typically used to efficiently read only a subset of the dataset. 

1079 collections : Any, optional 

1080 Collections to be searched, overriding ``self.collections``. 

1081 Can be any of the types supported by the ``collections`` argument 

1082 to butler construction. 

1083 storageClass : `StorageClass` or `str`, optional 

1084 The storage class to be used to override the Python type 

1085 returned by this method. By default the returned type matches 

1086 the dataset type definition for this dataset. Specifying a 

1087 read `StorageClass` can force a different type to be returned. 

1088 This type must be compatible with the original type. 

1089 timespan : `Timespan` or `None`, optional 

1090 A timespan that the validity range of the dataset must overlap. 

1091 If not provided and this is a calibration dataset type, an attempt 

1092 will be made to find the timespan from any temporal coordinate 

1093 in the data ID. 

1094 **kwargs 

1095 Additional keyword arguments used to augment or construct a 

1096 `DataId`. See `DataId` parameters. 

1097 

1098 Returns 

1099 ------- 

1100 obj : `DeferredDatasetHandle` 

1101 A handle which can be used to retrieve a dataset at a later time. 

1102 

1103 Raises 

1104 ------ 

1105 LookupError 

1106 Raised if no matching dataset exists in the `Registry` or 

1107 datastore. 

1108 ValueError 

1109 Raised if a resolved `DatasetRef` was passed as an input, but it 

1110 differs from the one found in the registry. 

1111 TypeError 

1112 Raised if no collections were provided. 

1113 """ 

1114 if isinstance(datasetRefOrType, DatasetRef): 

1115 # Do the quick check first and if that fails, check for artifact 

1116 # existence. This is necessary for datastores that are configured 

1117 # in trust mode where there won't be a record but there will be 

1118 # a file. 

1119 if self._datastore.knows(datasetRefOrType) or self._datastore.exists(datasetRefOrType): 

1120 ref = datasetRefOrType 

1121 else: 

1122 raise LookupError(f"Dataset reference {datasetRefOrType} does not exist.") 

1123 else: 

1124 ref = self._findDatasetRef( 

1125 datasetRefOrType, dataId, collections=collections, timespan=timespan, **kwargs 

1126 ) 

1127 return DeferredDatasetHandle(butler=self, ref=ref, parameters=parameters, storageClass=storageClass) 

1128 

1129 def get( 

1130 self, 

1131 datasetRefOrType: DatasetRef | DatasetType | str, 

1132 /, 

1133 dataId: DataId | None = None, 

1134 *, 

1135 parameters: dict[str, Any] | None = None, 

1136 collections: Any = None, 

1137 storageClass: StorageClass | str | None = None, 

1138 timespan: Timespan | None = None, 

1139 **kwargs: Any, 

1140 ) -> Any: 

1141 """Retrieve a stored dataset. 

1142 

1143 Parameters 

1144 ---------- 

1145 datasetRefOrType : `DatasetRef`, `DatasetType`, or `str` 

1146 When `DatasetRef` the `dataId` should be `None`. 

1147 Otherwise the `DatasetType` or name thereof. 

1148 If a resolved `DatasetRef`, the associated dataset 

1149 is returned directly without additional querying. 

1150 dataId : `dict` or `DataCoordinate` 

1151 A `dict` of `Dimension` link name, value pairs that label the 

1152 `DatasetRef` within a Collection. When `None`, a `DatasetRef` 

1153 should be provided as the first argument. 

1154 parameters : `dict` 

1155 Additional StorageClass-defined options to control reading, 

1156 typically used to efficiently read only a subset of the dataset. 

1157 collections : Any, optional 

1158 Collections to be searched, overriding ``self.collections``. 

1159 Can be any of the types supported by the ``collections`` argument 

1160 to butler construction. 

1161 storageClass : `StorageClass` or `str`, optional 

1162 The storage class to be used to override the Python type 

1163 returned by this method. By default the returned type matches 

1164 the dataset type definition for this dataset. Specifying a 

1165 read `StorageClass` can force a different type to be returned. 

1166 This type must be compatible with the original type. 

1167 timespan : `Timespan` or `None`, optional 

1168 A timespan that the validity range of the dataset must overlap. 

1169 If not provided and this is a calibration dataset type, an attempt 

1170 will be made to find the timespan from any temporal coordinate 

1171 in the data ID. 

1172 **kwargs 

1173 Additional keyword arguments used to augment or construct a 

1174 `DataCoordinate`. See `DataCoordinate.standardize` 

1175 parameters. 

1176 

1177 Returns 

1178 ------- 

1179 obj : `object` 

1180 The dataset. 

1181 

1182 Raises 

1183 ------ 

1184 LookupError 

1185 Raised if no matching dataset exists in the `Registry`. 

1186 TypeError 

1187 Raised if no collections were provided. 

1188 

1189 Notes 

1190 ----- 

1191 When looking up datasets in a `~CollectionType.CALIBRATION` collection, 

1192 this method requires that the given data ID include temporal dimensions 

1193 beyond the dimensions of the dataset type itself, in order to find the 

1194 dataset with the appropriate validity range. For example, a "bias" 

1195 dataset with native dimensions ``{instrument, detector}`` could be 

1196 fetched with a ``{instrument, detector, exposure}`` data ID, because 

1197 ``exposure`` is a temporal dimension. 

1198 """ 

1199 _LOG.debug("Butler get: %s, dataId=%s, parameters=%s", datasetRefOrType, dataId, parameters) 

1200 with self._metrics.instrument_get(_LOG, msg="Retrieved dataset"): 

1201 ref = self._findDatasetRef( 

1202 datasetRefOrType, 

1203 dataId, 

1204 collections=collections, 

1205 datastore_records=True, 

1206 timespan=timespan, 

1207 **kwargs, 

1208 ) 

1209 return self._datastore.get(ref, parameters=parameters, storageClass=storageClass) 

1210 

1211 def getURIs( 

1212 self, 

1213 datasetRefOrType: DatasetRef | DatasetType | str, 

1214 /, 

1215 dataId: DataId | None = None, 

1216 *, 

1217 predict: bool = False, 

1218 collections: Any = None, 

1219 run: str | None = None, 

1220 **kwargs: Any, 

1221 ) -> DatasetRefURIs: 

1222 """Return the URIs associated with the dataset. 

1223 

1224 Parameters 

1225 ---------- 

1226 datasetRefOrType : `DatasetRef`, `DatasetType`, or `str` 

1227 When `DatasetRef` the `dataId` should be `None`. 

1228 Otherwise the `DatasetType` or name thereof. 

1229 dataId : `dict` or `DataCoordinate` 

1230 A `dict` of `Dimension` link name, value pairs that label the 

1231 `DatasetRef` within a Collection. When `None`, a `DatasetRef` 

1232 should be provided as the first argument. 

1233 predict : `bool` 

1234 If `True`, allow URIs to be returned of datasets that have not 

1235 been written. 

1236 collections : Any, optional 

1237 Collections to be searched, overriding ``self.collections``. 

1238 Can be any of the types supported by the ``collections`` argument 

1239 to butler construction. 

1240 run : `str`, optional 

1241 Run to use for predictions, overriding ``self.run``. 

1242 **kwargs 

1243 Additional keyword arguments used to augment or construct a 

1244 `DataCoordinate`. See `DataCoordinate.standardize` 

1245 parameters. 

1246 

1247 Returns 

1248 ------- 

1249 uris : `DatasetRefURIs` 

1250 The URI to the primary artifact associated with this dataset (if 

1251 the dataset was disassembled within the datastore this may be 

1252 `None`), and the URIs to any components associated with the dataset 

1253 artifact. (can be empty if there are no components). 

1254 """ 

1255 ref = self._findDatasetRef( 

1256 datasetRefOrType, dataId, predict=predict, run=run, collections=collections, **kwargs 

1257 ) 

1258 return self._datastore.getURIs(ref, predict) 

1259 

1260 def get_dataset_type(self, name: str) -> DatasetType: 

1261 return self._registry.getDatasetType(name) 

1262 

1263 def get_dataset( 

1264 self, 

1265 id: DatasetId | str, 

1266 *, 

1267 storage_class: str | StorageClass | None = None, 

1268 dimension_records: bool = False, 

1269 datastore_records: bool = False, 

1270 ) -> DatasetRef | None: 

1271 id = _to_uuid(id) 

1272 ref = self._registry.getDataset(id) 

1273 if ref is not None: 

1274 if dimension_records: 

1275 ref = ref.expanded( 

1276 self._registry.expandDataId(ref.dataId, dimensions=ref.datasetType.dimensions) 

1277 ) 

1278 if storage_class: 

1279 ref = ref.overrideStorageClass(storage_class) 

1280 if datastore_records: 

1281 ref = self._registry.get_datastore_records(ref) 

1282 return ref 

1283 

1284 def get_many_datasets(self, ids: Iterable[DatasetId | str]) -> list[DatasetRef]: 

1285 uuids = [_to_uuid(id) for id in ids] 

1286 return self._registry._managers.datasets.get_dataset_refs(uuids) 

1287 

1288 def find_dataset( 

1289 self, 

1290 dataset_type: DatasetType | str, 

1291 data_id: DataId | None = None, 

1292 *, 

1293 collections: str | Sequence[str] | None = None, 

1294 timespan: Timespan | None = None, 

1295 storage_class: str | StorageClass | None = None, 

1296 dimension_records: bool = False, 

1297 datastore_records: bool = False, 

1298 **kwargs: Any, 

1299 ) -> DatasetRef | None: 

1300 # Handle any parts of the dataID that are not using primary dimension 

1301 # keys. 

1302 if isinstance(dataset_type, str): 

1303 actual_type = self.get_dataset_type(dataset_type) 

1304 else: 

1305 actual_type = dataset_type 

1306 

1307 # Store the component for later. 

1308 component_name = actual_type.component() 

1309 if actual_type.isComponent(): 

1310 parent_type = actual_type.makeCompositeDatasetType() 

1311 else: 

1312 parent_type = actual_type 

1313 

1314 data_id, kwargs = self._rewrite_data_id(data_id, parent_type, **kwargs) 

1315 

1316 ref = self.registry.findDataset( 

1317 parent_type, 

1318 data_id, 

1319 collections=collections, 

1320 timespan=timespan, 

1321 datastore_records=datastore_records, 

1322 **kwargs, 

1323 ) 

1324 if ref is not None and dimension_records: 

1325 ref = ref.expanded(self._registry.expandDataId(ref.dataId, dimensions=ref.datasetType.dimensions)) 

1326 if ref is not None and component_name: 

1327 ref = ref.makeComponentRef(component_name) 

1328 if ref is not None and storage_class is not None: 

1329 ref = ref.overrideStorageClass(storage_class) 

1330 

1331 return ref 

1332 

1333 def retrieve_artifacts_zip( 

1334 self, 

1335 refs: Iterable[DatasetRef], 

1336 destination: ResourcePathExpression, 

1337 overwrite: bool = True, 

1338 ) -> ResourcePath: 

1339 return retrieve_and_zip(refs, destination, self._datastore.retrieveArtifacts, overwrite) 

1340 

1341 def retrieveArtifacts( 

1342 self, 

1343 refs: Iterable[DatasetRef], 

1344 destination: ResourcePathExpression, 

1345 transfer: str = "auto", 

1346 preserve_path: bool = True, 

1347 overwrite: bool = False, 

1348 ) -> list[ResourcePath]: 

1349 # Docstring inherited. 

1350 outdir = ResourcePath(destination) 

1351 artifact_map = self._datastore.retrieveArtifacts( 

1352 refs, 

1353 outdir, 

1354 transfer=transfer, 

1355 preserve_path=preserve_path, 

1356 overwrite=overwrite, 

1357 write_index=True, 

1358 ) 

1359 return list(artifact_map) 

1360 

1361 def exists( 

1362 self, 

1363 dataset_ref_or_type: DatasetRef | DatasetType | str, 

1364 /, 

1365 data_id: DataId | None = None, 

1366 *, 

1367 full_check: bool = True, 

1368 collections: Any = None, 

1369 **kwargs: Any, 

1370 ) -> DatasetExistence: 

1371 # Docstring inherited. 

1372 existence = DatasetExistence.UNRECOGNIZED 

1373 

1374 if isinstance(dataset_ref_or_type, DatasetRef): 

1375 if collections is not None: 

1376 warnings.warn("Collections should not be specified with DatasetRef", stacklevel=2) 

1377 if data_id is not None: 

1378 warnings.warn("A DataID should not be specified with DatasetRef", stacklevel=2) 

1379 ref = dataset_ref_or_type 

1380 registry_ref = self._registry.getDataset(dataset_ref_or_type.id) 

1381 if registry_ref is not None: 

1382 existence |= DatasetExistence.RECORDED 

1383 

1384 if dataset_ref_or_type != registry_ref: 

1385 # This could mean that storage classes differ, so we should 

1386 # check for that but use the registry ref for the rest of 

1387 # the method. 

1388 if registry_ref.is_compatible_with(dataset_ref_or_type): 

1389 # Use the registry version from now on. 

1390 ref = registry_ref 

1391 else: 

1392 raise ValueError( 

1393 f"The ref given to exists() ({ref}) has the same dataset ID as one " 

1394 f"in registry but has different incompatible values ({registry_ref})." 

1395 ) 

1396 else: 

1397 try: 

1398 ref = self._findDatasetRef(dataset_ref_or_type, data_id, collections=collections, **kwargs) 

1399 except (LookupError, TypeError): 

1400 return existence 

1401 existence |= DatasetExistence.RECORDED 

1402 

1403 if self._datastore.knows(ref): 

1404 existence |= DatasetExistence.DATASTORE 

1405 

1406 if full_check: 

1407 if self._datastore.exists(ref): 

1408 existence |= DatasetExistence._ARTIFACT 

1409 elif existence.value != DatasetExistence.UNRECOGNIZED.value: 

1410 # Do not add this flag if we have no other idea about a dataset. 

1411 existence |= DatasetExistence(DatasetExistence._ASSUMED) 

1412 

1413 return existence 

1414 

1415 def _exists_many( 

1416 self, 

1417 refs: Iterable[DatasetRef], 

1418 /, 

1419 *, 

1420 full_check: bool = True, 

1421 ) -> dict[DatasetRef, DatasetExistence]: 

1422 # Docstring inherited. 

1423 existence = {ref: DatasetExistence.UNRECOGNIZED for ref in refs} 

1424 

1425 # Check which refs exist in the registry. 

1426 id_map = {ref.id: ref for ref in existence.keys()} 

1427 for registry_ref in self.get_many_datasets(id_map.keys()): 

1428 # Consistency between the given DatasetRef and the information 

1429 # recorded in the registry is not verified. 

1430 existence[id_map[registry_ref.id]] |= DatasetExistence.RECORDED 

1431 

1432 # Ask datastore if it knows about these refs. 

1433 knows = self._datastore.knows_these(refs) 

1434 for ref, known in knows.items(): 

1435 if known: 

1436 existence[ref] |= DatasetExistence.DATASTORE 

1437 

1438 if full_check: 

1439 mexists = self._datastore.mexists(refs) 

1440 for ref, exists in mexists.items(): 

1441 if exists: 

1442 existence[ref] |= DatasetExistence._ARTIFACT 

1443 else: 

1444 # Do not set this flag if nothing is known about the dataset. 

1445 for ref in existence: 

1446 if existence[ref] != DatasetExistence.UNRECOGNIZED: 

1447 existence[ref] |= DatasetExistence._ASSUMED 

1448 

1449 return existence 

1450 

1451 def removeRuns( 

1452 self, 

1453 names: Iterable[str], 

1454 unstore: bool | type[_DeprecatedDefault] = _DeprecatedDefault, 

1455 *, 

1456 unlink_from_chains: bool = False, 

1457 ) -> None: 

1458 # Docstring inherited. 

1459 if not self.isWriteable(): 

1460 raise TypeError("Butler is read-only.") 

1461 

1462 if unstore is not _DeprecatedDefault: 

1463 # The value was passed in by a user. Must report it is now 

1464 # ignored. 

1465 if unstore is True: 

1466 msg = "The unstore parameter is deprecated and is now always treated as True. " 

1467 else: 

1468 msg = "The unstore parameter for removeRuns can no longer be False and is now ignored. " 

1469 warnings.warn( 

1470 msg + " The parameter will be removed after v30.", 

1471 category=FutureWarning, 

1472 stacklevel=find_outside_stacklevel("lsst.daf.butler"), 

1473 ) 

1474 

1475 names = list(names) 

1476 refs: list[DatasetRef] = [] 

1477 # Map of the chained collections to the RUN children. 

1478 parents_to_children: dict[str, set[str]] = defaultdict(set) 

1479 

1480 with self._caching_context(): 

1481 # Get information about these RUNs. 

1482 collections_info = self.collections.query_info(names, include_parents=unlink_from_chains) 

1483 for info in collections_info: 

1484 if info.type is not CollectionType.RUN: 

1485 raise TypeError(f"The collection type of '{info.name}' is {info.type.name}, not RUN.") 

1486 if unlink_from_chains: 

1487 if info.parents is None: # For mypy. 

1488 raise AssertionError("Internal error: Collection parents required but not received") 

1489 for parent in info.parents: 

1490 parents_to_children[parent].add(info.name) 

1491 

1492 # Update the names in case the query unexpectedly had a wildcard. 

1493 names = [info.name for info in collections_info] 

1494 

1495 # Get all the datasets from these runs. 

1496 refs = self.query_all_datasets(names, find_first=False, limit=None) 

1497 

1498 # Call pruneDatasets since we are deliberately removing 

1499 # datasets in chunks from the RUN collections rather than 

1500 # attempting to remove everything at once. 

1501 with time_this( 

1502 _LOG, 

1503 msg="Removing %d dataset%s from %s", 

1504 args=(len(refs), "s" if len(refs) != 1 else "", ", ".join(names)), 

1505 ): 

1506 self.pruneDatasets(refs, unstore=True, purge=True, disassociate=True) 

1507 

1508 # Now can remove the actual RUN collection and unlink from chains. 

1509 with self._registry.transaction(): 

1510 # This will fail if caller is not unlinking from chains but the 

1511 # RUN is in a chain -- but we have already deleted all the datasets 

1512 # by this point. 

1513 if unlink_from_chains: 

1514 # Use deterministic order for deletions to attempt to minimize 

1515 # risk of deadlocks for parallel deletes. 

1516 for parent in sorted(parents_to_children): 

1517 self.collections.remove_from_chain(parent, sorted(parents_to_children[parent])) 

1518 # Sort to avoid potential deadlocks. 

1519 for name in sorted(names): 

1520 # This should be fast since the collection should be empty. 

1521 with time_this(_LOG, msg="Removing RUN collection %s", args=(name,)): 

1522 self._registry.removeCollection(name) 

1523 _LOG.info("Completely removed the following RUN collections: %s", ", ".join(names)) 

1524 

1525 def pruneDatasets( 

1526 self, 

1527 refs: Iterable[DatasetRef], 

1528 *, 

1529 disassociate: bool = True, 

1530 unstore: bool = False, 

1531 tags: Iterable[str] = (), 

1532 purge: bool = False, 

1533 ) -> None: 

1534 # docstring inherited from LimitedButler 

1535 

1536 if not self.isWriteable(): 

1537 raise TypeError("Butler is read-only.") 

1538 if purge: 

1539 if not disassociate: 

1540 raise TypeError("Cannot pass purge=True without disassociate=True.") 

1541 if not unstore: 

1542 raise TypeError("Cannot pass purge=True without unstore=True.") 

1543 elif disassociate: 

1544 tags = tuple(tags) 

1545 if not tags: 

1546 raise TypeError("No tags provided but disassociate=True.") 

1547 for tag in tags: 

1548 collectionType = self._registry.getCollectionType(tag) 

1549 if collectionType is not CollectionType.TAGGED: 

1550 raise TypeError( 

1551 f"Cannot disassociate from collection '{tag}' " 

1552 f"of non-TAGGED type {collectionType.name}." 

1553 ) 

1554 # Transform possibly-single-pass iterable into something we can iterate 

1555 # over multiple times. 

1556 refs = list(refs) 

1557 # Pruning a component of a DatasetRef makes no sense since registry 

1558 # doesn't know about components and datastore might not store 

1559 # components in a separate file 

1560 for ref in refs: 

1561 if ref.datasetType.component(): 

1562 raise ValueError(f"Can not prune a component of a dataset (ref={ref})") 

1563 

1564 # Chunk the deletions using a size that is reasonably efficient whilst 

1565 # also giving reasonable feedback to the user. Chunking also minimizes 

1566 # what needs to rollback if there is a failure and should allow 

1567 # incremental re-running of the pruning (assuming the query is 

1568 # repeated). The only issue will be if the Ctrl-C comes during 

1569 # emptyTrash since an admin command would need to run to finish the 

1570 # emptying of that chunk. 

1571 progress = Progress("lsst.daf.butler.Butler.pruneDatasets", level=_LOG.INFO) 

1572 chunk_size = 50_000 

1573 n_chunks = math.ceil(len(refs) / chunk_size) 

1574 if n_chunks > 1: 

1575 _LOG.verbose("Pruning a total of %d datasets", len(refs)) 

1576 chunk_num = 0 

1577 for chunked_refs in progress.wrap( 

1578 chunk_iterable(refs, chunk_size=chunk_size), desc="Deleting datasets", total=n_chunks 

1579 ): 

1580 chunk_num += 1 

1581 _LOG.verbose( 

1582 "Pruning %d dataset%s in chunk %d/%d", 

1583 len(chunked_refs), 

1584 "s" if len(chunked_refs) != 1 else "", 

1585 chunk_num, 

1586 n_chunks, 

1587 ) 

1588 with time_this( 

1589 _LOG, 

1590 msg="Removing %d datasets for chunk %d/%d", 

1591 args=(len(chunked_refs), chunk_num, n_chunks), 

1592 ): 

1593 self._prune_datasets( 

1594 chunked_refs, tags=tags, unstore=unstore, purge=purge, disassociate=disassociate 

1595 ) 

1596 

1597 def _prune_datasets( 

1598 self, 

1599 refs: Collection[DatasetRef], 

1600 *, 

1601 disassociate: bool = True, 

1602 unstore: bool = False, 

1603 tags: Iterable[str] = (), 

1604 purge: bool = False, 

1605 ) -> None: 

1606 # We don't need an unreliable Datastore transaction for this, because 

1607 # we've been extra careful to ensure that Datastore.trash only involves 

1608 # mutating the Registry (it can _look_ at Datastore-specific things, 

1609 # but shouldn't change them), and hence all operations here are 

1610 # Registry operations. 

1611 with self.transaction(): 

1612 plural = "s" if len(refs) != 1 else "" 

1613 if unstore: 

1614 with time_this( 

1615 _LOG, 

1616 msg="Marking %d dataset%s for removal during pruneDatasets", 

1617 args=(len(refs), plural), 

1618 ): 

1619 self._datastore.trash(refs) 

1620 if purge: 

1621 with time_this( 

1622 _LOG, msg="Removing %d pruned dataset%s from registry", args=(len(refs), plural) 

1623 ): 

1624 self._registry.removeDatasets(refs) 

1625 elif disassociate: 

1626 assert tags, "Guaranteed by earlier logic in this function." 

1627 with time_this( 

1628 _LOG, msg="Disassociating %d dataset%ss from tagged collections", args=(len(refs), plural) 

1629 ): 

1630 for tag in tags: 

1631 self._registry.disassociate(tag, refs) 

1632 # We've exited the Registry transaction, and apparently committed. 

1633 # (if there was an exception, everything rolled back, and it's as if 

1634 # nothing happened - and we never get here). 

1635 # Datastore artifacts are not yet gone, but they're clearly marked 

1636 # as trash, so if we fail to delete now because of (e.g.) filesystem 

1637 # problems we can try again later, and if manual administrative 

1638 # intervention is required, it's pretty clear what that should entail: 

1639 # deleting everything on disk and in private Datastore tables that is 

1640 # in the dataset_location_trash table. 

1641 if unstore: 

1642 # Point of no return for removing artifacts. Restrict the trash 

1643 # emptying to the refs that this call trashed. 

1644 with time_this( 

1645 _LOG, 

1646 msg="Attempting to remove artifacts for %d dataset%s associated with pruning", 

1647 args=(len(refs), plural), 

1648 ): 

1649 self._datastore.emptyTrash(refs=refs) 

1650 

1651 def ingest_zip( 

1652 self, 

1653 zip_file: ResourcePathExpression, 

1654 transfer: str = "auto", 

1655 *, 

1656 transfer_dimensions: bool = False, 

1657 dry_run: bool = False, 

1658 ) -> None: 

1659 """Ingest a Zip file into this butler. 

1660 

1661 The Zip file must have been created by `retrieve_artifacts_zip`. 

1662 

1663 Parameters 

1664 ---------- 

1665 zip_file : `lsst.resources.ResourcePathExpression` 

1666 Path to the Zip file. 

1667 transfer : `str`, optional 

1668 Method to use to transfer the Zip into the datastore. 

1669 transfer_dimensions : `bool`, optional 

1670 If `True`, dimension record data associated with the new datasets 

1671 will be transferred from the Zip, if present. 

1672 dry_run : `bool`, optional 

1673 If `True` the ingest will be processed without any modifications 

1674 made to the target butler and as if the target butler did not 

1675 have any of the datasets. 

1676 

1677 Notes 

1678 ----- 

1679 Run collections and dataset types are created as needed. 

1680 """ 

1681 if not self.isWriteable(): 

1682 raise TypeError("Butler is read-only.") 

1683 

1684 zip_path = ResourcePath(zip_file) 

1685 index = ZipIndex.from_zip_file(zip_path) 

1686 _LOG.verbose( 

1687 "Ingesting %s containing %d datasets and %d files.", zip_path, len(index.refs), len(index) 

1688 ) 

1689 

1690 # Need to ingest the refs into registry. Re-use the standard ingest 

1691 # code by reconstructing FileDataset from the index. 

1692 refs = index.refs.to_refs(universe=self.dimensions) 

1693 id_to_ref = {ref.id: ref for ref in refs} 

1694 datasets: list[FileDataset] = [] 

1695 processed_ids: set[uuid.UUID] = set() 

1696 for path_in_zip, index_info in index.artifact_map.items(): 

1697 # Disassembled composites need to check this ref isn't already 

1698 # included. 

1699 unprocessed = {id_ for id_ in index_info.ids if id_ not in processed_ids} 

1700 if not unprocessed: 

1701 continue 

1702 dataset = FileDataset(refs=[id_to_ref[id_] for id_ in unprocessed], path=path_in_zip) 

1703 datasets.append(dataset) 

1704 processed_ids.update(unprocessed) 

1705 

1706 # Ingest doesn't create the RUN collections so we have to do that 

1707 # here. 

1708 # 

1709 # Sort by run collection name to ensure Postgres takes locks in the 

1710 # same order between different processes, to mitigate an issue 

1711 # where Postgres can deadlock due to the unique index on collection 

1712 # name. (See DM-47543). 

1713 runs = {ref.run for ref in refs} 

1714 for run in sorted(runs): 

1715 registered = self.collections.register(run) 

1716 if registered: 

1717 _LOG.verbose("Created RUN collection %s as part of zip ingest", run) 

1718 

1719 progress = Progress("lsst.daf.butler.Butler.ingest", level=VERBOSE) 

1720 import_info = self._prepare_ingest_file_datasets( 

1721 datasets, progress, dry_run=dry_run, transfer_dimensions=transfer_dimensions 

1722 ) 

1723 

1724 with self.transaction(): 

1725 # Do not need expanded dataset refs so can ignore the return value. 

1726 self._ingest_file_datasets(datasets, import_info, progress, dry_run=dry_run) 

1727 

1728 try: 

1729 self._datastore.ingest_zip(zip_path, transfer=transfer, dry_run=dry_run) 

1730 except IntegrityError as e: 

1731 raise ConflictingDefinitionError( 

1732 f"Datastore already contains one or more datasets: {e}" 

1733 ) from e 

1734 

1735 def _prepare_ingest_file_datasets( 

1736 self, 

1737 datasets: Sequence[FileDataset], 

1738 progress: Progress, 

1739 *, 

1740 transfer_dimensions: bool = False, 

1741 dry_run: bool = False, 

1742 ) -> _ImportDatasetsInfo: 

1743 # Track DataIDs that are being ingested so we can spot issues early 

1744 # with duplication. Retain previous FileDataset so we can report it. 

1745 groupedDataIds: MutableMapping[tuple[DatasetType, str], dict[DataCoordinate, FileDataset]] = ( 

1746 defaultdict(dict) 

1747 ) 

1748 

1749 # All the refs we need to import. 

1750 refs: list[DatasetRef] = [] 

1751 

1752 for dataset in progress.wrap(datasets, desc="Validating dataIDs"): 

1753 for ref in dataset.refs: 

1754 group_key = (ref.datasetType, ref.run) 

1755 

1756 if ref.dataId in groupedDataIds[group_key]: 

1757 raise ConflictingDefinitionError( 

1758 f"Ingest conflict. Dataset {dataset.path} has same" 

1759 " DataId as other ingest dataset" 

1760 f" {groupedDataIds[group_key][ref.dataId].path} " 

1761 f" ({ref.dataId})" 

1762 ) 

1763 

1764 groupedDataIds[group_key][ref.dataId] = dataset 

1765 refs.extend(dataset.refs) 

1766 

1767 # Ensure that dataset types are created and all ref information 

1768 # extracted. 

1769 import_info = self._prepare_for_import_refs( 

1770 self, 

1771 refs, 

1772 register_dataset_types=True, 

1773 dry_run=dry_run, 

1774 transfer_dimensions=transfer_dimensions, 

1775 ) 

1776 return import_info 

1777 

1778 def _ingest_file_datasets( 

1779 self, 

1780 datasets: Sequence[FileDataset], 

1781 import_info: _ImportDatasetsInfo, 

1782 progress: Progress, 

1783 *, 

1784 dry_run: bool = False, 

1785 ) -> None: 

1786 self._import_dimension_records(import_info.dimension_records, dry_run=dry_run) 

1787 imported_refs = self._import_grouped_refs( 

1788 import_info.grouped_refs, None, progress, dry_run=dry_run, expand_refs=True 

1789 ) 

1790 

1791 # The expanded refs need to be attached back to the original 

1792 # FileDatasets for datastore to use. 

1793 id_to_ref = {ref.id: ref for ref in imported_refs} 

1794 

1795 for dataset in progress.wrap(datasets, desc="Re-attaching expanded refs"): 

1796 dataset.refs = [id_to_ref[ref.id] for ref in dataset.refs] 

1797 

1798 def ingest( 

1799 self, 

1800 *datasets: FileDataset, 

1801 transfer: str | None = "auto", 

1802 record_validation_info: bool = True, 

1803 skip_existing: bool = False, 

1804 ) -> None: 

1805 # Docstring inherited. 

1806 if not datasets: 

1807 return 

1808 if not self.isWriteable(): 

1809 raise TypeError("Butler is read-only.") 

1810 _LOG.verbose("Ingesting %d file dataset%s.", len(datasets), "" if len(datasets) == 1 else "s") 

1811 progress = Progress("lsst.daf.butler.Butler.ingest", level=VERBOSE) 

1812 

1813 new_datasets, existing_datasets = self._partition_datasets_by_known(datasets) 

1814 if existing_datasets: 

1815 if skip_existing: 

1816 _LOG.info( 

1817 "Skipping %d datasets which already exist in the repository.", len(existing_datasets) 

1818 ) 

1819 else: 

1820 raise ConflictingDefinitionError( 

1821 f"Datastore already contains {len(existing_datasets)} of the given datasets." 

1822 f" Example: {existing_datasets[0]}" 

1823 ) 

1824 

1825 # Calculate some statistics based on the given list of datasets. 

1826 n_files = len(datasets) 

1827 n_datasets = 0 

1828 for d in datasets: 

1829 n_datasets += len(d.refs) 

1830 sfiles = "s" if n_files != 1 else "" 

1831 srefs = "s" if n_datasets != 1 else "" 

1832 

1833 # We use `datasets` rather `new_datasets` for the Registry 

1834 # portion of this, to let it confirm that everything matches the 

1835 # existing datasets. 

1836 import_info = self._prepare_ingest_file_datasets(datasets, progress) 

1837 

1838 with ( 

1839 self._metrics.instrument_ingest( 

1840 n_datasets, _LOG, msg=f"Ingesting {n_files} file{sfiles} with {n_datasets} dataset{srefs}" 

1841 ), 

1842 self.transaction(), 

1843 ): 

1844 self._ingest_file_datasets(datasets, import_info, progress) 

1845 

1846 # Bulk-insert everything into Datastore. 

1847 # We do not know if any of the registry entries already existed 

1848 # (_importDatasets only complains if they exist but differ). 

1849 # The _partition_datasets_by_known logic above should catch most 

1850 # instances where we attempt to re-ingest files that were already 

1851 # ingested, but a concurrent writer could cause a unique constraint 

1852 # violation here. 

1853 try: 

1854 self._datastore.ingest( 

1855 *new_datasets, transfer=transfer, record_validation_info=record_validation_info 

1856 ) 

1857 except IntegrityError as e: 

1858 raise ConflictingDefinitionError( 

1859 f"Datastore already contains one or more datasets: {e}" 

1860 ) from e 

1861 

1862 def _partition_datasets_by_known( 

1863 self, datasets: Iterable[FileDataset] 

1864 ) -> tuple[list[FileDataset], list[FileDataset]]: 

1865 """Divides the given `FileDataset` objects into two groups: those for 

1866 which the Datastore already has an entry, and those for which it does 

1867 not. 

1868 """ 

1869 new_datasets = [] 

1870 existing_datasets = [] 

1871 

1872 refs = itertools.chain.from_iterable(dataset.refs for dataset in datasets) 

1873 known_refs = self._datastore.knows_these(refs) 

1874 

1875 for dataset in datasets: 

1876 if any(known_refs[ref] for ref in dataset.refs): 

1877 existing_datasets.append(dataset) 

1878 else: 

1879 new_datasets.append(dataset) 

1880 

1881 return new_datasets, existing_datasets 

1882 

1883 @contextlib.contextmanager 

1884 def export( 

1885 self, 

1886 *, 

1887 directory: str | None = None, 

1888 filename: str | None = None, 

1889 format: str | None = None, 

1890 transfer: str | None = None, 

1891 ) -> Iterator[RepoExportContext]: 

1892 # Docstring inherited. 

1893 if directory is None and transfer is not None: 

1894 raise TypeError("Cannot transfer without providing a directory.") 

1895 if transfer == "move": 

1896 raise TypeError("Transfer may not be 'move': export is read-only") 

1897 if format is None: 

1898 if filename is None: 

1899 raise TypeError("At least one of 'filename' or 'format' must be provided.") 

1900 else: 

1901 _, format = os.path.splitext(filename) 

1902 if not format: 

1903 raise ValueError("Please specify a file extension to determine export format.") 

1904 format = format[1:] # Strip leading "."" 

1905 elif filename is None: 

1906 filename = f"export.{format}" 

1907 if directory is not None: 

1908 filename = os.path.join(directory, filename) 

1909 formats = self._config["repo_transfer_formats"] 

1910 if format not in formats: 

1911 raise ValueError(f"Unknown export format {format!r}, allowed: {','.join(formats.keys())}") 

1912 BackendClass = get_class_of(formats[format, "export"]) 

1913 with open(filename, "w") as stream: 

1914 backend = BackendClass(stream, universe=self.dimensions) 

1915 try: 

1916 helper = RepoExportContext(self, backend=backend, directory=directory, transfer=transfer) 

1917 with self._caching_context(): 

1918 yield helper 

1919 except BaseException: 

1920 raise 

1921 else: 

1922 helper._finish() 

1923 

1924 def import_( 

1925 self, 

1926 *, 

1927 directory: ResourcePathExpression | None = None, 

1928 filename: ResourcePathExpression | TextIO | None = None, 

1929 format: str | None = None, 

1930 transfer: str | None = None, 

1931 skip_dimensions: set | None = None, 

1932 record_validation_info: bool = True, 

1933 without_datastore: bool = False, 

1934 ) -> None: 

1935 # Docstring inherited. 

1936 if not self.isWriteable(): 

1937 raise TypeError("Butler is read-only.") 

1938 if filename is None and format is not None: 

1939 filename = ResourcePath(f"export.{format}", forceAbsolute=False) 

1940 if directory is not None: 

1941 directory = ResourcePath(directory, forceDirectory=True) 

1942 # mypy doesn't think this will work but it does in python >= 3.10. 

1943 if isinstance(filename, ResourcePathExpression): # type: ignore 

1944 filename = ResourcePath(filename, forceAbsolute=False) # type: ignore 

1945 if format is None: 

1946 format = filename.getExtension() 

1947 if not filename.isabs() and directory is not None: 

1948 potential = directory.join(filename) 

1949 exists_in_cwd = filename.exists() 

1950 exists_in_dir = potential.exists() 

1951 if exists_in_cwd and exists_in_dir: 

1952 _LOG.warning( 

1953 "A relative path for filename was specified (%s) which exists relative to cwd. " 

1954 "Additionally, the file exists relative to the given search directory (%s). " 

1955 "Using the export file in the given directory.", 

1956 filename, 

1957 potential, 

1958 ) 

1959 # Given they specified an explicit directory and that 

1960 # directory has the export file in it, assume that that 

1961 # is what was meant despite the file in cwd. 

1962 filename = potential 

1963 elif exists_in_dir: 

1964 filename = potential 

1965 elif not exists_in_cwd and not exists_in_dir: 

1966 # Raise early. 

1967 raise FileNotFoundError( 

1968 f"Export file could not be found in {filename.abspath()} or {potential.abspath()}." 

1969 ) 

1970 elif format is None: 

1971 format = ".yaml" 

1972 BackendClass: type[RepoImportBackend] = get_class_of( 

1973 self._config["repo_transfer_formats"][format]["import"] 

1974 ) 

1975 

1976 def doImport(importStream: TextIO | ResourceHandleProtocol) -> None: 

1977 with self._caching_context(): 

1978 backend = BackendClass(importStream, self) # type: ignore[call-arg] 

1979 backend.register() 

1980 with self.transaction(): 

1981 backend.load( 

1982 datastore=self._datastore if not without_datastore else None, 

1983 directory=directory, 

1984 transfer=transfer, 

1985 skip_dimensions=skip_dimensions, 

1986 record_validation_info=record_validation_info, 

1987 ) 

1988 

1989 if isinstance(filename, ResourcePath): 

1990 # We can not use open() here at the moment because of 

1991 # DM-38589 since yaml does stream.read(8192) in a loop. 

1992 stream = io.StringIO(filename.read().decode()) 

1993 doImport(stream) 

1994 else: 

1995 doImport(filename) # type: ignore 

1996 

1997 def transfer_dimension_records_from( 

1998 self, source_butler: LimitedButler | Butler, source_refs: Iterable[DatasetRef | DataCoordinate] 

1999 ) -> None: 

2000 # Allowed dimensions in the target butler. 

2001 elements = frozenset(element for element in self.dimensions.elements if element.has_own_table) 

2002 

2003 data_ids = {ref.dataId for ref in source_refs} 

2004 

2005 dimension_records = self._extract_all_dimension_records_from_data_ids( 

2006 source_butler, data_ids, elements 

2007 ) 

2008 

2009 # Insert order is important. 

2010 for element in self.dimensions.sorted(dimension_records.keys()): 

2011 records = [r for r in dimension_records[element].values()] 

2012 # Assume that if the record is already present that we can 

2013 # use it without having to check that the record metadata 

2014 # is consistent. 

2015 self._registry.insertDimensionData(element, *records, skip_existing=True) 

2016 _LOG.debug("Dimension '%s' -- number of records transferred: %d", element.name, len(records)) 

2017 

2018 def _extract_all_dimension_records_from_data_ids( 

2019 self, 

2020 source_butler: LimitedButler | Butler, 

2021 data_ids: set[DataCoordinate], 

2022 allowed_elements: frozenset[DimensionElement], 

2023 ) -> dict[DimensionElement, dict[DataCoordinate, DimensionRecord]]: 

2024 primary_records = self._extract_dimension_records_from_data_ids( 

2025 source_butler, data_ids, allowed_elements 

2026 ) 

2027 

2028 additional_records: dict[DimensionElement, dict[DataCoordinate, DimensionRecord]] = defaultdict(dict) 

2029 for original_element, record_mapping in primary_records.items(): 

2030 # Get dimensions that depend on this dimension. 

2031 populated_by = self.dimensions.get_elements_populated_by( 

2032 self.dimensions[original_element.name] # type: ignore 

2033 ) 

2034 if populated_by: 

2035 for element in populated_by: 

2036 if element not in allowed_elements: 

2037 continue 

2038 if element.name == original_element.name: 

2039 continue 

2040 

2041 if element.name in primary_records: 

2042 # If this element has already been stored avoid 

2043 # re-finding records since that may lead to additional 

2044 # spurious records. e.g. visit is populated_by 

2045 # visit_detector_region but querying 

2046 # visit_detector_region by visit will return all the 

2047 # detectors for this visit -- the visit dataId does not 

2048 # constrain this. 

2049 # To constrain the query the original dataIds would 

2050 # have to be scanned. 

2051 continue 

2052 

2053 if record_mapping: 

2054 if not isinstance(source_butler, Butler): 

2055 raise RuntimeError( 

2056 f"Transferring populated_by records like {element.name}" 

2057 " requires a full Butler." 

2058 ) 

2059 

2060 with source_butler.query() as query: 

2061 records = query.join_data_coordinates(record_mapping.keys()).dimension_records( 

2062 element.name 

2063 ) 

2064 for record in records: 

2065 additional_records[record.definition].setdefault(record.dataId, record) 

2066 

2067 # The next step is to walk back through the additional records to 

2068 # pick up any missing content (such as visit_definition needing to 

2069 # know the exposure). Want to ensure we do not request records we 

2070 # already have. 

2071 missing_data_ids = set() 

2072 for record_mapping in additional_records.values(): 

2073 for data_id in record_mapping.keys(): 

2074 for dimension in data_id.dimensions.required: 

2075 element = source_butler.dimensions[dimension] 

2076 dimension_key = data_id.subset(dimension) 

2077 if dimension_key not in primary_records[element]: 

2078 missing_data_ids.add(dimension_key) 

2079 

2080 # Fill out the new records. Assume that these new records do not 

2081 # also need to carry over additional populated_by records. 

2082 secondary_records = self._extract_dimension_records_from_data_ids( 

2083 source_butler, missing_data_ids, allowed_elements 

2084 ) 

2085 

2086 # Merge the extra sets of records in with the original. 

2087 for name, record_mapping in itertools.chain(additional_records.items(), secondary_records.items()): 

2088 primary_records[name].update(record_mapping) 

2089 

2090 return primary_records 

2091 

2092 def _extract_dimension_records_from_data_ids( 

2093 self, 

2094 source_butler: LimitedButler | Butler, 

2095 data_ids: Iterable[DataCoordinate], 

2096 allowed_elements: frozenset[DimensionElement], 

2097 ) -> dict[DimensionElement, dict[DataCoordinate, DimensionRecord]]: 

2098 dimension_records: dict[DimensionElement, dict[DataCoordinate, DimensionRecord]] = defaultdict(dict) 

2099 

2100 data_ids = set(data_ids) 

2101 if not all(data_id.hasRecords() for data_id in data_ids): 

2102 if isinstance(source_butler, Butler): 

2103 data_ids = source_butler._expand_data_ids(data_ids) 

2104 else: 

2105 raise TypeError("Input butler needs to be a full butler to expand DataId.") 

2106 

2107 for data_id in data_ids: 

2108 # If this butler doesn't know about a dimension in the source 

2109 # butler things will break later. 

2110 for element_name in data_id.dimensions.elements: 

2111 record = data_id.records[element_name] 

2112 if record is not None and record.definition in allowed_elements: 

2113 dimension_records[record.definition].setdefault(record.dataId, record) 

2114 

2115 return dimension_records 

2116 

2117 def _prepare_for_import_refs( 

2118 self, 

2119 source_butler: LimitedButler, 

2120 source_refs: Iterable[DatasetRef], 

2121 *, 

2122 register_dataset_types: bool = False, 

2123 transfer_dimensions: bool = False, 

2124 dry_run: bool = False, 

2125 ) -> _ImportDatasetsInfo: 

2126 # Docstring inherited. 

2127 if not self.isWriteable() and not dry_run: 

2128 raise TypeError("Butler is read-only.") 

2129 

2130 # Will iterate through the refs multiple times so need to convert 

2131 # to a list if this isn't a collection. 

2132 if not isinstance(source_refs, collections.abc.Collection): 

2133 source_refs = list(source_refs) 

2134 

2135 original_count = len(source_refs) 

2136 log_level = _LOG.INFO if original_count > 1 else _LOG.VERBOSE 

2137 _LOG.log( 

2138 log_level, 

2139 "Importing %d dataset%s into %s", 

2140 original_count, 

2141 "s" if original_count != 1 else "", 

2142 str(self), 

2143 ) 

2144 

2145 # Importing requires that we group the refs by dimension group and run 

2146 # before doing the import. 

2147 source_dataset_types = set() 

2148 grouped_refs: defaultdict[_RefGroup, list[DatasetRef]] = defaultdict(list) 

2149 for ref in source_refs: 

2150 grouped_refs[_RefGroup(ref.datasetType.dimensions, ref.run)].append(ref) 

2151 source_dataset_types.add(ref.datasetType) 

2152 

2153 # Check to see if the dataset type in the source butler has 

2154 # the same definition in the target butler and register missing 

2155 # ones if requested. Registration must happen outside a transaction. 

2156 newly_registered_dataset_types = set() 

2157 for datasetType in source_dataset_types: 

2158 if register_dataset_types: 

2159 # Let this raise immediately if inconsistent. Continuing 

2160 # on to find additional inconsistent dataset types 

2161 # might result in additional unwanted dataset types being 

2162 # registered. 

2163 try: 

2164 if not dry_run and self._registry.registerDatasetType(datasetType): 

2165 newly_registered_dataset_types.add(datasetType) 

2166 except ConflictingDefinitionError as e: 

2167 # Be safe and require that conversions be bidirectional 

2168 # when there are storage class mismatches. This is because 

2169 # get() will have to support conversion from source to 

2170 # target python type (the source formatter will be 

2171 # returning source python type) but there also is an 

2172 # expectation that people will want to be able to get() in 

2173 # the target using the source python type, which will not 

2174 # require conversion for transferred datasets but might 

2175 # for target-native types. Additionally, butler.get does 

2176 # not know that the formatter will return the wrong 

2177 # python type and so will always check that the conversion 

2178 # works even though it won't need it. 

2179 target_dataset_type = self.get_dataset_type(datasetType.name) 

2180 target_compatible_with_source = target_dataset_type.is_compatible_with(datasetType) 

2181 source_compatible_with_target = datasetType.is_compatible_with(target_dataset_type) 

2182 if not (target_compatible_with_source and source_compatible_with_target): 

2183 if target_compatible_with_source: 

2184 e.add_note( 

2185 "Target dataset type storage class is compatible with source " 

2186 "but the reverse is not true." 

2187 ) 

2188 elif source_compatible_with_target: 

2189 e.add_note( 

2190 "Source dataset type storage class is compatible with target " 

2191 "but the reverse is not true." 

2192 ) 

2193 else: 

2194 e.add_note("If storage classes differ, please register converters.") 

2195 raise 

2196 else: 

2197 # If the dataset type is missing, let it fail immediately. 

2198 target_dataset_type = self.get_dataset_type(datasetType.name) 

2199 if target_dataset_type != datasetType: 

2200 target_compatible_with_source = target_dataset_type.is_compatible_with(datasetType) 

2201 source_compatible_with_target = datasetType.is_compatible_with(target_dataset_type) 

2202 # Both conversion directions are currently required. 

2203 if not (target_compatible_with_source and source_compatible_with_target): 

2204 msg = "" 

2205 if target_compatible_with_source: 

2206 msg = ( 

2207 "Target storage class is compatible with the source storage class " 

2208 "but the reverse is not true." 

2209 ) 

2210 elif source_compatible_with_target: 

2211 msg = ( 

2212 "Source storage class is compatible with the target storage class" 

2213 " but the reverse is not true." 

2214 ) 

2215 else: 

2216 msg = "If storage classes differ register converters." 

2217 if msg: 

2218 msg = f"({msg})" 

2219 raise ConflictingDefinitionError( 

2220 "Source butler dataset type differs from definition" 

2221 f" in target butler: {datasetType} !=" 

2222 f" {target_dataset_type} {msg}" 

2223 ) 

2224 if newly_registered_dataset_types: 

2225 # We may have registered some even if there were inconsistencies 

2226 # but should let people know (or else remove them again). 

2227 _LOG.verbose( 

2228 "Registered the following dataset types in the target Butler: %s", 

2229 ", ".join(d.name for d in newly_registered_dataset_types), 

2230 ) 

2231 else: 

2232 _LOG.verbose("All required dataset types are known to the target Butler") 

2233 

2234 dimension_records: dict[DimensionElement, dict[DataCoordinate, DimensionRecord]] = defaultdict(dict) 

2235 if transfer_dimensions: 

2236 # Collect all the dimension records for these refs. 

2237 # All dimensions are to be copied but the list of valid dimensions 

2238 # come from this butler's universe. 

2239 elements = frozenset(element for element in self.dimensions.elements if element.has_own_table) 

2240 dataIds = {ref.dataId for ref in source_refs} 

2241 dimension_records = self._extract_all_dimension_records_from_data_ids( 

2242 source_butler, dataIds, elements 

2243 ) 

2244 return _ImportDatasetsInfo(grouped_refs, dimension_records) 

2245 

2246 def _import_dimension_records( 

2247 self, 

2248 dimension_records: dict[DimensionElement, dict[DataCoordinate, DimensionRecord]], 

2249 *, 

2250 dry_run: bool, 

2251 ) -> None: 

2252 """Import dimension records collected during import pre-process.""" 

2253 if dimension_records and not dry_run: 

2254 _LOG.verbose("Ensuring that dimension records exist for transferred datasets.") 

2255 # Order matters. 

2256 for element in self.dimensions.sorted(dimension_records.keys()): 

2257 records = list(dimension_records[element].values()) 

2258 # Assume that if the record is already present that we can 

2259 # use it without having to check that the record metadata 

2260 # is consistent. 

2261 self._registry.insertDimensionData(element, *records, skip_existing=True) 

2262 

2263 def _import_grouped_refs( 

2264 self, 

2265 grouped_refs: defaultdict[_RefGroup, list[DatasetRef]], 

2266 source_butler: LimitedButler | None, 

2267 progress: Progress, 

2268 *, 

2269 dry_run: bool = False, 

2270 expand_refs: bool = False, 

2271 ) -> list[DatasetRef]: 

2272 handled_collections: set[str] = set() 

2273 n_to_import = 0 

2274 all_imported_refs: list[DatasetRef] = [] 

2275 # Sort by run collection name to ensure Postgres takes locks in the 

2276 # same order between different processes, to mitigate an issue 

2277 # where Postgres can deadlock due to the unique index on collection 

2278 # name. (See DM-47543). 

2279 groups = sorted(grouped_refs.items(), key=lambda item: item[0].run) 

2280 for (dimension_group, run), refs_to_import in progress.iter_item_chunks( 

2281 groups, desc="Importing to registry by run and dataset type" 

2282 ): 

2283 if run not in handled_collections: 

2284 # May need to create output collection. If source butler 

2285 # has a registry, ask for documentation string. 

2286 run_doc = None 

2287 if source_butler is not None and (registry := getattr(source_butler, "registry", None)): 

2288 run_doc = registry.getCollectionDocumentation(run) 

2289 if not dry_run: 

2290 registered = self.collections.register(run, doc=run_doc) 

2291 else: 

2292 registered = True 

2293 handled_collections.add(run) 

2294 if registered: 

2295 _LOG.verbose("Creating output run %s", run) 

2296 

2297 n_refs = len(refs_to_import) 

2298 n_to_import += n_refs 

2299 _LOG.verbose( 

2300 "Importing %d ref%s with dimensions %s into run %s", 

2301 n_refs, 

2302 "" if n_refs == 1 else "s", 

2303 dimension_group.names, 

2304 run, 

2305 ) 

2306 

2307 # Assume we are using UUIDs and the source refs will match 

2308 # those imported. 

2309 if not dry_run: 

2310 imported_refs = self._registry._importDatasets(refs_to_import, expand=expand_refs) 

2311 else: 

2312 imported_refs = refs_to_import 

2313 

2314 all_imported_refs.extend(imported_refs) 

2315 

2316 assert n_to_import == len(all_imported_refs) 

2317 _LOG.verbose("Imported %d datasets into destination butler", n_to_import) 

2318 return all_imported_refs 

2319 

2320 def transfer_from( 

2321 self, 

2322 source_butler: LimitedButler, 

2323 source_refs: Iterable[DatasetRef], 

2324 transfer: str = "auto", 

2325 skip_missing: bool = True, 

2326 register_dataset_types: bool = False, 

2327 transfer_dimensions: bool = False, 

2328 dry_run: bool = False, 

2329 ) -> collections.abc.Collection[DatasetRef]: 

2330 # Docstring inherited. 

2331 source_refs = list(source_refs) 

2332 if not self.isWriteable() and not dry_run: 

2333 raise TypeError("Butler is read-only.") 

2334 

2335 progress = Progress("lsst.daf.butler.Butler.transfer_from", level=VERBOSE) 

2336 

2337 artifact_existence: dict[ResourcePath, bool] = {} 

2338 file_transfer_source = source_butler._file_transfer_source 

2339 transfer_records = retrieve_file_transfer_records( 

2340 file_transfer_source, source_refs, artifact_existence 

2341 ) 

2342 # In some situations the datastore artifact may be missing and we do 

2343 # not want that registry entry to be imported. For example, this can 

2344 # happen if a file was removed but the dataset was left in the registry 

2345 # for provenance, or if a pipeline task didn't create all of the 

2346 # possible files in a QuantumBackedButler. 

2347 if skip_missing: 

2348 original_ids = {ref.id for ref in source_refs} 

2349 missing_ids = original_ids - transfer_records.keys() 

2350 if missing_ids: 

2351 original_count = len(source_refs) 

2352 source_refs = [ref for ref in source_refs if ref.id not in missing_ids] 

2353 filtered_count = len(source_refs) 

2354 n_missing = original_count - filtered_count 

2355 _LOG.verbose( 

2356 "%d dataset%s removed because the artifact does not exist. Now have %d.", 

2357 n_missing, 

2358 "" if n_missing == 1 else "s", 

2359 filtered_count, 

2360 ) 

2361 

2362 import_info = self._prepare_for_import_refs( 

2363 source_butler, 

2364 source_refs, 

2365 register_dataset_types=register_dataset_types, 

2366 dry_run=dry_run, 

2367 transfer_dimensions=transfer_dimensions, 

2368 ) 

2369 

2370 # Do all the importing in a single transaction. 

2371 with self.transaction(): 

2372 self._import_dimension_records(import_info.dimension_records, dry_run=dry_run) 

2373 imported_refs = self._import_grouped_refs( 

2374 import_info.grouped_refs, source_butler, progress, dry_run=dry_run 

2375 ) 

2376 

2377 # Ask the datastore to transfer. The datastore has to check that 

2378 # the source datastore is compatible with the target datastore. 

2379 _LOG.verbose("Transferring %d datasets from %s", len(transfer_records), file_transfer_source.name) 

2380 accepted, rejected = self._datastore.transfer_from( 

2381 transfer_records, 

2382 imported_refs, 

2383 transfer=transfer, 

2384 artifact_existence=artifact_existence, 

2385 dry_run=dry_run, 

2386 ) 

2387 if rejected: 

2388 # For now, accept the registry entries but not the files. 

2389 _LOG.warning( 

2390 "%d datasets were rejected and %d accepted for transfer.", 

2391 len(rejected), 

2392 len(accepted), 

2393 ) 

2394 

2395 return imported_refs 

2396 

2397 def validateConfiguration( 

2398 self, 

2399 logFailures: bool = False, 

2400 datasetTypeNames: Iterable[str] | None = None, 

2401 ignore: Iterable[str] | None = None, 

2402 ) -> None: 

2403 # Docstring inherited. 

2404 if datasetTypeNames: 

2405 datasetTypes = [self.get_dataset_type(name) for name in datasetTypeNames] 

2406 else: 

2407 datasetTypes = list(self._registry.queryDatasetTypes()) 

2408 

2409 # filter out anything from the ignore list 

2410 if ignore: 

2411 ignore = set(ignore) 

2412 datasetTypes = [ 

2413 e for e in datasetTypes if e.name not in ignore and e.nameAndComponent()[0] not in ignore 

2414 ] 

2415 else: 

2416 ignore = set() 

2417 

2418 # For each datasetType that has an instrument dimension, create 

2419 # a DatasetRef for each defined instrument 

2420 datasetRefs = [] 

2421 

2422 # Find all the registered instruments (if "instrument" is in the 

2423 # universe). 

2424 instruments: set[str] = set() 

2425 if "instrument" in self.dimensions: 

2426 instruments = {rec.name for rec in self.query_dimension_records("instrument", explain=False)} 

2427 

2428 for datasetType in datasetTypes: 

2429 if "instrument" in datasetType.dimensions: 

2430 # In order to create a conforming dataset ref, create 

2431 # fake DataCoordinate values for the non-instrument 

2432 # dimensions. The type of the value does not matter here. 

2433 dataId = {dim: 1 for dim in datasetType.dimensions.names if dim != "instrument"} 

2434 

2435 for instrument in instruments: 

2436 datasetRef = DatasetRef( 

2437 datasetType, 

2438 DataCoordinate.standardize( 

2439 dataId, instrument=instrument, dimensions=datasetType.dimensions 

2440 ), 

2441 run="validate", 

2442 ) 

2443 datasetRefs.append(datasetRef) 

2444 

2445 entities: list[DatasetType | DatasetRef] = [] 

2446 entities.extend(datasetTypes) 

2447 entities.extend(datasetRefs) 

2448 

2449 datastoreErrorStr = None 

2450 try: 

2451 self._datastore.validateConfiguration(entities, logFailures=logFailures) 

2452 except ValidationError as e: 

2453 datastoreErrorStr = str(e) 

2454 

2455 # Also check that the LookupKeys used by the datastores match 

2456 # registry and storage class definitions 

2457 keys = self._datastore.getLookupKeys() 

2458 

2459 failedNames = set() 

2460 failedDataId = set() 

2461 for key in keys: 

2462 if key.name is not None: 

2463 if key.name in ignore: 

2464 continue 

2465 

2466 # skip if specific datasetType names were requested and this 

2467 # name does not match 

2468 if datasetTypeNames and key.name not in datasetTypeNames: 

2469 continue 

2470 

2471 # See if it is a StorageClass or a DatasetType 

2472 if key.name in self.storageClasses: 

2473 pass 

2474 else: 

2475 try: 

2476 self.get_dataset_type(key.name) 

2477 except KeyError: 

2478 if logFailures: 

2479 _LOG.critical( 

2480 "Key '%s' does not correspond to a DatasetType or StorageClass", key 

2481 ) 

2482 failedNames.add(key) 

2483 else: 

2484 # Dimensions are checked for consistency when the Butler 

2485 # is created and rendezvoused with a universe. 

2486 pass 

2487 

2488 # Check that the instrument is a valid instrument 

2489 # Currently only support instrument so check for that 

2490 if key.dataId: 

2491 dataIdKeys = set(key.dataId) 

2492 if {"instrument"} != dataIdKeys: 

2493 if logFailures: 

2494 _LOG.critical("Key '%s' has unsupported DataId override", key) 

2495 failedDataId.add(key) 

2496 elif key.dataId["instrument"] not in instruments: 

2497 if logFailures: 

2498 _LOG.critical("Key '%s' has unknown instrument", key) 

2499 failedDataId.add(key) 

2500 

2501 messages = [] 

2502 

2503 if datastoreErrorStr: 

2504 messages.append(datastoreErrorStr) 

2505 

2506 for failed, msg in ( 

2507 (failedNames, "Keys without corresponding DatasetType or StorageClass entry: "), 

2508 (failedDataId, "Keys with bad DataId entries: "), 

2509 ): 

2510 if failed: 

2511 msg += ", ".join(str(k) for k in failed) 

2512 messages.append(msg) 

2513 

2514 if messages: 

2515 raise ValidationError(";\n".join(messages)) 

2516 

2517 @property 

2518 @deprecated( 

2519 "Please use 'collections' instead. collection_chains will be removed after v28.", 

2520 version="v28", 

2521 category=FutureWarning, 

2522 ) 

2523 def collection_chains(self) -> DirectButlerCollections: 

2524 """Object with methods for modifying collection chains.""" 

2525 return DirectButlerCollections(self._registry) 

2526 

2527 @property 

2528 def collections(self) -> DirectButlerCollections: 

2529 """Object with methods for modifying and inspecting collections.""" 

2530 return DirectButlerCollections(self._registry) 

2531 

2532 @property 

2533 def run(self) -> str | None: 

2534 """Name of the run this butler writes outputs to by default (`str` or 

2535 `None`). 

2536 

2537 This is an alias for ``self.registry.defaults.run``. It cannot be set 

2538 directly in isolation, but all defaults may be changed together by 

2539 assigning a new `RegistryDefaults` instance to 

2540 ``self.registry.defaults``. 

2541 """ 

2542 return self._registry.defaults.run 

2543 

2544 @property 

2545 def registry(self) -> Registry: 

2546 """The object that manages dataset metadata and relationships 

2547 (`Registry`). 

2548 

2549 Many operations that don't involve reading or writing butler datasets 

2550 are accessible only via `Registry` methods. Eventually these methods 

2551 will be replaced by equivalent `Butler` methods. 

2552 """ 

2553 return RegistryShim(self) 

2554 

2555 @property 

2556 def dimensions(self) -> DimensionUniverse: 

2557 # Docstring inherited. 

2558 return self._registry.dimensions 

2559 

2560 def query(self) -> contextlib.AbstractContextManager[Query]: 

2561 # Docstring inherited. 

2562 return self._registry._query() 

2563 

2564 def _query_driver( 

2565 self, 

2566 default_collections: Iterable[str], 

2567 default_data_id: DataCoordinate, 

2568 ) -> contextlib.AbstractContextManager[DirectQueryDriver]: 

2569 """Set up a QueryDriver instance for use with this Butler. Although 

2570 this is marked as a private method, it is also used by Butler server. 

2571 """ 

2572 return self._registry._query_driver(default_collections, default_data_id) 

2573 

2574 @contextlib.contextmanager 

2575 def _query_all_datasets_by_page( 

2576 self, args: QueryAllDatasetsParameters 

2577 ) -> Iterator[Iterator[list[DatasetRef]]]: 

2578 with self.query() as query: 

2579 pages = query_all_datasets(self, query, args) 

2580 yield iter(page.data for page in pages) 

2581 

2582 def _preload_cache(self, *, load_dimension_record_cache: bool = True) -> None: 

2583 """Immediately load caches that are used for common operations.""" 

2584 self._registry.preload_cache(load_dimension_record_cache=load_dimension_record_cache) 

2585 

2586 def _expand_data_ids(self, data_ids: Iterable[DataCoordinate]) -> list[DataCoordinate]: 

2587 return self._registry.expand_data_ids(data_ids) 

2588 

2589 _config: ButlerConfig 

2590 """Configuration for this Butler instance.""" 

2591 

2592 _registry: SqlRegistry 

2593 """The object that manages dataset metadata and relationships 

2594 (`SqlRegistry`). 

2595 

2596 Most operations that don't involve reading or writing butler datasets are 

2597 accessible only via `SqlRegistry` methods. 

2598 """ 

2599 

2600 storageClasses: StorageClassFactory 

2601 """An object that maps known storage class names to objects that fully 

2602 describe them (`StorageClassFactory`). 

2603 """ 

2604 

2605 _closed: bool 

2606 """`True` if close() has already been called on this instance; `False` 

2607 otherwise. 

2608 """ 

2609 

2610 

2611class _RefGroup(NamedTuple): 

2612 """Key identifying a batch of DatasetRefs to be inserted in 

2613 `Butler.transfer_from`. 

2614 """ 

2615 

2616 dimensions: DimensionGroup 

2617 run: str 

2618 

2619 

2620class _ImportDatasetsInfo(NamedTuple): 

2621 """Information extracted from datasets to be imported.""" 

2622 

2623 grouped_refs: defaultdict[_RefGroup, list[DatasetRef]] 

2624 dimension_records: dict[DimensionElement, dict[DataCoordinate, DimensionRecord]] 

2625 

2626 

2627def _to_uuid(id: DatasetId | str) -> uuid.UUID: 

2628 if isinstance(id, uuid.UUID): 

2629 return id 

2630 else: 

2631 return uuid.UUID(id) 

2632 

2633 

2634class _ButlerClosed: 

2635 def __getattr__(self, name: str) -> Any: 

2636 raise RuntimeError("Attempted to use a Butler instance which has been closed.") 

2637 

2638 

2639_BUTLER_CLOSED_INSTANCE: Any = _ButlerClosed() 

2640 

2641 

2642def _retrieve_dataset_type(registry: SqlRegistry, name: str) -> DatasetType | None: 

2643 """Return DatasetType defined in registry given dataset type name.""" 

2644 try: 

2645 return registry.getDatasetType(name) 

2646 except MissingDatasetTypeError: 

2647 return None