adk-java icon indicating copy to clipboard operation
adk-java copied to clipboard

feat: Add injectable time and UUID providers

Open DABH opened this issue 5 months ago • 4 comments

Link to Issue or Description of Change

Problem: ADK generates timestamps and IDs by calling Instant.now() and UUID.randomUUID() directly. There are use cases where it's useful to have custom clock and UUID providers, such as when you want to make runs reproducible/deterministic.

adk-python already solves this with platform.time / platform.uuid - see https://github.com/google/adk-python/pull/4200. Closely inspired by that, we propose adding similar functionality for adk-java. Note that a similar PR is open right now for adk-go: https://github.com/google/adk-go/pull/964.

Solution: Introduce a leaf package com.google.adk.platform with two functional interfaces:

  • TimeProvider — Instant now(), default SYSTEM backed by Instant::now.
  • UuidProvider — String newUuid(), default SYSTEM backed by UUID.randomUUID().

Both default to today's wall-clock / random behavior, so this change is fully backwards-compatible.

The providers are threaded as data through InvocationContext rather than stored in an ambient ThreadLocal. ADK's core flow hops threads via RxJava (e.g. BaseLlmFlow observes on Schedulers.io() / the agent executor), and events are built downstream on those worker threads. We considered using a ThreadLocal but that would silently fall back to the system providers after a thread hop, failing open with no error. So the proposed solution here, carrying the providers on the InvocationContext (which is already captured in the RxJava lambdas and passed down the chain) makes them visible on whatever thread builds an event, so this is thread-safe. This mirrors the proposed changes to adk-go, which diverged from adk-python's contextvar mechanism for the same concurrency reason.

Users configure the providers once on the Runner (Runner.builder().timeProvider(...).uuidProvider(...)); no knowledge of ADK's internal threads is required.

The other files edited in this PR are just call sites updated to derive from the in-scope providers:

  • InvocationContext — invocation ID, plus now() / newUuid() accessors.
  • BaseLlmFlow, Functions, OutputSchema — event IDs + timestamps, function-call IDs.
  • Runner — invocation ID + event builds.
  • InMemorySessionService — auto session ID + lastUpdateTime (constructor injection; default constructor keeps SYSTEM behavior).

Event.generateEventId() and the Event.Builder.build() timestamp default now delegate to UuidProvider.SYSTEM / TimeProvider.SYSTEM, so the platform interfaces are the single source for generated IDs and timestamps while the Event API stays unchanged.

Testing Plan

Unit Tests:

  • [x] I have added or updated unit tests for my change.
  • [x] All unit tests pass locally.

New/updated tests:

  • platform/TimeProviderTest, platform/UuidProviderTest — SYSTEM defaults + custom-provider behavior.
  • InvocationContextTest — providers default to SYSTEM, are carried by the builder/toBuilder(), and drive now() / newUuid().
  • FunctionsTest — function-call ID derives from the injected provider.
  • InMemorySessionServiceTest — injected providers produce a deterministic session ID and lastUpdateTime.
  • RunnerTest.runAsync_withDeterministicProviders_producesIdenticalEvents — the headline guarantee: running the same input twice through the full flow yields byte-identical event IDs, timestamps, and invocation IDs.

Local results (./mvnw -pl core test, openjdk@17), all green:

TimeProviderTest / UuidProviderTest  Tests run: 2,   Failures: 0, Errors: 0, Skipped: 0
RunnerTest                            Tests run: 139, Failures: 0, Errors: 0, Skipped: 0
InvocationContextTest / FunctionsTest / InMemorySessionServiceTest  Failures: 0, Errors: 0

./mvnw -pl core fmt:check — 0 non-complying files.

Manual End-to-End (E2E) Tests:

This is an in-process library seam with no runtime/config surface to exercise manually. The guarantee is verified by the unit test above, which asserts two independent runs of the same invocation produce identical IDs and timestamps.

Checklist

  • [x] I have read the CONTRIBUTING.md document.
  • [x] My pull request contains a single commit.
  • [x] I have performed a self-review of my own code.
  • [x] I have commented my code, particularly in hard-to-understand areas.
  • [x] I have added tests that prove my fix is effective or that my feature works.
  • [x] New and existing unit tests pass locally with my changes.
  • [x] I have manually tested my changes end-to-end.
  • [x] Any dependent changes have been merged and published in downstream modules.

Additional context

Motivated by maintaining feature parity with adk-python and the proposed changes to adk-go.

DABH avatar Jun 09 '26 19:06 DABH

Hi @DABH, thank you for your contribution! We appreciate you taking the time to submit this pull request. As per contribution policy, please ensure your PR consists of a single commit and i have noticed inconsistency code formatting. Could you please change your commits accordingly and address the code formatting issue?

hemasekhar-p avatar Jun 10 '26 12:06 hemasekhar-p

@DABH, thank you for your quick response. when running a Maven build, some files are modifying due to incorrect formatting. so, use the Maven build to ensure your changes are properly aligned and please make sure your PR contains a single commit.

hemasekhar-p avatar Jun 11 '26 05:06 hemasekhar-p

Thanks @hemasekhar-p — addressed both. I rebased onto the latest main and ran the full Maven build (which runs the bound fmt:format goal); mvn fmt:check now reports 0 non-complying files across all modules. I've also squashed the change into a single commit. Let me know if you still see any files being reformatted on your end.

DABH avatar Jun 11 '26 17:06 DABH

Also @hemasekhar-p I made a few improvements to the design/implementation based on @xumaple's feedback (updated the PR description accordingly). Thanks again for the fast review and please just let me know what else I can do to help make this PR mergeable. I appreciate your help and look forward to hearing from you!

DABH avatar Jun 11 '26 18:06 DABH

Hi @hemasekhar-p , any further thoughts here on this PR? The equivalent Go PR got merged so just wanted to follow up. Thanks again!

DABH avatar Jun 16 '26 20:06 DABH

@DABH, thank you for the updates, To proceed with the review, could you please address merge conflicts?

hemasekhar-p avatar Jul 22 '26 08:07 hemasekhar-p

@hemasekhar-p Thanks, this has been done - can you please review? Thanks again!

DABH avatar Jul 24 '26 04:07 DABH

@DABH, thank you for addressing the feedback and resolving the merge conflicts. The PR is currently under review by our team. We will keep you updated if any further changes or any additional information is required. Thank you.

hemasekhar-p avatar Jul 24 '26 06:07 hemasekhar-p

I need this for the same reason adk-python and adk-go added their platform seams: replay-safe event IDs and timestamps under a durable-execution host. adk-java is the one runtime without them. The branch conflicts with main again as of 4092a1fa, in two import blocks and the Role.USER change in LlmEventSummarizer, and after a local rebase with those resolved the core tests pass, so it should be a short fix on your side. Once it lands I'd like to send the Java equivalent of adk-go's platform.WithTaskRunner (google/adk-go#1050) as a follow-up, unless you have it in flight.

sangkyoonnam avatar Sep 24 '26 13:09 sangkyoonnam

Thanks @sangkyoonnam. To save you the trouble, I've opened the Java analog of adk-go's platform.WithTaskRunner as #1587: an invocation-scoped RxJava Scheduler set once via Runner.builder().scheduler(...), carried on InvocationContext, and consulted by ParallelAgent, the PARALLEL_SUBSCRIBE tool fan-out, and the live request loop (agent-level scheduler/executor settings keep precedence; default stays Schedulers.io()). It is independent of this PR, so either can land first. Reviews welcome over there.

DABH avatar Oct 01 '26 08:10 DABH

Thanks @damianmomotgoogle for the thorough review - really appreciated, this made the PR noticeably better. All nine threads are addressed in 05a35f12 (still a single commit, rebased onto current main); I replied inline on each. The headline changes:

  • Builder semantics match main again: the default InMemorySessionService is created once per Runner.Builder and shared by every runner built from it, sessionService(null) fails in build() with the original IllegalStateException, and InvocationContext.Builder mints its default invocation id once per builder.
  • TimeProvider is gone in favor of java.time.InstantSource (Runner.builder().instantSource(...)); UuidProvider is the only new type.
  • Event.toBuilder() now always copies the timestamp (the drop-zero behavior only existed to serve a template hack in BaseLlmFlow, which is removed), so a clock fixed at Instant.EPOCH stays at 0 end to end.
  • Determinism tests now cover a tool-call turn, agent callbacks, and an output-schema agent with an EPOCH clock, and fail if any swept site falls back to the wall clock or UUID.randomUUID().
  • API narrowed (one new public constructor each on InMemorySessionService / LlmEventSummarizer, package-private populateClientFunctionCallId), and the Javadoc trimmed.

Full ./mvnw -Prelease clean package is green locally on JDK 17 (core: 2078 tests, 0 failures). The PR description is updated to match. Thanks again!

DABH avatar Oct 04 '26 21:10 DABH

Thanks @damianmomotgoogle! Addressed in 387d79aa: instantSource(null) / uuidProvider(null) now select the defaults on both builders (same rule as scheduler(null)), with a test that runs an AgentTool from a Mockito-mocked InvocationContext like the suites you hit. The branch is also rebased onto current main with #1587 merged, so the two seams sit side by side (AgentTool passes the caller's scheduler and providers together); still a single commit. Full ./mvnw -Prelease clean package is green locally on JDK 17 (core: 2105 tests, 0 failures); the description is updated. Thanks again!

DABH avatar Oct 06 '26 06:10 DABH

I ran this PR at 387d79aa, rebased onto main with #1587 already merged, inside a Temporal workflow and replayed the history. For every emitted and persisted event, the event id, timestamp, invocation id, and the function-call ids ADK mints came back identical, and so did the session id, with no nondeterminism error.

I built the runner with instantSource(() -> Instant.ofEpochMilli(Workflow.currentTimeMillis())), uuidProvider(() -> Workflow.randomUUID().toString()), and scheduler(Schedulers.trampoline()), plus an InMemorySessionService built with the same providers. The model is a BaseLlm that calls an activity, and the root is a ParallelAgent over two LlmAgents in PARALLEL_SUBSCRIBE mode. The trampoline runs the fan-out sequentially. A scheduler that wraps each task in Async.procedure also replayed identically, and both sub-agents' first model activities were scheduled in the same workflow task. That variant passed when the workflow waited with subscribe plus Workflow.await. Waiting with blockingGet() tripped the deadlock detector.

Controls: with the system clock and UUID.randomUUID, the replay diverges, and each provider moves only its own fields among the ones compared. With the scheduler left at Schedulers.io(), the run never completes, because the providers and the activity stub get called from RxCachedThreadScheduler threads and the workflow task keeps failing or timing out. On released 1.11.0 the same ParallelAgent setup never completes, because the activity stub gets called from RxCachedThreadScheduler threads. A single LlmAgent with PARALLEL tool execution, and the parallel tree with per-agent trampoline and direct executor settings, complete but replay with different ids and timestamps.

Setup: head 387d79aa as pushed, no local merge. JDK 21, Temporal Java SDK 1.40.0. The model's first turn returns two function calls without ids, and each LlmAgent has before and after agent callbacks. I compared author, branch, ids, timestamps, invocation id, function-call and response names and ids, state delta, and text between the original run and a full-history WorkflowReplayer run on the test environment in one JVM. Worker restarts and mid-run recovery weren't tested.

Not covered: code execution (CodeExecutorContext), telemetry, streaming model adapters, runLive, AgentTool nested runs, resumability, compaction, and a model client that emits on its own thread. Here the model call returns on the workflow thread because it's an activity. The harness always passes non-null providers, so I checked the null case from the latest review separately: instantSource(null) and uuidProvider(null) on both Runner.Builder and InvocationContext.Builder build without error and use the system defaults, and non-null providers are still honored.

sangkyoonnam avatar Oct 06 '26 11:10 sangkyoonnam

Please also rebase on head revision

damianmomotgoogle avatar Oct 06 '26 13:10 damianmomotgoogle

Thanks @damianmomotgoogle! All seven threads are addressed in caccc7cb and the branch is rebased onto current main (still a single commit); I replied inline on each. The only API-visible changes are that LlmEventSummarizer.DEFAULT_PROMPT_TEMPLATE is private again (the constructors take a @Nullable template, null = default) and Functions.populateClientFunctionCallId(Event, UuidProvider) is public like its siblings.

One related thing I noticed while rebasing: main's new unconvertible-part filter in ResponseConverter drops a remote event after remoteAgentEventBuilder has already drawn its id and timestamp, the same pattern as the EventConverter thread. Those draws depend only on the peer's response, so replay stays deterministic, and I left it alone to keep this round small; happy to convert the parts before building the event, either here or as a follow-up PR, whichever you prefer.

Full ./mvnw -Prelease clean package is green locally on JDK 17 (core: 2113 tests, 0 failures); the description is updated. Thanks again!

DABH avatar Oct 07 '26 03:10 DABH