diff --git a/README.md b/README.md index e26e9f4..b049182 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ classification remains in `classification`. ### Expected product value When `GEMINI_API_KEY` is configured, each analysis also judges the value each sampled -PR is expected to deliver to the repository's product (`product_value.py`). One Gemini +PR is expected to deliver to the repository's product (`product_value.py`). A Gemini call turns the repository description, topics and README into product context: a summary, value proposition, lean canvas, and the strategic goals the repository appears focused on. Only public repositories are assessed, and the README is fetched @@ -78,6 +78,27 @@ rest of the analysis is unchanged. The hosted Worker caches each analysis for up hours (ten minutes when a Gemini call failed), so adding or removing the key shows on the next uncached or force-refreshed analysis. The dashboard shows the context and per-PR assessments under Content framing. + +Context generation starts with a 4,096-token output budget and asks for under 600 +words. A `MAX_TOKENS` finish triggers one fresh attempt with 8,192 tokens; both +attempts share a 45-second deadline, with a 25-second limit per request. Other +provider errors, blocked responses, and invalid JSON are not retried. Incomplete +responses are never used to score PRs. Each PR call remains independent, so one +failed assessment does not discard successful ones. When a deadline cancels a +Worker request, its abort signal cancels the outgoing fetch, including a pending +response-body read. + +For diagnosis, `/api/analyze` includes `product_value.analysis_id`; failures also +include a stable `error_code` and a safe explanation. Search Worker logs for that +analysis ID. Events identify `product_sources`, `product_context`, or +`pr_assessment`; generation events include the model, attempt, output budget, +HTTP status, finish reason, token usage, and elapsed milliseconds when available. +A PR failure also records its number and cohort. Workers receive structured +console objects; local runs emit JSON through Python logging. Prompts, source +text, model output, credentials, raw error bodies, and exception messages are +excluded. Cache hits reuse the previous analysis ID and do not run the model; +use `force_refresh: true` to verify a fresh attempt. Existing failed results can +remain cached for ten minutes after an update. ## Cloudflare deployment This project uses Cloudflare Python Workers (FastAPI), Workers Static Assets, KV for cached public results, and native Worker rate-limit bindings. diff --git a/app.py b/app.py index 385503e..c650a2f 100644 --- a/app.py +++ b/app.py @@ -6,6 +6,11 @@ """ import os +import logging + +logging.basicConfig(level=logging.WARNING, format="%(message)s") +logging.getLogger("github_api").setLevel(logging.INFO) +logging.getLogger("httpx").setLevel(logging.WARNING) import asyncio import subprocess diff --git a/github_api.py b/github_api.py index 3982063..6b13e17 100644 --- a/github_api.py +++ b/github_api.py @@ -1,11 +1,25 @@ """GitHub JSON requests using Workers fetch in production and httpx locally.""" +import asyncio import json import logging from typing import Any +from urllib.parse import urlsplit logger = logging.getLogger(__name__) +def log_event(level, event, **fields): + record = {"event": event, **fields} + try: + from js import Object, console + from pyodide.ffi import to_js + except (ImportError, ModuleNotFoundError): + logger.log(level, json.dumps(record, separators=(",", ":"))) + else: + emit = console.error if level >= logging.ERROR else console.warn if level >= logging.WARNING else console.log + emit(to_js(record, dict_converter=Object.fromEntries)) + + async def request_json( url: str, *, @@ -21,7 +35,7 @@ async def request_json( request headers. A CPython/httpx fallback keeps local development simple. """ try: - from js import Object, fetch as js_fetch + from js import AbortController, Object, fetch as js_fetch from pyodide.ffi import to_js except (ImportError, ModuleNotFoundError): import httpx @@ -33,23 +47,30 @@ async def request_json( text = response.text else: worker_headers = dict(headers) - options: dict[str, Any] = {"method": method, "headers": worker_headers} + controller = AbortController.new() + options: dict[str, Any] = {"method": method, "headers": worker_headers, "signal": controller.signal} if body is not None: worker_headers.setdefault("Content-Type", "application/json") options["body"] = json.dumps(body, separators=(",", ":")) - response = await js_fetch(url, to_js(options, dict_converter=Object.fromEntries)) - status = response.status - response_headers = { - name: response.headers.get(name, "") - for name in ("content-type", "server", "cf-ray", "x-github-request-id", "x-ratelimit-remaining") - } - text = await response.text() + try: + response = await js_fetch(url, to_js(options, dict_converter=Object.fromEntries)) + status = response.status + response_headers = { + name: response.headers.get(name, "") + for name in ("content-type", "server", "cf-ray", "x-github-request-id", "x-ratelimit-remaining") + } + text = await response.text() + except asyncio.CancelledError: + controller.abort() + raise + try: payload = json.loads(text) except (TypeError, ValueError): payload = {"message": text[:1000]} if status >= 400: - logger.error("GitHub API returned HTTP %s for %s %s; response_headers=%s; body=%s", - status, method, url, response_headers, text[:300]) + host = urlsplit(url).hostname + provider = {"api.github.com": "github", "generativelanguage.googleapis.com": "gemini"}.get(host, "other") + log_event(logging.ERROR, "upstream_http_error", provider=provider, http_status=status) return status, response_headers, payload diff --git a/product_value.py b/product_value.py index 794e24b..40f2ab9 100644 --- a/product_value.py +++ b/product_value.py @@ -9,11 +9,16 @@ import asyncio import base64 import json +import logging +import time +import uuid -from github_api import request_json +from httpx import TimeoutException + +from github_api import log_event, request_json from value_classification import compute_value_classification -VERSION = "gemini-product-value-1" +VERSION = "gemini-product-value-2" MODEL = "gemini-3.5-flash-lite" GEMINI_URL = f"https://generativelanguage.googleapis.com/v1beta/models/{MODEL}:generateContent" VALUE_LEVELS = ["High", "Medium", "Low", "Unclear"] @@ -23,6 +28,8 @@ BODY_CHARS = 4_000 CONCURRENCY = 5 GEMINI_TIMEOUT = 25 +CONTEXT_TIMEOUT = 45 +CONTEXT_TOKEN_BUDGETS = (4096, 8192) CANVAS_KEYS = ("customer_segments", "problem", "solution", "unique_value_proposition", "channels", "revenue_streams", "cost_structure", "key_metrics", "unfair_advantage") NARRATIVE_KEYS = ("value_summary", "beneficiaries", "why_it_matters") @@ -54,6 +61,9 @@ rather than guessing, and list what is missing in missing_context. Return a short product summary, a one-sentence value proposition, a lean canvas, and the 3 to 5 strategic goals the repository appears focused on now, most important first. +Keep the entire answer under 600 words. Use one short sentence per lean canvas field and strategic +goal, and at most two sentences each for the summary and missing context. +Summarize in your own words. Do not quote or reproduce passages from the README. Repository: {repo} Description: {description} @@ -116,20 +126,84 @@ async def fetch_product_sources(repo, token=None): "readme_truncated": len(text) > README_CHARS} -async def gemini_json(key, prompt, schema, max_tokens=1200): - """Call Gemini for a structured JSON answer; raise ValueError on any failure.""" +class GenerationError(ValueError): + def __init__(self, code): + self.code = code + super().__init__(code) + + +def _error_code(exc, fallback="invalid_response"): + if isinstance(exc, GenerationError): + return exc.code + return "timeout" if isinstance(exc, (TimeoutError, TimeoutException)) else fallback + + +def _failure_reason(code): + return {"output_truncated": "The AI response was truncated. Please try again.", + "timeout": "The AI request timed out. Please try again.", + "provider_http_error": "The AI provider returned an error. Please try again later.", + "blocked_response": "The AI provider did not return an allowed response.", + "source_unavailable": "Repository sources could not be loaded.", + "invalid_response": "The AI provider returned an unreadable response.", + "transport_error": "The AI provider could not be reached."}[code] + + +async def gemini_json(key, prompt, schema, max_tokens=1200, *, diagnostics=None, attempt=1): + started = time.monotonic() + info = {**(diagnostics or {}), "model": MODEL, "attempt": attempt, "max_output_tokens": max_tokens} body = {"contents": [{"role": "user", "parts": [{"text": prompt}]}], "generationConfig": {"temperature": 0.2, "maxOutputTokens": max_tokens, "responseMimeType": "application/json", "responseSchema": schema}} - status, _, payload = await _request(GEMINI_URL, GEMINI_TIMEOUT, method="POST", - headers={"x-goog-api-key": key}, body=body) - if status < 200 or status >= 300: - raise ValueError(f"Gemini returned HTTP {status}") + code = None + fallback = "transport_error" try: - parts = payload["candidates"][0]["content"]["parts"] + status, _, payload = await _request(GEMINI_URL, GEMINI_TIMEOUT, method="POST", + headers={"x-goog-api-key": key}, body=body) + info["http_status"] = status + if status < 200 or status >= 300: + raise GenerationError("provider_http_error") + fallback = "invalid_response" + usage = payload.get("usageMetadata", {}) + if isinstance(usage, dict): + info["usage"] = {k: v for k, v in usage.items() if k in ( + "promptTokenCount", "candidatesTokenCount", "totalTokenCount", "thoughtsTokenCount") + and type(v) is int and v >= 0} + feedback = payload.get("promptFeedback", {}) + if isinstance(feedback, dict) and feedback.get("blockReason"): + raise GenerationError("blocked_response") + candidate = payload["candidates"][0] + finish = candidate.get("finishReason") + info["finish_reason"] = finish if finish in ("STOP", "MAX_TOKENS", "SAFETY", "RECITATION") else "OTHER" + if finish == "MAX_TOKENS": + raise GenerationError("output_truncated") + if finish != "STOP": + raise GenerationError("blocked_response") + parts = candidate["content"]["parts"] return json.loads("".join(part.get("text", "") for part in parts)) - except (KeyError, IndexError, TypeError, ValueError) as exc: - raise ValueError("Gemini returned an unreadable answer") from exc + except asyncio.CancelledError: + code = "cancelled" + raise + except Exception as exc: + code = _error_code(exc, fallback) + raise GenerationError(code) from None + finally: + info["elapsed_ms"] = round((time.monotonic() - started) * 1000) + info["outcome"] = "failed" if code else "completed" + if code: + info["error_code"] = code + log_event(logging.WARNING if code else logging.INFO, "gemini_generation", **info) + + +async def generate_context(key, prompt, diagnostics): + async def attempts(): + for attempt, budget in enumerate(CONTEXT_TOKEN_BUDGETS, 1): + try: + return await gemini_json(key, prompt, CONTEXT_SCHEMA, budget, + diagnostics=diagnostics, attempt=attempt) + except GenerationError as exc: + if exc.code != "output_truncated" or attempt == len(CONTEXT_TOKEN_BUDGETS): + raise + return await asyncio.wait_for(attempts(), CONTEXT_TIMEOUT) def select_prs(data, value_classification, max_prs=DEFAULT_MAX_PRS): @@ -182,17 +256,24 @@ def _clean(assessment): return result -async def assess_pr(key, context_text, item, pr): +async def assess_pr(key, context_text, item, pr, *, diagnostics=None): prompt = ASSESSMENT_PROMPT.format( context=context_text, number=item["number"], cohort=item["cohort"], title=item["title"], size=(pr.get("additions") or 0) + (pr.get("deletions") or 0) or "unknown", framing=item["level"], rationale=item["rationale"], body=(pr.get("body") or "(no body)")[:BODY_CHARS]) base = {"number": item["number"], "title": item["title"], "cohort": item["cohort"], "framing": item["level"]} + started = time.monotonic() + info = {**(diagnostics or {}), "stage": "pr_assessment", "pr_number": item["number"], "cohort": item["cohort"]} try: - return {**base, "status": "assessed", **_clean(await gemini_json(key, prompt, ASSESSMENT_SCHEMA, 600))} - except Exception: # one failed PR must not lose the others - return {**base, "status": "failed"} + return {**base, "status": "assessed", **_clean(await gemini_json( + key, prompt, ASSESSMENT_SCHEMA, 600, diagnostics=info))} + except Exception as exc: + code = _error_code(exc) + if not isinstance(exc, GenerationError): + log_event(logging.WARNING, "pr_assessment_failed", **info, error_code=code, + elapsed_ms=round((time.monotonic() - started) * 1000)) + return {**base, "status": "failed", "error_code": code, "reason": _failure_reason(code)} async def assess_product_value(repo, data, key, token=None, max_prs=DEFAULT_MAX_PRS): @@ -201,30 +282,43 @@ async def assess_product_value(repo, data, key, token=None, max_prs=DEFAULT_MAX_ Never raises: a missing key or failed context call returns a status the dashboard explains, so the rest of the analysis is unaffected. """ + started = time.monotonic() + diagnostics = {"analysis_id": uuid.uuid4().hex, "repo": repo} value_classification = compute_value_classification(data) result = {"method": "gemini", "model": MODEL, "version": VERSION, "levels": VALUE_LEVELS, "disclaimer": DISCLAIMER, "context": None, "sources": None, "items": [], - "total_prs": value_classification["prs"]["total"]} + "total_prs": value_classification["prs"]["total"], "analysis_id": diagnostics["analysis_id"]} if not key: - return {**result, "status": "unavailable", "reason": "No Gemini API key is configured."} + log_event(logging.WARNING, "product_value_unavailable", **diagnostics, stage="product_context", + error_code="not_configured", elapsed_ms=round((time.monotonic() - started) * 1000)) + return {**result, "status": "unavailable", "error_code": "not_configured", + "reason": "No Gemini API key is configured."} + stage = "product_sources" try: sources = await fetch_product_sources(repo, token) - context = await gemini_json(key, CONTEXT_PROMPT.format( + result["sources"] = {"description": bool(sources["description"]), "readme": bool(sources["readme"]), + "readme_truncated": sources["readme_truncated"]} + log_event(logging.INFO, "product_sources_loaded", **diagnostics, stage=stage, + elapsed_ms=round((time.monotonic() - started) * 1000), **result["sources"]) + stage = "product_context" + context = await generate_context(key, CONTEXT_PROMPT.format( repo=repo, description=sources["description"] or "(none)", topics=", ".join(sources["topics"]) or "(none)", homepage=sources["homepage"] or "(none)", - readme=sources["readme"] or "(no README)"), CONTEXT_SCHEMA, 1500) + readme=sources["readme"] or "(no README)"), {**diagnostics, "stage": stage}) context = _clean_context(context) - except Exception: # httpx errors locally, JS fetch errors on Workers, bad answers - return {**result, "status": "failed", "reason": "Product context could not be generated."} - result["sources"] = {"description": bool(sources["description"]), "readme": bool(sources["readme"]), - "readme_truncated": sources["readme_truncated"]} + except Exception as exc: + code = _error_code(exc, "source_unavailable" if stage == "product_sources" else "invalid_response") + log_event(logging.ERROR, "product_value_failed", **diagnostics, stage=stage, error_code=code, + elapsed_ms=round((time.monotonic() - started) * 1000)) + reason = f"Product context could not be generated. {_failure_reason(code)}" + return {**result, "status": "failed", "error_code": code, "reason": reason} result["context"] = context context_text = _context_text(context) limit = asyncio.Semaphore(CONCURRENCY) async def bounded(item, pr): async with limit: - return await assess_pr(key, context_text, item, pr) + return await assess_pr(key, context_text, item, pr, diagnostics=diagnostics) selected = select_prs(data, value_classification, max_prs) result["selected"] = len(selected) @@ -233,5 +327,8 @@ async def bounded(item, pr): for item in result["items"]: if item["status"] == "assessed": counts[item["expected_value"]] += 1 + log_event(logging.INFO, "product_value_completed", **diagnostics, stage="pr_assessment", + assessed=sum(counts.values()), failed=sum(i["status"] == "failed" for i in result["items"]), + elapsed_ms=round((time.monotonic() - started) * 1000)) return {**result, "status": "ok", "counts": counts, "assessed": sum(counts.values()), "failed": sum(i["status"] == "failed" for i in result["items"])} diff --git a/tests/integration/test_product_value.py b/tests/integration/test_product_value.py index 9d969eb..3ce62f7 100644 --- a/tests/integration/test_product_value.py +++ b/tests/integration/test_product_value.py @@ -21,7 +21,7 @@ def gemini_reply(answer): - return 200, {}, {"candidates": [{"content": {"parts": [{"text": json.dumps(answer)}]}}]} + return 200, {}, {"candidates": [{"finishReason": "STOP", "content": {"parts": [{"text": json.dumps(answer)}]}}]} class FakeServices: @@ -228,3 +228,233 @@ async def put(self, key, value, expiration_ttl): assert seen["args"] == ("o/r", {"repo": "o/r"}, "k") assert cache.stored[hosted.METRICS_CACHE_PREFIX + "o/r"]["product_value"]["status"] == value["status"] assert cache.ttls[-1] == ttl + + +def _events(caplog): + return [json.loads(r.message) for r in caplog.records if r.name in ("product_value", "github_api")] + + +def test_truncated_context_retries_once_then_assesses_prs(monkeypatch, caplog): + fake = FakeServices(assessments={n: assessment("High") for n in (1, 2, 3)}) + budgets = [] + + async def upstream(url, **kwargs): + body = kwargs.get("body") + if body and "## Pull request #" not in body["contents"][0]["parts"][0]["text"]: + budgets.append(body["generationConfig"]["maxOutputTokens"]) + if len(budgets) == 1: + return 200, {}, {"candidates": [{"finishReason": "MAX_TOKENS", "content": { + "parts": [{"text": '{"product_summary":"private-body-sentinel'}]}}], + "usageMetadata": {"promptTokenCount": 3302, "candidatesTokenCount": 4096, + "untrusted": "secret-sentinel"}} + return await fake(url, **kwargs) + + monkeypatch.setattr(product_value, "request_json", upstream) + with caplog.at_level("INFO"): + result = run(key="key-sentinel") + assert result["status"] == "ok" and result["assessed"] == 3 + assert budgets == [4096, 8192] + events = _events(caplog) + failed = next(e for e in events if e.get("error_code") == "output_truncated") + assert failed["finish_reason"] == "MAX_TOKENS" and failed["http_status"] == 200 + assert failed["usage"]["candidatesTokenCount"] == 4096 + assert failed["stage"] == "product_context" and failed["attempt"] == 1 + assert all(e["analysis_id"] == result["analysis_id"] for e in events) + assert all("elapsed_ms" in e for e in events) + assert all(secret not in caplog.text for secret in ("key-sentinel", "private-body-sentinel", "secret-sentinel")) + + +@pytest.mark.parametrize("text", ['{"product_summary":', json.dumps(CONTEXT)]) +def test_repeated_truncation_is_explicit_and_bounded(monkeypatch, services, text, caplog): + fake = services() + context_calls = [] + + async def upstream(url, **kwargs): + if kwargs.get("body"): + context_calls.append(kwargs["body"]) + return 200, {}, {"candidates": [{"finishReason": "MAX_TOKENS", "content": {"parts": [{"text": text}]}}]} + return await fake(url, **kwargs) + + monkeypatch.setattr(product_value, "request_json", upstream) + result = run() + assert result["status"] == "failed" and result["error_code"] == "output_truncated" + assert "truncated" in result["reason"].lower() + assert result["items"] == [] and len(context_calls) == 2 + assert len([e for e in _events(caplog) if e.get("event") == "product_value_failed"]) == 1 + + +@pytest.mark.parametrize("reply,code", [ + ((429, {}, {"error": "provider-secret-sentinel"}), "provider_http_error"), + ((200, {}, {"promptFeedback": {"blockReason": "SAFETY"}}), "blocked_response"), + ((200, {}, {"candidates": [{"finishReason": "SAFETY", "content": {"parts": [{"text": json.dumps(CONTEXT)}]}}]}), "blocked_response"), + ((200, {}, {"candidates": [{"finishReason": "STOP", "content": {"parts": [{"text": "provider-secret-sentinel"}]}}]}), "invalid_response"), + ((200, {}, {"candidates": "provider-secret-sentinel"}), "invalid_response"), +]) +def test_non_truncation_errors_are_specific_safe_and_not_retried(monkeypatch, services, caplog, reply, code): + fake = services() + calls = [] + + async def upstream(url, **kwargs): + if kwargs.get("body"): + calls.append(url) + return reply + return await fake(url, **kwargs) + + monkeypatch.setattr(product_value, "request_json", upstream) + result = run() + assert result["status"] == "failed" and result["error_code"] == code + assert len(calls) == 1 + assert "provider-secret-sentinel" not in json.dumps(result) + caplog.text + event = next(e for e in _events(caplog) if e.get("event") == "gemini_generation") + assert event["error_code"] == code and event["stage"] == "product_context" + + +def test_context_retry_shares_one_deadline(monkeypatch, services, caplog): + fake = services() + calls = [] + + async def upstream(url, **kwargs): + if kwargs.get("body"): + calls.append(url) + if len(calls) == 1: + await asyncio.sleep(.02) + return 200, {}, {"candidates": [{"finishReason": "MAX_TOKENS"}]} + await asyncio.sleep(10) + return await fake(url, **kwargs) + + monkeypatch.setattr(product_value, "request_json", upstream) + monkeypatch.setattr(product_value, "CONTEXT_TIMEOUT", .04) + result = run() + assert result["error_code"] == "timeout" and len(calls) == 2 + assert any(e.get("error_code") == "timeout" and e["stage"] == "product_context" for e in _events(caplog)) + + +def test_pr_failure_logs_identify_the_pr_without_its_contents(services, caplog): + services(assessments={1: assessment("High"), 3: assessment("Low")}) + with caplog.at_level("INFO"): + result = run() + events = _events(caplog) + failure = next(e for e in events if e.get("stage") == "pr_assessment" and e.get("error_code")) + assert failure["pr_number"] == 2 and failure["cohort"] == "merged" + assert result["assessed"] == 2 and result["failed"] == 1 + assert result["items"][1]["error_code"] == "provider_http_error" + assert not any(key in failure for key in ("prompt", "body", "headers", "response", "title")) + + +def test_source_failure_is_distinguished_from_model_failure(monkeypatch, caplog): + async def failing(*_, **__): + raise ValueError("source-secret-sentinel") + + monkeypatch.setattr(product_value, "fetch_product_sources", failing) + result = run() + assert result["error_code"] == "source_unavailable" + event = next(e for e in _events(caplog) if e.get("event") == "product_value_failed") + assert event["stage"] == "product_sources" + assert "source-secret-sentinel" not in json.dumps(result) + caplog.text + + +def test_local_transport_timeout_is_reported_as_timeout(monkeypatch, services, caplog): + import httpx + fake = services() + + async def upstream(url, **kwargs): + if kwargs.get('body'): + raise httpx.ReadTimeout('exception-secret-sentinel') + return await fake(url, **kwargs) + + monkeypatch.setattr(product_value, 'request_json', upstream) + result = run() + assert result['error_code'] == 'timeout' + assert 'exception-secret-sentinel' not in json.dumps(result) + caplog.text + + +def test_retry_cannot_reset_the_shared_context_deadline(monkeypatch, services): + import selectors + fake = services() + calls = [] + clock = [0.0] + + class ClockSelector(selectors.SelectSelector): + def select(self, timeout=None): + assert timeout is not None, "the context operation must always have a deadline" + clock[0] += timeout + return super().select(0) + + async def upstream(url, **kwargs): + if kwargs.get('body'): + calls.append(url) + await asyncio.sleep(6) + if len(calls) == 1: + return 200, {}, {'candidates': [{'finishReason': 'MAX_TOKENS'}]} + return await fake(url, **kwargs) + + monkeypatch.setattr(product_value, 'request_json', upstream) + monkeypatch.setattr(product_value, 'CONTEXT_TIMEOUT', 10) + loop = asyncio.SelectorEventLoop(selector=ClockSelector()) + try: + with monkeypatch.context() as controlled: + controlled.setattr(loop, 'time', lambda: clock[0]) + result = loop.run_until_complete(product_value.assess_product_value('o/r', DATA, 'k')) + finally: + loop.close() + assert result['error_code'] == 'timeout' and len(calls) == 2 + + +def test_unconfigured_result_exposes_the_logged_error_code(services): + services() + result = run(key=None) + assert result['status'] == 'unavailable' and result['error_code'] == 'not_configured' + assert result['reason'] + + +def test_failed_pr_has_a_safe_explanation(services): + services() + result = run() + assert all(item['reason'] and item['error_code'] == 'provider_http_error' for item in result['items']) + + +@pytest.mark.parametrize('waiting_for', ['headers', 'body']) +@pytest.mark.parametrize('deadline', ['request', 'context']) +def test_worker_deadlines_abort_fetch_and_body_reads(monkeypatch, waiting_for, deadline): + import sys + from types import ModuleType + + controller = SimpleNamespace(signal=object(), aborted=False) + + def abort(): + controller.aborted = True + + controller.abort = abort + seen = [] + + async def stalled(): + await asyncio.Event().wait() + + async def body(): + if waiting_for == 'body': + await stalled() + return '{}' + + async def fetch(url, options): + seen.append(options) + if waiting_for == 'headers': + await stalled() + return SimpleNamespace(status=200, headers=SimpleNamespace(get=lambda *args: ''), text=body) + + js = ModuleType('js') + js.Object = SimpleNamespace(fromEntries=object()) + js.AbortController = SimpleNamespace(new=lambda: controller) + js.fetch = fetch + ffi = ModuleType('pyodide.ffi') + ffi.to_js = lambda value, **_: value + monkeypatch.setitem(sys.modules, 'js', js) + monkeypatch.setitem(sys.modules, 'pyodide.ffi', ffi) + monkeypatch.setattr(product_value, 'GEMINI_TIMEOUT', .01 if deadline == 'request' else 1) + monkeypatch.setattr(product_value, 'CONTEXT_TIMEOUT', .01 if deadline == 'context' else 1) + expected = product_value.GenerationError if deadline == 'request' else TimeoutError + with pytest.raises(expected) as failure: + asyncio.run(product_value.generate_context('key', 'prompt', {'stage': 'product_context'})) + if deadline == 'request': + assert failure.value.code == 'timeout' + assert controller.aborted and len(seen) == 1 + assert seen[0]['signal'] is controller.signal diff --git a/tests/integration/test_security_boundaries.py b/tests/integration/test_security_boundaries.py index b655d3f..a71613e 100644 --- a/tests/integration/test_security_boundaries.py +++ b/tests/integration/test_security_boundaries.py @@ -168,3 +168,89 @@ def fake(cmd, **kwargs): local._run_analysis('o/r', False) assert len(calls) >= 4 assert all('--hostname' in cmd and cmd[cmd.index('--hostname') + 1] == 'github.com' for cmd in calls) + + +def test_upstream_error_logs_never_include_provider_body_url_or_credentials(monkeypatch, caplog): + import json + import asyncio + import httpx + import github_api + + class FakeClient: + def __init__(self, **_): + pass + + async def __aenter__(self): + return self + + async def __aexit__(self, *_): + pass + + async def request(self, *_args, **_kwargs): + return httpx.Response(429, json={"error": "provider-body-secret"}, + headers={"X-GitHub-Request-ID": "header-secret"}) + + monkeypatch.setattr(httpx, "AsyncClient", FakeClient) + response = asyncio.run(github_api.request_json( + "https://generativelanguage.googleapis.com/v1beta/models/test:generateContent?key=url-secret", + headers={"x-goog-api-key": "key-secret"}, method="POST", body={"prompt": "prompt-secret"})) + assert response[0] == 429 + assert all(value not in caplog.text for value in ( + "provider-body-secret", "header-secret", "url-secret", "key-secret", "prompt-secret")) + event = json.loads(caplog.records[-1].message) + assert event == {"event": "upstream_http_error", "provider": "gemini", "http_status": 429} + + +@pytest.mark.parametrize("level,expected", [(20, "log"), (30, "warn"), (40, "error")]) +def test_worker_logs_emit_structured_objects(monkeypatch, level, expected): + import sys + import github_api + from types import ModuleType, SimpleNamespace + + emitted = [] + console = SimpleNamespace(**{name: (lambda value, name=name: emitted.append((name, value))) + for name in ("log", "warn", "error")}) + js = ModuleType("js") + js.console = console + js.Object = SimpleNamespace(fromEntries=object()) + ffi = ModuleType("pyodide.ffi") + ffi.to_js = lambda value, **_: value + monkeypatch.setitem(sys.modules, "js", js) + monkeypatch.setitem(sys.modules, "pyodide.ffi", ffi) + github_api.log_event(level, "generation_test", analysis_id="safe-id", error_code="output_truncated") + assert emitted == [(expected, {"event": "generation_test", "analysis_id": "safe-id", "error_code": "output_truncated"})] + + +def test_application_startup_keeps_diagnostics_without_httpx_url_logs(monkeypatch): + import asyncio + import contextlib + import io + import logging + import runpy + from pathlib import Path + import httpx + import github_api + + original_client = httpx.AsyncClient + transport = httpx.MockTransport(lambda _: httpx.Response(429, json={'error': 'body-secret'})) + output = io.StringIO() + root_logger = logging.getLogger() + with monkeypatch.context() as isolated: + isolated.setattr(root_logger, 'handlers', []) + isolated.setattr(root_logger, 'level', logging.WARNING) + isolated.setattr(logging.getLogger('httpx'), 'level', logging.NOTSET) + isolated.setattr(github_api.logger, 'level', logging.NOTSET) + isolated.setattr(httpx, 'AsyncClient', lambda **kwargs: original_client(transport=transport, **kwargs)) + try: + with contextlib.redirect_stderr(output): + runpy.run_path(str(Path(__file__).resolve().parents[2] / 'app.py')) + response = asyncio.run(github_api.request_json( + 'https://generativelanguage.googleapis.com/v1beta/models/test:generateContent?key=url-secret', + headers={'x-goog-api-key': 'header-secret'}, method='POST')) + github_api.log_event(logging.INFO, 'diagnostic_probe', analysis_id='safe-id') + finally: + for handler in root_logger.handlers: + handler.close() + assert response[0] == 429 + assert 'diagnostic_probe' in output.getvalue() and 'upstream_http_error' in output.getvalue() + assert all(value not in output.getvalue() for value in ('url-secret', 'header-secret', 'body-secret', 'HTTP Request:'))