Skip to content

Conversation

@gaby
Copy link
Member

@gaby gaby commented Dec 24, 2025

Summary

  • clear session data maps in session middleware without reallocating to retain capacity between pool uses
  • add regression coverage ensuring pooled data reuses the same map after reset and does not leak prior entries

@gaby gaby requested a review from a team as a code owner December 24, 2025 15:08
@gaby gaby requested review from Copilot and sixcolors December 24, 2025 15:08
@gaby gaby requested review from ReneWerner87 and efectn December 24, 2025 15:08
@gaby gaby added the codex label Dec 24, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 24, 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

Reset now clears the existing session data map with clear(d.Data) instead of allocating a new map, preserving the map reference for pool reuse. Tests were added to assert the map pointer is reused, contents are cleared after Reset, and pooled instances don't leak prior entries.

Changes

Cohort / File(s) Summary
Session data reset optimization
middleware/session/data.go
Replaced d.Data = make(map[any]any) with clear(d.Data) in Reset, preserving the original map reference to enable sync.Pool reuse while retaining locking semantics.
Session data tests
middleware/session/data_test.go
Added reflect import, helper mapPointer, TestData_ResetPreservesAllocation and TestData_PoolReuseDoesNotLeakEntries to verify map-pointer preservation, clearing behavior, and pool reuse without leaking entries.

Sequence Diagram(s)

(omitted — changes are local memory-management and tests, not a multi-component control flow)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

SessionMW

Suggested reviewers

  • ReneWerner87
  • efectn

Poem

🐰 I kept the hole and cleaned my mat,
No new bucket, just a careful pat.
I hop through pools without a trace,
Old crumbs gone from this tidy place —
Hooray for reuse, neat as a hat.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description check ❓ Inconclusive The description provides a summary of changes but is minimal and does not follow the required template structure with sections like 'Changes introduced', 'Type of change', or the checklist items. Expand the description to match the repository template, including sections for 'Changes introduced' (with checkboxes), 'Type of change', and relevant items from the 'Checklist' to provide comprehensive context.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: preserving session data map across resets. It is concise, specific, and directly related to the core modification in the changeset.
✨ 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 update-reset-method-in-session-data

📜 Recent review details

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c55e901 and 90c52f8.

📒 Files selected for processing (1)
  • middleware/session/data_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • middleware/session/data_test.go
⏰ 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: unit (1.25.x, windows-latest)
  • GitHub Check: repeated
  • GitHub Check: lint
  • GitHub Check: Compare

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 @gaby, 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 optimizes the handling of session data maps by changing how they are reset. Instead of creating a new map each time, the existing map is now cleared, which allows its capacity to be retained. This change is particularly beneficial when these maps are managed within a pool, as it reduces memory allocations and improves overall efficiency. A new test case has been introduced to validate this behavior and prevent data leakage across map reuses.

Highlights

  • Performance Improvement: The Reset method for session data maps now uses clear() instead of make(map[any]any), which prevents reallocation and preserves the underlying map's capacity, leading to better performance and reduced garbage collection overhead when maps are reused from a pool.
  • Regression Test: A new test, TestData_ResetReuseMap, has been added to ensure that pooled session data maps are correctly cleared and reused, verifying that no previous entries leak into subsequent uses.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

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 a performance optimization by using clear() to reset a session data map instead of reallocating it. This is a good change that preserves the map's capacity when objects are reused from a sync.Pool. The new regression test is thorough in verifying this behavior. I've added one comment with a suggestion to improve the robustness of the new test by restructuring it slightly, which should help prevent potential test flakiness.

Comment on lines 181 to 217
func TestData_ResetReuseMap(t *testing.T) {
t.Parallel()

t.Run("Reuse cleared map across pool cycles", func(t *testing.T) {
t.Parallel()

d := acquireData()
originalPtr := mapPointer(d.Data)

d.Set("key1", "value1")
d.Set("key2", "value2")
require.Equal(t, originalPtr, mapPointer(d.Data), "Expected map pointer to stay constant after writes")

d.Reset()
require.Empty(t, d.Data, "Expected data map to be empty after reset")
require.Equal(t, originalPtr, mapPointer(d.Data), "Expected reset to preserve underlying map")

d.Set("key3", "value3")
require.Nil(t, d.Get("key1"), "Expected cleared key not to leak after reset")

d.Reset()
dataPool.Put(d)

reused := acquireData()
t.Cleanup(func() {
reused.Reset()
dataPool.Put(reused)
})

require.Equal(t, originalPtr, mapPointer(reused.Data), "Expected pooled data to reuse cleared map")
require.Empty(t, reused.Data, "Expected pooled data to be empty after reuse")
require.Nil(t, reused.Get("key2"), "Expected no leakage of prior entries on reuse")

reused.Set("key4", "value4")
require.Equal(t, "value4", reused.Get("key4"), "Expected pooled map to accept new values")
})
}
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

This test combines verifying the Reset behavior with the sync.Pool reuse logic. This structure makes it difficult to ensure the acquired data object d is always returned to the pool if an assertion fails, as it's manually returned mid-test. A test failure before dataPool.Put(d) would leak the object, potentially causing flakiness in other parallel tests.

To improve robustness and clarity, consider splitting this into two more focused tests:

  1. A test to verify that Reset clears the map while preserving the underlying allocation.
  2. A separate test to verify that an object returned to the pool is correctly reused.

This separation makes each test's purpose clearer and allows for more straightforward resource management using t.Cleanup or defer.

Copy link
Contributor

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 optimizes memory usage in the session middleware by replacing map reallocation with in-place clearing during reset operations. Instead of creating a new map with make(), the code now uses Go's clear() built-in (available since Go 1.21) to remove all entries while preserving the underlying map capacity.

Key Changes:

  • Modified Reset() method to clear map entries in-place rather than reallocating
  • Added comprehensive regression test to verify map reuse across pool cycles and prevent data leakage

Reviewed changes

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

File Description
middleware/session/data.go Changed Reset() to use clear(d.Data) instead of d.Data = make(map[any]any) to preserve map capacity
middleware/session/data_test.go Added TestData_ResetReuseMap test and mapPointer helper to verify map pointer stability and proper clearing behavior across pool cycles

@codecov
Copy link

codecov bot commented Dec 24, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.59%. Comparing base (032ff5f) to head (90c52f8).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3968      +/-   ##
==========================================
- Coverage   91.67%   91.59%   -0.09%     
==========================================
  Files         119      119              
  Lines       10177    10194      +17     
==========================================
+ Hits         9330     9337       +7     
- Misses        536      543       +7     
- Partials      311      314       +3     
Flag Coverage Δ
unittests 91.59% <100.00%> (-0.09%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Contributor

@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: 1

📜 Review details

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b0448ed and a175e54.

📒 Files selected for processing (1)
  • middleware/session/data_test.go
🧰 Additional context used
📓 Path-based instructions (2)
**/*_test.go

📄 CodeRabbit inference engine (AGENTS.md)

When adding Go tests, always invoke t.Parallel() at the start of each test and subtest to maximize concurrency

Files:

  • middleware/session/data_test.go
**/*.go

📄 CodeRabbit inference engine (AGENTS.md)

Prefer github.com/gofiber/utils/v2 helpers (for example, utils.Trim) when performing common operations such as string manipulation, whenever it is practical and appropriate for the surrounding code

Files:

  • middleware/session/data_test.go
🧠 Learnings (8)
📓 Common learnings
Learnt from: sixcolors
Repo: gofiber/fiber PR: 3016
File: middleware/session/session.go:46-61
Timestamp: 2024-10-02T23:02:12.306Z
Learning: In this codebase, the `sessionPool` only contains `Session` instances, so type assertions without additional checks are acceptable.
Learnt from: sixcolors
Repo: gofiber/fiber PR: 3016
File: middleware/session/session.go:46-61
Timestamp: 2024-10-08T19:06:06.583Z
Learning: In this codebase, the `sessionPool` only contains `Session` instances, so type assertions without additional checks are acceptable.
📚 Learning: 2024-10-02T23:02:12.306Z
Learnt from: sixcolors
Repo: gofiber/fiber PR: 3016
File: middleware/session/session.go:46-61
Timestamp: 2024-10-02T23:02:12.306Z
Learning: In this codebase, the `sessionPool` only contains `Session` instances, so type assertions without additional checks are acceptable.

Applied to files:

  • middleware/session/data_test.go
📚 Learning: 2025-09-14T00:10:40.547Z
Learnt from: sixcolors
Repo: gofiber/fiber PR: 0
File: :0-0
Timestamp: 2025-09-14T00:10:40.547Z
Learning: The `session.Release()` method in the `middleware/session` package is responsible for returning the Session back to `sync.Pool` via `sessionPool.Put(s)`. It also calls Reset() to clear session data. Users must call Release() when done with the session, even after calling Save().

Applied to files:

  • middleware/session/data_test.go
📚 Learning: 2024-07-26T21:00:12.902Z
Learnt from: sixcolors
Repo: gofiber/fiber PR: 2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The project uses the testify/assert package for assertions in unit tests.

Applied to files:

  • middleware/session/data_test.go
📚 Learning: 2024-10-08T19:06:06.583Z
Learnt from: sixcolors
Repo: gofiber/fiber PR: 3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests in this project use testify require.

Applied to files:

  • middleware/session/data_test.go
📚 Learning: 2024-12-13T08:14:22.851Z
Learnt from: efectn
Repo: gofiber/fiber PR: 3162
File: hooks_test.go:228-228
Timestamp: 2024-12-13T08:14:22.851Z
Learning: In Go test files, prefer using the `require` methods from the `testify` package for assertions instead of manual comparisons and calls to `t.Fatal` or `t.Fatalf`.

Applied to files:

  • middleware/session/data_test.go
📚 Learning: 2025-10-16T07:19:52.418Z
Learnt from: grivera64
Repo: gofiber/fiber PR: 3807
File: adapter_test.go:118-144
Timestamp: 2025-10-16T07:19:52.418Z
Learning: In the Fiber codebase, the linter does not allow `require` assertions from within HTTP handlers (including net/http-style handlers). Use `t.Fatalf`, `t.Errorf`, or similar `testing.T` methods for error handling inside handler functions instead.

Applied to files:

  • middleware/session/data_test.go
📚 Learning: 2025-12-07T15:07:23.885Z
Learnt from: CR
Repo: gofiber/fiber PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-07T15:07:23.885Z
Learning: Applies to **/*_test.go : When adding Go tests, always invoke `t.Parallel()` at the start of each test and subtest to maximize concurrency

Applied to files:

  • middleware/session/data_test.go
⏰ 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: lint
  • GitHub Check: Compare
  • GitHub Check: repeated
  • GitHub Check: unit (1.25.x, windows-latest)
🔇 Additional comments (2)
middleware/session/data_test.go (2)

4-4: LGTM: Necessary import for map pointer comparison.

The reflect import is correctly added to support the mapPointer helper function used for verifying map identity across pool cycles.


238-240: LGTM: Clean reflection-based helper for map identity verification.

The mapPointer helper correctly uses reflect.ValueOf(m).Pointer() to obtain the underlying map pointer, enabling precise verification that the same map instance is preserved across Reset operations and pool cycles.

Copy link
Member

@sixcolors sixcolors left a comment

Choose a reason for hiding this comment

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

LGTM, aside from CI lint fail and other comments

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

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

4 participants