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

Problem: output artifact gets expired easily #1671

Merged
merged 3 commits into from
Nov 4, 2024

Conversation

mmsqe
Copy link
Collaborator

@mmsqe mmsqe commented Nov 4, 2024

record in log

👮🏻👮🏻👮🏻 !!!! REFERENCE THE PROBLEM YOUR ARE SOLVING IN THE PR TITLE AND DESCRIBE YOUR SOLUTION HERE !!!! DO NOT FORGET !!!! 👮🏻👮🏻👮🏻

PR Checklist:

  • Have you read the CONTRIBUTING.md?
  • Does your PR follow the C4 patch requirements?
  • Have you rebased your work on top of the latest master?
  • Have you checked your code compiles? (make)
  • Have you included tests for any non-trivial functionality?
  • Have you checked your code passes the unit tests? (make test)
  • Have you checked your code formatting is correct? (go fmt)
  • Have you checked your basic code style is fine? (golangci-lint run)
  • If you added any dependencies, have you checked they do not contain any known vulnerabilities? (go list -json -m all | nancy sleuth)
  • If your changes affect the client infrastructure, have you run the integration test?
  • If your changes affect public APIs, does your PR follow the C4 evolution of public contracts?
  • If your code changes public APIs, have you incremented the crate version numbers and documented your changes in the CHANGELOG.md?
  • If you are contributing for the first time, please read the agreement in CONTRIBUTING.md now and add a comment to this pull request stating that your PR is in accordance with the Developer's Certificate of Origin.

Thank you for your code, it's appreciated! :)

Summary by CodeRabbit

  • New Features

    • Introduced a Tee class to enable simultaneous logging to both a file and the console.
    • Enhanced the logging mechanism in the do_run function for improved output handling.
  • Bug Fixes

    • No significant bug fixes were reported in this release.
  • Documentation

    • Updated documentation to reflect the new logging capabilities and usage of the Tee class.

@mmsqe mmsqe requested a review from a team as a code owner November 4, 2024 06:26
@mmsqe mmsqe requested review from calvinaco and thomas-nguy and removed request for a team November 4, 2024 06:26
Copy link
Contributor

coderabbitai bot commented Nov 4, 2024

Walkthrough

The changes introduce a new Tee class in the utils.py file, enabling simultaneous writing to two file-like objects. The do_run function in stateless.py is updated to utilize this class, allowing log output to be directed both to a log file and the console. The overall command-line interface remains unchanged, preserving the existing functionality of generating nodes and running commands.

Changes

File Path Change Summary
testground/benchmark/benchmark/stateless.py - Updated do_run to use Tee for logging output to both log file and console.
- No changes to validate_json.
testground/benchmark/benchmark/utils.py - Added Tee class for simultaneous writing to two file-like objects.
- Implemented __init__ and write methods.

Suggested reviewers

  • mmsqe

🐇 In the meadow, where the bunnies play,
A new Tee class brightens the day.
Logs now dance on the screen and the file,
Output together, making us smile!
With do_run updated, our tasks are a breeze,
Hopping along with such joyful ease! 🌼


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.

Copy link

codecov bot commented Nov 4, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 16.84%. Comparing base (9a9018f) to head (f2a3362).
Report is 1 commits behind head on main.

❗ There is a different number of reports uploaded between BASE (9a9018f) and HEAD (f2a3362). Click for more details.

HEAD has 12 uploads less than BASE
Flag BASE (9a9018f) HEAD (f2a3362)
2 0
integration_tests 20 10
Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##             main    #1671       +/-   ##
===========================================
- Coverage   35.27%   16.84%   -18.43%     
===========================================
  Files         123       72       -51     
  Lines       11752     6161     -5591     
===========================================
- Hits         4145     1038     -3107     
+ Misses       7193     5000     -2193     
+ Partials      414      123      -291     

see 70 files with indirect coverage changes

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: 0

🧹 Outside diff range and nitpick comments (3)
testground/benchmark/benchmark/stats.py (3)

60-61: Refactor duplicate print statements to improve maintainability.

The identical format in both print statements creates unnecessary duplication. Consider extracting the format into a single string template.

-        print("block", i, txs, timestamp, tps)
-        print("block", i, txs, timestamp, tps, file=fp)
+        stats_line = f"block {i} {txs} {timestamp} {tps}"
+        print(stats_line)
+        print(stats_line, file=fp)

Line range hint 33-63: Consider implementing error handling and memory optimization.

The function has several areas that could be improved:

  1. No error handling for file operations or RPC calls
  2. Keeps all blocks in memory which could be problematic for large ranges
  3. The function name undersells its capabilities

Consider these improvements:

  1. Add try-except blocks around RPC calls and file operations
  2. Implement periodic file flushing to ensure data persistence
  3. Consider renaming to analyze_block_stats or similar to better reflect its TPS analysis capability

Would you like me to provide a detailed implementation of these improvements?


Line range hint 33-63: Address artifact expiration by implementing proper file handling.

This change adds console output but doesn't address the core issue of artifact expiration. The function should ensure data persistence through proper file handling.

Consider these changes to address artifact expiration:

 def dump_block_stats(
     fp,
     eth=True,
     json_rpc=LOCAL_JSON_RPC,
     rpc=LOCAL_RPC,
     start: int = 2,
     end: int = None,
 ):
+    # Ensure file handle is in write mode and buffering is enabled
+    if not fp.writable():
+        raise ValueError("File handle must be writable")
+
     tps_list = []
     if end is None:
         end = block_height(rpc)
     blocks = []
     # skip block 1 whose timestamp is not accurate
     for i in range(start, end + 1):
         if eth:
             timestamp, txs = get_block_info_eth(i, json_rpc)
         else:
             timestamp, txs = get_block_info_cosmos(i, rpc)
         blocks.append((txs, timestamp))
         tps = calculate_tps(blocks[-TPS_WINDOW:])
         tps_list.append(tps)
         print("block", i, txs, timestamp, tps)
         print("block", i, txs, timestamp, tps, file=fp)
+        # Flush every N blocks to ensure data persistence
+        if i % 100 == 0:
+            fp.flush()
     tps_list.sort(reverse=True)
     print("top_tps", tps_list[:5], file=fp)
+    fp.flush()  # Final flush to ensure all data is written
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9a9018f and 80df109.

📒 Files selected for processing (1)
  • testground/benchmark/benchmark/stats.py (1 hunks)

Copy link
Collaborator

@yihuang yihuang left a comment

Choose a reason for hiding this comment

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

I did a refactoring, please review that.

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: 0

🧹 Outside diff range and nitpick comments (3)
testground/benchmark/benchmark/utils.py (2)

212-221: LGTM! Consider adding essential file-like object methods.

The Tee class implementation looks good for the basic use case of duplicating output. However, it should implement additional essential methods to fully comply with the file-like object protocol.

Add these essential methods:

 class Tee:
     def __init__(self, f1, f2):
         self.f1 = f1
         self.f2 = f2
 
     def write(self, s) -> int:
         s1 = self.f1.write(s)
         s2 = self.f2.write(s)
         assert s1 == s2
         return s1
+
+    def flush(self):
+        self.f1.flush()
+        self.f2.flush()
+
+    def close(self):
+        self.f1.close()
+        self.f2.close()

212-221: Consider these improvements for better robustness.

The current implementation could be enhanced with better type safety and error handling.

Consider these improvements:

+from typing import TextIO
+
 class Tee:
-    def __init__(self, f1, f2):
+    def __init__(self, f1: TextIO, f2: TextIO):
         self.f1 = f1
         self.f2 = f2
 
     def write(self, s) -> int:
-        s1 = self.f1.write(s)
-        s2 = self.f2.write(s)
-        assert s1 == s2
-        return s1
+        try:
+            s1 = self.f1.write(s)
+            s2 = self.f2.write(s)
+            if s1 != s2:
+                raise IOError(f"Write sizes differ: {s1} != {s2}")
+            return s1
+        except Exception as e:
+            raise IOError(f"Write failed: {str(e)}")

This version:

  • Adds type hints for better IDE support
  • Replaces assertion with proper error handling
  • Wraps writes in try-except to handle IO errors gracefully
testground/benchmark/benchmark/stateless.py (1)

306-306: Consider enhancing error handling

While the current implementation is good, consider adding error handling for potential I/O issues with the Tee writer. This would make the test infrastructure more robust.

Example scenarios to handle:

  • IOError when writing to either destination
  • Partial writes
  • Resource cleanup on errors
-        dump_block_stats(Tee(logfile, sys.stdout))
+        try:
+            tee = Tee(logfile, sys.stdout)
+            dump_block_stats(tee)
+        except IOError as e:
+            print(f"Warning: Failed to write block stats: {e}", file=sys.stderr)
+            # Attempt to write to individual streams as fallback
+            try:
+                dump_block_stats(logfile)
+            except IOError:
+                try:
+                    dump_block_stats(sys.stdout)
+                except IOError:
+                    print("Error: Failed to write block stats to any output", file=sys.stderr)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 80df109 and f2a3362.

📒 Files selected for processing (2)
  • testground/benchmark/benchmark/stateless.py (2 hunks)
  • testground/benchmark/benchmark/utils.py (1 hunks)
🔇 Additional comments (2)
testground/benchmark/benchmark/stateless.py (2)

31-31: LGTM: Clean import addition

The import of Tee is properly placed with related utility imports.


306-306: LGTM: Enhanced logging visibility

Good improvement that writes block stats to both the log file and console. This ensures:

  1. Block statistics are preserved in output artifacts
  2. Real-time visibility in console output for monitoring
  3. Data availability even if artifacts expire

This change effectively addresses the PR objective of handling output artifact expiration.

@mmsqe
Copy link
Collaborator Author

mmsqe commented Nov 4, 2024

I did a refactoring, please review that.

nice, can tee 2 outputs at the same time

@mmsqe mmsqe added this pull request to the merge queue Nov 4, 2024
Merged via the queue into crypto-org-chain:main with commit 45aaff0 Nov 4, 2024
34 of 35 checks passed
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