Skip to content

Conversation

@carcer
Copy link
Contributor

@carcer carcer commented Jan 11, 2026

This PR fixes a code generation bug where route parameters were used before they were declared when combining [WriteAggregate]/[ReadAggregate] attributes with Load/Before midleware methods.

The fix ensures MartenBatchFrame properly declares its dependencies on variables used by batchable frames, allowing the code generation topological sort to order frames correctly.

Issue

When an endpoint combined:

  1. A middleware method like Load(Guid id) or Before(Guid id)
  2. A [WriteAggregate] or similar attribute

The generated code would fail with CS0841: Cannot use local variable 'id' before it is declared because:

  • The batch query enlistment code tried to use the route parameter id
  • But the route parameter variable was declared AFTER the batch query code
  • This happened because MartenBatchFrame didn't declare its dependencies on route parameters

Root Cause

The MartenBatchFrame.FindVariables() method only yielded IDocumentSession and CancellationToken, but not the variables that its batchable frames (like LoadAggregateFrame) needed.

Solution

Adjusted MartenBatchFrame.FindVariables() to also enumerate and yield all variables that its enlisted batchable frames depend on.

Test Results

reacting_to_read_aggregate was modified to add Load and Before., this cuased 3 tests to fail. Adding the fix makes them pass, and not additional tests to fail.

Generated Code Verification

The generated code now correctly declares the route parameter before using it in the batch query:

// Before (broken):
var stream_letters_BatchItem = batchedQuery.Events.FetchForWriting<LetterAggregate>(id);  // ERROR: id not declared
await batchedQuery.Execute(httpContext.RequestAborted);
string id_rawValue = (string?)httpContext.GetRouteValue("id");
System.Guid id = default;

// After (correct):
string id_rawValue = (string?)httpContext.GetRouteValue("id");
System.Guid id = default;
var batchedQuery = documentSession.CreateBatchQuery();
var stream_letters_BatchItem = batchedQuery.Events.FetchForWriting<LetterAggregate>(id);  // OK: id declared
await batchedQuery.Execute(httpContext.RequestAborted);

@jeremydmiller jeremydmiller merged commit a630a81 into JasperFx:main Jan 12, 2026
1 check passed
@carcer carcer deleted the missed_vars branch January 12, 2026 14:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants