Skip to content

Fix require.True usage in checkTimeStamp function and improve variable scoping and timing validation in Benchmark_CalculateTimestamp. - #124

Closed
sixcolors wants to merge 17 commits into
masterfrom
fix-time-test
Closed

Fix require.True usage in checkTimeStamp function and improve variable scoping and timing validation in Benchmark_CalculateTimestamp.#124
sixcolors wants to merge 17 commits into
masterfrom
fix-time-test

Conversation

@sixcolors

@sixcolors sixcolors commented Jul 7, 2025

Copy link
Copy Markdown
Member

This pull request refines the time_test.go file by improving the accuracy of assertions, enhancing benchmarking practices, and ensuring more precise timing measurements during tests. The key changes focus on updating the checkTimeStamp function and restructuring benchmarking logic to isolate function timing from validation steps.

Improvements to assertions:

  • Updated the condition in checkTimeStamp to use a logical AND instead of OR, ensuring that the actual timestamp falls strictly within the expected range. time_test.goL13-R13

Enhancements to benchmarking:

  • Introduced bb.StopTimer() and bb.StartTimer() calls in the Benchmark_CalculateTimestamp function to isolate the timing of the function call from validation and setup steps. time_test.goL70-R95
  • Added logic to capture the expected timestamp before starting the timer in the default_asserted benchmark, ensuring validation does not interfere with timing measurements. time_test.goL70-R95

Code cleanup:

  • Removed an unused variable res in the Benchmark_CalculateTimestamp function to simplify the code. time_test.goL48

Summary by CodeRabbit

  • Bug Fixes

    • Corrected timestamp assertion logic to ensure accurate verification within the expected time window.
  • Tests

    • Improved reliability of timestamp tests by adding a brief delay for background initialization.
    • Refined benchmark tests to measure only the intended code execution, excluding validation overhead for more accurate performance results.
    • Enhanced test synchronization to prevent concurrency issues and reduce flakiness.
  • Performance

    • Optimized timestamp updater to use a simpler timer-based delay, improving efficiency.

@sixcolors
sixcolors requested a review from a team as a code owner July 7, 2025 16:46
@sixcolors
sixcolors requested review from ReneWerner87, efectn and gaby and removed request for a team July 7, 2025 16:46
@coderabbitai

coderabbitai Bot commented Jul 7, 2025

Copy link
Copy Markdown
Contributor

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

## Walkthrough

The timestamp updater goroutine was modified to fix ticker initialization by hardcoding a 1-second interval and using `time.Now()` directly for updates. The `checkTimeStamp` function was corrected to use an inclusive ±2 second range with logical AND. Tests replaced `time.Sleep` with `<-time.After`, added waiting loops, and refined benchmarks to exclude validation overhead.

## Changes

| File(s)      | Change Summary                                                                                                                         |
|--------------|-----------------------------------------------------------------------------------------------------------------------------------------|
| time.go      | Renamed synchronization variables for clarity; added `updaterDone` channel to signal goroutine exit; updater fetches timestamp via `time.Now()`; stop waits for goroutine completion. |
| time_test.go | Corrected `checkTimeStamp` logic to use AND with ±2 seconds; replaced `time.Sleep` with `<-time.After`; added wait loop in test; added global mutex for synchronization; localized benchmark variable; adjusted benchmark timers to exclude validation overhead and capture expected timestamp before timing; added logging and short sleeps to reduce flakiness. |

## Suggested labels

`🧹 Updates`

## Suggested reviewers

- gaby

## Poem

> A tick, a tock, the tests align,  
> Within two seconds, clocks combine.  
> Tickers fixed, timers true,  
> Benchmarks trimmed for me and you.  
> ⏳🐇✨
✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-time-test

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.

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

Copy link
Copy Markdown
Contributor

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 contains a focused fix for a test assertion within the checkTimeStamp helper function. The change ensures that the require.True assertion correctly evaluates the intended timestamp comparison, thereby improving the accuracy and reliability of the test suite.

Highlights

  • Test Fix: Corrected the usage of require.True in the checkTimeStamp test helper function by removing a redundant true argument. This ensures the actual timestamp comparison logic (actualCurrent >= expectedCurrent-1 || actualCurrent <= expectedCurrent+1) is correctly evaluated by the assertion.
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.

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

Copy link
Copy Markdown
Contributor

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 fixes the signature for the require.True call, but the boolean logic of the assertion itself is flawed, which makes the test always pass. The review provides a correction to ensure the test validates the timestamp within the intended range.

Comment thread time_test.go Outdated
@codecov

codecov Bot commented Jul 7, 2025

Copy link
Copy Markdown

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 96.44%. Comparing base (af68b46) to head (9c7373a).
Report is 3 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #124      +/-   ##
==========================================
+ Coverage   95.95%   96.44%   +0.49%     
==========================================
  Files           9        9              
  Lines         495      507      +12     
==========================================
+ Hits          475      489      +14     
+ Misses         14       12       -2     
  Partials        6        6              
Flag Coverage Δ
unittests 96.44% <100.00%> (+0.49%) ⬆️

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.

sixcolors and others added 3 commits July 7, 2025 16:39
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
@sixcolors sixcolors changed the title Fix require.True usage in checkTimeStamp function Fix require.True usage in checkTimeStamp function and improve variable scoping and timing validation Jul 7, 2025
@sixcolors sixcolors changed the title Fix require.True usage in checkTimeStamp function and improve variable scoping and timing validation Fix require.True usage in checkTimeStamp function and improve variable scoping and timing validation in Benchmark_CalculateTimestamp. Jul 7, 2025
@sixcolors

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 7, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@sixcolors

Copy link
Copy Markdown
Member Author

Tests passing locally, failing on CI, timing tests are flaky now that the require.True is actually checking. Will see what I can do here.

…immediately and then every second

fix(tests): replace time.Sleep with polling in Test_TimeStampUpdater for better synchronization

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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)
time.go (1)

34-35: Remove unnecessary continue statement.

The continue statement on line 35 is redundant. In a for loop, execution automatically continues to the next iteration when reaching the end of the loop body.

 				select {
 				case <-time.After(sleep):
-					continue
 				case <-localChan:
 					return
 				}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9dd0a6f and c63ee02.

📒 Files selected for processing (2)
  • time.go (1 hunks)
  • time_test.go (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • time_test.go
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
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: juls0730
PR: gofiber/recipes#2710
File: tableflip/main.go:61-62
Timestamp: 2024-12-01T01:15:48.126Z
Learning: In the GoFiber `tableflip` recipe (`tableflip/main.go`), the implementation matches the upstream reference implementation. Future code suggestions should consider maintaining this alignment to ensure consistency.
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#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: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.
time.go (7)
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: 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-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: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/config.go:122-122
Timestamp: 2024-10-08T19:06:06.583Z
Learning: In `DefaultErrorHandler(c *fiber.Ctx, err error)`, since `c` is a pointer to an interface, we need to dereference `*c` when calling interface methods like `SendStatus`.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/config.go:122-122
Timestamp: 2024-09-25T16:18:34.719Z
Learning: In `DefaultErrorHandler(c *fiber.Ctx, err error)`, since `c` is a pointer to an interface, we need to dereference `*c` when calling interface methods like `SendStatus`.
⏰ 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). (3)
  • GitHub Check: Compare
  • GitHub Check: Build (1.24.x, windows-latest)
  • GitHub Check: Analyse
🔇 Additional comments (1)
time.go (1)

32-32: LGTM: Timestamp update positioning improved.

Moving the timestamp update to the start of each iteration is a good change. This ensures the timestamp is updated immediately when the goroutine starts and provides more predictable timing behavior compared to a ticker-based approach.

sixcolors added 6 commits July 8, 2025 11:25
…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
@sixcolors
sixcolors marked this pull request as draft July 8, 2025 15:04
@sixcolors sixcolors closed this Jul 8, 2025
@sixcolors
sixcolors deleted the fix-time-test branch July 8, 2025 15:35
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.

1 participant