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
41 changes: 41 additions & 0 deletions src/google/adk/artifacts/artifact_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@

from __future__ import annotations

from collections.abc import Mapping
import json
import re
from typing import Any
from typing import NamedTuple

from google.genai import types
Expand Down Expand Up @@ -173,6 +176,44 @@ def _is_rewind_tombstone(artifact: types.Part) -> bool:
return artifact == _REWIND_TOMBSTONE


# GCS object metadata values are strings only, so GcsArtifactService stores the
# caller's custom_metadata as one JSON object under this key.
# FsspecArtifactService decodes it the same way when reading such objects.
GCS_CUSTOM_METADATA_KEY = "adkCustomMetadata"


def decode_gcs_custom_metadata(
user_metadata: Mapping[str, Any],
) -> dict[str, Any]:
"""Returns the caller's custom_metadata stored on a GCS object.

Objects written before custom_metadata was stored as JSON hold the caller's
values as plain strings. They are returned unchanged rather than parsed, so a
legacy ``"3"`` or ``"false"`` stays a string. The reserved key is decoded only
when it is the object's sole user key and holds a JSON object, as on objects
written with JSON metadata. Otherwise, such as when the caller used that key
alongside others before it was reserved, the object is treated as legacy.
Decoding never raises.

Args:
user_metadata: The object's metadata without ADK's other bookkeeping
keys.

Returns:
The JSON object stored under the reserved key, or every key of
``user_metadata`` unchanged for legacy objects.
"""
encoded = user_metadata.get(GCS_CUSTOM_METADATA_KEY)
if len(user_metadata) == 1 and isinstance(encoded, str):
try:
decoded = json.loads(encoded)
except (ValueError, RecursionError):
decoded = None
if isinstance(decoded, dict):
return decoded
return dict(user_metadata)


def validate_artifact_reference_scope(
*,
app_name: str,
Expand Down
87 changes: 82 additions & 5 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 Down Expand Up @@ -57,6 +58,10 @@
_LEGACY_GCS_FILE_URI_METADATA_KEY,
})
_MAX_SAVE_VERSION_ATTEMPTS = 10
# GCS limit on the combined size of an object's custom metadata keys and
# values, checked against the UTF-8 bytes of every key and value this service
# sends, including its own bookkeeping keys.
_GCS_MAX_CUSTOM_METADATA_BYTES = 8 * 1024


def _user_metadata(
Expand All @@ -72,6 +77,65 @@ def _user_metadata(
}


def _encode_user_metadata(
custom_metadata: dict[str, Any] | None,
) -> str | None:
"""Encodes caller metadata as the JSON object stored on the blob.

A JSON round trip returns tuples as lists and non-string dict keys as
strings.

Args:
custom_metadata: The caller's metadata. Reserved keys are dropped.

Returns:
The compact JSON object, with non-ASCII characters kept as is so they
count once toward the GCS metadata size limit, or None if there is no
caller metadata to store.

Raises:
InputValidationError: If a value cannot be represented as JSON, such as
NaN or infinity, or a key or string is not valid Unicode text.
"""
user_metadata = {
key: value
for key, value in _user_metadata(custom_metadata).items()
if key != artifact_util.GCS_CUSTOM_METADATA_KEY
}
if not user_metadata:
return None
try:
encoded = json.dumps(
user_metadata,
ensure_ascii=False,
allow_nan=False,
separators=(",", ":"),
)
except (TypeError, ValueError) as e:
raise InputValidationError(
"custom_metadata must contain only JSON-serializable values (str,"
" int, finite float, bool, None, list, dict) to be stored in GCS."
" Convert other values, such as datetime, bytes, or NaN, before"
f" saving: {e}"
) from e
try:
# GCS stores metadata as UTF-8, which cannot hold lone surrogates.
encoded.encode("utf-8")
except UnicodeEncodeError as e:
raise InputValidationError(
"custom_metadata keys and strings must be valid Unicode text to be"
f" stored in GCS, without unpaired surrogates: {e}"
) from e
return encoded


def _decode_user_metadata(
blob_metadata: dict[str, Any] | None,
) -> dict[str, Any]:
"""Decodes JSON metadata, leaving legacy string values unchanged."""
return artifact_util.decode_gcs_custom_metadata(_user_metadata(blob_metadata))


def _get_file_uri(
blob_metadata: dict[str, Any] | None,
) -> str | None:
Expand Down Expand Up @@ -295,9 +359,10 @@ def _save_artifact(
artifact_util._validate_session_id_for_flat_storage(session_id)

artifact = ensure_part(artifact)
blob_metadata = {
k: str(v) for k, v in _user_metadata(custom_metadata).items()
}
blob_metadata: dict[str, str] = {}
encoded_metadata = _encode_user_metadata(custom_metadata)
if encoded_metadata is not None:
blob_metadata[artifact_util.GCS_CUSTOM_METADATA_KEY] = encoded_metadata
if artifact.inline_data and artifact.inline_data.display_name:
blob_metadata[_GCS_DISPLAY_NAME_METADATA_KEY] = (
artifact.inline_data.display_name
Expand Down Expand Up @@ -348,6 +413,18 @@ def _save_artifact(
"Artifact must have either inline_data or text."
)

metadata_size = sum(
len(key.encode("utf-8")) + len(value.encode("utf-8"))
for key, value in blob_metadata.items()
)
if metadata_size > _GCS_MAX_CUSTOM_METADATA_BYTES:
raise InputValidationError(
f"Artifact metadata is {metadata_size} bytes when stored in GCS,"
f" over the {_GCS_MAX_CUSTOM_METADATA_BYTES}-byte custom metadata"
" limit. Reduce custom_metadata or store large values in the"
" artifact itself."
)

versions = self._list_versions(
app_name=app_name,
user_id=user_id,
Expand Down Expand Up @@ -595,7 +672,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 @@ -622,7 +699,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
11 changes: 9 additions & 2 deletions src/google/adk/integrations/fsspec/_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
from packaging.version import Version
from typing_extensions import override

from ...artifacts import artifact_util
from ...errors.input_validation_error import InputValidationError
from ...platform import time as platform_time

Expand Down Expand Up @@ -264,8 +265,14 @@ def file_mime_type(self) -> Optional[str]:

@property
def user_metadata(self) -> dict[str, Any]:
"""Returns caller-supplied metadata with ADK bookkeeping keys removed."""
return _user_metadata(self.raw_metadata)
"""Returns caller-supplied metadata with ADK bookkeeping keys removed.

Metadata that ``GcsArtifactService`` stored as JSON is decoded the same way
that service decodes it.
"""
return artifact_util.decode_gcs_custom_metadata(
_user_metadata(self.raw_metadata)
)


class _BackendAdapter(abc.ABC):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -310,8 +310,12 @@ def _save_artifact(
artifact_util._validate_session_id_for_flat_storage(session_id)

part = ensure_part(artifact)
# The key GcsArtifactService stores JSON metadata under is reserved, as it
# is there, so a caller value is never decoded as that JSON on read.
blob_metadata = {
k: str(v) for k, v in _user_metadata(custom_metadata).items()
k: str(v)
for k, v in _user_metadata(custom_metadata).items()
if k != artifact_util.GCS_CUSTOM_METADATA_KEY
}

data: bytes
Expand Down
Loading