Fix double commit in create_from_hash

Move mime_type update into _register_existing_asset so it shares a
single transaction with reference creation. Log a warning when the
hash is not found instead of silently returning None.

Amp-Thread-ID: https://ampcode.com/threads/T-019ce377-8bde-7048-bc28-a9df063409f9
Co-authored-by: Amp <amp@ampcode.com>
This commit is contained in:
Luke Mino-Altherr 2026-03-12 13:21:58 -07:00
parent 9f404be3c5
commit aef0330555

View File

@ -136,6 +136,7 @@ def _register_existing_asset(
tags: list[str] | None = None, tags: list[str] | None = None,
tag_origin: str = "manual", tag_origin: str = "manual",
owner_id: str = "", owner_id: str = "",
mime_type: str | None = None,
) -> RegisterAssetResult: ) -> RegisterAssetResult:
user_metadata = user_metadata or {} user_metadata = user_metadata or {}
@ -144,6 +145,9 @@ def _register_existing_asset(
if not asset: if not asset:
raise ValueError(f"No asset with hash {asset_hash}") raise ValueError(f"No asset with hash {asset_hash}")
if mime_type and asset.mime_type != mime_type:
update_asset_hash_and_mime(session, asset_id=asset.id, mime_type=mime_type)
ref, ref_created = get_or_create_reference( ref, ref_created = get_or_create_reference(
session, session,
asset_id=asset.id, asset_id=asset.id,
@ -411,25 +415,21 @@ def create_from_hash(
) -> UploadResult | None: ) -> UploadResult | None:
canonical = hash_str.strip().lower() canonical = hash_str.strip().lower()
with create_session() as session: try:
asset = get_asset_by_hash(session, asset_hash=canonical) result = _register_existing_asset(
if not asset: asset_hash=canonical,
return None name=_sanitize_filename(
name, fallback=canonical.split(":", 1)[1] if ":" in canonical else canonical
if mime_type and asset.mime_type != mime_type: ),
update_asset_hash_and_mime(session, asset_id=asset.id, mime_type=mime_type) user_metadata=user_metadata or {},
session.commit() tags=tags or [],
tag_origin="manual",
result = _register_existing_asset( owner_id=owner_id,
asset_hash=canonical, mime_type=mime_type,
name=_sanitize_filename( )
name, fallback=canonical.split(":", 1)[1] if ":" in canonical else canonical except ValueError:
), logging.warning("create_from_hash: no asset found for hash %s", canonical)
user_metadata=user_metadata or {}, return None
tags=tags or [],
tag_origin="manual",
owner_id=owner_id,
)
return UploadResult( return UploadResult(
ref=result.ref, ref=result.ref,