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

1183 implement verify for pricepredict future handler #1204

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

mn13
Copy link
Contributor

@mn13 mn13 commented Jan 31, 2025

Implementation of verify for pricepredict handler.

First make a bit refactoring of client to make common generic post function that used in all client public methods.
Then I've added a Verify to client.
I've extended OutputData with SolverReceipt for using it in Verify in PricePredictorSolidity.

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.25;

import "./async/IAsync.sol";

enum PricePredictMetric {
    Count,
	Mape,
	Rmse,
	R2,
	MaxError,
	Dae,
	Mae,
	Confidence,
	Pct1,
	Pct5,
	Pct10,
	Pct15,
	Pct20,
	Pct25,
	Pct50,
	P0,
	P5,
	P10,
	P15,
	P20,
	P25,
	P50,
	P75,
	P95,
	P100
}

struct PricePredictInput {
    uint256 date;
    string[] tokens;
    PricePredictMetric[] metrics;
    uint64[2] falsePositiveRate;
}

struct SolverReceipt {
    bytes bloomFilter;
    uint256 countItems;
}

struct PricePredictOutput {
    uint256[] predictions;
    SolverReceipt solverReceipt;
    uint256[][] metrics;
}

contract PricePredExample {
    // ID of the last future created by run().
    uint64 public lastFutureId;

    // Prices of the last future received.
    uint256 public bitcoinPrice;
    uint256 public bitcoinMetricCount;
    uint256 public bitcoinMetricP75;

    uint256 public tetherPrice;
    uint256 public tetherMetricCount;
    uint256 public tetherMetricP75;

    uint256 public uniswapPrice;
    uint256 public uniswapMetricCount;
    uint256 public uniswapMetricP75;

    function run() public returns (PricePredictInput memory input) {
        string[] memory tokens = new string[](3);
        tokens[0] = "bitcoin";
        tokens[1] = "tether";
        tokens[2] = "uniswap";

        PricePredictMetric[] memory metrics = new PricePredictMetric[](2);
        metrics[0] = PricePredictMetric.Count;
        metrics[1] = PricePredictMetric.P75;

        uint64[2] memory falsePositiveRate = [uint64(1), uint64(100)];

        input = PricePredictInput(
            block.timestamp + 24 hours,
            tokens,
            metrics,
            falsePositiveRate);
        
        lastFutureId = IASYNC_CONTRACT.addFuture("pricepred", abi.encode(input));

        // reset predictions while the future is running
        bitcoinPrice = 0;
        tetherPrice = 0;
        uniswapPrice = 0;
    }

    function cb() external {
        FutureByIdResponse memory future = IASYNC_CONTRACT.futureById(lastFutureId);
        if (future.futureResponse.result.id == 0) revert("Not ready yet");
        PricePredictOutput memory pricePredictOutput = abi.decode(future.futureResponse.result.output, (PricePredictOutput));
        bitcoinPrice = pricePredictOutput.predictions[0];
        bitcoinMetricCount = pricePredictOutput.metrics[0][0];
        bitcoinMetricP75 = pricePredictOutput.metrics[0][1];

        tetherPrice = pricePredictOutput.predictions[1];
        tetherMetricCount = pricePredictOutput.metrics[1][0];
        tetherMetricP75 = pricePredictOutput.metrics[1][1];
        
        uniswapPrice = pricePredictOutput.predictions[2];
        uniswapMetricCount = pricePredictOutput.metrics[2][0];
        uniswapMetricP75 = pricePredictOutput.metrics[2][1];
    }
}

Summary by CodeRabbit

Release Notes

  • New Features

    • Added verification functionality for price prediction requests
    • Introduced new methods to handle solver receipts and verification
  • Improvements

    • Enhanced error handling and request processing
    • Improved data validation for price prediction inputs
    • Centralized HTTP request logic with generic post function
  • Technical Updates

    • Updated data structures to support more comprehensive solver information
    • Added support for bloom filter and item count tracking in solver receipts

The updates provide more robust and detailed price prediction verification capabilities.

@mn13 mn13 linked an issue Jan 31, 2025 that may be closed by this pull request
Copy link
Contributor

coderabbitai bot commented Jan 31, 2025

📝 Walkthrough

Walkthrough

The pull request introduces a comprehensive enhancement to the price prediction client and handler in the Prophet system. The changes focus on adding a verification mechanism, refactoring the HTTP request handling, and improving data structures. A new Verify method is implemented in the client, along with supporting request and response types. The code introduces a generic post function to centralize HTTP request logic, and updates the existing prediction and backtesting methods to utilize this new approach.

Changes

File Change Summary
prophet/handlers/pricepred/client.go - Added verifyURL field to client struct
- Implemented new Verify method
- Added VerifyRequest and VerifyResponse types
- Refactored post function to be generic
prophet/handlers/pricepred/client_test.go - Added TestVerify test function
- Tested new verification functionality
prophet/handlers/pricepred/pricepred.go - Added ToPredictRequest method to InputData
- Updated Execute method
- Added decodeOutput and getOutputABIType methods
- Introduced SolverReceipt in output structures
prophet/handlers/pricepred/pricepred_test.go - Updated test structures with SolverReceipt
- Modified TestBuildOutput to handle new fields

Sequence Diagram

sequenceDiagram
    participant Client
    participant PricePredictorService
    participant VerificationService

    Client->>PricePredictorService: Predict Request
    PricePredictorService-->>Client: Prediction Response
    Client->>VerificationService: Verify Request
    VerificationService-->>Client: Verification Response
Loading

Possibly related PRs

Suggested Labels

protocol, test

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

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.

@github-actions github-actions bot added the test label Jan 31, 2025
Copy link

Hey @mn13 and thank you for opening this pull request! 👋🏼

It looks like you forgot to add a changelog entry for your changes. Make sure to add a changelog entry in the 'CHANGELOG.md' file.

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

🧹 Nitpick comments (7)
prophet/handlers/pricepred/pricepred.go (3)

91-100: Avoid overshadowing the res variable for readability.
Inside Execute, you reassign the res variable to hold backtesting responses, potentially confusing future readers. Consider renaming one of these variables (e.g., btRes) to keep logic clear.

- var backtestingRes *BacktestingResponse
...
- res, err := s.c.Backtesting(ctx, ...)
- backtestingRes = &res
+ var btRes *BacktestingResponse
...
+ btResData, err := s.c.Backtesting(ctx, ...)
+ btRes = &btResData

165-170: Add a short doc-comment to clarify usage.
Consider adding a brief summary of each OutputData field to assist maintainers in understanding the data structure's purpose.


288-320: Make verification ratio configurable.
The verification ratio is currently hardcoded to 0.01. Allowing dynamic configuration might make this more flexible for different confidence levels.

prophet/handlers/pricepred/client_test.go (1)

60-90: Consider using local mock server to reduce external call dependency.
Presently, TestVerify is skipped because it relies on external HTTP calls. Mocking the endpoint or injecting an interface can make tests more consistent and independent of external environments.

prophet/handlers/pricepred/client.go (2)

18-18: Add a brief docstring for verifyURL field.
Clarity on the expected endpoint and usage helps future maintainers.


125-164: Enhance error handling for non-JSON responses.
Currently, a non-JSON response from the server yields an unmarshal error. Consider logging server-provided content to help with debugging.

if res.StatusCode != http.StatusOK {
  return empty, fmt.Errorf("unexpected status code: %d. Server returned error: %s", res.StatusCode, response)
}

var resResp Resp
+// Optionally log or store `response` in logs for debugging if needed
err = json.Unmarshal(response, &resResp)
...
prophet/handlers/pricepred/pricepred_test.go (1)

Line range hint 41-126: Enhance test coverage for SolverReceipt scenarios.

The TestBuildOutput function would benefit from additional test cases to ensure robust handling of SolverReceipt:

  1. Nil/empty SolverReceipt
  2. Invalid BloomFilter data
  3. Zero/negative CountItems
  4. Edge cases for large CountItems values

This will help validate error handling and edge cases for the new fields.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7a69988 and 5354788.

📒 Files selected for processing (4)
  • prophet/handlers/pricepred/client.go (3 hunks)
  • prophet/handlers/pricepred/client_test.go (2 hunks)
  • prophet/handlers/pricepred/pricepred.go (4 hunks)
  • prophet/handlers/pricepred/pricepred_test.go (2 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
prophet/handlers/pricepred/client_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

prophet/handlers/pricepred/pricepred.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

prophet/handlers/pricepred/pricepred_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

prophet/handlers/pricepred/client.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

🔇 Additional comments (13)
prophet/handlers/pricepred/pricepred.go (5)

72-89: Consider additional validation for fixture edge cases.
Currently, if i.FalsePositiveRate[0] exceeds i.FalsePositiveRate[1], the fpr can be > 1, which may be an unintended edge case. Also, negative or extremely large timestamps for i.Date might affect time-based logic.

Would you like me to create a script to locate and check all calls to ToPredictRequest to confirm whether these edge cases are handled or tested?


174-174: No issues found.
The invocation of getOutputABIType() is clear and consistent.


271-278: Validate res.SolverReceipt before building the output.
Ensure res.SolverReceipt is always non-nil. If there's a scenario where it may be nil, consider adding a safety check to prevent a nil pointer reference.


324-349: Tuple decoding logic looks good.
The decodeOutput function is straightforward, and argument mapping appears correct.


350-359: Local struct definitions match ABI fields.
This approach ensures accurate decoding of complex types. No issues found.

prophet/handlers/pricepred/client_test.go (1)

5-5: Import statement is appropriate for BloomFilter decoding.
The addition of "encoding/base64" is correctly used in TestVerify.

prophet/handlers/pricepred/client.go (6)

24-30: Confirm correctness of the verify endpoint.
Double-check that the path "/api/task/inference/verify" is accurate and functional.


56-56: Generic post usage is clean and straightforward.
The refactoring to use post[PredictRequest, PredictResponse] is good for DRY principles.


107-108: Solid extension for backtesting.
The same post logic is consistently applied, improving maintainability.


110-114: Definition of VerifyRequest is clear.
The struct fields are well-labeled, aiding readability.


116-119: VerifyResponse struct looks good.
The fields and types match the verification scenario.


121-123: Introduction of Verify method is consistent.
The method mirrors existing patterns in Predict and Backtesting.

prophet/handlers/pricepred/pricepred_test.go (1)

77-80: LGTM! Test data structure updated with SolverReceipt field.

The test case correctly initializes the new SolverReceipt field with appropriate test data.

Comment on lines +112 to +118
SolverReceipt: struct {
BloomFilter []byte
CountItems *big.Int
}{
BloomFilter: []byte("BgAAAAAAAAApt1DE"),
CountItems: big.NewInt(3),
},
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix type mismatch in CountItems between input and expected output.

There's a type mismatch in the CountItems field:

  • Input: CountItems: 3 (int)
  • Expected: CountItems: big.NewInt(3) (*big.Int)

This could lead to subtle bugs if the actual implementation expects consistency in types.

Consider using the same type in both structures. If *big.Int is the correct type, update the ResponseSolverReceipt struct to use *big.Int for CountItems.

 SolverReceipt: ResponseSolverReceipt{
   BloomFilter: []byte("BgAAAAAAAAApt1DE"),
-  CountItems:  3,
+  CountItems:  big.NewInt(3),
 },

Committable suggestion skipped: line range outside the PR's diff.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Implement Verify for pricepredict future handler
1 participant