📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Code review: an AI coding agent opened a PR adding a CSV price-import endpoint to an ASP.NET Core API. It compiles, CI is green and the agent's own tests pass, but it pins an old Newtonsoft.Json version and has subtle bugs. Walk me through what you find, how you rank it, and how you close the review.

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.

Senior CodeReview Advanced ai aspnet-core code-review ef-core supply-chain-security testing

🎯 Key points

  • Green CI and agent-written tests prove only self-consistency; review against the requirement
  • Security first: endpoint missing RequireAuthorization; unbounded upload size
  • Fire-and-forget Task.Run with a scoped DbContext and request stream: ObjectDisposedException, lost work, unobserved exceptions
  • decimal.Parse without CultureInfo.InvariantCulture: wrong prices on servers with a different culture
  • Validate first, then one SaveChangesAsync (or an explicit transaction) so failures leave no partial import
  • Failures returned as ProblemDetails with per-row errors and logged with structured fields, not swallowed
  • Newtonsoft.Json 12.0.x pinned: GHSA-5crp-9r3c-p9vr (deep nesting DoS), fixed in 13.0.1; and unneeded next to System.Text.Json
  • Close with blocking vs suggested comments and a reusable agent-PR checklist; automate findings (CA1305, NuGetAudit errors, fallback auth policy)

⏱ 30-second answer

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:

  • Security: the endpoint has no RequireAuthorization() and no upload size limit.
  • Stall or lost work: Task.Run fire-and-forget using a scoped DbContext after the request ends.
  • Wrong data: decimal.Parse without CultureInfo.InvariantCulture, and no transaction, so failures leave half-imported prices.
  • Supply chain: Newtonsoft.Json 12.0.x pinned, with a known DoS advisory fixed in 13.0.1, and not needed at all.
  • Tests: 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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.Run with the request's DbContext, which is disposed when the request ends, so imports randomly failed with ObjectDisposedException and nobody saw it. It parsed prices with decimal.Parse on the server's culture, so on [an instance configured for a culture using comma decimals] 12.50 became 1250. It saved each row separately with no transaction. And it had pinned Newtonsoft.Json 12.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 asserted Save was 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."


Code under review

// 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));
}

Findings, ranked by severity

# 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

The rewrite

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, []));
    }
}

How I'd close the review

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).

Production example

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.

🔍 What the interviewer is checking

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

  • Discounts green CI because the agent wrote the tests
  • Finds the auth gap and fire-and-forget scope bug first
  • Spots culture parsing, partial writes and the vulnerable package
  • Gives a clear rewrite and blocking vs suggested comments
  • Turns findings into analysers, audit settings and instruction rules

Red flags

  • Comments on naming and formatting first
  • Approves because tests pass
  • Misses the security or data-integrity issues
  • No follow-up to stop it recurring

📚 Learn in depth

1. Why agent PRs need a different review

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 ──┘

2. A review checklist for agent PRs

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.

3. Fire-and-forget and scoped services

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.

4. Culture-sensitive parsing

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.

5. Transactions in EF Core

  • A single SaveChangesAsync call wraps all tracked changes in one database transaction, so "validate everything, then save once" is atomic without extra code.
  • When you need several saves or raw SQL in the same unit, use an explicit transaction:
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
  • With 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.
  • For very large files use 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.

6. The vulnerable dependency

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.

7. Errors, logging and tests that prove behaviour

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

Try it yourself

  1. Reproduce the culture bug: set CultureInfo.CurrentCulture = new("de-DE") and parse "12.50".
  2. Write an endpoint that uses a DbContext inside Task.Run and run a load test; watch for ObjectDisposedException.
  3. Add Newtonsoft.Json 12.0.3 to a project and run dotnet restore; read the NuGetAudit warning.
  4. Enable CA1305 as an error in .editorconfig and count the violations in your codebase.
  5. Rewrite a mock-only test as a WebApplicationFactory test and see which bugs it finds.

💻 Code

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>

⚠ Common mistakes

  • Mistake: Approving because CI is green. Why it is wrong: the agent wrote the tests, so they share its assumptions. Instead: review against the ticket and require tests derived from it.
  • Mistake: Reviewing AI PRs more lightly because the code looks clean. Why it is wrong: AI defects hide in assumptions, not style. Instead: check lifetimes, culture, partial failure, auth and dependencies explicitly.
  • Mistake: Accepting tests that only mock and verify calls. Why it is wrong: mocks replace exactly the behaviour that fails in production (EF Core translation, transactions, auth, model binding), so the suite can't catch these bugs. Instead: keep unit tests for pure logic and add integration tests with WebApplicationFactory and Testcontainers for anything that writes data.
  • Mistake: Accepting fire-and-forget 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.
  • Mistake: Ignoring culture in parsing. Why it is wrong: prices change by orders of magnitude on a different culture. Instead: CultureInfo.InvariantCulture and CA1305 as an error.
  • Mistake: Saving row by row without a transaction. Why it is wrong: failures leave inconsistent data and it's slow. Instead: validate first, then one SaveChangesAsync or a set-based bulk path inside a transaction.
  • Mistake: Letting errors disappear. Why it is wrong: the caller gets 202 and nobody learns the import failed. Instead: return ProblemDetails with per-row errors and log the outcome with structured fields (file name, rows, failures, user).
  • Mistake: Letting a pinned old package through because "it builds". Why it is wrong: it brings known vulnerabilities. Instead: NuGetAudit as an error and remove packages that aren't needed.
  • Mistake: Fixing the PR but not the process. Why it is wrong: the next agent PR repeats the same mistakes. Instead: add instruction rules, analysers, CODEOWNERS and an agent-PR checklist.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says agent-written tests can't be trusted Why: Checks how they verify AI-generated tests in general
    How to answer

    AI is a strong first pass, never the final check.

    • Code review: tools like Copilot code review catch missing null checks, undisposed resources, inconsistent naming and obvious logic slips in seconds, so humans can focus on design and domain rules. It comments; a human still approves.
    • Tests: great for scaffolding and edge-case lists, risky as proof: generated tests often assert what the code does, not what it should do. Check them by breaking the code or with mutation testing (Stryker.NET).
    • Docs: fast drafts of XML comments, READMEs and ADR skeletons; every statement is checked against the code.

    The trade-off: minutes saved on drafting against the risk of false confidence, so verification is part of the workflow.

  2. When: Candidate mentions NuGetAudit or the vulnerable Newtonsoft.Json version Why: Checks depth on dependency scanning policy in CI
    How to answer

    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.

  3. When: Candidate mentions agents adding packages Why: Checks awareness of hallucinated packages and slopsquatting
    How to answer

    AI-generated code carries the usual risks plus some new ones:

    • Insecure patterns: models reproduce what's common, such as string-built SQL, a certificate callback that returns true, MD5, or a missing [Authorize].
    • Hallucinated packages: the model names a NuGet or npm package that doesn't exist, and attackers register those names (slopsquatting).
    • Licence exposure from suggestions matching public code, and data leakage when secrets or personal information go into prompts.
    • Poisoned context: instruction files or docs that steer agent mode into unsafe edits or commands.

    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.

🛠 Real-world problems: how you handle them

Agent-written price import passed CI and overwrote prices in production
Situation
[An e-commerce platform] with [~40,000 SKUs] merged an agent-generated CSV price import after a quick review. The first real import from [the merchandising team] ran on [a Windows App Service instance with a non-English culture].
Signals
Customer reports of prices [100x] too high on [~3,000] products; some products updated and others not; no errors in the API logs; Application Insights showed `ObjectDisposedException` traces from a background thread.
Investigation
Compared the CSV with the database: every price with a decimal point had lost it, so checked `CurrentCulture` on the instance. Traced the partial import to the fire-and-forget task losing its `DbContext` when the request ended. Read the PR: tests only verified mock calls. Ran `dotnet list package --vulnerable` and found the pinned Newtonsoft.Json advisory as well.
Resolution
Immediately restored prices from the [hourly] audit table and disabled the endpoint with a feature flag. Then shipped the rewrite: authorisation, size limit, CsvHelper with invariant culture, validate-then-apply in one transaction, per-row error report, and removed Newtonsoft.Json.
Prevention
CA1305 and NuGetAudit high/critical as build errors; fallback authorisation policy; `WebApplicationFactory` + Testcontainers tests required for endpoints that write data; CODEOWNERS on pricing; instruction-file rules for agents; a review checklist for agent PRs (auth, lifetimes, culture, transactions, dependencies).

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.

More in AI-Assisted Development

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me