Providing LLM Codegen Best Practices
The user is asking about safe LLM code generation practices, likely seeking guidance. I’ll structure the answer by touching on key areas: a threat model, workflow, and tooling.
Guardrails will include prompts, constraints, patterns, and security guidelines. For diff reviews, I'll suggest a PR style, code review checklist, and static analysis tools.
Unit tests and fuzzing are essential too, as well as integration tests. I should also mention privacy concerns like data handling, avoiding secrets, and using enterprise options for redaction and on-prem models. Additionally, mitigations such as sandboxing and least privilege will be covered.
1) Guardrails for LLM-generated code (before it hits your repo)
Constrain the task
- Require small, incremental diffs (“change only X file(s); do not refactor unrelated code”).
- Provide explicit non-goals: “no new dependencies”, “don’t change public APIs”, “no network calls”, etc.
- Ask for design intent first: brief plan + risks + test plan, then code.
Constrain the output
- Prefer “patch format” or “unified diff” output to avoid hidden edits.
- Require: “list assumptions”, “list files modified”, “explain why each change is needed”.
Security-by-default prompts
- State rules: parameterized SQL, no shell string concatenation, validate input, avoid
eval, avoid insecure crypto, no logging secrets, correct authz checks.
- Request secure patterns: least privilege, explicit allowlists, timeouts/retries, safe deserialization.
Execution guardrails
- Run generated code only in a sandbox (container/VM) with:
- no production credentials
- restricted network egress
- read-only mounts where possible
- resource limits (CPU/mem/time)
- Keep a “no direct prod access” rule for AI-assisted changes.
Dependency guardrail
- Default stance: no new deps unless justified.
- If deps are added: pin versions, verify license, run SCA (software composition analysis), and add to SBOM.
2) Diff review workflow (treat LLM like a junior contributor)
Make every change a PR with mandatory checks
- Enforce branch protection: tests + lint + security scans must pass.
- Require human review for:
- auth/authz, cryptography, payment flows, PII handling
- infra/IaC, CI/CD scripts, permission changes
- anything that touches secrets, logging, telemetry
Review checklist (fast, effective)
- Scope: Is the diff minimal? Any unrelated refactors?
- Correctness: Edge cases, null/empty, concurrency, error handling.
- Security: input validation, injection risks, file/path traversal, SSRF, deserialization, authz.
- Privacy: logging of identifiers? new telemetry? data retention?
- Operational: timeouts, retries, idempotency, backward compatibility.
- Maintainability: clear names, comments only where needed, consistent style.
Automate diff scrutiny
- Static analysis (language-specific): e.g., Semgrep, CodeQL.
- Secret scanning: GitHub secret scanning / gitleaks.
- SAST + IaC scanning: Checkov/Terrascan for Terraform/K8s.
- Dependency scanning: Dependabot/Snyk/OSV-Scanner.
- Add “danger rules” to flag sensitive files (auth, payments, infra).
3) Unit tests (and beyond) to catch subtle LLM mistakes
Require tests as part of the change
- Policy: “No code without tests” for non-trivial behavior.
- Prefer behavioral tests over implementation-detail tests.
What to test (common LLM failure modes)
- Boundary conditions: empty input, max sizes, unicode, timezones.
- Error paths: exceptions, network failures, partial failures.
- Security invariants: auth required, role checks, allowlist enforcement.
- Determinism: stable sorting, consistent formatting.
- Regression tests: reproduce the bug with a failing test first.
Add stronger testing where it matters
- Property-based tests (Hypothesis/QuickCheck style) for parsing/validation.
- Fuzzing for parsers/decoders and file format handling.
- Integration tests for API endpoints and DB interactions (use test containers).
- Mutation testing (optional) to measure test quality on critical modules.
CI gating
- Run tests in clean env; fail on warnings for critical modules.
- Coverage thresholds can help, but don’t substitute for meaningful assertions.
4) Privacy & data handling (avoid leaking sensitive info to the model)
Data minimization
- Never paste secrets, private keys, tokens, customer data, or proprietary dumps.
- Use synthetic examples and redact logs/stack traces.
- If you must share code context, share the smallest excerpt needed.
Redaction tooling
- Pre-commit hooks or chat-side tooling to remove:
- API keys, JWTs, connection strings, emails, phone numbers
- internal hostnames, customer identifiers
- Maintain an allowlist of what’s okay to send.
Choose the right deployment model
- For sensitive codebases: enterprise plans or self-hosted/on-prem models where:
- prompts/responses are not used for training by default
- retention is configurable/short
- access is audited and role-based
Policy + training
- Define what engineers may send to an LLM.
- Keep an audit trail for AI-assisted changes (PR labels, metadata).
Watch generated code for privacy regressions
- New logging statements, debug dumps, “temporary” telemetry.
- Accidental inclusion of real sample data in tests/docs.
- Changes that expand data collection or retention.
A practical “safe codegen” pipeline (quick template)
- Engineer writes a tight prompt + constraints + asks for a plan.
- LLM returns plan + patch + test plan.
- Apply patch to a branch; run formatter + lint locally.
- CI runs: unit/integration tests, SAST, secret scan, dependency scan.
- Human review with a security/privacy checklist for sensitive areas.
- Merge with protected branch rules; monitor with rollout/feature flags if risky.
If you tell me your stack (language, framework, repo host, CI), I can suggest a concrete set of tools and PR checks tailored to it.