{"slug": "the-agentic-code-that-compiles-but-crashes-in-production", "title": "The Agentic Code That Compiles but Crashes in Production", "summary": "A developer outlined a set of defensive patterns for catching agent-generated Python code that passes CI but fails at runtime, including try-except guards around imports like `requests`, retry wrappers with exponential backoff and limits for external API calls, and explicit environment-variable checks that raise clear configuration errors at startup. The writeup also recommends running agentic output through the same GitHub Actions validation pipeline as hand-written code so failures surface early rather than in production.", "body_md": "You see a pull request where the agent generated a function that imports `requests` and calls an external API. The CI passes, but the service crashes in staging because the container lacks the library. This mismatch between sandbox and production is why good developers stay wary of agentic development.\n\nYou will learn how to spot hallucinated imports, add safety wrappers around external calls, and integrate agentic output into a CI pipeline so it fails fast instead of at runtime.\n\n``` php\n# Generated by an agent – looks fine locally\ndef fetch_data(url: str) -> dict:\n    import requests\n    resp = requests.get(url, timeout=5)\n    return resp.json()\n```\n\nThe snippet imports `requests` without checking if the package is installed. In a production container that only has `requests` in a dev-only extra, the import fails at runtime.\n\nYou can guard against this by adding a try-except around the import and falling back to a safe stub:\n\n``` php\ndef fetch_data(url: str) -> dict:\n    try:\n        import requests\n    except ImportError:\n        class MissingPackage:\n            def get(self, *args, **kwargs):\n                raise RuntimeError(\"The 'requests' package is missing in production.\")\n        requests = MissingPackage()\n    resp = requests.get(url, timeout=5)\n    return resp.json()\n```\n\nThe guard makes the failure explicit early, so you can add the missing dependency to your production image before the service starts.\n\nGenerated code often omits rate limiting or circuit breaking. An agent may produce a function that blindly retries on failure, exhausting a third-party quota.\n\n``` php\n# Agent output – no throttling\ndef query_service(payload: dict) -> str:\n    return httpx.post(\"https://api.example.com/endpoint\", json=payload).text\n```\n\nWrap it with a simple retry with exponential backoff and a limit:\n\n``` python\nimport httpx\nimport time\n\ndef query_service(payload: dict, max_retries: int = 3, base_delay: float = 0.5) -> str:\n    for attempt in range(max_retries + 1):\n        try:\n            resp = httpx.post(\"https://api.example.com/endpoint\", json=payload, timeout=10)\n            resp.raise_for_status()\n            return resp.text\n        except (httpx.HTTPStatusError, httpx.NetworkError) as exc:\n            if attempt == max_retries:\n                raise RuntimeError(f\"Service call failed after {max_retries} attempts\") from exc\n            delay = base_delay * (2 ** attempt)\n            time.sleep(delay)\n```\n\nThe wrapper ensures you do not hammer the external API and you get a clear error after the final attempt.\n\nAgents frequently reference environment variables without verifying they exist. A generated function might read a secret from `os.environ` that was never set in the deployment environment, causing an immediate crash on startup.\n\n``` php\n# Generated code – assumes the env var exists\ndef get_api_key() -> str:\n    return os.environ[\"API_KEY\"]\n```\n\nIf `API_KEY` is absent, this raises a `KeyError` with no context about whether the variable is misconfigured or genuinely missing. Replace the bare lookup with a helper that surfaces configuration errors clearly:\n\n``` php\ndef get_api_key() -> str:\n    key = os.environ.get(\"API_KEY\")\n    if key is None:\n        raise RuntimeError(\"Configuration error: 'API_KEY' is not set. Check your environment variables.\")\n    return key\n```\n\nThis pattern catches missing configuration at startup rather than failing later when the feature is actually used.\n\nEven well-checked generated code should be validated by the same pipeline as hand-written code. A minimal GitHub Actions workflow looks like this:\n\n```\nname: Validate Agentic Code\non: [push, pull_request]\njobs:\n  validate:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - name: Set up Python\n        uses: actions/setup-python@v5\n        with:\n          python-version: \"3.11\"\n      - name: Install dependencies\n        run: |\n          python -m pip install --upgrade pip\n          pip install -r requirements.txt\n      - name: Run unit tests\n        run: pytest\n      - name: Run static type check\n        run: mypy src/\n```\n\nThe workflow installs the exact dependencies you declare, runs unit tests, and runs a static type checker. This catches missing imports and type mismatches before the code reaches production.\n\nEven with guards, agentic output can introduce subtle bugs:\n\nMitigate these by treating generated code as a draft. Run a linter, enforce code-review checklists, and keep a log of which files were auto-generated.\n\n[Why are good developers so wary of agentic development?](https://martinfowler.com/rachels-ramblings/good-devs-wary.html) – I added concrete code examples for import guards, retry wrappers, and environment-variable handling, plus a full CI workflow, to show how you can safely incorporate agentic output into production-ready systems.\n\nThese write-ups are researched and published with no paywall, sponsor, or tracking. If one saved you an afternoon, a small tip keeps them coming.\n\nUSDT, USDC or USDD · TRC-20 (Tron)\n\n```\nTFTNsfyomKrnUutRjBTGVULp19ByW29KbY\n```\n\n", "url": "https://wpnews.pro/news/the-agentic-code-that-compiles-but-crashes-in-production", "canonical_source": "https://dev.to/robust_true_try/the-agentic-code-that-compiles-but-crashes-in-production-i3", "published_at": "2026-10-29 21:41:50+00:00", "updated_at": "2026-10-29 21:47:52.662414+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools", "mlops"], "entities": ["GitHub Actions", "Python", "requests", "httpx"], "also_reported_by": [], "alternates": {"html": "https://wpnews.pro/news/the-agentic-code-that-compiles-but-crashes-in-production", "markdown": "https://wpnews.pro/news/the-agentic-code-that-compiles-but-crashes-in-production.md", "text": "https://wpnews.pro/news/the-agentic-code-that-compiles-but-crashes-in-production.txt", "jsonld": "https://wpnews.pro/news/the-agentic-code-that-compiles-but-crashes-in-production.jsonld"}}