Reviewing an AI-generated pull request: missing authorisation, fire-and-forget work, culture-dependent parsing, partial writes, a vulnerable pinned dependency and self-confirming tests, ranked by severity with a rewrite and review-closing policy.
I review an AI-generated PR against the requirement, not against its own tests, because agent-written tests mostly prove the code agrees with itself. Ranked by severity, I'd expect to find:
RequireAuthorization() and no upload size limit.Task.Run fire-and-forget using a scoped DbContext after the request ends.decimal.Parse without CultureInfo.InvariantCulture, and no transaction, so failures leave half-imported prices.Newtonsoft.Json 12.0.x pinned, with a known DoS advisory fixed in 13.0.1, and not needed at all.Verify on mocks only.I block on the first four, then fix the process so the next agent PR can't repeat them. The trade-off: agents make drafting cheap, so review is now the expensive step.
"With an AI-generated PR, the first thing I do is ignore the green tick. The agent wrote the code and the tests, so a passing suite only proves the two agree. I read the ticket, write down what must be true, and review against that. Then I go through it in severity order: security holes and stalls first, then wrong data, then diagnostics, then design.
For example, at [company] I reviewed [an agent PR] much like this one. The endpoint had no authorisation, so anyone with the URL could change prices. It returned 202 and did the import in
Task.Runwith the request'sDbContext, which is disposed when the request ends, so imports randomly failed withObjectDisposedExceptionand nobody saw it. It parsed prices withdecimal.Parseon the server's culture, so on [an instance configured for a culture using comma decimals]12.50became1250. It saved each row separately with no transaction. And it had pinnedNewtonsoft.Json12.0.3, which has a known advisory for deeply nested JSON, in a project that already used System.Text.Json. The tests mocked the repository and assertedSavewas called [n] times. [Result: we caught it before merge; the rewrite imported 50,000 rows in X seconds instead of Y.]The mistake I see is reviewing AI PRs more lightly because they look tidy. They need a different kind of attention: AI code is clean on the surface and wrong in the assumptions. So I block on the real issues, and then I fix the system: an instructions file rule, NuGetAudit as an error, CODEOWNERS on the pricing module. Reviewing the agent's output once is good; making the next output better is the senior part."
// Program.cs (excerpt)
app.MapPost("/api/prices/import", async (IFormFile file, PricingDbContext db, ILogger<Program> log) => // 1, 2
{
_ = Task.Run(async () => // 3
{
using var reader = new StreamReader(file.OpenReadStream());
while (await reader.ReadLineAsync() is { } line)
{
var parts = line.Split(','); // 4
var product = await db.Products.FirstAsync(p => p.Sku == parts[0]); // 5
product.Price = decimal.Parse(parts[1]); // 6
await db.SaveChangesAsync(); // 7
}
log.LogInformation("Import done");
});
return Results.Accepted();
}).DisableAntiforgery();
<!-- Pricing.Api.csproj -->
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" /> <!-- 8 -->
// Agent-written test // 9
[Fact]
public async Task Import_saves_prices()
{
var repo = new Mock<IPriceRepository>();
await new PriceImporter(repo.Object).ImportAsync("SKU1,10\nSKU2,20");
repo.Verify(r => r.Save(It.IsAny<Product>()), Times.Exactly(2));
}
| # | Severity | Finding | Why it matters |
|---|---|---|---|
| 1 | Security hole | No RequireAuthorization("PricingAdmin"); antiforgery disabled with no other protection |
Anyone who can reach the API can change every price |
| 2 | Security / availability | No size limit on the upload; the whole file is processed | Large files exhaust memory and CPU |
| 3 | Stall / lost work | Fire-and-forget Task.Run captures the scoped DbContext and the IFormFile |
Both are disposed when the request ends: ObjectDisposedException, partial imports, exceptions unobserved |
| 4 | Wrong data | Split(',') breaks on quoted fields; no header handling; parts[1] may not exist |
Rows silently skipped or the import crashes midway |
| 5 | Wrong data | FirstAsync throws on an unknown SKU, mid-file |
Half the file applied, the rest not |
| 6 | Wrong data | decimal.Parse uses the current culture |
12.50 parses as 1250 under a comma-decimal culture |
| 7 | Wrong data / performance | SaveChangesAsync per row, no transaction |
Inconsistent prices on failure; 50,000 round trips |
| 8 | Supply chain | Newtonsoft.Json 12.0.3: advisory GHSA-5crp-9r3c-p9vr (DoS via deeply nested JSON), fixed in 13.0.1; unused alongside System.Text.Json |
Known vulnerability added for no benefit |
| 9 | Diagnostics / tests | Tests verify mock calls only; no failure paths; endpoint not tested | Green CI hides every bug above |
| 10 | Design | No result for the caller: which rows failed and why | Users can't fix their file |
Validate the whole file first, then apply it in one transaction and return a per-row report. Imports of this size (up to [50,000] rows) fit comfortably in a request; for larger ones, store the file and hand it to a background worker with its own scope.
namespace Pricing.Api.Import;
public sealed record ImportRow(int Line, string Sku, decimal Price);
public sealed record ImportError(int Line, string Message);
public sealed record ImportResult(int Updated, IReadOnlyList<ImportError> Errors);
public static class PriceImportEndpoint
{
public static void Map(IEndpointRouteBuilder app) =>
app.MapPost("/api/prices/import", HandleAsync)
.RequireAuthorization("PricingAdmin") // 1: only pricing admins
.WithMetadata(new RequestSizeLimitAttribute(5_000_000)) // 2: 5 MB cap
.DisableAntiforgery(); // token-authenticated API, no cookies
private static async Task<Results<Ok<ImportResult>, ValidationProblem>> HandleAsync(
IFormFile file, PricingDbContext db, CancellationToken ct)
{
var (rows, errors) = await CsvPriceParser.ParseAsync(file.OpenReadStream(), ct); // 4, 6: CsvHelper, invariant culture
var skus = rows.Select(r => r.Sku).ToHashSet();
var products = await db.Products.Where(p => skus.Contains(p.Sku)).ToDictionaryAsync(p => p.Sku, ct);
foreach (var row in rows)
{
if (products.TryGetValue(row.Sku, out var product)) product.Price = row.Price;
else errors.Add(new(row.Line, $"Unknown SKU '{row.Sku}'")); // 5: report, don't throw
}
if (errors.Count > 0) // all or nothing
return TypedResults.ValidationProblem(errors.ToDictionary(e => $"line {e.Line}", e => new[] { e.Message }));
await db.SaveChangesAsync(ct); // 3, 7: one transaction, inside the request scope
return TypedResults.Ok(new ImportResult(rows.Count, []));
}
}
| Comment | Type |
|---|---|
| Add authorisation policy and size limit | Blocking |
| Remove fire-and-forget; process inside the request or via a queued worker with its own scope | Blocking |
| Invariant-culture parsing with a real CSV parser; validate before applying; single transaction | Blocking |
Remove Newtonsoft.Json (or upgrade to 13.0.x if truly needed) |
Blocking |
Replace mock-only tests with WebApplicationFactory + Testcontainers SQL Server tests from the requirement |
Blocking |
| Return a per-row error report | Suggested |
Process follow-ups: NuGetAudit warnings NU1903/NU1904 as errors, a copilot-instructions.md rule ("no Task.Run in endpoints; parse numbers with CultureInfo.InvariantCulture; ask before adding packages"), CODEOWNERS for /src/Pricing, and an analyser rule banning decimal.Parse without a format provider (CA1305).
The rewritten import handled [50,000] rows in about [4 seconds] with [1] database round trip for reads and one transaction for writes, versus [~3 minutes] and partial failures before. NuGetAudit as an error has since blocked [2] vulnerable package additions from agent PRs.
Checks whether the candidate can review AI-generated code against the requirement, rank findings by real impact, and improve the process, not just the PR.
Green flags
Red flags
An agent optimises for "build and tests pass". It writes the tests, so passing is a weak signal. Its code is also stylistically clean, which lowers reviewer suspicion. The defects cluster in assumptions: lifetimes, culture, partial failure, security context and dependencies.
ticket ──► agent ──► code + tests (same assumptions) ──► CI green
│ │
└───────── reviewer compares against the ticket, not the tests ──┘
Keep it in the PR template so the author (human or agent) and the reviewer use the same list:
| Check | Question |
|---|---|
| Requirement | Does each acceptance criterion have a test written from the ticket? |
| Security | Auth policy on every endpoint? Input limits? Secrets? |
| Lifetimes | Any scoped service, HttpContext or request stream used after the request? |
| Data integrity | What happens if it fails halfway? One transaction? Idempotent retry? |
| Parsing and formats | Culture, time zones, encodings explicit? |
| Errors and logging | Failures returned as ProblemDetails and logged with structured fields? |
| Dependencies | Any new or pinned package? Needed? NuGetAudit clean? |
| Scope | Files changed outside the ticket? Revert them. |
In ASP.NET Core, DbContext is registered as scoped: one instance per request, disposed when the request scope ends. IFormFile streams are also tied to the request. Task.Run without awaiting lets the request complete and the scope dispose while the background code still runs, so you get ObjectDisposedException or reads from a closed stream. Exceptions in an unobserved task don't reach the client or the exception handler middleware. If you truly need background work: write the file to Blob Storage, enqueue a message, and process it in a BackgroundService that creates its own scope with IServiceScopeFactory, disposing the scope and streams with using/await using.
decimal.Parse(string) uses CultureInfo.CurrentCulture. Containers often run with invariant culture, but a Windows VM or an app with RequestLocalization can run as de-DE or similar, where , is the decimal separator and . a group separator. Then 12.50 parses as 1250. Data formats must use CultureInfo.InvariantCulture; analyser CA1305 flags the missing provider.
SaveChangesAsync call wraps all tracked changes in one database transaction, so "validate everything, then save once" is atomic without extra code.await using var tx = await db.Database.BeginTransactionAsync(ct);
await db.Products.Where(p => p.IsDiscontinued).ExecuteUpdateAsync(s => s.SetProperty(p => p.Price, 0m), ct);
await db.SaveChangesAsync(ct);
await tx.CommitAsync(ct); // disposal without commit rolls back
EnableRetryOnFailure (common on Azure SQL), wrap the explicit transaction in db.Database.CreateExecutionStrategy().ExecuteAsync(...), otherwise EF Core throws because a user transaction can't be retried safely.SqlBulkCopy into a staging table and a set-based MERGE inside one transaction, and add optimistic concurrency (rowversion) if other users edit prices at the same time.GitHub advisory GHSA-5crp-9r3c-p9vr: Newtonsoft.Json before 13.0.1 can be driven into excessive resource use by deeply nested JSON. Agents pin versions they saw often in training data, which skews old. NuGetAudit reports it during restore (NU1903 for high severity); making high and critical audit warnings errors turns it into a build break. The better fix is removing the package: .NET 10 APIs use System.Text.Json.
Return failures as ProblemDetails (TypedResults.ValidationProblem) with a per-row error list, and log one structured event per import ({FileName} {Rows} {Failed} {UserId}), never the file contents. Then replace mock verification with tests that exercise the endpoint end to end:
WebApplicationFactory<Program> ──► real routing, auth, model binding, size limit
Testcontainers (SQL Server) ──► real transaction and query behaviour
test cases from the ticket ──► unknown SKU, bad price, quoted field, culture, unauthorised user
CultureInfo.CurrentCulture = new("de-DE") and parse "12.50".DbContext inside Task.Run and run a load test; watch for ObjectDisposedException.Newtonsoft.Json 12.0.3 to a project and run dotnet restore; read the NuGetAudit warning..editorconfig and count the violations in your codebase.WebApplicationFactory test and see which bugs it finds.A requirement-based integration test for the rewrite, and the build settings that make the reviewer's findings automatic next time.
namespace Pricing.Api.Tests;
public sealed class PriceImportTests(PricingApiFactory factory) : IClassFixture<PricingApiFactory>
{
[Fact]
public async Task Unauthorised_user_cannot_import()
{
var client = factory.CreateClient(); // no token
var response = await client.PostAsync("/api/prices/import", Csv("Sku,Price\nSKU1,10.00"));
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task Unknown_sku_rejects_the_whole_file_and_changes_nothing()
{
var client = factory.CreateAuthenticatedClient(role: "PricingAdmin");
var response = await client.PostAsync("/api/prices/import", Csv("Sku,Price\nSKU1,12.50\nNOPE,1.00"));
response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
(await factory.PriceOf("SKU1")).Should().Be(10.00m); // unchanged: all or nothing
}
[Fact]
public async Task Prices_parse_with_invariant_culture()
{
CultureInfo.CurrentCulture = new CultureInfo("de-DE"); // a comma-decimal culture
var client = factory.CreateAuthenticatedClient(role: "PricingAdmin");
await client.PostAsync("/api/prices/import", Csv("Sku,Price\nSKU1,12.50"));
(await factory.PriceOf("SKU1")).Should().Be(12.50m); // not 1250
}
private static MultipartFormDataContent Csv(string body) =>
new() { { new StringContent(body), "file", "prices.csv" } };
}
# .editorconfig: culture-sensitive parsing is a build error
[*.cs]
dotnet_diagnostic.CA1305.severity = error
<!-- Directory.Build.props: high and critical NuGet advisories break the build -->
<PropertyGroup>
<NuGetAudit>true</NuGetAudit>
<NuGetAuditMode>all</NuGetAuditMode>
<WarningsAsErrors>$(WarningsAsErrors);NU1903;NU1904</WarningsAsErrors>
</PropertyGroup>
WebApplicationFactory and Testcontainers for anything that writes data.Task.Run in an endpoint. Why it is wrong: scoped services and the request stream are disposed, and exceptions vanish. Instead: do the work in the request or queue it to a BackgroundService with its own scope.CultureInfo.InvariantCulture and CA1305 as an error.SaveChangesAsync or a set-based bulk path inside a transaction.Agents shift effort from writing to reviewing, so a senior reviewer's leverage is in turning each finding into a guard that applies to every future PR: an analyser rule, an audit setting, an instruction-file line, an architecture test. If the same finding appears twice, it should have become automation after the first time.
| Finding type | Best guard | Cost | When a human must still look |
|---|---|---|---|
| Culture-sensitive parsing | CA1305 as error | One-off clean-up | Custom formats and user-facing input |
| Vulnerable or unneeded package | NuGetAudit as error, allow-list | Some build breaks | Choosing between alternatives |
| Fire-and-forget in endpoints | Custom analyser or architecture test | Writing the rule | Legitimate background designs |
| Missing authorisation | Fallback policy requiring authenticated users | Explicit AllowAnonymous where needed |
Which role or policy is right |
| Weak tests | Mutation testing on critical modules | CI time | Whether tests match the requirement |
A useful habit is setting FallbackPolicy so every endpoint requires authentication unless marked otherwise; then a forgotten RequireAuthorization fails safe.
AI is a strong first pass, never the final check.
The trade-off: minutes saved on drafting against the risk of false confidence, so verification is part of the workflow.
I use NuGetAudit, which runs during dotnet restore and reports known vulnerabilities as NU1901-NU1904 (low to critical). With the .NET 10 SDK, net10.0 projects audit transitive packages by default (NuGetAuditMode=all). For policy, I set WarningsAsErrors for NU1903 and NU1904 in CI so high and critical findings fail the build, while low and moderate stay as warnings with tickets. Reviewed false positives get a NuGetAuditSuppress entry with the advisory URL and a recorded expiry. dotnet list package --vulnerable --include-transitive --format json feeds reports. Dependabot opens grouped upgrade PRs and security updates. If restore uses only a private feed, I add <auditSources> pointing at nuget.org. And I scan container images separately. Trade-off: strict gates on transitive findings can block a release for an unreachable code path, so exceptions must be quick, visible and time-boxed.
AI-generated code carries the usual risks plus some new ones:
true, MD5, or a missing [Authorize].Control it with the gates you already need (SAST, secret scanning, dependency review, human approval) plus package source mapping, lock files and allow-lists, content exclusions and a data policy. The trade-off: a little friction on new dependencies in exchange for closing the cheapest attack path.
How to tell it (STAR)
**S:** At [company], an agent-generated price import passed CI and review, and its first real run set [~3,000] prices [100x] too high and left others unchanged. **T:** I led the fix and the follow-up. **A:** I restored prices from the audit table and flagged the endpoint off, then found three root causes: culture-dependent parsing, a fire-and-forget task losing its `DbContext`, and mock-only tests. I rewrote it to validate then apply in one transaction with invariant parsing and authorisation, and turned each cause into a guard: CA1305 and NuGetAudit as errors, integration tests for write endpoints, and an agent PR checklist. **R:** Prices were correct within [40 minutes], the new import handles [50,000] rows in [~4 seconds], and the guards have blocked [several] similar issues since.
Last updated 23 Nov 2026.