Skip to content

feat(gapic-generator): wire async REST total_attempts and async trace response recording - #19154

Draft
chalmerlowe wants to merge 1 commit into
feat/otel-logging-m3-s7-grpc-rpc-methodfrom
feat/otel-logging-rest-asyncio
Draft

chalmerlowe wants to merge 1 commit into
feat/otel-logging-m3-s7-grpc-rpc-methodfrom
feat/otel-logging-rest-asyncio

Conversation

@chalmerlowe

@chalmerlowe chalmerlowe commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Context

End-to-end compliance testing of the experimental rest_asyncio transport surfaced two gaps in how generated async REST transports dispatch HTTP requests and report failed responses to google-api-core's observability hooks:

  1. Hidden google-auth 503 retries: Unlike synchronous AuthorizedSession, google.auth.aio.transport.sessions.AsyncAuthorizedSession wraps every outgoing call in an internal 3-attempt retry loop on (500, 503, 504, 408, 429) unless total_attempts=1 is passed (google-auth >= 2.49.0). Because generated async REST transports did not pass total_attempts=1, transient 503 responses were silently retried inside google-auth before GAPIC's AsyncRetry, T4 spans, or L4 attempt logs could observe them.
  2. Synchronous response inspection on async HTTP errors: _shared_macros.j2 called synchronous trace_ctx.record_response(response) on rest_asyncio responses. Because aiohttp response bodies must be awaited via await response.read(), google.rpc.ErrorInfo and server status.message were unavailable to L4 attempt logs and T4 spans on failed (>= 400) async REST calls.

Bug: b/479827845

Solution

  • packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/_compat.py.j2:
    • Add async def record_response_async() (and record_http_response_async alias) to _FallbackTraceContext for parity with _TraceContext.
    • Add async def record_http_response_async(trace_ctx, response) to await trace_ctx.record_response_async(response) when supported by google-api-core, falling back to synchronous trace_ctx.record_response(response) on older releases.
    • Add ASYNC_SESSION_SUPPORTS_TOTAL_ATTEMPTS and async_rest_request_kwargs(session) (matching google.api_core.resumable_transfer.upload_async) to pass total_attempts=1 when session is an AsyncAuthorizedSession backed by google-auth >= 2.49.0.
  • packages/gapic-generator/gapic/templates/tests/unit/gapic/%name_%version/%sub/test_compat.py.j2:
    • Add unit test coverage for _FallbackTraceContext.record_response_async, record_http_response_async (async and sync-fallback paths), and async_rest_request_kwargs.
  • packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/_shared_macros.j2 & transports/rest_asyncio.py.j2:
    • Wire **async_rest_request_kwargs(session) and await record_http_response_async(trace_ctx, response) on the is_async HTTP dispatch path.
  • Bazel Goldens (packages/gapic-generator/tests/integration/goldens/):
    • Regenerated all affected golden libraries (_compat.py, test_compat.py, and redis/redis_selective rest_asyncio.py).
  • Tracing Matrix Alignment (packages/gapic-generator/tests/system/telemetry_requirements_matrix.csv):

Notes for Reviewers

Verification

  • Verified locally with bazelisk test //tests/integration:all, Docker Nox unit-3.10, unit-3.14, showcase_unit_w_rest_async-3.14 (100.00% line and branch coverage), and showcase_mypy (0 issues across 74 source files).
  • Relying on GitHub Actions CI for full multi-version verification.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces async REST support and compatibility utilities for older versions of google-api-core and google-auth, specifically adding record_http_response_async and async_rest_request_kwargs to disable internal retries on AsyncAuthorizedSession. These changes are integrated across templates, shared macros, and generated golden files, alongside corresponding unit tests. Feedback recommends adding a defensive None check for trace_ctx in record_http_response_async (with an accompanying unit test) and wrapping the import-time inspect.signature call in a try...except block to prevent potential failures.

Comment on lines +98 to +103
async def record_http_response_async(trace_ctx: Any, response: Any) -> None:
"""Records an async HTTP response with fallback for older google-api-core."""
if hasattr(trace_ctx, "record_response_async"):
await trace_ctx.record_response_async(response)
else:
trace_ctx.record_response(response)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To enforce defensive programming and prevent potential AttributeError exceptions, we should check if trace_ctx is None before attempting to access its attributes or methods.

async def record_http_response_async(trace_ctx: Any, response: Any) -> None:\n    \"\"\"Records an async HTTP response with fallback for older google-api-core.\"\"\"\n    if trace_ctx is None:\n        return\n    if hasattr(trace_ctx, \"record_response_async\"):\n        await trace_ctx.record_response_async(response)\n    else:\n        trace_ctx.record_response(response)

Comment on lines +137 to +141
ASYNC_SESSION_SUPPORTS_TOTAL_ATTEMPTS = (
_AsyncAuthorizedSession is not None
and "total_attempts"
in inspect.signature(_AsyncAuthorizedSession.request).parameters
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using inspect.signature on third-party library methods at module import time can raise ValueError or TypeError in certain environments (e.g., when the library is mocked, has C-extensions, or has unexpected wrappers). Wrapping this check in a try...except (ValueError, TypeError) block ensures that the module imports successfully even if the signature inspection fails.

try:\n    ASYNC_SESSION_SUPPORTS_TOTAL_ATTEMPTS = (\n        _AsyncAuthorizedSession is not None\n        and \"total_attempts\"\n        in inspect.signature(_AsyncAuthorizedSession.request).parameters\n    )\nexcept (ValueError, TypeError):\n    ASYNC_SESSION_SUPPORTS_TOTAL_ATTEMPTS = False

Comment on lines +604 to +614
def test_record_http_response_async_compat():
resp = mock.Mock()

async_ctx = mock.Mock(spec_set=["record_response_async"])
async_ctx.record_response_async = mock.AsyncMock()
asyncio.run(record_http_response_async(async_ctx, resp))
async_ctx.record_response_async.assert_awaited_once_with(resp)

sync_only_ctx = mock.Mock(spec_set=["record_response"])
asyncio.run(record_http_response_async(sync_only_ctx, resp))
sync_only_ctx.record_response.assert_called_once_with(resp)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Update the unit test to verify that record_http_response_async handles a None trace_ctx gracefully without raising any exceptions.

def test_record_http_response_async_compat():\n    resp = mock.Mock()\n\n    async_ctx = mock.Mock(spec_set=[\"record_response_async\"])\n    async_ctx.record_response_async = mock.AsyncMock()\n    asyncio.run(record_http_response_async(async_ctx, resp))\n    async_ctx.record_response_async.assert_awaited_once_with(resp)\n\n    sync_only_ctx = mock.Mock(spec_set=[\"record_response\"])\n    asyncio.run(record_http_response_async(sync_only_ctx, resp))\n    sync_only_ctx.record_response.assert_called_once_with(resp)\n\n    # Test with None trace_ctx\n    asyncio.run(record_http_response_async(None, resp))

@chalmerlowe
chalmerlowe force-pushed the feat/otel-logging-rest-asyncio branch from c45a48b to b47d72d Compare November 20, 2026 18:45
@chalmerlowe
chalmerlowe force-pushed the feat/otel-logging-m3-s7-grpc-rpc-method branch from 873d998 to 367071a Compare November 20, 2026 18:45
@chalmerlowe chalmerlowe added this to the [o11y] Logging milestone Nov 23, 2026

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant