Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion .github/workflows/diagnose-cached-stage-failure.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ on:
required: false
default: false
type: boolean
snapshot_request_logs_only:
description: Read bounded snapshot request logs as fixed safe categories only
required: false
default: false
type: boolean
failure_window_start:
description: UTC RFC3339 start time for the failed stage deployment
required: true
Expand Down Expand Up @@ -77,8 +82,13 @@ jobs:
FUNDS_SCHEMA_ONLY: ${{ inputs.funds_schema_only }}
FUNDS_HISTORY_SCHEMA_ONLY: ${{ inputs.funds_history_schema_only }}
EXECUTION_REPORTS_SCHEMA_ONLY: ${{ inputs.execution_reports_schema_only }}
SNAPSHOT_REQUEST_LOGS_ONLY: ${{ inputs.snapshot_request_logs_only }}
run: |
set -euo pipefail
if [ "${SNAPSHOT_REQUEST_LOGS_ONLY}" = "true" ] && { [ "${FUNDS_SCHEMA_ONLY}" = "true" ] || [ "${FUNDS_HISTORY_SCHEMA_ONLY}" = "true" ] || [ "${EXECUTION_REPORTS_SCHEMA_ONLY}" = "true" ]; }; then
echo "Snapshot request logs cannot be combined with schema inspection." >&2
exit 1
fi
if [ "${FUNDS_HISTORY_SCHEMA_ONLY}" = "true" ] && [ "${FUNDS_SCHEMA_ONLY}" != "true" ]; then
echo "History inspection requires funds_schema_only." >&2
exit 1
Expand Down Expand Up @@ -137,7 +147,7 @@ jobs:
version: ">= 416.0.0"

- name: Read private Cloud Run, IAM, Scheduler, and audit evidence
if: inputs.funds_schema_only != true
if: inputs.funds_schema_only != true && inputs.snapshot_request_logs_only != true
env:
EXPECTED_SERVICE: ${{ secrets.CLOUD_RUN_SERVICE }}
run: |
Expand Down Expand Up @@ -186,6 +196,10 @@ jobs:
--scheduler-jobs "${scheduler_file}" --audit-entries "${audit_file}" \
--audit-status "${audit_status}"

- name: Summarize bounded snapshot request logs
if: inputs.snapshot_request_logs_only == true
run: python3 -m scripts.diagnose_snapshot_request_logs

- name: Inspect existing private funds snapshot schema
if: inputs.funds_schema_only == true
env:
Expand Down
18 changes: 18 additions & 0 deletions docs/account-archive-history.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
# Saved account history

## Snapshot request log diagnosis

The existing `Diagnose cached-balance stage failure` workflow also has a
default-off `snapshot_request_logs_only` mode. It requires the exact current
main SHA, the approved main ref, `run_readonly_diagnostic=true`, and a past UTC
window of at most 30 minutes. It cannot be combined with a schema inspection.
It reads bounded Scheduler completion and Cloud Run request logs for the fixed
account-facts sync target, then reads application logs only for a uniquely
identified request trace. Truncated or inaccessible reads remain explicit; the
Scheduler-to-request association is based only on target and time, not a
proven common invocation. Only fixed categories, HTTP status codes and counts
are printed. No Scheduler job, broker request or sync is invoked.
The serving application's ordinary text logs may not carry a request trace;
in that case the application failure stays unknown even when request logs exist.
`unique_trace` means the one candidate request has a valid trace identifier;
it does not establish that an application log matched it or that the Scheduler
attempt caused that request. Unrecognized reasons remain `unknown`.

`Publish saved account history day` previews one existing UTC day by default.
It reads private funds archives in the cloud runner with the existing deployment
identity. It never authenticates to Firstrade, invokes a broker service, or
Expand Down
184 changes: 184 additions & 0 deletions scripts/diagnose_snapshot_request_logs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
"""Summarize bounded snapshot request logs without emitting their contents."""
from __future__ import annotations

import json
import os
import re
import subprocess
from urllib.parse import urlsplit

from scripts.diagnose_cached_stage_failure import _validate_window

LIMIT = 200
REASONS = frozenset({
'cache_config_error', 'cache_read_failed', 'cache_missing', 'cache_stale',
'cache_invalid', 'cache_tokens_incomplete', 'cache_missing_or_stale',
'read_timeout', 'read_network_error', 'read_http_error', 'read_invalid_payload',
'read_provider_error', 'account_data_invalid', 'account_identity_unavailable',
'account_identity_mismatch', 'account_list_empty', 'balances_unavailable',
'positions_unavailable', 'readonly_client_unavailable', 'sync_unavailable',
'sync_rejected', 'sync_ack_invalid', 'configuration_incomplete',
'account_facts_unavailable', 'runtime_target_mismatch',
})
STAGES = frozenset({'cache', 'userinfo', 'account_list', 'account_read', 'unclassified'})
STATUSES = frozenset({'OK', 'CANCELLED', 'UNKNOWN', 'INVALID_ARGUMENT', 'DEADLINE_EXCEEDED',
'NOT_FOUND', 'ALREADY_EXISTS', 'PERMISSION_DENIED', 'RESOURCE_EXHAUSTED',
'FAILED_PRECONDITION', 'ABORTED', 'OUT_OF_RANGE', 'UNIMPLEMENTED', 'INTERNAL',
'UNAVAILABLE', 'DATA_LOSS', 'UNAUTHENTICATED'})


def _http(value):
return value if type(value) is int and 100 <= value <= 599 else None


def _target(url):
if not isinstance(url, str):
return None
try:
p = urlsplit(url)
if (p.scheme != 'https' or not p.hostname or p.username or p.password
or p.port is not None or p.path != '/account-facts-sync' or p.query or p.fragment):
return None
return p.netloc
except ValueError:
return None


def _resource(row, kind, project, service, location):
resource = row.get('resource') if isinstance(row, dict) else None
labels = resource.get('labels') if isinstance(resource, dict) else None
return (isinstance(labels, dict) and resource.get('type') == kind
and labels.get('project_id') == project and labels.get('location') == location
and labels.get('service_name' if kind == 'cloud_run_revision' else 'job_id')
== (service if kind == 'cloud_run_revision' else service + '-account-facts-sync-scheduler'))


def summarize(rows, app_rows, project, service, region, run_region=None):
run_region = run_region or region
job = f'projects/{project}/locations/{region}/jobs/{service}-account-facts-sync-scheduler'
finished, requests = [], []
for row in rows:
payload = row.get('jsonPayload', {}) if isinstance(row, dict) else {}
if (_resource(row, 'cloud_scheduler_job', project, service, region) and isinstance(payload, dict)
and payload.get('@type') == 'type.googleapis.com/google.cloud.scheduler.logging.AttemptFinished'
and payload.get('jobName') == job and _target(payload.get('url'))):
finished.append(payload)
http = row.get('httpRequest', {}) if isinstance(row, dict) else {}
if (_resource(row, 'cloud_run_revision', project, service, run_region) and isinstance(http, dict)
and http.get('requestMethod') == 'POST' and _target(http.get('requestUrl'))):
requests.append(row)
result = {'scheduler_count': len(finished), 'request_count': len(requests),
'scheduler_status': 'unknown', 'scheduler_http_status': None,
'request_http_status': None, 'association': 'unverified',
'scheduler_request_relation': 'unknown', 'app_reason': 'unknown',
'app_stage': 'unknown', 'app_http_status': None, 'app_match_count': 0}
if len(finished) == 1:
event = finished[0]
status = event.get('status')
result['scheduler_status'] = status if status in STATUSES else 'unknown'
debug = event.get('debugInfo')
match = re.search(r'\bresponse code number = ([1-5][0-9]{2})\b', debug) if isinstance(debug, str) else None
result['scheduler_http_status'] = int(match.group(1)) if match else None
if len(requests) == 1:
result['request_http_status'] = _http(requests[0]['httpRequest'].get('status'))
if len(finished) != 1 or len(requests) != 1:
result['association'] = 'ambiguous' if len(finished) > 1 or len(requests) > 1 else 'unverified'
return result
if _target(finished[0].get('url')) != _target(requests[0]['httpRequest'].get('requestUrl')):
return result
result['scheduler_request_relation'] = 'same_target_and_window_only'
trace = requests[0].get('trace')
if not isinstance(trace, str) or not re.fullmatch(r'projects/' + re.escape(project) + r'/traces/[0-9a-f]{32}', trace):
return result
result['association'] = 'unique_trace'
matched = [row for row in app_rows if _resource(row, 'cloud_run_revision', project, service, run_region)
and row.get('trace') == trace and not row.get('httpRequest')]
result['app_match_count'] = len(matched)
classifications = []
for row in matched:
msg = row.get('textPayload')
if not isinstance(msg, str):
continue
client = re.search(r'account_facts_sync client failed exc_type=\w+ reason=([a-z_]+) stage=([a-z_]+) http_status=(None|[1-5][0-9]{2})(?:\s|$)', msg)
other = re.search(r'account_facts_sync (?:collect|build|publish) failed reason=([a-z_]+)(?:\s|$)', msg)
if client and client.group(1) in REASONS and client.group(2) in STAGES:
classifications.append((client.group(1), client.group(2),
None if client.group(3) == 'None' else int(client.group(3))))
elif other and other.group(1) in REASONS:
classifications.append((other.group(1), 'unclassified', None))
if len(matched) == 1 and len(classifications) == 1:
result['app_reason'], result['app_stage'], result['app_http_status'] = classifications[0]
return result


def _read_logs(query, project):
try:
proc = subprocess.run(['gcloud', 'logging', 'read', query, '--project', project,
'--limit', str(LIMIT + 1), '--format=json', '--quiet'],
capture_output=True, text=True, timeout=60, check=False)
except (OSError, subprocess.TimeoutExpired):
return 'unavailable', []
if proc.returncode:
return ('permission_denied' if re.search(r'permission.denied|forbidden|\b403\b', proc.stderr, re.I)
else 'unavailable'), []
try:
rows = json.loads(proc.stdout)
if not isinstance(rows, list):
return 'unavailable', []
except (ValueError, TypeError):
return 'unavailable', []
return ('truncated' if len(rows) > LIMIT else 'ok'), rows[:LIMIT]


def run(project, service, region, run_region, start, end, *, read=_read_logs):
_validate_window(start, end)
if (not re.fullmatch(r'[a-z][a-z0-9-]{4,62}', project)
or not re.fullmatch(r'[a-z][a-z0-9-]{0,62}', service)
or not re.fullmatch(r'[a-z]+(?:-[a-z0-9]+)+[0-9]', region)
or not re.fullmatch(r'[a-z]+(?:-[a-z0-9]+)+[0-9]', run_region)):
raise ValueError('target_invalid')
window = f'timestamp >= "{start}" AND timestamp <= "{end}"'
job_id = service + '-account-facts-sync-scheduler'
route = r'^https://[^/?#]+/account-facts-sync$'
scope = (f'{window} AND resource.labels.project_id="{project}" AND ('
f'(resource.type="cloud_scheduler_job" AND resource.labels.location="{region}" '
f'AND resource.labels.job_id="{job_id}" AND jsonPayload."@type"="type.googleapis.com/google.cloud.scheduler.logging.AttemptFinished") OR '
f'(resource.type="cloud_run_revision" AND resource.labels.location="{run_region}" '
f'AND resource.labels.service_name="{service}" AND httpRequest.requestMethod="POST" '
f'AND httpRequest.requestUrl=~"{route}"))')
status, rows = read(scope, project)
output = {'status': status, 'app_read_status': 'not_attempted'}
if status != 'ok':
return output
partial = summarize(rows, [], project, service, region, run_region)
if partial['association'] != 'unique_trace':
return {**output, **partial}
request = next(row for row in rows if _resource(row, 'cloud_run_revision', project, service, run_region)
and (row.get('httpRequest') or {}).get('requestMethod') == 'POST'
and _target((row.get('httpRequest') or {}).get('requestUrl')))
trace = request['trace']
app_filter = (f'{window} AND resource.type="cloud_run_revision" '
f'AND resource.labels.project_id="{project}" AND resource.labels.location="{run_region}" '
f'AND resource.labels.service_name="{service}" AND trace="{trace}"')
app_status, app_rows = read(app_filter, project)
output['app_read_status'] = app_status
if app_status != 'ok':
return {**output, **partial}
return {**output, **summarize(rows, app_rows, project, service, region, run_region)}


def main():
try:
output = run(os.environ['GCP_PROJECT_ID'], os.environ['CLOUD_RUN_SERVICE'],
os.environ['SCHEDULER_LOCATION'], os.environ['CLOUD_RUN_REGION'], os.environ['FAILURE_WINDOW_START'],
os.environ['FAILURE_WINDOW_END'])
except (KeyError, ValueError, TypeError):
output = {'status': 'invalid_configuration'}
except Exception:
output = {'status': 'unavailable'}
print(json.dumps(output, sort_keys=True))
return 0 if output['status'] == 'ok' and output.get('app_read_status') not in {'permission_denied', 'unavailable', 'truncated'} else 1


if __name__ == '__main__':
raise SystemExit(main())
113 changes: 113 additions & 0 deletions tests/test_snapshot_log_diagnostic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import unittest
from types import SimpleNamespace
from unittest.mock import patch

from scripts.diagnose_snapshot_request_logs import _read_logs, run, summarize

PROJECT = 'example-project'
SERVICE = 'sample-service'
JOB = f'projects/{PROJECT}/locations/us-central1/jobs/{SERVICE}-account-facts-sync-scheduler'
URL = 'https://example.invalid/account-facts-sync'
TRACE = f'projects/{PROJECT}/traces/' + 'a' * 32


def scheduler():
return {'resource': {'type': 'cloud_scheduler_job', 'labels': {'project_id': PROJECT, 'location': 'us-central1', 'job_id': SERVICE + '-account-facts-sync-scheduler'}}, 'jsonPayload': {'@type': 'type.googleapis.com/google.cloud.scheduler.logging.AttemptFinished', 'jobName': JOB, 'url': URL, 'status': 'UNAVAILABLE', 'debugInfo': 'Original HTTP response code number = 503'}}


def request():
return {'resource': {'type': 'cloud_run_revision', 'labels': {'project_id': PROJECT, 'location': 'us-central1', 'service_name': SERVICE}}, 'httpRequest': {'requestUrl': URL, 'requestMethod': 'POST', 'status': 503}, 'trace': TRACE}


def app(reason='cache_missing', trace=TRACE):
return {'resource': {'type': 'cloud_run_revision', 'labels': {'project_id': PROJECT, 'location': 'us-central1', 'service_name': SERVICE}}, 'trace': trace, 'textPayload': 'account_facts_sync client failed exc_type=FirstradeCachedSessionError reason=' + reason + ' stage=cache http_status=None'}


class SnapshotLogDiagnosticTest(unittest.TestCase):
def test_unique_trace_and_safe_category(self):
result = summarize([scheduler(), request()], [app()], PROJECT, SERVICE, 'us-central1')
self.assertEqual(result['association'], 'unique_trace')
self.assertEqual(result['app_reason'], 'cache_missing')
self.assertEqual(result['app_stage'], 'cache')
self.assertEqual(result['request_http_status'], 503)
self.assertNotIn(URL, str(result))
self.assertNotIn(TRACE, str(result))

def test_no_trace_or_multiple_requests_are_never_correlated(self):
no_trace = request(); del no_trace['trace']
for rows in ([scheduler(), no_trace], [scheduler(), request(), request()]):
result = summarize(rows, [app()], PROJECT, SERVICE, 'us-central1')
self.assertNotEqual(result['association'], 'unique_trace')
self.assertEqual(result['app_reason'], 'unknown')

def test_malicious_or_unmatched_payload_never_leaks(self):
for row in (app('secret-account-123'), app(trace='unrelated')):
result = summarize([scheduler(), request()], [row], PROJECT, SERVICE, 'us-central1')
self.assertEqual(result['app_reason'], 'unknown')
self.assertNotIn('secret-account-123', str(result))

def test_wrong_job_or_url_cannot_match(self):
wrong = scheduler(); wrong['jsonPayload']['jobName'] += '-wrong'
result = summarize([wrong, request()], [app()], PROJECT, SERVICE, 'us-central1')
self.assertEqual(result['scheduler_count'], 0)
self.assertEqual(result['association'], 'unverified')
self.assertEqual(result['app_reason'], 'unknown')

def test_actual_read_path_and_incomplete_reads(self):
start, end = '2026-10-30T01:57:00Z', '2026-10-30T02:10:00Z'
queries = []
def read(query, project):
queries.append(query)
return ('ok', [scheduler(), request()]) if len(queries) == 1 else ('ok', [app()])
result = run(PROJECT, SERVICE, 'us-central1', 'us-central1', start, end, read=read)
self.assertEqual(result['app_reason'], 'cache_missing')
self.assertEqual(len(queries), 2)
self.assertIn('jsonPayload."@type"=', queries[0])
self.assertIn('httpRequest.requestUrl=~', queries[0])
self.assertIn('trace=', queries[1])
for failure in ('permission_denied', 'truncated', 'unavailable'):
def failed_read(query, project):
return failure, []
result = run(PROJECT, SERVICE, 'us-central1', 'us-central1', start, end, read=failed_read)
self.assertEqual(result['status'], failure)
self.assertNotIn('app_reason', result)

def test_app_read_truncation_never_claims_reason(self):
calls = []
def read(query, project):
calls.append(query)
return ('ok', [scheduler(), request()]) if len(calls) == 1 else ('truncated', [app()])
result = run(PROJECT, SERVICE, 'us-central1', 'us-central1',
'2026-10-30T01:57:00Z', '2026-10-30T02:10:00Z', read=read)
self.assertEqual(result['app_read_status'], 'truncated')
self.assertEqual(result['app_reason'], 'unknown')

def test_app_classification_with_wrong_trace_or_multiple_events(self):
for second in (app(), app('unrecognized'), {k: v for k, v in app().items() if k != 'textPayload'}):
result = summarize([scheduler(), request()], [app(), second], PROJECT, SERVICE, 'us-central1')
self.assertEqual(result['app_reason'], 'unknown')
self.assertEqual(result['app_match_count'], 2)

def test_gcloud_output_is_bounded_and_errors_are_sanitized(self):
for completed, expected in (
(SimpleNamespace(returncode=1, stdout='', stderr='PERMISSION_DENIED sensitive-value'), 'permission_denied'),
(SimpleNamespace(returncode=1, stdout='', stderr='other sensitive-value'), 'unavailable'),
(SimpleNamespace(returncode=0, stdout='[' + ','.join('{}' for _ in range(201)) + ']', stderr=''), 'truncated'),
):
with patch('scripts.diagnose_snapshot_request_logs.subprocess.run', return_value=completed) as call:
status, rows = _read_logs('synthetic filter', PROJECT)
self.assertEqual(status, expected)
self.assertLessEqual(len(rows), 200)
self.assertNotIn('sensitive-value', str((status, rows)))
self.assertEqual(call.call_args.args[0][:3], ['gcloud', 'logging', 'read'])

def test_invalid_window_never_reads(self):
def forbidden(*_args):
raise AssertionError('read attempted')
with self.assertRaises(ValueError):
run(PROJECT, SERVICE, 'us-central1', 'us-central1',
'2026-10-30T01:00:00Z', '2026-10-30T02:00:01Z', read=forbidden)


if __name__ == '__main__':
unittest.main()
Loading