Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a new validator to convert blockchain timestamps to correct datetime #438

Merged
merged 18 commits into from
Sep 30, 2024

Conversation

kongzii
Copy link
Contributor

@kongzii kongzii commented Sep 26, 2024

No description provided.

Copy link

coderabbitai bot commented Sep 26, 2024

Walkthrough

The pull request introduces several changes across multiple files, primarily focusing on the modification of timezone validation methods. The function add_utc_timezone_validator has been replaced with convert_to_utc_datetime in various classes and utility functions, affecting how datetime objects are processed. Additionally, there are adjustments to the formatting and structure of the code, including improvements in the handling of market agents and the organization of import statements. Overall, the changes enhance the clarity and functionality of datetime handling within the codebase.

Changes

Files Change Summary
.github/workflows/python_ci.yaml Removed --quiet flag from autoflake and isort jobs for better visibility in output.
prediction_market_agent_tooling/.../agent_market.py Replaced add_utc_timezone_validator with convert_to_utc_datetime for datetime fields; corrected indentation for volume.
prediction_market_agent_tooling/.../monitor.py Replaced add_utc_timezone_validator with convert_to_utc_datetime for start_time and end_time; adjusted attributes for consistency.
prediction_market_agent_tooling/.../monitor_app.py Updated add_utc_timezone_validator to convert_to_utc_datetime for start_time; improved agent loading logic.
prediction_market_agent_tooling/.../contract.py Replaced add_utc_timezone_validator with utc_timestamp_to_utc_datetime in get_now method; adjusted import statements.
prediction_market_agent_tooling/.../langfuse_client_utils.py Updated get_trace_for_bet to use convert_to_utc_datetime; streamlined error handling in from_langfuse_trace.
prediction_market_agent_tooling/.../utils.py Renamed add_utc_timezone_validator to convert_to_utc_datetime; added utc_timestamp_to_utc_datetime function; updated now function.

Suggested reviewers

  • evangriffiths

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 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 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.


def utc_timestamp_to_utc_datetime(ts: int | None) -> DatetimeWithTimezone | None:
return (
convert_to_utc_datetime(datetime.fromtimestamp(ts, tz=pytz.UTC))
Copy link
Contributor Author

Choose a reason for hiding this comment

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

There's a difference between adding timezone into this function and not:

>>> from datetime import datetime
>>> import pytz
>>> datetime.fromtimestamp(1727349783)
datetime.datetime(2024, 9, 26, 13, 23, 3)
>>> datetime.fromtimestamp(1727349783, tz=pytz.UTC)
datetime.datetime(2024, 9, 26, 11, 23, 3, tzinfo=<UTC>)
>>> 

@coderabbitai Please create an issue for me to go over the code and check where all we need to fix.

Copy link

Choose a reason for hiding this comment

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

@kongzii, I've created an issue for you to review the code and check where timezone handling needs to be fixed: #439.

🔗 Analysis chain

@kongzii, I've created an issue for you to review the code and check where timezone handling needs to be fixed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Create a GitHub issue to review timezone handling
gh issue create --title "Review code for correct timezone handling" --body "As per PR [#438](https://github.com/gnosis/prediction-market-agent-tooling/pull/438), there is a difference in how \`datetime.fromtimestamp()\` handles timezones when a timezone is specified or not. We need to review the codebase to identify where timezone handling needs to be fixed.

Refer to the comment: https://github.com/gnosis/prediction-market-agent-tooling/pull/438#discussion_r1776869154

Requested by @kongzii
" --assignee kongzii

Length of output: 586


✏️ Learnings added
Learnt from: kongzii
PR: gnosis/prediction-market-agent-tooling#438
File: prediction_market_agent_tooling/tools/utils.py:124-124
Timestamp: 2024-09-26T11:28:10.335Z
Learning: When using `datetime.fromtimestamp()`, always specify the timezone argument to ensure correct timezone handling.

Learnt from: kongzii
PR: gnosis/prediction-market-agent-tooling#438
File: prediction_market_agent_tooling/tools/utils.py:124-124
Timestamp: 2024-09-26T11:28:10.335Z
Learning: When using datetime.fromtimestamp(), specify the timezone argument to ensure correct timezone handling.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

)


UTCDatetimeFromUTCTimestamp = t.Annotated[
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Not used yet, but needs to. I will take a fresh look at it next week, because it's all over the codebase.

Base automatically changed from peter/debugging-contract to main September 30, 2024 12:56
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

🧹 Outside diff range and nitpick comments (5)
.github/workflows/python_ci.yaml (1)

70-70: Approved: Increased visibility for autoflake changes

Removing the --quiet flag from the git diff command will make the differences found by autoflake visible in the CI logs. This change improves transparency and can help developers understand what automated fixes are being applied.

Consider adding a conditional to only show the diff if changes were made:

- git diff --exit-code || exit 1
+ git diff --exit-code || (git diff && exit 1)

This way, the diff is only shown when there are actual changes, reducing noise in the logs when no changes are needed.

prediction_market_agent_tooling/tools/langfuse_client_utils.py (1)

150-150: LGTM: Improved timestamp handling with UTC conversion.

The use of convert_to_utc_datetime for bet.created_time ensures consistent UTC-based timestamp comparison, addressing the PR objective. This change improves the accuracy of finding the closest trace to a bet.

Consider updating the variable name bet_timestamp to bet_utc_timestamp for clarity:

-        bet_timestamp = convert_to_utc_datetime(bet.created_time)
+        bet_utc_timestamp = convert_to_utc_datetime(bet.created_time)

This small change would make it explicit that we're working with UTC timestamps throughout the function.

prediction_market_agent_tooling/tools/utils.py (3)

Line range hint 89-109: LGTM: Improved function naming and type hinting

The renaming of add_utc_timezone_validator to convert_to_utc_datetime better reflects the function's purpose. The added type hints and overloads enhance type safety and IDE support.

One minor suggestion:

Consider adding a more descriptive docstring explaining the function's behavior, especially regarding the assumption of UTC for timezone-naive datetimes. For example:

def convert_to_utc_datetime(value: datetime | None) -> DatetimeWithTimezone | None:
    """
    Convert a datetime object to UTC.
    
    If the input datetime is timezone-naive, it is assumed to be in UTC.
    If the input datetime has a non-UTC timezone, it is converted to UTC.
    
    Args:
        value (datetime | None): The datetime to convert or None.
    
    Returns:
        DatetimeWithTimezone | None: The UTC datetime or None if the input is None.
    """
    # ... (rest of the function remains the same)

112-127: LGTM: New function for timestamp to UTC datetime conversion

The new utc_timestamp_to_utc_datetime function is a valuable addition for handling UTC timestamps. It correctly uses convert_to_utc_datetime to ensure consistency in timezone handling.

One minor suggestion:

Consider adding a docstring to explain the function's purpose and behavior, especially regarding the handling of None values. For example:

def utc_timestamp_to_utc_datetime(ts: int | None) -> DatetimeWithTimezone | None:
    """
    Convert a UTC timestamp (in seconds) to a UTC datetime.
    
    Args:
        ts (int | None): The UTC timestamp in seconds or None.
    
    Returns:
        DatetimeWithTimezone | None: The corresponding UTC datetime or None if the input is None.
    """
    return (
        convert_to_utc_datetime(datetime.fromtimestamp(ts, tz=pytz.UTC))
        if ts is not None
        else None
    )

130-132: LGTM: New type annotation for automatic timestamp conversion

The UTCDatetimeFromUTCTimestamp type annotation is a clever use of Pydantic's validation system to ensure consistent handling of UTC timestamps. It will automatically convert timestamps to UTC datetimes when used in Pydantic models.

Suggestion:

Consider adding a comment or docstring to explain the purpose and usage of this type annotation. For example:

UTCDatetimeFromUTCTimestamp = t.Annotated[
    datetime, BeforeValidator(utc_timestamp_to_utc_datetime)
]
"""
A type annotation for automatic conversion of UTC timestamps to UTC datetimes.
Use this type in Pydantic models to automatically convert int timestamps to datetime objects.
"""
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ffa1a20 and 002e7fc.

📒 Files selected for processing (7)
  • .github/workflows/python_ci.yaml (2 hunks)
  • prediction_market_agent_tooling/markets/agent_market.py (2 hunks)
  • prediction_market_agent_tooling/monitor/monitor.py (2 hunks)
  • prediction_market_agent_tooling/monitor/monitor_app.py (2 hunks)
  • prediction_market_agent_tooling/tools/contract.py (2 hunks)
  • prediction_market_agent_tooling/tools/langfuse_client_utils.py (2 hunks)
  • prediction_market_agent_tooling/tools/utils.py (3 hunks)
🔇 Additional comments (19)
.github/workflows/python_ci.yaml (2)

80-80: Consistent change for isort job

This change is identical to the one made in the autoflake job, maintaining consistency across the workflow. The same benefits and considerations apply.

Please refer to the comment on line 70 for a suggested improvement that could also be applied here.


Line range hint 1-80: Summary: Improved visibility in CI workflow

The changes made to this workflow file are minor but beneficial. By removing the --quiet flag from git diff commands in both the autoflake and isort jobs, the workflow now provides more visibility into the automated code formatting process. This can help developers quickly identify and understand any formatting issues caught by the CI process.

These changes do not alter the core functionality of the workflow but enhance its usefulness for debugging and maintaining code quality. Consider implementing the suggested conditional diff output to further optimize the balance between visibility and log clarity.

prediction_market_agent_tooling/tools/langfuse_client_utils.py (2)

17-17: LGTM: New import for UTC datetime conversion.

The addition of convert_to_utc_datetime from the utils module aligns with the PR objective of improving timestamp handling. This import supports the changes in the get_trace_for_bet function.


Line range hint 1-164: Overall assessment: Improvements in timestamp handling.

The changes in this file successfully address the PR objective of converting blockchain timestamps to correct datetime. The introduction of convert_to_utc_datetime and its usage in the get_trace_for_bet function enhance the accuracy of timestamp comparisons. The modifications are focused and do not introduce unnecessary complexity to the existing codebase.

prediction_market_agent_tooling/tools/utils.py (4)

12-12: LGTM: New import for BeforeValidator

The addition of BeforeValidator from pydantic.functional_validators is consistent with the changes made to improve datetime handling and validation in this file.


134-136: LGTM: Simplified utcnow function

The change to use convert_to_utc_datetime in the utcnow function ensures consistency with the new timezone handling approach and simplifies the implementation.


124-124: Addressed: Timezone handling in datetime.fromtimestamp()

The previous concern about timezone handling in datetime.fromtimestamp() has been addressed in the new utc_timestamp_to_utc_datetime function. This function explicitly specifies the UTC timezone when creating datetime objects from timestamps.


130-130: Resolved: Usage of timezone conversion functions

The previous comment about unused code seems to be outdated. The new changes introduce usage of the timezone conversion functions throughout the file, improving consistency in datetime handling.

prediction_market_agent_tooling/markets/agent_market.py (4)

22-22: LGTM: Import of convert_to_utc_datetime function.

The import of convert_to_utc_datetime is correctly placed with other imports from the same module. This function will be used in the updated validators, which is a good practice for handling timezone conversions.


Line range hint 52-52: LGTM: Corrected indentation for volume attribute.

The indentation correction for the volume attribute improves code readability and consistency with other attributes in the class. This change doesn't affect functionality but enhances code quality.


Line range hint 1-338: Overall assessment: Changes improve datetime handling and code quality.

The modifications in this file successfully address the PR objective of converting blockchain timestamps to correct datetime. The consistent use of convert_to_utc_datetime in validators and the correction of indentation contribute to better code quality and maintainability.

To ensure a smooth transition, consider the following:

  1. Update any documentation or comments that might reference the old add_utc_timezone_validator function.
  2. If there are unit tests for the AgentMarket class, make sure they are updated to reflect these changes.
  3. Verify that any code depending on the created_time and close_time fields still functions correctly with the new UTC conversion.

64-67: LGTM: Updated validators for created_time and close_time.

The change from add_utc_timezone_validator to convert_to_utc_datetime aligns with the PR objective of converting blockchain timestamps to correct datetime. The implementation is consistent across both validators.

To ensure this change doesn't have unintended consequences, let's verify its usage across the codebase:

✅ Verification successful

Action Required: Re-verify Validator Changes with Updated Shell Scripts

Let's run updated shell scripts to accurately check the usage of add_utc_timezone_validator and convert_to_utc_datetime:


: Validators have been successfully updated.

All instances of add_utc_timezone_validator have been removed, and convert_to_utc_datetime is consistently used throughout the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining usage of `add_utc_timezone_validator` and verify `convert_to_utc_datetime` usage.

echo "Checking for any remaining usage of add_utc_timezone_validator:"
rg "add_utc_timezone_validator" --type python

echo "\nVerifying usage of convert_to_utc_datetime:"
rg "convert_to_utc_datetime" --type python

Length of output: 388


Script:

# Re-checking for any remaining usage of add_utc_timezone_validator and verifying convert_to_utc_datetime usage with correct file type

echo "Checking for any remaining usage of add_utc_timezone_validator:"
rg "add_utc_timezone_validator" --type py

echo "\nVerifying usage of convert_to_utc_datetime:"
rg "convert_to_utc_datetime" --type py

Length of output: 1840

prediction_market_agent_tooling/monitor/monitor.py (3)

31-31: LGTM: Import change aligns with PR objective

The addition of convert_to_utc_datetime to the imports is consistent with the changes in the DeployedAgent class and supports the PR objective of converting blockchain timestamps to correct datetime.


52-56: LGTM: Timezone conversion update in DeployedAgent class

The changes in _add_timezone_validator_start_time and _add_timezone_validator_end_time methods to use convert_to_utc_datetime are consistent and align with the PR objective. The validation mechanism remains intact, and backward compatibility is maintained.


Line range hint 1-458: Overall impact: Improved timezone handling with minimal changes

The changes are localized to the DeployedAgent class and its timezone validation methods. The rest of the file, including the monitoring functions, remains unchanged. This update improves the handling of blockchain timestamps while maintaining the existing functionality of the monitoring system.

prediction_market_agent_tooling/tools/contract.py (2)

27-27: LGTM: Import change is consistent with implementation update.

The import of utc_timestamp_to_utc_datetime is correctly placed and aligns with the changes made in the get_now method of the DebuggingContract class.


456-456: LGTM: Implementation update simplifies timestamp conversion.

The change from add_utc_timezone_validator to utc_timestamp_to_utc_datetime simplifies the conversion process while maintaining the same functionality. The method signature and return type remain consistent, ensuring backward compatibility.

prediction_market_agent_tooling/monitor/monitor_app.py (2)

32-32: Appropriate imports for UTC datetime conversion

The addition of convert_to_utc_datetime and utcnow to the imports is necessary for handling UTC datetime conversions properly in the application.


Line range hint 107-117: Correct usage of convert_to_utc_datetime for start_time

The replacement of add_utc_timezone_validator with convert_to_utc_datetime ensures that start_time is converted to a timezone-aware UTC datetime. This is essential for accurate time comparisons and scheduling within the application.

@kongzii kongzii merged commit 186aa5d into main Sep 30, 2024
14 checks passed
@kongzii kongzii deleted the peter/new-timezone-validator branch September 30, 2024 14:05
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