From 593d1f914f85e8f8132091acac9d444d176bf29b Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Thu, 19 Nov 2026 11:12:25 -0500 Subject: [PATCH 1/2] test(gapic-generator): add Showcase operational error logging compliance suite Add the 28-row operational error logging matrix (F4.1-F5.14), Showcase compliance harness, sync/async compliance tests, and CI raw_logs_output.json artifact upload. Bug: b/479827845 --- .github/workflows/gapic-generator-tests.yml | 30 + .../system/logging_requirements_matrix.csv | 29 + .../tests/system/showcase_harness.py | 437 +++++++++++ .../tests/system/test_logging_compliance.py | 721 ++++++++++++++++++ 4 files changed, 1217 insertions(+) create mode 100644 packages/gapic-generator/tests/system/logging_requirements_matrix.csv create mode 100644 packages/gapic-generator/tests/system/showcase_harness.py create mode 100644 packages/gapic-generator/tests/system/test_logging_compliance.py diff --git a/.github/workflows/gapic-generator-tests.yml b/.github/workflows/gapic-generator-tests.yml index 70536daadcd8..09bd8bcb1df2 100644 --- a/.github/workflows/gapic-generator-tests.yml +++ b/.github/workflows/gapic-generator-tests.yml @@ -139,6 +139,7 @@ jobs: # TODO(https://github.com/googleapis/gapic-generator-python/issues/2286): Construct nox sessions with logging enabled. GOOGLE_SDK_PYTHON_LOGGING_SCOPE: ${{ matrix.logging_scope }} MATRIX_PYTHON: ${{ matrix.python }} + SHOWCASE_RAW_LOGS_OUTPUT_PATH: ${{ github.workspace }}/packages/gapic-generator/tests/system/raw_logs_output.json run: | cd packages/gapic-generator nox -s ${{ matrix.target }}-${MATRIX_PYTHON} @@ -149,6 +150,20 @@ jobs: name: raw-spans-${{ matrix.target }}-${{ matrix.python }}${{ matrix.logging_scope && format('-{0}', matrix.logging_scope) || '' }} path: packages/gapic-generator/tests/system/raw_spans_output.json if-no-files-found: ignore + - name: Upload Raw Logs Artifact + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: raw-logs-${{ matrix.target }}-${{ matrix.python }}${{ matrix.logging_scope && format('-{0}', matrix.logging_scope) || '' }} + path: packages/gapic-generator/tests/system/raw_logs_output.json + if-no-files-found: ignore + - name: Upload Raw Logging Spans Artifact + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: raw-logging-spans-${{ matrix.target }}-${{ matrix.python }}${{ matrix.logging_scope && format('-{0}', matrix.logging_scope) || '' }} + path: packages/gapic-generator/tests/system/raw_logging_spans_output.json + if-no-files-found: ignore showcase-canary: needs: python_config @@ -194,6 +209,7 @@ jobs: env: INSTALL_LOCAL_CORE: "true" MATRIX_PYTHON: ${{ matrix.python }} + SHOWCASE_RAW_LOGS_OUTPUT_PATH: ${{ github.workspace }}/packages/gapic-generator/tests/system/raw_logs_output.json run: | cd packages/gapic-generator nox -s ${{ matrix.target }}-${MATRIX_PYTHON} @@ -204,6 +220,20 @@ jobs: name: raw-spans-canary-${{ matrix.target }}-${{ matrix.python }} path: packages/gapic-generator/tests/system/raw_spans_output.json if-no-files-found: ignore + - name: Upload Raw Logs Artifact + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: raw-logs-canary-${{ matrix.target }}-${{ matrix.python }} + path: packages/gapic-generator/tests/system/raw_logs_output.json + if-no-files-found: ignore + - name: Upload Raw Logging Spans Artifact + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: raw-logging-spans-canary-${{ matrix.target }}-${{ matrix.python }} + path: packages/gapic-generator/tests/system/raw_logging_spans_output.json + if-no-files-found: ignore showcase-mypy: needs: python_config diff --git a/packages/gapic-generator/tests/system/logging_requirements_matrix.csv b/packages/gapic-generator/tests/system/logging_requirements_matrix.csv new file mode 100644 index 000000000000..32bb7dcff301 --- /dev/null +++ b/packages/gapic-generator/tests/system/logging_requirements_matrix.csv @@ -0,0 +1,29 @@ +Feature ID,Feature Name,Tier,Attempt,Transport,Scenario,RPC Service,Logging Enabled,Tracing Enabled,Configured Logger Level,Tier Log Count,Total Log Count,Log Level,Logger Name,Message Prefix,Async Message Prefix,exc_info Present,rpc.system.name,rpc.response.status_code,rpc.method,url.full,httpRequest.requestMethod,httpRequest.requestUrl,httpRequest.status,error.type,Async error.type,gcp.errors.domain,gcp.errors.metadata.zone,status.message,Async status.message,exception.type,Async exception.type,exception.message,Async exception.message,exception.stacktrace,trace_id,span_id,Cloud Logging Trace Fields +F4.1,HTTP no logs emitted unless enabled,L4,N/A,HTTP/REST,Logging Off,Echo.Echo,False,False,DEBUG,0,0,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A +F4.2,HTTP L4 log emitted on low-level request failure,L4,0,HTTP/REST,Server Failure,Echo.Echo,True,False,DEBUG,1,2,DEBUG,google.api_core._observability,Transport attempt failed for http://localhost:7469/v1beta1/echo:echo (status=400),Transport attempt failed for http://localhost:7469/v1beta1/echo:echo (status=400),False,http,NOT SET,NOT SET,http://localhost:7469/v1beta1/echo:echo,POST,http://localhost:7469/v1beta1/echo:echo,400,INVALID_ARGUMENT_REASON,INVALID_ARGUMENT_REASON,showcase.googleapis.com,us-east1-a,Simulated unretryable invalid argument error.,Simulated unretryable invalid argument error.,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET +F4.3,HTTP no L4 log emitted on request success,L4,N/A,HTTP/REST,Happy Path,Echo.Echo,True,False,DEBUG,0,0,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A +F4.4,HTTP L4 log recorded in context of T4 span,L4,0,HTTP/REST,Active Trace,Echo.Echo,True,True,DEBUG,1,2,DEBUG,google.api_core._observability,Transport attempt failed for http://localhost:7469/v1beta1/echo:echo (status=400),Transport attempt failed for http://localhost:7469/v1beta1/echo:echo (status=400),False,http,NOT SET,NOT SET,http://localhost:7469/v1beta1/echo:echo,POST,http://localhost:7469/v1beta1/echo:echo,400,INVALID_ARGUMENT_REASON,INVALID_ARGUMENT_REASON,showcase.googleapis.com,us-east1-a,Simulated unretryable invalid argument error.,Simulated unretryable invalid argument error.,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,T3.trace_id,T4.span_id,MATCH_SPAN_CONTEXT +F4.5,HTTP L4 client timeout failure attributes,L4,0,HTTP/REST,Client Timeout,Echo.Block,True,False,DEBUG,1,2,DEBUG,google.api_core._observability,Transport attempt failed for http://localhost:7469/v1beta1/echo:block (status=ReadTimeout),Transport attempt failed for http://localhost:7469/v1beta1/echo:block (status=TimeoutError),False,http,NOT SET,NOT SET,http://localhost:7469/v1beta1/echo:block,POST,http://localhost:7469/v1beta1/echo:block,NOT SET,ReadTimeout,TimeoutError,NOT SET,NOT SET,*Read timed out*,*exceeded the configured timeout*,ReadTimeout,TimeoutError,*Read timed out*,*exceeded the configured timeout*,,NOT SET,NOT SET,NOT SET +F4.6a,HTTP L4 logs for retries - Attempt 1,L4,0,HTTP/REST,Retry Recovery,SequenceService.AttemptSequence,True,False,DEBUG,2,2,DEBUG,google.api_core._observability,Transport attempt failed for http://localhost:7469/v1beta1/sequences/* (status=503),Transport attempt failed for http://localhost:7469/v1beta1/sequences/* (status=503),False,http,NOT SET,NOT SET,http://localhost:7469/v1beta1/sequences/*,POST,http://localhost:7469/v1beta1/sequences/*,503,503,503,NOT SET,NOT SET,Temporary glitch,Temporary glitch,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET +F4.6b,HTTP L4 logs for retries - Attempt 2,L4,1,HTTP/REST,Retry Recovery,SequenceService.AttemptSequence,True,False,DEBUG,2,2,DEBUG,google.api_core._observability,Transport attempt failed for http://localhost:7469/v1beta1/sequences/* (status=503),Transport attempt failed for http://localhost:7469/v1beta1/sequences/* (status=503),False,http,NOT SET,NOT SET,http://localhost:7469/v1beta1/sequences/*,POST,http://localhost:7469/v1beta1/sequences/*,503,503,503,NOT SET,NOT SET,Temporary glitch,Temporary glitch,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET,NOT SET +F4.7,gRPC no logs emitted unless enabled,L4,N/A,gRPC,Logging Off,Echo.Echo,False,False,DEBUG,0,0,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A +F4.8,gRPC L4 log emitted on low-level request failure,L4,0,gRPC,Server Failure,Echo.Echo,True,False,DEBUG,1,2,DEBUG,google.api_core._observability,Transport attempt failed for /google.showcase.v1beta1.Echo/Echo (status=INVALID_ARGUMENT),Transport attempt failed for /google.showcase.v1beta1.Echo/Echo (status=INVALID_ARGUMENT),False,grpc,INVALID_ARGUMENT,google.showcase.v1beta1.Echo/Echo,NOT SET,NOT SET,NOT SET,NOT SET,INVALID_ARGUMENT_REASON,INVALID_ARGUMENT_REASON,showcase.googleapis.com,us-east1-a,Simulated unretryable invalid argument error.,Simulated unretryable invalid argument error.,_InactiveRpcError,AioRpcError,*Simulated unretryable invalid argument error.*,*Simulated unretryable invalid argument error.*,,NOT SET,NOT SET,NOT SET +F4.9,gRPC no L4 log emitted on request success,L4,N/A,gRPC,Happy Path,Echo.Echo,True,False,DEBUG,0,0,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A +F4.10,gRPC L4 log recorded in context of T4 span,L4,0,gRPC,Active Trace,Echo.Echo,True,True,DEBUG,1,2,DEBUG,google.api_core._observability,Transport attempt failed for /google.showcase.v1beta1.Echo/Echo (status=INVALID_ARGUMENT),Transport attempt failed for /google.showcase.v1beta1.Echo/Echo (status=INVALID_ARGUMENT),False,grpc,INVALID_ARGUMENT,google.showcase.v1beta1.Echo/Echo,NOT SET,NOT SET,NOT SET,NOT SET,INVALID_ARGUMENT_REASON,INVALID_ARGUMENT_REASON,showcase.googleapis.com,us-east1-a,Simulated unretryable invalid argument error.,Simulated unretryable invalid argument error.,_InactiveRpcError,AioRpcError,*Simulated unretryable invalid argument error.*,*Simulated unretryable invalid argument error.*,,T3.trace_id,T4.span_id,MATCH_SPAN_CONTEXT +F4.11,gRPC L4 client timeout failure attributes,L4,0,gRPC,Client Timeout,Echo.Block,True,False,DEBUG,1,2,DEBUG,google.api_core._observability,Transport attempt failed for /google.showcase.v1beta1.Echo/Block (status=DEADLINE_EXCEEDED),Transport attempt failed for /google.showcase.v1beta1.Echo/Block (status=DEADLINE_EXCEEDED),False,grpc,DEADLINE_EXCEEDED,google.showcase.v1beta1.Echo/Block,NOT SET,NOT SET,NOT SET,NOT SET,DEADLINE_EXCEEDED,DEADLINE_EXCEEDED,NOT SET,NOT SET,Deadline Exceeded,Deadline Exceeded,_InactiveRpcError,AioRpcError,*Deadline Exceeded*,*Deadline Exceeded*,,NOT SET,NOT SET,NOT SET +F4.12a,gRPC L4 logs for retries - Attempt 1,L4,0,gRPC,Retry Recovery,SequenceService.AttemptSequence,True,False,DEBUG,2,2,DEBUG,google.api_core._observability,Transport attempt failed for /google.showcase.v1beta1.SequenceService/AttemptSequence (status=UNAVAILABLE),Transport attempt failed for /google.showcase.v1beta1.SequenceService/AttemptSequence (status=UNAVAILABLE),False,grpc,UNAVAILABLE,google.showcase.v1beta1.SequenceService/AttemptSequence,NOT SET,NOT SET,NOT SET,NOT SET,UNAVAILABLE,UNAVAILABLE,NOT SET,NOT SET,Temporary glitch,Temporary glitch,_InactiveRpcError,AioRpcError,*Temporary glitch*,*Temporary glitch*,,NOT SET,NOT SET,NOT SET +F4.12b,gRPC L4 logs for retries - Attempt 2,L4,1,gRPC,Retry Recovery,SequenceService.AttemptSequence,True,False,DEBUG,2,2,DEBUG,google.api_core._observability,Transport attempt failed for /google.showcase.v1beta1.SequenceService/AttemptSequence (status=UNAVAILABLE),Transport attempt failed for /google.showcase.v1beta1.SequenceService/AttemptSequence (status=UNAVAILABLE),False,grpc,UNAVAILABLE,google.showcase.v1beta1.SequenceService/AttemptSequence,NOT SET,NOT SET,NOT SET,NOT SET,UNAVAILABLE,UNAVAILABLE,NOT SET,NOT SET,Temporary glitch,Temporary glitch,_InactiveRpcError,AioRpcError,*Temporary glitch*,*Temporary glitch*,,NOT SET,NOT SET,NOT SET +F5.1,HTTP no L3 logs emitted unless enabled,L3,N/A,HTTP/REST,Logging Off,Echo.Echo,False,False,WARNING,0,0,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A +F5.2,HTTP L3 log emitted on client-level failure,L3,0,HTTP/REST,Server Failure,Echo.Echo,True,False,WARNING,1,1,WARNING,google.api_core._observability,RPC failed for google.showcase.v1beta1.Echo/Echo:,RPC failed for google.showcase.v1beta1.Echo/Echo:,True,http,INVALID_ARGUMENT,google.showcase.v1beta1.Echo/Echo,NOT SET,NOT SET,NOT SET,NOT SET,INVALID_ARGUMENT_REASON,INVALID_ARGUMENT_REASON,showcase.googleapis.com,us-east1-a,Simulated unretryable invalid argument error.,Simulated unretryable invalid argument error.,BadRequest,BadRequest,*Simulated unretryable invalid argument error.*,*Simulated unretryable invalid argument error.*,,NOT SET,NOT SET,NOT SET +F5.3,HTTP no L3 log emitted on request success,L3,N/A,HTTP/REST,Happy Path,Echo.Echo,True,False,WARNING,0,0,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A +F5.4,HTTP L3 log recorded in context of T3 span,L3,0,HTTP/REST,Active Trace,Echo.Echo,True,True,WARNING,1,1,WARNING,google.api_core._observability,RPC failed for google.showcase.v1beta1.Echo/Echo:,RPC failed for google.showcase.v1beta1.Echo/Echo:,True,http,INVALID_ARGUMENT,google.showcase.v1beta1.Echo/Echo,NOT SET,NOT SET,NOT SET,NOT SET,INVALID_ARGUMENT_REASON,INVALID_ARGUMENT_REASON,showcase.googleapis.com,us-east1-a,Simulated unretryable invalid argument error.,Simulated unretryable invalid argument error.,BadRequest,BadRequest,*Simulated unretryable invalid argument error.*,*Simulated unretryable invalid argument error.*,,T3.trace_id,T3.span_id,MATCH_SPAN_CONTEXT +F5.5,HTTP L3 client timeout failure attributes,L3,0,HTTP/REST,Client Timeout,Echo.Block,True,False,WARNING,1,1,WARNING,google.api_core._observability,RPC failed for google.showcase.v1beta1.Echo/Block:,RPC failed for google.showcase.v1beta1.Echo/Block:,True,http,NOT SET,google.showcase.v1beta1.Echo/Block,NOT SET,NOT SET,NOT SET,NOT SET,ReadTimeout,TimeoutError,NOT SET,NOT SET,*Read timed out*,*exceeded the configured timeout*,ReadTimeout,TimeoutError,*Read timed out*,*exceeded the configured timeout*,,NOT SET,NOT SET,NOT SET +F5.6,HTTP no L3 log emitted when retry succeeds,L3,N/A,HTTP/REST,Retry Recovery,SequenceService.AttemptSequence,True,False,WARNING,0,0,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A +F5.7,HTTP single L3 log emitted when retries exhausted,L3,0,HTTP/REST,Retries Exhausted,SequenceService.AttemptSequence,True,False,WARNING,1,1,WARNING,google.api_core._observability,RPC failed for google.showcase.v1beta1.SequenceService/AttemptSequence:,RPC failed for google.showcase.v1beta1.SequenceService/AttemptSequence:,True,http,UNAVAILABLE,google.showcase.v1beta1.SequenceService/AttemptSequence,NOT SET,NOT SET,NOT SET,NOT SET,503,503,NOT SET,NOT SET,Persistent outage,Persistent outage,RetryError,RetryError,*Persistent outage*,*Persistent outage*,,NOT SET,NOT SET,NOT SET +F5.8,gRPC no L3 logs emitted unless enabled,L3,N/A,gRPC,Logging Off,Echo.Echo,False,False,WARNING,0,0,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A +F5.9,gRPC L3 log emitted on client-level failure,L3,0,gRPC,Server Failure,Echo.Echo,True,False,WARNING,1,1,WARNING,google.api_core._observability,RPC failed for google.showcase.v1beta1.Echo/Echo:,RPC failed for google.showcase.v1beta1.Echo/Echo:,True,grpc,INVALID_ARGUMENT,google.showcase.v1beta1.Echo/Echo,NOT SET,NOT SET,NOT SET,NOT SET,INVALID_ARGUMENT_REASON,INVALID_ARGUMENT_REASON,showcase.googleapis.com,us-east1-a,Simulated unretryable invalid argument error.,Simulated unretryable invalid argument error.,InvalidArgument,InvalidArgument,*Simulated unretryable invalid argument error.*,*Simulated unretryable invalid argument error.*,,NOT SET,NOT SET,NOT SET +F5.10,gRPC no L3 log emitted on request success,L3,N/A,gRPC,Happy Path,Echo.Echo,True,False,WARNING,0,0,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A +F5.11,gRPC L3 log recorded in context of T3 span,L3,0,gRPC,Active Trace,Echo.Echo,True,True,WARNING,1,1,WARNING,google.api_core._observability,RPC failed for google.showcase.v1beta1.Echo/Echo:,RPC failed for google.showcase.v1beta1.Echo/Echo:,True,grpc,INVALID_ARGUMENT,google.showcase.v1beta1.Echo/Echo,NOT SET,NOT SET,NOT SET,NOT SET,INVALID_ARGUMENT_REASON,INVALID_ARGUMENT_REASON,showcase.googleapis.com,us-east1-a,Simulated unretryable invalid argument error.,Simulated unretryable invalid argument error.,InvalidArgument,InvalidArgument,*Simulated unretryable invalid argument error.*,*Simulated unretryable invalid argument error.*,,T3.trace_id,T3.span_id,MATCH_SPAN_CONTEXT +F5.12,gRPC L3 client timeout failure attributes,L3,0,gRPC,Client Timeout,Echo.Block,True,False,WARNING,1,1,WARNING,google.api_core._observability,RPC failed for google.showcase.v1beta1.Echo/Block:,RPC failed for google.showcase.v1beta1.Echo/Block:,True,grpc,DEADLINE_EXCEEDED,google.showcase.v1beta1.Echo/Block,NOT SET,NOT SET,NOT SET,NOT SET,DEADLINE_EXCEEDED,DEADLINE_EXCEEDED,NOT SET,NOT SET,Deadline Exceeded,Deadline Exceeded,DeadlineExceeded,DeadlineExceeded,*Deadline Exceeded*,*Deadline Exceeded*,,NOT SET,NOT SET,NOT SET +F5.13,gRPC no L3 log emitted when retry succeeds,L3,N/A,gRPC,Retry Recovery,SequenceService.AttemptSequence,True,False,WARNING,0,0,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A +F5.14,gRPC single L3 log emitted when retries exhausted,L3,0,gRPC,Retries Exhausted,SequenceService.AttemptSequence,True,False,WARNING,1,1,WARNING,google.api_core._observability,RPC failed for google.showcase.v1beta1.SequenceService/AttemptSequence:,RPC failed for google.showcase.v1beta1.SequenceService/AttemptSequence:,True,grpc,UNAVAILABLE,google.showcase.v1beta1.SequenceService/AttemptSequence,NOT SET,NOT SET,NOT SET,NOT SET,UNAVAILABLE,UNAVAILABLE,NOT SET,NOT SET,Persistent outage,Persistent outage,RetryError,RetryError,*Persistent outage*,*Persistent outage*,,NOT SET,NOT SET,NOT SET diff --git a/packages/gapic-generator/tests/system/showcase_harness.py b/packages/gapic-generator/tests/system/showcase_harness.py new file mode 100644 index 000000000000..2c24f5f9a1c4 --- /dev/null +++ b/packages/gapic-generator/tests/system/showcase_harness.py @@ -0,0 +1,437 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Shared Showcase client construction, matrix loader, scenario runners, and log capture.""" + +from __future__ import annotations + +import asyncio +import contextlib +import csv +import logging +import os +import time +from collections.abc import Mapping +from collections.abc import Sequence as AbstractSequence +from pathlib import Path +from typing import Any, TypeVar + +import grpc +import pytest +import requests.exceptions +from google import showcase +from google.api_core import exceptions +from google.api_core import retry as retries +from google.api_core.client_options import ClientOptions +from google.protobuf import any_pb2, duration_pb2 +from google.rpc import code_pb2, error_details_pb2, status_pb2 +from google.showcase import ( + AttemptSequenceRequest, + CreateSequenceRequest, + EchoClient, + Sequence, + SequenceServiceClient, +) + +try: + from . import conftest +except (ImportError, ValueError): + import conftest + +HAS_ASYNC_CLIENTS = os.environ.get("GAPIC_PYTHON_ASYNC", "true") == "true" +if HAS_ASYNC_CLIENTS: + from google.api_core import retry_async as retries_async + from google.showcase import EchoAsyncClient, SequenceServiceAsyncClient + from grpc.experimental import aio + +_ClientT = TypeVar("_ClientT") + +# Deterministic timing constants for fast, non-flaky Showcase system tests. +# Use a negative deadline (-1.0s) for gRPC so C-core immediately expires the call +# locally with DEADLINE_EXCEEDED without racing Go Showcase HTTP/2 RST_STREAM CANCEL. +GRPC_CLIENT_TIMEOUT_SECONDS = -1.0 +REST_CLIENT_TIMEOUT_SECONDS = 0.2 +CLIENT_TIMEOUT_SECONDS = { + "grpc": GRPC_CLIENT_TIMEOUT_SECONDS, + "grpc_asyncio": GRPC_CLIENT_TIMEOUT_SECONDS, + "rest": REST_CLIENT_TIMEOUT_SECONDS, + "rest_asyncio": REST_CLIENT_TIMEOUT_SECONDS, +} +SERVER_BLOCK_DELAY_SECONDS = 2 +FAST_RETRY_BACKOFF_SECONDS = 0.01 +CONSTANT_BACKOFF_MULTIPLIER = 1.0 +EXHAUSTION_DEADLINE_SECONDS = 0.1 +GENEROUS_RECOVERY_DEADLINE_SECONDS = 5.0 +EXHAUSTED_RETRY_ATTEMPTS = 2 +RECOVERY_FAILED_ATTEMPTS = 2 + +SERVER_FAILURE_MESSAGE = "Simulated unretryable invalid argument error." +SERVER_FAILURE_REASON = "INVALID_ARGUMENT_REASON" +SERVER_FAILURE_DOMAIN = "showcase.googleapis.com" +SERVER_FAILURE_METADATA = {"zone": "us-east1-a"} + +ECHO_SCENARIOS = frozenset( + { + "Happy Path", + "Logging Off", + "Server Failure", + "Active Trace", + "Client Timeout", + } +) + + +def load_csv_matrix(csv_path: Path) -> AbstractSequence[Mapping[str, str]]: + """Loads atomic specification rows from a Tidy Data compliance CSV matrix.""" + with open(csv_path, mode="r", encoding="utf-8") as csv_file: + return list(csv.DictReader(csv_file)) + + +class InMemoryLogCapture(logging.Handler): + """Thread-safe in-memory handler that captures raw `logging.LogRecord` events.""" + + def __init__(self, level: int = logging.NOTSET): + super().__init__(level=level) + self.records: list[logging.LogRecord] = [] + + def emit(self, record: logging.LogRecord) -> None: + self.records.append(record) + + def clear(self) -> None: + """Clears all captured log records under the handler lock.""" + with self.lock: + self.records.clear() + + +def _insecure_channel_factory(host: str, **kwargs: Any) -> grpc.Channel: + """Callable channel factory preserving `self._host` on sync gRPC transports.""" + del kwargs + return grpc.insecure_channel(host) + + +def _async_insecure_channel_factory(host: str, **kwargs: Any) -> Any: + """Callable channel factory preserving `self._host` on async gRPC transports.""" + del kwargs + return aio.insecure_channel(host) + + +def build_server_failure_status( + *, include_error_info: bool = True +) -> status_pb2.Status: + """Builds an INVALID_ARGUMENT gRPC Status with optional packed `ErrorInfo`.""" + details = [] + if include_error_info: + error_info = error_details_pb2.ErrorInfo( + reason=SERVER_FAILURE_REASON, + domain=SERVER_FAILURE_DOMAIN, + metadata=SERVER_FAILURE_METADATA, + ) + packed_any = any_pb2.Any() + packed_any.Pack(error_info) + details.append(packed_any) + return status_pb2.Status( + code=code_pb2.INVALID_ARGUMENT, + message=SERVER_FAILURE_MESSAGE, + details=details, + ) + + +def construct_showcase_client( + client_class: type[_ClientT], + transport_name: str, + client_options: ClientOptions | None = None, + use_mtls: bool = False, +) -> _ClientT: + """Instantiates a sync or async Showcase client for the requested transport.""" + extra_kwargs: dict[str, Any] = {} + if transport_name == "grpc" and not use_mtls: + extra_kwargs["channel"] = _insecure_channel_factory + elif transport_name == "grpc_asyncio" and not use_mtls: + extra_kwargs["channel"] = _async_insecure_channel_factory + extra_kwargs["credentials"] = conftest.async_anonymous_credentials() + elif transport_name == "rest_asyncio": + extra_kwargs["credentials"] = conftest.async_anonymous_credentials() + + return conftest.construct_client( + client_class, + use_mtls=use_mtls, + transport_name=transport_name, + client_options=client_options, + **extra_kwargs, + ) + + +def _expected_timeout_exceptions() -> tuple[type[BaseException], ...]: + """Returns genuine transport timeout exception types across sync and async stacks.""" + exc_types: list[type[BaseException]] = [ + exceptions.DeadlineExceeded, + requests.exceptions.Timeout, + TimeoutError, + asyncio.TimeoutError, + ] + try: + import aiohttp + + server_timeout = getattr(aiohttp, "ServerTimeoutError", None) + if server_timeout is not None: + exc_types.append(server_timeout) + except ImportError: + pass + try: + from google.auth import exceptions as auth_exceptions + + # google.auth.exceptions.TimeoutError was introduced after google-auth 2.14.x. + auth_timeout = getattr(auth_exceptions, "TimeoutError", None) + if auth_timeout is not None: + exc_types.append(auth_timeout) + except ImportError: + pass + return tuple(exc_types) + + +async def _drain_async_inspection_tasks() -> None: + """Drains `done_callback` scheduling ticks and pending `_inspect_async_call` tasks.""" + await asyncio.sleep(0) + await asyncio.sleep(0) + current = asyncio.current_task() + pending = [ + task + for task in asyncio.all_tasks() + if task is not current + and not task.done() + and getattr(task.get_coro(), "__name__", "") == "_inspect_async_call" + ] + if pending: + await asyncio.gather(*pending, return_exceptions=True) + + +def _build_echo_plan( + scenario: str, + transport_name: str, + *, + include_error_info: bool = True, +) -> tuple[str, Any, dict[str, Any], Any]: + """Builds RPC method name, request message, call kwargs, and exception expectation.""" + match scenario: + case "Happy Path": + return ( + "echo", + showcase.EchoRequest(content="hello"), + {}, + contextlib.nullcontext(), + ) + case "Logging Off" | "Server Failure" | "Active Trace": + return ( + "echo", + showcase.EchoRequest( + error=build_server_failure_status( + include_error_info=include_error_info + ) + ), + {}, + pytest.raises( + (exceptions.InvalidArgument, exceptions.BadRequest), + match=r"Simulated unretryable invalid argument error\.", + ), + ) + case "Client Timeout": + return ( + "block", + showcase.BlockRequest( + response_delay=duration_pb2.Duration( + seconds=SERVER_BLOCK_DELAY_SECONDS + ) + ), + {"timeout": CLIENT_TIMEOUT_SECONDS[transport_name], "retry": None}, + pytest.raises( + _expected_timeout_exceptions(), + match=r"(?i)deadline exceeded|timed out|timeout", + ), + ) + case _: + raise ValueError(f"Unsupported Echo scenario: {scenario!r}") + + +def _build_sequence_plan( + scenario: str, + *, + recovery_failed_attempts: int = RECOVERY_FAILED_ATTEMPTS, +) -> tuple[list[Sequence.Response], Any, float, Any]: + """Builds responses, `on_error` hook, deadline, and context expectation for Sequence RPCs.""" + if scenario == "Retries Exhausted": + responses = [ + Sequence.Response( + status=status_pb2.Status( + code=code_pb2.UNAVAILABLE, + message="Persistent outage", + ) + ) + for _ in range(EXHAUSTED_RETRY_ATTEMPTS) + ] + attempts_seen = 0 + + def on_error(_exc: Exception) -> None: + nonlocal attempts_seen + attempts_seen += 1 + if attempts_seen >= EXHAUSTED_RETRY_ATTEMPTS: + time.sleep(EXHAUSTION_DEADLINE_SECONDS) + + return ( + responses, + on_error, + EXHAUSTION_DEADLINE_SECONDS, + pytest.raises( + exceptions.RetryError, + match=r"Deadline of .* exceeded|Persistent outage", + ), + ) + + if scenario == "Retry Recovery": + responses = [ + Sequence.Response( + status=status_pb2.Status( + code=code_pb2.UNAVAILABLE, + message="Temporary glitch", + ) + ) + for _ in range(recovery_failed_attempts) + ] + [Sequence.Response(status=status_pb2.Status(code=code_pb2.OK))] + return ( + responses, + None, + GENEROUS_RECOVERY_DEADLINE_SECONDS, + contextlib.nullcontext(), + ) + + raise ValueError(f"Unsupported Sequence scenario: {scenario!r}") + + +def execute_showcase_scenario( + scenario: str, + transport_name: str, + client_options: ClientOptions | None = None, + *, + span_exporter: Any = None, + log_capture: InMemoryLogCapture | None = None, + include_error_info: bool = True, + recovery_failed_attempts: int = RECOVERY_FAILED_ATTEMPTS, +) -> None: + """Executes a Showcase Echo or Sequence compliance scenario synchronously.""" + if scenario in ECHO_SCENARIOS: + method_name, request, call_kwargs, expectation = _build_echo_plan( + scenario, + transport_name, + include_error_info=include_error_info, + ) + with construct_showcase_client( + EchoClient, transport_name, client_options=client_options + ) as client: + with expectation: + getattr(client, method_name)(request, **call_kwargs) + return + + responses, on_error, deadline, expectation = _build_sequence_plan( + scenario, + recovery_failed_attempts=recovery_failed_attempts, + ) + with construct_showcase_client( + SequenceServiceClient, transport_name, client_options=client_options + ) as client: + seq = client.create_sequence( + CreateSequenceRequest(sequence=Sequence(responses=responses)) + ) + if span_exporter is not None: + span_exporter.clear() + if log_capture is not None: + log_capture.clear() + + retry_policy = retries.Retry( + predicate=retries.if_exception_type(exceptions.ServiceUnavailable), + initial=FAST_RETRY_BACKOFF_SECONDS, + maximum=FAST_RETRY_BACKOFF_SECONDS, + multiplier=CONSTANT_BACKOFF_MULTIPLIER, + deadline=deadline, + on_error=on_error, + ) + with expectation: + client.attempt_sequence( + AttemptSequenceRequest(name=seq.name), + retry=retry_policy, + ) + + +async def execute_showcase_scenario_async( + scenario: str, + transport_name: str, + client_options: ClientOptions | None = None, + *, + span_exporter: Any = None, + log_capture: InMemoryLogCapture | None = None, + include_error_info: bool = True, + recovery_failed_attempts: int = RECOVERY_FAILED_ATTEMPTS, +) -> None: + """Executes a Showcase Echo or Sequence compliance scenario asynchronously.""" + if transport_name == "rest_asyncio" and not conftest.HAS_ASYNC_REST_ECHO_TRANSPORT: + pytest.skip("Async REST transport is not generated in this session.") + + if scenario in ECHO_SCENARIOS: + method_name, request, call_kwargs, expectation = _build_echo_plan( + scenario, + transport_name, + include_error_info=include_error_info, + ) + client = construct_showcase_client( + EchoAsyncClient, transport_name, client_options=client_options + ) + async with client: + try: + with expectation: + await getattr(client, method_name)(request, **call_kwargs) + finally: + await _drain_async_inspection_tasks() + return + + responses, on_error, deadline, expectation = _build_sequence_plan( + scenario, + recovery_failed_attempts=recovery_failed_attempts, + ) + client = construct_showcase_client( + SequenceServiceAsyncClient, transport_name, client_options=client_options + ) + async with client: + seq = await client.create_sequence( + CreateSequenceRequest(sequence=Sequence(responses=responses)) + ) + await _drain_async_inspection_tasks() + if span_exporter is not None: + span_exporter.clear() + if log_capture is not None: + log_capture.clear() + + retry_policy = retries_async.AsyncRetry( + predicate=retries.if_exception_type(exceptions.ServiceUnavailable), + initial=FAST_RETRY_BACKOFF_SECONDS, + maximum=FAST_RETRY_BACKOFF_SECONDS, + multiplier=CONSTANT_BACKOFF_MULTIPLIER, + deadline=deadline, + on_error=on_error, + ) + try: + with expectation: + await client.attempt_sequence( + AttemptSequenceRequest(name=seq.name), + retry=retry_policy, + ) + finally: + await _drain_async_inspection_tasks() diff --git a/packages/gapic-generator/tests/system/test_logging_compliance.py b/packages/gapic-generator/tests/system/test_logging_compliance.py new file mode 100644 index 000000000000..b2d216a01193 --- /dev/null +++ b/packages/gapic-generator/tests/system/test_logging_compliance.py @@ -0,0 +1,721 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Operational Error Logging Compliance Suite (`F4` & `F5`). + +Executes declarative, Tidy Data specification rows from +`logging_requirements_matrix.csv` against a live GAPIC Showcase server across +synchronous and asynchronous gRPC and HTTP/REST transports. +""" + +from __future__ import annotations + +import fnmatch +import json +import logging +import os +from collections.abc import Iterator, Mapping, Sequence +from pathlib import Path +from typing import Any + +import pytest + +try: + from opentelemetry.sdk.trace import ReadableSpan, TracerProvider + from opentelemetry.sdk.trace.export import SimpleSpanProcessor + from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( + InMemorySpanExporter, + ) + from opentelemetry.trace import SpanKind + + HAS_OPENTELEMETRY = True +except ImportError: + HAS_OPENTELEMETRY = False + +if not HAS_OPENTELEMETRY: + pytest.skip("OpenTelemetry is not installed", allow_module_level=True) + +try: + from google.api_core import client_logging + from google.api_core.client_logging import StructuredLogFormatter + + HAS_ERROR_LOGGING = hasattr(client_logging, "is_error_logging_enabled") +except ImportError: + HAS_ERROR_LOGGING = False + +if not HAS_ERROR_LOGGING: + pytest.skip( + "Installed google-api-core lacks Operational Error Logging", + allow_module_level=True, + ) + +from google.api_core.client_options import ClientOptions + +try: + from . import conftest + from .showcase_harness import ( + HAS_ASYNC_CLIENTS, + InMemoryLogCapture, + execute_showcase_scenario, + execute_showcase_scenario_async, + load_csv_matrix, + ) +except (ImportError, ValueError): + import conftest + from showcase_harness import ( + HAS_ASYNC_CLIENTS, + InMemoryLogCapture, + execute_showcase_scenario, + execute_showcase_scenario_async, + load_csv_matrix, + ) + +LOGGING_MATRIX_CSV = Path(__file__).parent / "logging_requirements_matrix.csv" +LOGGING_MATRIX_ROWS = load_csv_matrix(LOGGING_MATRIX_CSV) + + +BASE_GOOGLE_LOGGER_NAME = "google" +OBSERVABILITY_LOGGER_NAME = "google.api_core._observability" +ENV_LOGGING_SCOPE = "GOOGLE_SDK_PYTHON_LOGGING_SCOPE" +ENV_LOGGING_ENABLED = "GOOGLE_SDK_EXPERIMENTAL_PYTHON_LOGGING_ENABLED" +ENV_TRACING_ENABLED = "GOOGLE_SDK_EXPERIMENTAL_PYTHON_TRACING_ENABLED" +ENV_RAW_LOGS_OUTPUT_PATH = "SHOWCASE_RAW_LOGS_OUTPUT_PATH" +ENV_RAW_LOGGING_SPANS_OUTPUT_PATH = "SHOWCASE_RAW_LOGGING_SPANS_OUTPUT_PATH" + +EXACT_OR_GLOB_ATTRIBUTES = ( + "rpc.system.name", + "rpc.response.status_code", + "rpc.method", + "url.full", + "error.type", + "gcp.errors.domain", + "gcp.errors.metadata.zone", + "status.message", + "exception.message", +) + +ASYNC_OVERRIDE_COLUMNS = frozenset( + { + "Message Prefix", + "error.type", + "status.message", + "exception.type", + "exception.message", + } +) + +CLOUD_LOGGING_TRACE_KEYS = ( + "logging.googleapis.com/trace", + "logging.googleapis.com/spanId", + "logging.googleapis.com/trace_sampled", +) + +TelemetryHarness = tuple[InMemoryLogCapture, InMemorySpanExporter, TracerProvider] +RawLogsCatalog = dict[str, list[dict[str, Any]]] +RawSpansCatalog = dict[str, list[dict[str, Any]]] + + +def _expected_value(row: Mapping[str, str], column: str, *, is_async: bool) -> str: + """Resolves the expected CSV value for `column`, using the Async override when applicable.""" + if is_async and column in ASYNC_OVERRIDE_COLUMNS: + return row[f"Async {column}"] + return row[column] + + +def _param_id(row: Mapping[str, str], *, prefix: str = "") -> str: + """Formats a readable pytest parameter ID from a matrix row.""" + slug = row["Feature Name"].replace(" ", "_") + return f"{prefix}{row['Feature ID']}_{slug}" + + +@pytest.fixture(scope="session") +def raw_logs_catalog( + tmp_path_factory: pytest.TempPathFactory, +) -> Iterator[RawLogsCatalog]: + """Collects structured JSON logs per feature and writes them hermetically at teardown.""" + catalog: RawLogsCatalog = {} + yield catalog + if catalog: + configured_path = os.environ.get(ENV_RAW_LOGS_OUTPUT_PATH) + output_path = ( + Path(configured_path) + if configured_path + else tmp_path_factory.mktemp("showcase_logs") / "raw_logs_output.json" + ) + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text( + json.dumps(catalog, indent=2, sort_keys=True), + encoding="utf-8", + ) + + +@pytest.fixture(scope="session") +def raw_spans_catalog( + tmp_path_factory: pytest.TempPathFactory, +) -> Iterator[RawSpansCatalog]: + """Collects companion OpenTelemetry spans for active-trace logging cases at teardown.""" + catalog: RawSpansCatalog = {} + yield catalog + if catalog: + configured_spans_path = os.environ.get(ENV_RAW_LOGGING_SPANS_OUTPUT_PATH) + configured_logs_path = os.environ.get(ENV_RAW_LOGS_OUTPUT_PATH) + if configured_spans_path: + output_path = Path(configured_spans_path) + elif configured_logs_path: + output_path = ( + Path(configured_logs_path).parent / "raw_logging_spans_output.json" + ) + else: + output_path = ( + tmp_path_factory.mktemp("showcase_logs") + / "raw_logging_spans_output.json" + ) + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text( + json.dumps(catalog, indent=2, sort_keys=True), + encoding="utf-8", + ) + + +@pytest.fixture +def telemetry_harness( + monkeypatch: pytest.MonkeyPatch, +) -> Iterator[TelemetryHarness]: + """Provides isolated OpenTelemetry span capture and `"google"` logger capture.""" + exporter = InMemorySpanExporter() + provider = TracerProvider() + provider.add_span_processor(SimpleSpanProcessor(exporter)) + + base_logger = logging.getLogger(BASE_GOOGLE_LOGGER_NAME) + obs_logger = logging.getLogger(OBSERVABILITY_LOGGER_NAME) + orig_base_level = base_logger.level + orig_base_propagate = base_logger.propagate + orig_base_handlers = list(base_logger.handlers) + orig_obs_level = obs_logger.level + orig_obs_propagate = obs_logger.propagate + orig_obs_handlers = list(obs_logger.handlers) + + capture = InMemoryLogCapture(level=logging.NOTSET) + # Keep "google" at WARNING so legacy GAPIC payload debug logging (`google.showcase_v1beta1.*`) + # stays disabled unless explicitly configured, while child `google.api_core._observability` + # controls L4 DEBUG vs L3 WARNING visibility cleanly. + base_logger.handlers = [capture] + base_logger.setLevel(logging.WARNING) + base_logger.propagate = False + obs_logger.setLevel(logging.NOTSET) + obs_logger.handlers = [] + obs_logger.propagate = True + + monkeypatch.delenv(ENV_LOGGING_SCOPE, raising=False) + monkeypatch.delenv(ENV_LOGGING_ENABLED, raising=False) + monkeypatch.delenv(ENV_TRACING_ENABLED, raising=False) + + try: + yield capture, exporter, provider + finally: + exporter.clear() + capture.clear() + obs_logger.setLevel(orig_obs_level) + obs_logger.handlers = orig_obs_handlers + obs_logger.propagate = orig_obs_propagate + base_logger.handlers = orig_base_handlers + base_logger.setLevel(orig_base_level) + base_logger.propagate = orig_base_propagate + + +def _configure_environment_for_row( + row: Mapping[str, str], + monkeypatch: pytest.MonkeyPatch, + provider: TracerProvider, +) -> ClientOptions: + """Applies environment flags, logger level, and `ClientOptions` from a matrix row.""" + logging_enabled = row["Logging Enabled"] == "True" + tracing_enabled = row["Tracing Enabled"] == "True" + monkeypatch.setenv( + ENV_LOGGING_ENABLED, + "true" if logging_enabled else "false", + ) + monkeypatch.setenv( + ENV_TRACING_ENABLED, + "true" if tracing_enabled else "false", + ) + + obs_logger = logging.getLogger(OBSERVABILITY_LOGGER_NAME) + configured_level = getattr(logging, row["Configured Logger Level"]) + obs_logger.setLevel(configured_level) + + if tracing_enabled: + return ClientOptions(tracer_provider=provider) + return ClientOptions() + + +def _execute_row_sync( + row: Mapping[str, str], + capture: InMemoryLogCapture, + exporter: InMemorySpanExporter, + provider: TracerProvider, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Executes a matrix row synchronously against Showcase.""" + client_options = _configure_environment_for_row(row, monkeypatch, provider) + transport_name = "grpc" if row["Transport"] == "gRPC" else "rest" + execute_showcase_scenario( + row["Scenario"], + transport_name, + client_options, + span_exporter=exporter, + log_capture=capture, + include_error_info=True, + ) + + +async def _execute_row_async( + row: Mapping[str, str], + capture: InMemoryLogCapture, + exporter: InMemorySpanExporter, + provider: TracerProvider, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Executes a matrix row asynchronously (`grpc_asyncio` or `rest_asyncio`) against Showcase.""" + client_options = _configure_environment_for_row(row, monkeypatch, provider) + transport_name = "grpc_asyncio" if row["Transport"] == "gRPC" else "rest_asyncio" + await execute_showcase_scenario_async( + row["Scenario"], + transport_name, + client_options, + span_exporter=exporter, + log_capture=capture, + include_error_info=True, + ) + + +def _partition_tier_records( + records: Sequence[logging.LogRecord], tier: str +) -> Sequence[logging.LogRecord]: + """Selects captured records belonging to the target logging tier (`L4` or `L3`).""" + expected_level = logging.DEBUG if tier == "L4" else logging.WARNING + return [r for r in records if r.levelno == expected_level] + + +def _archive_records( + catalog: RawLogsCatalog, + feature_id: str, + records: Sequence[logging.LogRecord], +) -> None: + """Serializes captured records via `StructuredLogFormatter` into `catalog`.""" + formatter = StructuredLogFormatter() + entries: list[dict[str, Any]] = [] + for record in records: + payload = json.loads(formatter.format(record)) + payload["created_unix_nano"] = int(record.created * 1_000_000_000) + entries.append(payload) + catalog[feature_id] = entries + + +def _archive_spans( + catalog: RawSpansCatalog, + feature_id: str, + spans: Sequence[ReadableSpan], +) -> None: + """Serializes captured OpenTelemetry spans for active-trace audit verification.""" + catalog[feature_id] = [ + { + "name": span.name, + "kind": span.kind.name, + "trace_id": f"{span.context.trace_id:032x}", + "span_id": f"{span.context.span_id:016x}", + "parent_span_id": ( + f"{span.parent.span_id:016x}" if span.parent is not None else None + ), + "start_time_unix_nano": span.start_time, + "end_time_unix_nano": span.end_time, + } + for span in spans + ] + + +def _assert_string_or_glob(actual: Any, expected: str, *, field_label: str) -> None: + """Asserts exact string equality, or `fnmatchcase` glob matching if `*` is in `expected`.""" + assert isinstance(actual, str), ( + f"{field_label}: expected str {expected!r}, got {actual!r}" + ) + if "*" in expected: + assert fnmatch.fnmatchcase(actual, expected), ( + f"{field_label}: {actual!r} did not match pattern {expected!r}" + ) + else: + assert actual == expected, ( + f"{field_label}: expected {expected!r}, got {actual!r}" + ) + + +def _assert_http_request_fields( + record_dict: Mapping[str, Any], + json_payload: Mapping[str, Any], + row: Mapping[str, str], +) -> None: + """Validates `httpRequest.*` columns on both raw `LogRecord` and JSON output.""" + expected_method = row["httpRequest.requestMethod"] + if expected_method == "NOT SET": + assert "httpRequest" not in record_dict + assert "httpRequest" not in json_payload + return + + for container_name, container in ( + ("LogRecord", record_dict), + ("StructuredLogFormatter", json_payload), + ): + http_req = container.get("httpRequest") + assert isinstance(http_req, dict), ( + f"{container_name} missing httpRequest dict: {http_req!r}" + ) + assert http_req.get("requestMethod") == expected_method + _assert_string_or_glob( + http_req.get("requestUrl"), + row["httpRequest.requestUrl"], + field_label=f"{container_name}.httpRequest.requestUrl", + ) + expected_status = row["httpRequest.status"] + if expected_status == "NOT SET": + assert "status" not in http_req, ( + f"{container_name}.httpRequest should omit 'status', got {http_req!r}" + ) + else: + assert http_req.get("status") == int(expected_status) + + +def _assert_trace_correlation( + record_dict: Mapping[str, Any], + json_payload: Mapping[str, Any], + row: Mapping[str, str], + spans: Sequence[ReadableSpan], +) -> None: + """Validates `trace_id`, `span_id`, and `logging.googleapis.com/*` correlation fields.""" + expected_trace = row["trace_id"] + expected_span = row["span_id"] + expected_cloud = row["Cloud Logging Trace Fields"] + + if expected_trace == "NOT SET": + for key in ("trace_id", "span_id", *CLOUD_LOGGING_TRACE_KEYS): + assert key not in record_dict, f"Unexpected {key} on LogRecord" + assert key not in json_payload, f"Unexpected {key} in JSON output" + return + + t3_spans = [s for s in spans if s.kind == SpanKind.INTERNAL] + t4_spans = [s for s in spans if s.kind == SpanKind.CLIENT] + assert len(t3_spans) == 1, f"Expected 1 T3 INTERNAL span, got {len(t3_spans)}" + assert len(t4_spans) >= 1, f"Expected >= 1 T4 CLIENT span, got {len(t4_spans)}" + + attempt_idx = int(row["Attempt"]) + t4_attempt_span = t4_spans[attempt_idx] + assert t4_attempt_span.parent is not None + assert t4_attempt_span.parent.span_id == t3_spans[0].context.span_id + assert t4_attempt_span.context.span_id != t3_spans[0].context.span_id + + if expected_span == "T3.span_id": + target_span = t3_spans[0] + elif expected_span == "T4.span_id": + target_span = t4_attempt_span + else: + raise ValueError(f"Unsupported span_id sentinel: {expected_span!r}") + + expected_trace_hex = f"{t3_spans[0].context.trace_id:032x}" + expected_span_hex = f"{target_span.context.span_id:016x}" + + for container_name, container in ( + ("LogRecord", record_dict), + ("StructuredLogFormatter", json_payload), + ): + assert container.get("trace_id") == expected_trace_hex, ( + f"{container_name}.trace_id mismatch" + ) + assert container.get("span_id") == expected_span_hex, ( + f"{container_name}.span_id mismatch" + ) + if expected_cloud == "MATCH_SPAN_CONTEXT": + assert container.get("logging.googleapis.com/trace") == expected_trace_hex + assert container.get("logging.googleapis.com/spanId") == expected_span_hex + assert container.get("logging.googleapis.com/trace_sampled") is True + else: + raise ValueError( + f"Unsupported Cloud Logging Trace Fields sentinel: {expected_cloud!r}" + ) + + +def assert_log_record_matches_row( + record: logging.LogRecord, + row: Mapping[str, str], + spans: Sequence[ReadableSpan], + *, + is_async: bool = False, +) -> None: + """Validates a single captured `LogRecord` and its `StructuredLogFormatter` JSON against `row`.""" + formatter = StructuredLogFormatter() + json_payload = json.loads(formatter.format(record)) + record_dict = vars(record) + + # 1. Envelope fields + assert record.levelname == row["Log Level"] + assert json_payload["severity"] == row["Log Level"] + assert record.name == row["Logger Name"] + assert json_payload["name"] == row["Logger Name"] + + message = record.getMessage() + expected_prefix = _expected_value(row, "Message Prefix", is_async=is_async) + if "*" in expected_prefix: + assert fnmatch.fnmatchcase(message, f"{expected_prefix}*"), ( + f"Message {message!r} did not match prefix pattern {expected_prefix!r}" + ) + else: + assert message.startswith(expected_prefix), ( + f"Message {message!r} did not start with {expected_prefix!r}" + ) + assert json_payload["message"] == message + + expected_exc_info = row["exc_info Present"] == "True" + assert bool(record.exc_info) is expected_exc_info + + # Ensure StructuredLogFormatter unpacked json_fields without emitting a duplicate nested key + assert "json_fields" not in json_payload + + # 2. Exact / glob string attributes across both LogRecord and JSON output + assert "rpcName" not in record_dict, "Legacy rpcName must not be emitted" + assert "rpcName" not in json_payload, "Legacy rpcName must not be emitted in JSON" + for attr_name in EXACT_OR_GLOB_ATTRIBUTES: + expected_val = _expected_value(row, attr_name, is_async=is_async) + if expected_val == "NOT SET": + assert attr_name not in record_dict, ( + f"Expected {attr_name} NOT SET on LogRecord, got {record_dict.get(attr_name)!r}" + ) + assert attr_name not in json_payload, ( + f"Expected {attr_name} NOT SET in JSON, got {json_payload.get(attr_name)!r}" + ) + else: + _assert_string_or_glob( + record_dict.get(attr_name), + expected_val, + field_label=f"LogRecord[{attr_name!r}]", + ) + _assert_string_or_glob( + json_payload.get(attr_name), + expected_val, + field_label=f"JSON[{attr_name!r}]", + ) + + # 3. HTTP request sub-dictionary + _assert_http_request_fields(record_dict, json_payload, row) + + # 4. Exception type & stacktrace + expected_exc_type = _expected_value(row, "exception.type", is_async=is_async) + if expected_exc_type == "NOT SET": + assert "exception.type" not in record_dict + assert "exception.type" not in json_payload + else: + assert record_dict.get("exception.type") == expected_exc_type + assert json_payload.get("exception.type") == expected_exc_type + + expected_stack = row["exception.stacktrace"] + if expected_stack == "NOT SET": + assert "exception.stacktrace" not in record_dict + assert "exception.stacktrace" not in json_payload + elif expected_stack == "": + for container_name, container in ( + ("LogRecord", record_dict), + ("JSON", json_payload), + ): + stack = container.get("exception.stacktrace") + assert ( + isinstance(stack, str) + and "Traceback (most recent call last):" in stack + and '\n File "' in stack + ), ( + f"{container_name}['exception.stacktrace']: expected multi-frame Python " + f"traceback, got {stack!r}" + ) + else: + raise ValueError( + f"Unsupported exception.stacktrace sentinel: {expected_stack!r}" + ) + + # 6. Trace & Span correlation + _assert_trace_correlation(record_dict, json_payload, row, spans) + + +# --------------------------------------------------------------------------- +# Boundary & Matrix Compliance Tests (`F4.1` - `F5.14`) +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "transport_name,expected_l4_error_type,expected_l3_error_type", + [ + pytest.param("rest", "400", "400", id="rest_without_error_info"), + pytest.param( + "grpc", "INVALID_ARGUMENT", "INVALID_ARGUMENT", id="grpc_without_error_info" + ), + ], +) +def test_server_failure_without_error_info_falls_back_to_status( + transport_name: str, + expected_l4_error_type: str, + expected_l3_error_type: str, + telemetry_harness: TelemetryHarness, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Verifies `error.type` falls back to status code and omits `gcp.errors.*` when `ErrorInfo` is absent.""" + capture, _, _ = telemetry_harness + monkeypatch.setenv(ENV_LOGGING_ENABLED, "true") + logging.getLogger(OBSERVABILITY_LOGGER_NAME).setLevel(logging.DEBUG) + + execute_showcase_scenario( + "Server Failure", + transport_name, + ClientOptions(), + include_error_info=False, + ) + + with conftest.skip_on_core_mismatch(): + l4_records = _partition_tier_records(capture.records, "L4") + l3_records = _partition_tier_records(capture.records, "L3") + assert len(l4_records) == 1 + assert len(l3_records) == 1 + assert vars(l4_records[0])["error.type"] == expected_l4_error_type + assert vars(l3_records[0])["error.type"] == expected_l3_error_type + for record in (l4_records[0], l3_records[0]): + assert "gcp.errors.domain" not in vars(record) + assert "gcp.errors.metadata.zone" not in vars(record) + + +@pytest.mark.parametrize( + "row", + [ + pytest.param(r, id=_param_id(r)) + for r in LOGGING_MATRIX_ROWS + if int(r["Tier Log Count"]) == 0 + ], +) +def test_sync_no_logs_emitted( + row: Mapping[str, str], + telemetry_harness: TelemetryHarness, + raw_logs_catalog: RawLogsCatalog, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Verifies zero logs are emitted synchronously when disabled, on success, or on L3 retry recovery.""" + capture, exporter, provider = telemetry_harness + + _execute_row_sync(row, capture, exporter, provider, monkeypatch) + + with conftest.skip_on_core_mismatch(): + _archive_records(raw_logs_catalog, row["Feature ID"], capture.records) + assert capture.records == [] + + +@pytest.mark.parametrize( + "row", + [ + pytest.param(r, id=_param_id(r)) + for r in LOGGING_MATRIX_ROWS + if int(r["Tier Log Count"]) > 0 + ], +) +def test_sync_error_log_emitted( + row: Mapping[str, str], + telemetry_harness: TelemetryHarness, + raw_logs_catalog: RawLogsCatalog, + raw_spans_catalog: RawSpansCatalog, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Verifies sync L4 `DEBUG` and L3 `WARNING` error logs match matrix specs across HTTP/REST and gRPC.""" + capture, exporter, provider = telemetry_harness + + _execute_row_sync(row, capture, exporter, provider, monkeypatch) + + with conftest.skip_on_core_mismatch(): + spans = exporter.get_finished_spans() + _archive_records(raw_logs_catalog, row["Feature ID"], capture.records) + if row["trace_id"] != "NOT SET": + _archive_spans(raw_spans_catalog, row["Feature ID"], spans) + assert len(capture.records) == int(row["Total Log Count"]) + tier_records = _partition_tier_records(capture.records, row["Tier"]) + assert len(tier_records) == int(row["Tier Log Count"]) + target_record = tier_records[int(row["Attempt"])] + assert_log_record_matches_row(target_record, row, spans) + + +@pytest.mark.skipif(not HAS_ASYNC_CLIENTS, reason="Async clients disabled") +@pytest.mark.asyncio +@pytest.mark.parametrize( + "row", + [ + pytest.param(r, id=_param_id(r, prefix="async_")) + for r in LOGGING_MATRIX_ROWS + if int(r["Tier Log Count"]) == 0 + ], +) +async def test_async_no_logs_emitted( + row: Mapping[str, str], + telemetry_harness: TelemetryHarness, + raw_logs_catalog: RawLogsCatalog, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Verifies zero logs are emitted asynchronously when disabled, on success, or on L3 retry recovery.""" + capture, exporter, provider = telemetry_harness + + await _execute_row_async(row, capture, exporter, provider, monkeypatch) + + with conftest.skip_on_core_mismatch(): + _archive_records( + raw_logs_catalog, f"async_{row['Feature ID']}", capture.records + ) + assert capture.records == [] + + +@pytest.mark.skipif(not HAS_ASYNC_CLIENTS, reason="Async clients disabled") +@pytest.mark.asyncio +@pytest.mark.parametrize( + "row", + [ + pytest.param(r, id=_param_id(r, prefix="async_")) + for r in LOGGING_MATRIX_ROWS + if int(r["Tier Log Count"]) > 0 + ], +) +async def test_async_error_log_emitted( + row: Mapping[str, str], + telemetry_harness: TelemetryHarness, + raw_logs_catalog: RawLogsCatalog, + raw_spans_catalog: RawSpansCatalog, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Verifies async gRPC (`grpc_asyncio`) and async REST (`rest_asyncio`) error logs match matrix specs.""" + capture, exporter, provider = telemetry_harness + + await _execute_row_async(row, capture, exporter, provider, monkeypatch) + + with conftest.skip_on_core_mismatch(): + spans = exporter.get_finished_spans() + feature_key = f"async_{row['Feature ID']}" + _archive_records(raw_logs_catalog, feature_key, capture.records) + if row["trace_id"] != "NOT SET": + _archive_spans(raw_spans_catalog, feature_key, spans) + assert len(capture.records) == int(row["Total Log Count"]) + tier_records = _partition_tier_records(capture.records, row["Tier"]) + assert len(tier_records) == int(row["Tier Log Count"]) + target_record = tier_records[int(row["Attempt"])] + assert_log_record_matches_row( + target_record, + row, + spans, + is_async=True, + ) From 5b50f2d3883ba553c02f6b134babe47840815102 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Fri, 20 Nov 2026 12:14:27 -0500 Subject: [PATCH 2/2] test(gapic-generator): enforce explicit F5 message globs, span windows, and authentic tracebacks - Appends explicit trailing '*' wildcards to active F5 Message Prefix cells and validates log messages with exact equality unless '*' is present. - Asserts active-trace logs fall within target span start/end timestamps. - Rejects synthetic _build_attempt_log_extra / build_telemetry_error_attributes frames in assertions. --- .../system/logging_requirements_matrix.csv | 16 +++++----- .../tests/system/test_logging_compliance.py | 32 +++++++++++-------- 2 files changed, 27 insertions(+), 21 deletions(-) diff --git a/packages/gapic-generator/tests/system/logging_requirements_matrix.csv b/packages/gapic-generator/tests/system/logging_requirements_matrix.csv index 32bb7dcff301..b469696e2888 100644 --- a/packages/gapic-generator/tests/system/logging_requirements_matrix.csv +++ b/packages/gapic-generator/tests/system/logging_requirements_matrix.csv @@ -14,16 +14,16 @@ F4.11,gRPC L4 client timeout failure attributes,L4,0,gRPC,Client Timeout,Echo.Bl F4.12a,gRPC L4 logs for retries - Attempt 1,L4,0,gRPC,Retry Recovery,SequenceService.AttemptSequence,True,False,DEBUG,2,2,DEBUG,google.api_core._observability,Transport attempt failed for /google.showcase.v1beta1.SequenceService/AttemptSequence (status=UNAVAILABLE),Transport attempt failed for /google.showcase.v1beta1.SequenceService/AttemptSequence (status=UNAVAILABLE),False,grpc,UNAVAILABLE,google.showcase.v1beta1.SequenceService/AttemptSequence,NOT SET,NOT SET,NOT SET,NOT SET,UNAVAILABLE,UNAVAILABLE,NOT SET,NOT SET,Temporary glitch,Temporary glitch,_InactiveRpcError,AioRpcError,*Temporary glitch*,*Temporary glitch*,,NOT SET,NOT SET,NOT SET F4.12b,gRPC L4 logs for retries - Attempt 2,L4,1,gRPC,Retry Recovery,SequenceService.AttemptSequence,True,False,DEBUG,2,2,DEBUG,google.api_core._observability,Transport attempt failed for /google.showcase.v1beta1.SequenceService/AttemptSequence (status=UNAVAILABLE),Transport attempt failed for /google.showcase.v1beta1.SequenceService/AttemptSequence (status=UNAVAILABLE),False,grpc,UNAVAILABLE,google.showcase.v1beta1.SequenceService/AttemptSequence,NOT SET,NOT SET,NOT SET,NOT SET,UNAVAILABLE,UNAVAILABLE,NOT SET,NOT SET,Temporary glitch,Temporary glitch,_InactiveRpcError,AioRpcError,*Temporary glitch*,*Temporary glitch*,,NOT SET,NOT SET,NOT SET F5.1,HTTP no L3 logs emitted unless enabled,L3,N/A,HTTP/REST,Logging Off,Echo.Echo,False,False,WARNING,0,0,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A -F5.2,HTTP L3 log emitted on client-level failure,L3,0,HTTP/REST,Server Failure,Echo.Echo,True,False,WARNING,1,1,WARNING,google.api_core._observability,RPC failed for google.showcase.v1beta1.Echo/Echo:,RPC failed for google.showcase.v1beta1.Echo/Echo:,True,http,INVALID_ARGUMENT,google.showcase.v1beta1.Echo/Echo,NOT SET,NOT SET,NOT SET,NOT SET,INVALID_ARGUMENT_REASON,INVALID_ARGUMENT_REASON,showcase.googleapis.com,us-east1-a,Simulated unretryable invalid argument error.,Simulated unretryable invalid argument error.,BadRequest,BadRequest,*Simulated unretryable invalid argument error.*,*Simulated unretryable invalid argument error.*,,NOT SET,NOT SET,NOT SET +F5.2,HTTP L3 log emitted on client-level failure,L3,0,HTTP/REST,Server Failure,Echo.Echo,True,False,WARNING,1,1,WARNING,google.api_core._observability,RPC failed for google.showcase.v1beta1.Echo/Echo: *,RPC failed for google.showcase.v1beta1.Echo/Echo: *,True,http,INVALID_ARGUMENT,google.showcase.v1beta1.Echo/Echo,NOT SET,NOT SET,NOT SET,NOT SET,INVALID_ARGUMENT_REASON,INVALID_ARGUMENT_REASON,showcase.googleapis.com,us-east1-a,Simulated unretryable invalid argument error.,Simulated unretryable invalid argument error.,BadRequest,BadRequest,*Simulated unretryable invalid argument error.*,*Simulated unretryable invalid argument error.*,,NOT SET,NOT SET,NOT SET F5.3,HTTP no L3 log emitted on request success,L3,N/A,HTTP/REST,Happy Path,Echo.Echo,True,False,WARNING,0,0,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A -F5.4,HTTP L3 log recorded in context of T3 span,L3,0,HTTP/REST,Active Trace,Echo.Echo,True,True,WARNING,1,1,WARNING,google.api_core._observability,RPC failed for google.showcase.v1beta1.Echo/Echo:,RPC failed for google.showcase.v1beta1.Echo/Echo:,True,http,INVALID_ARGUMENT,google.showcase.v1beta1.Echo/Echo,NOT SET,NOT SET,NOT SET,NOT SET,INVALID_ARGUMENT_REASON,INVALID_ARGUMENT_REASON,showcase.googleapis.com,us-east1-a,Simulated unretryable invalid argument error.,Simulated unretryable invalid argument error.,BadRequest,BadRequest,*Simulated unretryable invalid argument error.*,*Simulated unretryable invalid argument error.*,,T3.trace_id,T3.span_id,MATCH_SPAN_CONTEXT -F5.5,HTTP L3 client timeout failure attributes,L3,0,HTTP/REST,Client Timeout,Echo.Block,True,False,WARNING,1,1,WARNING,google.api_core._observability,RPC failed for google.showcase.v1beta1.Echo/Block:,RPC failed for google.showcase.v1beta1.Echo/Block:,True,http,NOT SET,google.showcase.v1beta1.Echo/Block,NOT SET,NOT SET,NOT SET,NOT SET,ReadTimeout,TimeoutError,NOT SET,NOT SET,*Read timed out*,*exceeded the configured timeout*,ReadTimeout,TimeoutError,*Read timed out*,*exceeded the configured timeout*,,NOT SET,NOT SET,NOT SET +F5.4,HTTP L3 log recorded in context of T3 span,L3,0,HTTP/REST,Active Trace,Echo.Echo,True,True,WARNING,1,1,WARNING,google.api_core._observability,RPC failed for google.showcase.v1beta1.Echo/Echo: *,RPC failed for google.showcase.v1beta1.Echo/Echo: *,True,http,INVALID_ARGUMENT,google.showcase.v1beta1.Echo/Echo,NOT SET,NOT SET,NOT SET,NOT SET,INVALID_ARGUMENT_REASON,INVALID_ARGUMENT_REASON,showcase.googleapis.com,us-east1-a,Simulated unretryable invalid argument error.,Simulated unretryable invalid argument error.,BadRequest,BadRequest,*Simulated unretryable invalid argument error.*,*Simulated unretryable invalid argument error.*,,T3.trace_id,T3.span_id,MATCH_SPAN_CONTEXT +F5.5,HTTP L3 client timeout failure attributes,L3,0,HTTP/REST,Client Timeout,Echo.Block,True,False,WARNING,1,1,WARNING,google.api_core._observability,RPC failed for google.showcase.v1beta1.Echo/Block: *,RPC failed for google.showcase.v1beta1.Echo/Block: *,True,http,NOT SET,google.showcase.v1beta1.Echo/Block,NOT SET,NOT SET,NOT SET,NOT SET,ReadTimeout,TimeoutError,NOT SET,NOT SET,*Read timed out*,*exceeded the configured timeout*,ReadTimeout,TimeoutError,*Read timed out*,*exceeded the configured timeout*,,NOT SET,NOT SET,NOT SET F5.6,HTTP no L3 log emitted when retry succeeds,L3,N/A,HTTP/REST,Retry Recovery,SequenceService.AttemptSequence,True,False,WARNING,0,0,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A -F5.7,HTTP single L3 log emitted when retries exhausted,L3,0,HTTP/REST,Retries Exhausted,SequenceService.AttemptSequence,True,False,WARNING,1,1,WARNING,google.api_core._observability,RPC failed for google.showcase.v1beta1.SequenceService/AttemptSequence:,RPC failed for google.showcase.v1beta1.SequenceService/AttemptSequence:,True,http,UNAVAILABLE,google.showcase.v1beta1.SequenceService/AttemptSequence,NOT SET,NOT SET,NOT SET,NOT SET,503,503,NOT SET,NOT SET,Persistent outage,Persistent outage,RetryError,RetryError,*Persistent outage*,*Persistent outage*,,NOT SET,NOT SET,NOT SET +F5.7,HTTP single L3 log emitted when retries exhausted,L3,0,HTTP/REST,Retries Exhausted,SequenceService.AttemptSequence,True,False,WARNING,1,1,WARNING,google.api_core._observability,RPC failed for google.showcase.v1beta1.SequenceService/AttemptSequence: *,RPC failed for google.showcase.v1beta1.SequenceService/AttemptSequence: *,True,http,UNAVAILABLE,google.showcase.v1beta1.SequenceService/AttemptSequence,NOT SET,NOT SET,NOT SET,NOT SET,503,503,NOT SET,NOT SET,Persistent outage,Persistent outage,RetryError,RetryError,*Persistent outage*,*Persistent outage*,,NOT SET,NOT SET,NOT SET F5.8,gRPC no L3 logs emitted unless enabled,L3,N/A,gRPC,Logging Off,Echo.Echo,False,False,WARNING,0,0,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A -F5.9,gRPC L3 log emitted on client-level failure,L3,0,gRPC,Server Failure,Echo.Echo,True,False,WARNING,1,1,WARNING,google.api_core._observability,RPC failed for google.showcase.v1beta1.Echo/Echo:,RPC failed for google.showcase.v1beta1.Echo/Echo:,True,grpc,INVALID_ARGUMENT,google.showcase.v1beta1.Echo/Echo,NOT SET,NOT SET,NOT SET,NOT SET,INVALID_ARGUMENT_REASON,INVALID_ARGUMENT_REASON,showcase.googleapis.com,us-east1-a,Simulated unretryable invalid argument error.,Simulated unretryable invalid argument error.,InvalidArgument,InvalidArgument,*Simulated unretryable invalid argument error.*,*Simulated unretryable invalid argument error.*,,NOT SET,NOT SET,NOT SET +F5.9,gRPC L3 log emitted on client-level failure,L3,0,gRPC,Server Failure,Echo.Echo,True,False,WARNING,1,1,WARNING,google.api_core._observability,RPC failed for google.showcase.v1beta1.Echo/Echo: *,RPC failed for google.showcase.v1beta1.Echo/Echo: *,True,grpc,INVALID_ARGUMENT,google.showcase.v1beta1.Echo/Echo,NOT SET,NOT SET,NOT SET,NOT SET,INVALID_ARGUMENT_REASON,INVALID_ARGUMENT_REASON,showcase.googleapis.com,us-east1-a,Simulated unretryable invalid argument error.,Simulated unretryable invalid argument error.,InvalidArgument,InvalidArgument,*Simulated unretryable invalid argument error.*,*Simulated unretryable invalid argument error.*,,NOT SET,NOT SET,NOT SET F5.10,gRPC no L3 log emitted on request success,L3,N/A,gRPC,Happy Path,Echo.Echo,True,False,WARNING,0,0,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A -F5.11,gRPC L3 log recorded in context of T3 span,L3,0,gRPC,Active Trace,Echo.Echo,True,True,WARNING,1,1,WARNING,google.api_core._observability,RPC failed for google.showcase.v1beta1.Echo/Echo:,RPC failed for google.showcase.v1beta1.Echo/Echo:,True,grpc,INVALID_ARGUMENT,google.showcase.v1beta1.Echo/Echo,NOT SET,NOT SET,NOT SET,NOT SET,INVALID_ARGUMENT_REASON,INVALID_ARGUMENT_REASON,showcase.googleapis.com,us-east1-a,Simulated unretryable invalid argument error.,Simulated unretryable invalid argument error.,InvalidArgument,InvalidArgument,*Simulated unretryable invalid argument error.*,*Simulated unretryable invalid argument error.*,,T3.trace_id,T3.span_id,MATCH_SPAN_CONTEXT -F5.12,gRPC L3 client timeout failure attributes,L3,0,gRPC,Client Timeout,Echo.Block,True,False,WARNING,1,1,WARNING,google.api_core._observability,RPC failed for google.showcase.v1beta1.Echo/Block:,RPC failed for google.showcase.v1beta1.Echo/Block:,True,grpc,DEADLINE_EXCEEDED,google.showcase.v1beta1.Echo/Block,NOT SET,NOT SET,NOT SET,NOT SET,DEADLINE_EXCEEDED,DEADLINE_EXCEEDED,NOT SET,NOT SET,Deadline Exceeded,Deadline Exceeded,DeadlineExceeded,DeadlineExceeded,*Deadline Exceeded*,*Deadline Exceeded*,,NOT SET,NOT SET,NOT SET +F5.11,gRPC L3 log recorded in context of T3 span,L3,0,gRPC,Active Trace,Echo.Echo,True,True,WARNING,1,1,WARNING,google.api_core._observability,RPC failed for google.showcase.v1beta1.Echo/Echo: *,RPC failed for google.showcase.v1beta1.Echo/Echo: *,True,grpc,INVALID_ARGUMENT,google.showcase.v1beta1.Echo/Echo,NOT SET,NOT SET,NOT SET,NOT SET,INVALID_ARGUMENT_REASON,INVALID_ARGUMENT_REASON,showcase.googleapis.com,us-east1-a,Simulated unretryable invalid argument error.,Simulated unretryable invalid argument error.,InvalidArgument,InvalidArgument,*Simulated unretryable invalid argument error.*,*Simulated unretryable invalid argument error.*,,T3.trace_id,T3.span_id,MATCH_SPAN_CONTEXT +F5.12,gRPC L3 client timeout failure attributes,L3,0,gRPC,Client Timeout,Echo.Block,True,False,WARNING,1,1,WARNING,google.api_core._observability,RPC failed for google.showcase.v1beta1.Echo/Block: *,RPC failed for google.showcase.v1beta1.Echo/Block: *,True,grpc,DEADLINE_EXCEEDED,google.showcase.v1beta1.Echo/Block,NOT SET,NOT SET,NOT SET,NOT SET,DEADLINE_EXCEEDED,DEADLINE_EXCEEDED,NOT SET,NOT SET,Deadline Exceeded,Deadline Exceeded,DeadlineExceeded,DeadlineExceeded,*Deadline Exceeded*,*Deadline Exceeded*,,NOT SET,NOT SET,NOT SET F5.13,gRPC no L3 log emitted when retry succeeds,L3,N/A,gRPC,Retry Recovery,SequenceService.AttemptSequence,True,False,WARNING,0,0,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A -F5.14,gRPC single L3 log emitted when retries exhausted,L3,0,gRPC,Retries Exhausted,SequenceService.AttemptSequence,True,False,WARNING,1,1,WARNING,google.api_core._observability,RPC failed for google.showcase.v1beta1.SequenceService/AttemptSequence:,RPC failed for google.showcase.v1beta1.SequenceService/AttemptSequence:,True,grpc,UNAVAILABLE,google.showcase.v1beta1.SequenceService/AttemptSequence,NOT SET,NOT SET,NOT SET,NOT SET,UNAVAILABLE,UNAVAILABLE,NOT SET,NOT SET,Persistent outage,Persistent outage,RetryError,RetryError,*Persistent outage*,*Persistent outage*,,NOT SET,NOT SET,NOT SET +F5.14,gRPC single L3 log emitted when retries exhausted,L3,0,gRPC,Retries Exhausted,SequenceService.AttemptSequence,True,False,WARNING,1,1,WARNING,google.api_core._observability,RPC failed for google.showcase.v1beta1.SequenceService/AttemptSequence: *,RPC failed for google.showcase.v1beta1.SequenceService/AttemptSequence: *,True,grpc,UNAVAILABLE,google.showcase.v1beta1.SequenceService/AttemptSequence,NOT SET,NOT SET,NOT SET,NOT SET,UNAVAILABLE,UNAVAILABLE,NOT SET,NOT SET,Persistent outage,Persistent outage,RetryError,RetryError,*Persistent outage*,*Persistent outage*,,NOT SET,NOT SET,NOT SET diff --git a/packages/gapic-generator/tests/system/test_logging_compliance.py b/packages/gapic-generator/tests/system/test_logging_compliance.py index b2d216a01193..7255f12a8e7a 100644 --- a/packages/gapic-generator/tests/system/test_logging_compliance.py +++ b/packages/gapic-generator/tests/system/test_logging_compliance.py @@ -396,12 +396,13 @@ def _assert_http_request_fields( def _assert_trace_correlation( + record: logging.LogRecord, record_dict: Mapping[str, Any], json_payload: Mapping[str, Any], row: Mapping[str, str], spans: Sequence[ReadableSpan], ) -> None: - """Validates `trace_id`, `span_id`, and `logging.googleapis.com/*` correlation fields.""" + """Validates `trace_id`, `span_id`, span window containment, and Cloud Logging trace fields.""" expected_trace = row["trace_id"] expected_span = row["span_id"] expected_cloud = row["Cloud Logging Trace Fields"] @@ -430,6 +431,14 @@ def _assert_trace_correlation( else: raise ValueError(f"Unsupported span_id sentinel: {expected_span!r}") + created_unix_nano = int(record.created * 1_000_000_000) + assert target_span.start_time is not None and target_span.end_time is not None + assert target_span.start_time <= created_unix_nano <= target_span.end_time, ( + f"Log emitted outside active {target_span.kind.name} span window: " + f"created_unix_nano={created_unix_nano}, " + f"span=[{target_span.start_time}, {target_span.end_time}]" + ) + expected_trace_hex = f"{t3_spans[0].context.trace_id:032x}" expected_span_hex = f"{target_span.context.span_id:016x}" @@ -472,15 +481,10 @@ def assert_log_record_matches_row( assert json_payload["name"] == row["Logger Name"] message = record.getMessage() - expected_prefix = _expected_value(row, "Message Prefix", is_async=is_async) - if "*" in expected_prefix: - assert fnmatch.fnmatchcase(message, f"{expected_prefix}*"), ( - f"Message {message!r} did not match prefix pattern {expected_prefix!r}" - ) - else: - assert message.startswith(expected_prefix), ( - f"Message {message!r} did not start with {expected_prefix!r}" - ) + expected_message = _expected_value(row, "Message Prefix", is_async=is_async) + _assert_string_or_glob( + message, expected_message, field_label="LogRecord['message']" + ) assert json_payload["message"] == message expected_exc_info = row["exc_info Present"] == "True" @@ -539,9 +543,11 @@ def assert_log_record_matches_row( isinstance(stack, str) and "Traceback (most recent call last):" in stack and '\n File "' in stack + and "_build_attempt_log_extra" not in stack + and "build_telemetry_error_attributes" not in stack ), ( - f"{container_name}['exception.stacktrace']: expected multi-frame Python " - f"traceback, got {stack!r}" + f"{container_name}['exception.stacktrace']: expected authentic " + f"multi-frame Python exception traceback, got {stack!r}" ) else: raise ValueError( @@ -549,7 +555,7 @@ def assert_log_record_matches_row( ) # 6. Trace & Span correlation - _assert_trace_correlation(record_dict, json_payload, row, spans) + _assert_trace_correlation(record, record_dict, json_payload, row, spans) # ---------------------------------------------------------------------------