Skip to content

Fix timestamp updater synchronization and improve tests#126

Merged
ReneWerner87 merged 21 commits intomasterfrom
fix-time
Jul 8, 2025
Merged

Fix timestamp updater synchronization and improve tests#126
ReneWerner87 merged 21 commits intomasterfrom
fix-time

Conversation

@sixcolors
Copy link
Member

@sixcolors sixcolors commented Jul 8, 2025

Enhance the timestamp updater for immediate updates and better synchronization. Adjust tests to allow for CI environment tolerance and improve logging and synchronization mechanisms. Refactor code for clarity and performance.

Summary by CodeRabbit

  • Refactor

    • Improved the reliability and lifecycle management of the timestamp updater, allowing it to be safely stopped and restarted without resource leaks.
    • Enhanced comments for better clarity on usage and safety.
  • Tests

    • Introduced synchronization to prevent test interference and improved the accuracy and clarity of timestamp-related tests and benchmarks.

sixcolors and others added 19 commits July 7, 2025 13:46
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
…tion in Test_TimeStampUpdater and Test_StopTimeStampUpdater
…immediately and then every second

fix(tests): replace time.Sleep with polling in Test_TimeStampUpdater for better synchronization
…ater and adjust wait time in Test_TimeStampUpdater
… adjust wait loop for timestamp synchronization
… ticker's time and adjust Test_TimeStampUpdater wait loop for better synchronization
…ter for improved synchronization and performance
…ocking updaterMu and adjusting goroutine closure
…improve Test_TimeStampUpdater for better timestamp accuracy
…e scoping and timing validation in Benchmark_CalculateTimestamp
@sixcolors sixcolors requested a review from a team as a code owner July 8, 2025 15:39
@sixcolors sixcolors requested review from ReneWerner87, efectn and gaby and removed request for a team July 8, 2025 15:39
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 8, 2025

Walkthrough

The code refactors the timestamp updater's internal lifecycle management by renaming variables, introducing a new channel to signal goroutine exit, and ensuring the updater can be safely stopped and restarted. Tests and benchmarks are updated with improved synchronization, tighter assertions, and clearer error reporting.

Changes

Files Change Summary
time.go Refactored timestamp updater internals: renamed variables, added updaterDone channel, improved shutdown and restart logic, updated comments.
time_test.go Introduced global mutex for test synchronization, enhanced assertions, improved error messages, updated benchmark logic.

Sequence Diagram(s)

sequenceDiagram
    participant Test/Caller
    participant Updater Goroutine

    Test/Caller->>StartTimeStampUpdater: Start updater
    activate Updater Goroutine
    Updater Goroutine-->>Test/Caller: Updater running, updates timestamp every second

    Test/Caller->>StopTimeStampUpdater: Stop updater
    StopTimeStampUpdater->>Updater Goroutine: Signal stop via channel
    Updater Goroutine-->>StopTimeStampUpdater: Close updaterDone on exit
    StopTimeStampUpdater-->>Test/Caller: Wait for updaterDone, then reset state
Loading

Possibly related PRs

  • 🔥 feat: Add support for stopping timestamp updater #101: The main PR refines and extends the timestamp updater's stop-and-restart lifecycle management by renaming variables, adding a done channel, and improving synchronization, building directly upon the initial stop mechanism introduced in the retrieved PR which added the stop channel and basic stop functionality.

Suggested labels

✏️ Feature

Poem

A tick, a tock, a timer anew,
With channels and locks, the seconds flew.
Goroutines now come and go with grace,
No leaks, no race—just a tidy place.
Tests march in sync, all neat and bright,
This bunny’s code now sleeps at night! 🕰️🐇


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 065106b and 72b711b.

📒 Files selected for processing (1)
  • time_test.go (3 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: efectn
PR: gofiber/fiber#3162
File: app_test.go:893-895
Timestamp: 2024-11-29T12:37:27.581Z
Learning: In the `Test_App_ShutdownWithContext` function in `app_test.go`, the `clientDone` channel is used to synchronize the client's request completion before proceeding, eliminating the need for additional `time.Sleep` calls.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/middleware_test.go:190-191
Timestamp: 2024-09-25T17:05:06.991Z
Learning: When testing session `IdleTimeout` expiration, it's acceptable to use `time.Sleep` to simulate the passage of time in tests.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/middleware_test.go:190-191
Timestamp: 2024-10-12T10:01:44.206Z
Learning: When testing session `IdleTimeout` expiration, it's acceptable to use `time.Sleep` to simulate the passage of time in tests.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/middleware_test.go:400-407
Timestamp: 2024-09-25T17:09:03.756Z
Learning: In the `Test_Session_Next` function in `middleware/session/middleware_test.go`, the variable `doNext` is properly synchronized with the `muNext` mutex for both read and write access.
Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/main.go:0-0
Timestamp: 2024-11-23T19:35:36.767Z
Learning: In the Go `clean-code` example (`clean-code/app/main.go`) in the `gofiber/recipes` repository, it's acceptable to omit graceful shutdown handling, as the example code prioritizes simplicity over production-level practices.
time_test.go (12)
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/middleware_test.go:400-407
Timestamp: 2024-09-25T17:09:03.756Z
Learning: In the `Test_Session_Next` function in `middleware/session/middleware_test.go`, the variable `doNext` is properly synchronized with the `muNext` mutex for both read and write access.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/middleware_test.go:190-191
Timestamp: 2024-09-25T17:05:06.991Z
Learning: When testing session `IdleTimeout` expiration, it's acceptable to use `time.Sleep` to simulate the passage of time in tests.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/middleware_test.go:190-191
Timestamp: 2024-10-12T10:01:44.206Z
Learning: When testing session `IdleTimeout` expiration, it's acceptable to use `time.Sleep` to simulate the passage of time in tests.
Learnt from: efectn
PR: gofiber/fiber#3162
File: app_test.go:893-895
Timestamp: 2024-11-29T12:37:27.581Z
Learning: In the `Test_App_ShutdownWithContext` function in `app_test.go`, the `clientDone` channel is used to synchronize the client's request completion before proceeding, eliminating the need for additional `time.Sleep` calls.
Learnt from: luk3skyw4lker
PR: gofiber/storage#1342
File: clickhouse/clickhouse.go:106-107
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The `IsZero` function for `time.Time` structs in the ClickHouse storage driver was returning false even for zero value `time.Time` structs. As a result, a different verification logic was implemented to avoid bugs.
Learnt from: luk3skyw4lker
PR: gofiber/storage#1342
File: clickhouse/clickhouse.go:106-107
Timestamp: 2024-07-01T15:49:51.308Z
Learning: The `IsZero` function for `time.Time` structs in the ClickHouse storage driver was returning false even for zero value `time.Time` structs. As a result, a different verification logic was implemented to avoid bugs.
Learnt from: efectn
PR: gofiber/fiber#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`.
Learnt from: sixcolors
PR: gofiber/fiber#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.
Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The project uses the testify/assert package for assertions in unit tests.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-02T23:03:31.727Z
Learning: Unit tests in this project use testify require.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests in this project use testify require.
Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/datasources/database/db_mock.go:13-19
Timestamp: 2024-11-23T19:50:06.387Z
Learning: In test code within `clean-code/app/datasources/database/db_mock.go`, adding safety checks like context validation, safe type assertions, and extra documentation is not necessary.
🧬 Code Graph Analysis (1)
time_test.go (1)
time.go (3)
  • StartTimeStampUpdater (24-45)
  • StopTimeStampUpdater (49-58)
  • Timestamp (18-20)
⏰ 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). (8)
  • GitHub Check: Build (1.24.x, ubuntu-latest)
  • GitHub Check: Build (1.24.x, macos-13)
  • GitHub Check: Build (1.24.x, macos-latest)
  • GitHub Check: Build (1.24.x, windows-latest)
  • GitHub Check: Analyse
  • GitHub Check: Build (1.23.x, windows-latest)
  • GitHub Check: Build (1.23.x, macos-13)
  • GitHub Check: Compare
🔇 Additional comments (8)
time_test.go (8)

4-4: Good addition of mutex for test synchronization.

The introduction of a global mutex timerTestMu is an excellent solution to prevent concurrent test interference, which is crucial for timestamp updater tests that rely on shared global state.

Also applies to: 11-11


15-17: Improved tolerance and error messages enhance CI reliability.

The updated checkTimeStamp function with ±2 seconds tolerance and detailed error messages including the difference calculation will significantly improve debugging in CI environments where timing can be less predictable.


21-25: Proper test synchronization and cleanup.

The mutex locking and deferred StopTimeStampUpdater() call ensure proper test isolation and cleanup, preventing state leakage between tests.


29-35: Enhanced initial timestamp validation.

The updated assertion provides more precise validation with detailed error messages, making it easier to diagnose timing issues in CI environments.


37-48: Comprehensive timestamp update verification.

The enhanced assertions now verify both that the timestamp has incremented and that it falls within the expected time range, providing better test coverage and debugging information.


52-69: Improved stop functionality test with better timing.

The test now uses more appropriate timing (2 seconds vs 5 seconds) and provides detailed error messages that include wall time for better debugging of stop functionality.


73-76: Proper benchmark synchronization and cleanup.

Adding mutex synchronization and deferred cleanup to the benchmark ensures it doesn't interfere with other tests and properly manages the timestamp updater lifecycle.


94-112: Enhanced asserted benchmarks with clearer semantics.

The updated benchmarks now properly capture the expected timestamp before calling the function under test, making the benchmarks more realistic and the assertions more meaningful.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-time

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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.

Summary of Changes

Hello @sixcolors, 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 focuses on enhancing the existing timestamp updater by improving its internal synchronization mechanisms and overall reliability. The changes ensure more immediate and accurate timestamp updates, better control over the updater's lifecycle, and significantly improved test stability, particularly in continuous integration environments. The refactoring also contributes to clearer code and more precise performance measurements.

Highlights

  • Timestamp Updater Refactor: The internal timestamp updater mechanism has been significantly refactored for improved synchronization and reliability. This includes replacing the timestampTimer with updaterOnce (a sync.Once instance) and introducing a new updaterDone channel for more robust goroutine management and graceful shutdown.
  • Enhanced Updater Lifecycle Management: The StopTimeStampUpdater function now explicitly waits for the background goroutine to complete its execution before returning, preventing goroutine leaks. It also resets the sync.Once instance, allowing the timestamp updater to be safely re-initialized if needed.
  • Improved Test Reliability and CI Tolerance: Tests for the timestamp updater have been enhanced to be more robust and reliable, especially in CI environments. A global mutex (timerTestMu) was introduced to prevent race conditions during concurrent test execution, and the checkTimeStamp helper now allows a ±2 seconds tolerance for timestamp comparisons to accommodate timing variations.
  • Refined Test Assertions and Benchmarks: The Test_TimeStampUpdater and Test_StopTimeStampUpdater functions have been updated with more precise timing and assertions to accurately validate the updater's behavior. Benchmark tests were also adjusted to correctly measure performance by stopping and starting the timer around assertion calls, ensuring more accurate results.
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 in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

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 issue 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 is currently in preview and 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 to provide feedback.

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.

@codecov
Copy link

codecov bot commented Jul 8, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 96.44%. Comparing base (a64d545) to head (72b711b).
Report is 22 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #126      +/-   ##
==========================================
+ Coverage   96.42%   96.44%   +0.02%     
==========================================
  Files           9        9              
  Lines         503      507       +4     
==========================================
+ Hits          485      489       +4     
  Misses         12       12              
  Partials        6        6              
Flag Coverage Δ
unittests 96.44% <100.00%> (+0.02%) ⬆️

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

@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

The pull request enhances the timestamp updater for immediate updates and better synchronization. It also adjusts tests to allow for CI environment tolerance and improves logging and synchronization mechanisms. The changes include fixes for potential race conditions, improved test logic, and more accurate benchmarking.

@ReneWerner87 ReneWerner87 merged commit 844d4de into master Jul 8, 2025
17 of 18 checks passed
@sixcolors sixcolors deleted the fix-time branch July 8, 2025 16:25
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