Skip to content

GcsArtifactService converts JSON-native custom_metadata values to strings #8401

In review

Description

@sumedh-aerram

GcsArtifactService applies str() to custom_metadata values. Integers, booleans, lists, and nested objects therefore change type when read through either artifact-version API. False becomes a truthy string.

Environment: ADK main (2.15.x), Python 3.11.

Run this offline reproduction; no credentials or network calls are needed:

"""Offline: compare user metadata round trips through public artifact APIs."""
import asyncio
import datetime
from unittest.mock import patch
from google.adk.artifacts.gcs_artifact_service import GcsArtifactService
from google.adk.artifacts.in_memory_artifact_service import InMemoryArtifactService
from google.genai import types

class Blob:
    def __init__(self, name):
        self.name = name
        self.metadata = None
        self.time_created = datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc)
        self.content_type = None
    def upload_from_string(self, data, content_type=None, if_generation_match=None):
        self.content_type = content_type
        self.data = data

class Bucket:
    def __init__(self):
        self.blobs = {}
    def blob(self, name):
        return self.blobs.setdefault(name, Blob(name))
    def get_blob(self, name):
        return self.blobs.get(name)

class Client:
    def __init__(self):
        self.b = Bucket()
    def bucket(self, name):
        return self.b
    def list_blobs(self, bucket, prefix):
        return [b for name, b in bucket.blobs.items() if name.startswith(prefix)]

async def main():
    with patch('google.cloud.storage.Client', return_value=Client()):
        gcs = GcsArtifactService(bucket_name='offline')
    metadata = {'count': 3, 'approved': False, 'tags': ['a', 'b'], 'source': {'page': 2}}
    for svc in (InMemoryArtifactService(), gcs):
        args = dict(app_name='app', user_id='u', session_id='s', filename='report.txt')
        await svc.save_artifact(**args, artifact=types.Part(text='hello'), custom_metadata=metadata)
        result = await svc.get_artifact_version(**args)
        listed = await svc.list_artifact_versions(**args)
        print(type(svc).__name__)
        print('  get metadata:', result.custom_metadata)
        print('  list matches input:', listed[0].custom_metadata == metadata)

asyncio.run(main())

Expected: get_artifact_version and list_artifact_versions return the original JSON-native values, matching the in-memory and file services. Existing GCS string metadata remains strings.

Actual: GCS returns stringified values; the in-memory backend returns the original JSON values.

Activity

  1. added
    services
    on Nov 30, 2026
  2. surajksharma07 commented on Dec 1, 2026

    @surajksharma07
    Collaborator

    @sumedh-aerram. Reproduced on main (2.15.1) with your offline client. The str(v) in _save_artifact has been there since v1.18.0, and FileArtifactService keeps the types fine, so GCS is the odd one out. False -> 'False' is the nasty part, since it's truthy.

    A workaround that held up for me: since GCS metadata is string-only, store the caller's dict as one JSON string under a reserved key and json.loads it in both version readers. Blobs without that key stay as plain strings, so old "3"/"true" values don't get guessed into int/bool.

    Could you check if that matches what you're seeing, and whether you hit this against a real bucket? I only tried the mocked client. I'm also curious how #8402 handles values json.dumps can't serialize (datetime, bytes) and the ~8 KiB metadata limit.

    Please give #8402 a thorough test first before marking it ready. Ideally that means one live GCS run plus a mixed old/new-blob case.

  3. sumedh-aerram commented on Dec 1, 2026

    @sumedh-aerram
    Author

    Thanks for reproducing it, @surajksharma07. I'm seeing the same thing, and #8402 now uses the design you suggested:

    • Storage: the caller's dict is stored as one JSON string under the reserved key adkCustomMetadata, and both version readers decode it. Blobs without the key, or whose key doesn't hold a JSON object, come back as plain strings, so old "3"/"true" values aren't reinterpreted and decoding never raises.
    • Unsupported values: datetime, bytes, and other values JSON can't encode raise InputValidationError at save time, and no blob is written. Tuples come back as lists.
    • 8 KiB limit: before upload, the service sums the UTF-8 bytes of all metadata keys and values and rejects anything over 8192 bytes. Nothing is truncated. The emulator doesn't enforce the real limit, so this boundary hasn't been checked against GCS.
    • fsspec: FsspecArtifactService on gs:// now decodes the key through the same helper, so artifacts written by either service read back identically.
    • Testing: unit tests cover typed values, legacy blobs, mixed versions, and the size boundary. The end-to-end run used fake-gcs-server with the real client, not a real bucket. I'm happy to run it against a real bucket if you'd like.
  4. surajksharma07 commented on Dec 1, 2026

    @surajksharma07
    Collaborator

    Thanks @sumedh-aerram, went through 780c451 and it looks solid. The size check runs after the bookkeeping keys are added and before the version is picked, so nothing is written on a reject, and the bad-value and surrogate errors fire before upload. #8402 merges cleanly with main (30737fa), and main/2.15.1 still do str(v), so this is still needed.

    A few small things:

    1. A legacy blob where the caller used adkCustomMetadata with a JSON object value next to other keys would decode to just that object and drop the rest. New writes only carry the reserved key once internal keys are stripped, so only decoding when it's the sole user key would close that.
    2. Skipping the key when custom_metadata is empty would leave most blobs byte-for-byte as today.
    3. allow_nan=False would keep NaN/Infinity out, since other JSON readers reject them.

    On fsspec, reading now matches, but FsspecArtifactService still writes str(v) per key, so its own typed values still come back as strings. That's fine as a follow-up, but worth a line in the PR description so reviewers don't read "identically" as covering writes.

    Yes please on the real bucket: one save/read round trip and the 8192/8193 boundary would settle the size check. I'll flag #8402 for review so the 2 pending workflows get approved.

  5. sumedh-aerram commented on Dec 1, 2026

    @sumedh-aerram
    Author

    Thanks @surajksharma07, all three are in c6ac525 (merged with current main, still mergeable):

    • Sole-key decode: adkCustomMetadata is decoded only when it is the blob's only user key after bookkeeping keys are stripped. A legacy blob using it next to other keys, even with a JSON object value, returns every key as a plain string.
    • Empty metadata: with no caller metadata (None, {}, or only reserved keys), the key isn't written, so those blobs stay byte-for-byte as today.
    • allow_nan=False: NaN and ±Infinity, including nested, raise InputValidationError at save time with nothing written.
    • fsspec: the PR description now says only reads match. FsspecArtifactService still writes str(v) per key, so I've left its writes as a follow-up.

    I re-ran the emulator at that commit (18 scenarios, including the new cases, plus GCS↔fsspec reads both ways) and the full unit suite shows no new failures. The real-bucket round trip and the 8192/8193 check are still pending until I have a GCS project to run them in. I'll post the results here once they're done.

  6. surajksharma07 commented on Dec 2, 2026

    @surajksharma07
    Collaborator

    @sumedh-aerram, c6ac525 covers all three. I merged #8402 with today's main (b1566b8) and ran it. Artifacts + fsspec gives 2505 passed and 29 xfailed. My offline repro now matches across InMemory, File and GCS. Empty metadata writes only adkIsText. NaN, date and bytes are rejected and no blob gets written.

    One small thing. Main just added a private-name import check (62a488d). artifact_util._decode_gcs_custom_metadata and _GCS_CUSTOM_METADATA_KEY don't trip it since they are used as module attributes and not imported with from. But the new visibility rule says a helper other modules need should drop the underscore. Renaming them now would likely save a review round.

    That leaves the real-bucket round trip and the 8192/8193 check. Post them when you can and I'll push for review once they're in.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

services

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions