Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions src/google/adk/artifacts/gcs_artifact_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

import asyncio
import datetime
import json
import logging
from typing import Any
from typing import cast
Expand All @@ -47,6 +48,7 @@
_GCS_FILE_URI_METADATA_KEY = "adkFileUri"
_GCS_FILE_MIME_TYPE_METADATA_KEY = "adkFileMimeType"
_LEGACY_GCS_FILE_URI_METADATA_KEY = "file_uri"
_GCS_CUSTOM_METADATA_KEY = "adkCustomMetadata"
# Blob metadata keys reserved for this service's own bookkeeping. They are
# dropped from custom_metadata on save and hidden from it on read.
_INTERNAL_METADATA_KEYS = frozenset({
Expand All @@ -55,6 +57,7 @@
_GCS_FILE_URI_METADATA_KEY,
_GCS_FILE_MIME_TYPE_METADATA_KEY,
_LEGACY_GCS_FILE_URI_METADATA_KEY,
_GCS_CUSTOM_METADATA_KEY,
})
_MAX_SAVE_VERSION_ATTEMPTS = 10

Expand All @@ -72,6 +75,15 @@ def _user_metadata(
}


def _decode_user_metadata(
blob_metadata: dict[str, Any] | None,
) -> dict[str, Any]:
"""Decodes new JSON metadata, leaving legacy string values unchanged."""
if blob_metadata and _GCS_CUSTOM_METADATA_KEY in blob_metadata:
return _user_metadata(json.loads(blob_metadata[_GCS_CUSTOM_METADATA_KEY]))
return _user_metadata(blob_metadata)


def _get_file_uri(
blob_metadata: dict[str, Any] | None,
) -> str | None:
Expand Down Expand Up @@ -296,7 +308,7 @@ def _save_artifact(

artifact = ensure_part(artifact)
blob_metadata = {
k: str(v) for k, v in _user_metadata(custom_metadata).items()
_GCS_CUSTOM_METADATA_KEY: json.dumps(_user_metadata(custom_metadata))
}
if artifact.inline_data and artifact.inline_data.display_name:
blob_metadata[_GCS_DISPLAY_NAME_METADATA_KEY] = (
Expand Down Expand Up @@ -592,7 +604,7 @@ def _get_artifact_version_sync(
canonical_uri=canonical_uri,
create_time=blob.time_created.timestamp(),
mime_type=blob.content_type,
custom_metadata=_user_metadata(blob.metadata),
custom_metadata=_decode_user_metadata(blob.metadata),
)

def _list_artifact_versions_sync(
Expand All @@ -619,7 +631,7 @@ def _list_artifact_versions_sync(
canonical_uri=canonical_uri,
create_time=blob.time_created.timestamp(),
mime_type=blob.content_type,
custom_metadata=_user_metadata(blob.metadata),
custom_metadata=_decode_user_metadata(blob.metadata),
)
artifact_versions.append(av)

Expand Down
73 changes: 73 additions & 0 deletions tests/unittests/artifacts/test_artifact_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -5168,3 +5168,76 @@ async def test_in_memory_plain_identifier_keys_are_unchanged():
"app/u1/s1/notes.txt",
"app/u1/user/user:prefs.json",
}


@pytest.mark.parametrize(
"service_type",
[
ArtifactServiceType.IN_MEMORY,
ArtifactServiceType.FILE,
ArtifactServiceType.GCS,
],
)
@pytest.mark.parametrize("filename", ["report.txt", "user:report.txt"])
async def test_custom_metadata_preserves_json_types(
service_type, filename, artifact_service_factory
):
"""Both version readers preserve JSON values across versions and scopes."""
service = artifact_service_factory(service_type)
scope = dict(
app_name="app", user_id="user", session_id="session", filename=filename
)
metadata = {
"integer": 3,
"float": 2.5,
"approved": False,
"null": None,
"list": [1, False, None],
"nested": {"page": 2},
"number_string": "3",
"bool_string": "false",
"object_string": '{"a": 1}',
"empty": "",
"unicode": "café",
}
for values in [metadata, {}]:
await service.save_artifact(
**scope, artifact=types.Part(text="hello"), custom_metadata=values
)
first = await service.get_artifact_version(**scope, version=0)
latest = await service.get_artifact_version(**scope)
listed = await service.list_artifact_versions(**scope)

assert first.custom_metadata == metadata
assert {key: type(value) for key, value in first.custom_metadata.items()} == {
key: type(value) for key, value in metadata.items()
}
assert latest.custom_metadata == {}
assert [version.custom_metadata for version in listed] == [metadata, {}]


async def test_gcs_legacy_custom_metadata_stays_strings():
"""Old string metadata must not be interpreted as JSON values."""
service = mock_gcs_artifact_service()
scope = dict(
app_name="app",
user_id="user",
session_id="session",
filename="report.txt",
)
await service.save_artifact(**scope, artifact=types.Part(text="hello"))
blob = service.bucket.blob("app/user/session/report.txt/0")
metadata = {
"count": "3",
"approved": "false",
"null": "null",
"list": "[1]",
"object": '{"a": 1}',
}
blob.metadata = {**metadata, "adkIsText": "true", "file_uri": "gs://old/file"}

fetched = await service.get_artifact_version(**scope)
listed = await service.list_artifact_versions(**scope)

assert fetched.custom_metadata == metadata
assert listed[0].custom_metadata == metadata