Skip to content

Conversation

@ReneWerner87
Copy link
Member

@ReneWerner87 ReneWerner87 commented Dec 7, 2025

Summary

  • add reusable AST helpers for parsing import aliases and call-based assignments
  • tighten the session release migration to only annotate stores created from the session package
  • cover aliased and non-session store cases to prevent false positives

Testing

  • make lint
  • make test

Codex Task

Summary by CodeRabbit

  • New Features

    • Migration now more accurately detects real session stores before inserting defer cleanup, reducing false positives.
  • Bug Fixes

    • Avoids inserting defer statements for unrelated or non-session objects.
    • Better handling of aliased session imports so cleanup is applied correctly.
  • Tests

    • Added and updated tests covering non-session cases, aliased imports, and new constructor usage.

✏️ Tip: You can customize this high-level summary in your review settings.

Copilot AI review requested due to automatic review settings December 7, 2025 15:20
@ReneWerner87 ReneWerner87 requested a review from a team as a code owner December 7, 2025 15:20
@ReneWerner87 ReneWerner87 requested review from efectn, gaby and sixcolors and removed request for a team December 7, 2025 15:20
@coderabbitai
Copy link

coderabbitai bot commented Dec 7, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Adds Go AST helper utilities and tests, and integrates them into the session-release migration to ensure defer sess.Release() is only injected when the assigned variable originates from a session store created via session.New() (including aliased imports).

Changes

Cohort / File(s) Summary
AST Helper Utilities
cmd/internal/migrations/v3/ast_helpers.go
New helpers: parseGoFile(content string) (*ast.File, error), collectImportAliases(file *ast.File, importPath string) map[string]struct{}, and collectAssignedCallIdents(file *ast.File, predicate func(*ast.CallExpr) bool) map[string]struct{}.
AST Helper Tests
cmd/internal/migrations/v3/ast_helpers_test.go
Tests for parsing invalid/valid content, import alias extraction (default, explicit, blank, dot, unrelated), and collecting assigned identifiers from call expressions matching a predicate.
Session Release Migration
cmd/internal/migrations/v3/session_release.go
Integrates AST helpers to collect session import aliases and store variables created via New(); guards insertion of defer sess.Release() so it only runs when Get/ByID assignments originate from such session stores.
Session Release Migration Tests
cmd/internal/migrations/v3/session_release_test.go
Replaces NewStore() calls with New(); adds tests for ignoring non-session stores and handling aliased imports; updates expected defer-insertion outputs accordingly.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Inspect AST traversal in collectAssignedCallIdents for correct handling of multi-value assignments and ignored _ idents.
  • Verify collectImportAliases correctly derives basename aliases and excludes _ / . imports.
  • Confirm integration in session_release.go correctly matches Get/ByID assignment targets against discovered session store vars and doesn't over-filter valid cases.
  • Review updated tests to ensure they reflect intended constructor change (New()), aliasing, and negative cases.

Possibly related PRs

Suggested reviewers

  • sixcolors
  • gaby
  • efectn

Poem

🐰 I hopped through nodes of code and leaf,

found imports, names and assignment beef.
I nudged a defer where stores are born,
ignored the rest and kept the lawn.
Hooray — neat hops, no needless mourn! 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.77% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: improving session release migration targeting through AST-based analysis to prevent false positives.
Description check ✅ Passed The description covers the main objectives (AST helpers, tightened migration logic, handling aliased imports), includes testing steps, but lacks detailed explanation of the problem being solved.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/2025-12-07-15-20-25

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @ReneWerner87, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request refines the session release migration process by integrating new AST parsing utilities. These enhancements allow the migration tool to accurately identify and target session stores originating specifically from the session package, including those with aliased imports. This ensures that the defer session.Release() annotation is applied precisely where needed, improving the reliability and correctness of the migration by avoiding modifications to unrelated code.

Highlights

  • New AST Helpers: Introduced reusable Abstract Syntax Tree (AST) helper functions for parsing Go files, collecting import aliases, and identifying identifiers assigned from specific call expressions.
  • Improved Session Release Migration Targeting: The session release migration logic has been tightened to only annotate stores that are explicitly created from the github.com/gofiber/fiber/v3/middleware/session package, preventing unintended modifications.
  • Aliased and Non-Session Store Handling: The migration now correctly handles cases where the session package is imported with an alias and ensures that non-session stores are ignored, significantly reducing false positives.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces reusable AST helpers to improve the accuracy of the session release migration. The new logic correctly identifies session stores by parsing import aliases and call-based assignments, preventing false positives on stores from other packages. The changes also include new tests to cover aliased imports and non-session store scenarios.

My review has identified a couple of areas for improvement:

  • The new AST helper collectAssignedCallIdents has a logic issue that makes it brittle for functions with multiple return values.
  • The migration logic for identifying session store creation seems to be checking for a non-existent function NewStore, which could lead to incorrect migrations.

Details and suggestions are in the comments below.

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR improves the precision of the session release migration by using AST analysis to identify session stores from the correct package, preventing false positives from similarly-named packages or methods.

  • Introduces reusable AST helper functions for parsing Go files and extracting import aliases and call-based assignments
  • Enhances the session release migration to filter store variables based on package origin
  • Adds tests to verify correct handling of non-session packages and aliased imports

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.

File Description
cmd/internal/migrations/v3/ast_helpers.go New file containing reusable AST utility functions for import alias detection and call expression tracking
cmd/internal/migrations/v3/session_release.go Enhanced migration logic to use AST analysis for identifying session stores, preventing false positives
cmd/internal/migrations/v3/session_release_test.go Added test cases covering non-session store packages and aliased import scenarios

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
cmd/internal/migrations/v3/ast_helpers.go (1)

37-44: Blank and dot imports correctly filtered.

The implementation properly skips _ (blank) and . (dot) imports, which addresses the past review concern. These import types either don't provide a usable alias or would require different handling for the store variable matching logic.

🧹 Nitpick comments (1)
cmd/internal/migrations/v3/ast_helpers.go (1)

64-76: Potential index out of bounds if Lhs is shorter than Rhs.

While unlikely in well-formed Go code, if len(assign.Lhs) < len(assign.Rhs), accessing assign.Lhs[idx] at line 70 could panic. This could occur with malformed or partial AST representations.

Consider adding a bounds check:

 		for idx, rhs := range assign.Rhs {
 			call, ok := rhs.(*ast.CallExpr)
 			if !ok || !predicate(call) {
 				continue
 			}
 
+			if idx >= len(assign.Lhs) {
+				continue
+			}
+
 			ident, ok := assign.Lhs[idx].(*ast.Ident)
 			if !ok {
 				continue
 			}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e8aeaff and d9bd671.

📒 Files selected for processing (4)
  • cmd/internal/migrations/v3/ast_helpers.go (1 hunks)
  • cmd/internal/migrations/v3/ast_helpers_test.go (1 hunks)
  • cmd/internal/migrations/v3/session_release.go (3 hunks)
  • cmd/internal/migrations/v3/session_release_test.go (5 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
cmd/internal/migrations/v3/session_release_test.go (1)
cmd/internal/migrations/v3/session_release.go (1)
  • MigrateSessionRelease (20-165)
cmd/internal/migrations/v3/session_release.go (1)
cmd/internal/helpers.go (1)
  • ChangeFileContent (54-110)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Build (1.25.x, macos-13)
  • GitHub Check: Build (1.25.x, macos-latest)
  • GitHub Check: Build (1.25.x, windows-latest)
  • GitHub Check: Build (1.25.x, ubuntu-latest)
🔇 Additional comments (8)
cmd/internal/migrations/v3/session_release.go (2)

31-61: LGTM! AST-based targeting logic looks correct.

The implementation properly:

  1. Parses the file and collects session package aliases
  2. Identifies store variables assigned from session.New() calls
  3. Guards against processing files without the session import or store variables

The fix to use "New" instead of "NewStore" at line 56 aligns with the actual Fiber v3 session API.


76-79: Good guard against false positives.

This check ensures defer sess.Release() is only inserted when the store variable was actually created from the session package's New() function, preventing incorrect modifications to code using similarly-named methods from other packages.

cmd/internal/migrations/v3/ast_helpers_test.go (2)

18-64: Good test coverage for import alias edge cases.

The table-driven tests properly cover:

  • Default alias derivation from path basename
  • Explicit alias handling
  • Blank import (_) filtering
  • Dot import (.) filtering
  • Unrelated imports returning empty set

This addresses the past review concern about handling special import cases.


66-97: Test correctly validates assignment collection behavior.

The test verifies:

  • First identifier from multi-return assignments is captured (primary)
  • Single assignments are captured (single)
  • Blank identifiers (_) are correctly skipped
  • Calls to non-matching functions (other()) are excluded

One observation: secondary from primary, secondary := target() is not captured because the implementation matches Lhs[idx] to Rhs[idx], and there's only one RHS expression. This is the expected behavior for tracking store variables.

cmd/internal/migrations/v3/session_release_test.go (3)

29-29: API usage updated correctly.

Changed from session.NewStore() to session.New() to match the actual Fiber v3 session middleware API.


184-219: Excellent test for false positive prevention.

This test validates that store.Get() calls on stores from non-Fiber session packages are correctly ignored, preventing unintended code modifications.


221-258: Good coverage for aliased import handling.

This test ensures the migration correctly handles cases where the session package is imported with a custom alias (alias), and properly inserts the defer statement using the actual session variable name (session).

cmd/internal/migrations/v3/ast_helpers.go (1)

13-20: Clean implementation of Go file parsing.

The function properly wraps the parse error with context, making debugging easier when parsing fails.

@ReneWerner87
Copy link
Member Author

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request significantly improves the session release migration by using AST parsing to more accurately identify session store creation. This is a great enhancement that reduces the chance of false positives. The new AST helper functions are well-designed and reusable. I've identified a potential issue in collectAssignedCallIdents where it doesn't fully handle multiple return values from a function call, and I've provided a suggestion to make it more robust, along with a corresponding test update.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
cmd/internal/migrations/v3/ast_helpers_test.go (1)

53-63: Avoid range-variable capture pitfalls in parallel subtests (if supporting Go < 1.22)

In older Go versions, capturing tt directly in the subtest closure can cause all subtests to see the final loop value. If you still target Go < 1.22, consider rebinding inside the loop:

for name, tt := range tests {
	name, tt := name, tt
	t.Run(name, func(t *testing.T) {
		t.Parallel()
		// use tt here
	})
}

If the project requires Go 1.22+ only, this is purely stylistic and can be skipped.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d9bd671 and 1b1b0e7.

📒 Files selected for processing (2)
  • cmd/internal/migrations/v3/ast_helpers.go (1 hunks)
  • cmd/internal/migrations/v3/ast_helpers_test.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Build (1.25.x, windows-latest)
  • GitHub Check: Build (1.25.x, macos-latest)
  • GitHub Check: Build (1.25.x, macos-13)
  • GitHub Check: Build (1.25.x, ubuntu-latest)
🔇 Additional comments (5)
cmd/internal/migrations/v3/ast_helpers.go (3)

11-20: parseGoFile wrapper is clean and sufficient

Straightforward use of parser.ParseFile with a fresh FileSet and wrapped error context; nothing to change here.


22-50: Import alias collection correctly handles default, explicit, and special imports

The helper nicely filters by exact import path, skips blank/dot imports, and falls back to path.Base(importPath) when no alias is provided, which is exactly what the session migration needs.


52-93: Assignment walker correctly supports multi-return and multi-RHS calls

The split between len(assign.Rhs) == 1 (multi-return from a single call) and the indexed multi-RHS path covers a, b := target(), _, x := target(), and a, b := other(), target() while ignoring _ and non-ident LHS. This is a solid, generally reusable helper.

cmd/internal/migrations/v3/ast_helpers_test.go (2)

11-64: Good coverage for parsing and import alias handling

Tests exercise invalid content, default vs explicit aliases, and ensure blank/dot/unrelated imports are ignored, which aligns well with the helper’s responsibilities.


66-101: Assignment helper tests nicely cover multi-return and mixed-RHS cases

The test exercises target() in multi-return, single-return, ignored-identifier, and mixed other(), target() assignments, plus a selector LHS, which gives strong confidence in collectAssignedCallIdents.

@ReneWerner87
Copy link
Member Author

replace #251

@ReneWerner87
Copy link
Member Author

replaced by #251

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants