Skip to content

fix(storage): Always create a reference when getting data from storage (fixes #132). - #119

Merged
sitaowang1998 merged 9 commits into
y-scope:mainfrom
sitaowang1998:data_reference
May 9, 2025
Merged

fix(storage): Always create a reference when getting data from storage (fixes #132).#119
sitaowang1998 merged 9 commits into
y-scope:mainfrom
sitaowang1998:data_reference

Conversation

@sitaowang1998

@sitaowang1998 sitaowang1998 commented May 1, 2025

Copy link
Copy Markdown
Collaborator

Description

Problem

Spider currently only tracks Data references when they are created by a task or client. However, if a job returns a Data object to a client, Spider does not register that the client is referencing this Data. As a result, when the job is removed from storage, the Data may be garbage collected, even though the client is still referencing , leading to potential errors.

Solution

This PR introduces new storage functions that retrieve Data and register a reference to it within the same transaction. All existing calls to get_data have been replaced with these new functions to ensure proper tracking of Data references. The associated tests have also been updated to reflect and validate the new behavior.

Fixes #132.

Checklist

  • The PR satisfies the contribution guidelines.
  • This is a breaking change and that has been indicated in the PR title, OR this isn't a
    breaking change.
  • Necessary docs have been updated, OR no docs need to be updated.

Validation performed

  • GitHub workflows pass.
  • Unit tests pass in dev container.
  • Integration tests pass in dev container.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features
    • Enhanced data retrieval to distinguish between driver and task sources, allowing more precise data association and access.
  • Refactor
    • Updated job and function handling to explicitly track and propagate the source and ID of jobs and tasks throughout the system.
    • Modularized data retrieval with locality and added explicit transaction handling.
    • Adjusted function invocation signatures and task execution to include explicit task ID propagation.
  • Tests
    • Improved tests to validate correct handling of task IDs and job associations in function execution and task management.

@sitaowang1998
sitaowang1998 requested a review from a team as a code owner May 1, 2025 02:31
@coderabbitai

coderabbitai Bot commented May 1, 2025

Copy link
Copy Markdown
Contributor
## Walkthrough

This change introduces explicit tracking of job sources (Driver or Task) throughout the job execution and data retrieval workflow. The `Job` class now records its source and associated identifier, which are propagated from both the `Driver` and `TaskContext` classes during job creation. Data retrieval in jobs is updated to use source-specific methods (`get_driver_data` or `get_task_data`) from the `DataStorage` interface, which are implemented in the MySQL storage backend. Function invocation and test code are updated to pass and utilize the task ID, ensuring consistent source-aware data handling.

## Changes

| File(s)                                                                 | Change Summary                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
|-------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `src/spider/client/Driver.hpp`, `src/spider/client/TaskContext.hpp`     | Updated `start` methods to pass job source (`JobSource::Driver` or `JobSource::Task`) and the relevant source ID (driver or task) to `Job` constructors.                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `src/spider/client/Job.hpp`                                             | Added `JobSource` enum, new private members for source and source ID, and updated constructors and result retrieval logic to use source-specific data fetching (`get_driver_data` or `get_task_data`).                                                                                                                                                                                                                                                                                                                                                                                      |
| `src/spider/storage/DataStorage.hpp`                                    | Added new pure virtual methods: `get_driver_data` and `get_task_data` to the `DataStorage` interface for source-specific data retrieval.                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `src/spider/storage/mysql/MySqlStorage.cpp`, `src/spider/storage/mysql/MySqlStorage.hpp` | Implemented `get_driver_data` and `get_task_data` methods, introduced helper for retrieving data with locality, and refactored data retrieval logic to support source-aware access.                                                                                                                                                                                                                                                                                                                                                                                                        |
| `src/spider/worker/FunctionManager.hpp`, `src/spider/worker/task_executor.cpp` | Modified function signatures and invocation flow to include and propagate the task ID, and updated data retrieval in function application to use `get_task_data`.                                                                                                                                                                                                                                                                                                                                                                                    |
| `tests/worker/test-FunctionManager.cpp`, `tests/worker/test-TaskExecutor.cpp` | Updated tests to generate, pass, and utilize explicit task IDs in context creation, function invocation, and job submission, ensuring source-aware job and data handling is exercised.                                                                                                                                                                                                                                                                                                                                                               |

## Sequence Diagram(s)

```mermaid
sequenceDiagram
    participant Driver
    participant Job
    participant DataStorage
    participant MySqlDataStorage

    Driver->>Job: start(...)\n(JobSource::Driver, driver_id, ...)
    Job->>DataStorage: get_result_conn()
    alt JobSource::Driver
        DataStorage->>MySqlDataStorage: get_driver_data(conn, driver_id, data_id, data)
    else JobSource::Task
        DataStorage->>MySqlDataStorage: get_task_data(conn, task_id, data_id, data)
    end
    MySqlDataStorage-->>DataStorage: Data
    DataStorage-->>Job: Data
    Job-->>Driver: Result

Assessment against linked issues

Objective Addressed Explanation
Prevent dangling data references by registering data references when client retrieves data (Issue #132)

Possibly related PRs

Suggested reviewers

  • kirkrodrigues

<!-- walkthrough_end -->

<!-- announcements_start -->

> [!TIP]
> <details>
> <summary>⚡️ Faster reviews with caching</summary>
> 
> - CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure `Review - Disable Cache` at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the `Data Retention` setting under your Organization Settings.
> 
> Enjoy the performance boost—your workflow just got faster.
> 
> </details>

<!-- announcements_end -->

---

<details>
<summary>📜 Recent review details</summary>

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

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between aa994f5ab563044d65b734b0e8d4a21eb02fe4e0 and b3096483e10d1ccbd8e91334910f5e18ace8e410.

</details>

<details>
<summary>📒 Files selected for processing (2)</summary>

* `src/spider/worker/FunctionManager.hpp` (4 hunks)
* `tests/worker/test-FunctionManager.cpp` (8 hunks)

</details>

<details>
<summary>🚧 Files skipped from review as they are similar to previous changes (2)</summary>

* tests/worker/test-FunctionManager.cpp
* src/spider/worker/FunctionManager.hpp

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms (3)</summary>

* GitHub Check: non-storage-unit-tests (ubuntu-22.04)
* GitHub Check: non-storage-unit-tests (ubuntu-24.04)
* GitHub Check: lint

</details>

</details>
<!-- internal state start -->


<!-- DwQgtGAEAqAWCWBnSTIEMB26CuAXA9mAOY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qu1tAHtehh7VoAe1l0BlU1g3W2IGAPa3dGgAYgCBl1A68ucOv3QkBd1bagdWgDbW2JW1UG66LuiHUDqH16GOdWuvjWXrd0tiBURlIYhQb61wGhiJdFsRdqBAo6idf+svVKBgNd0OdT2oHXoaN1aANALdHQyxAX1Agejbui7XoZ0MtAAdT2oEDXr0Mu6pdbQHQxoBbEl0cDV2tsSlB0MJALtYxogDCRuN10AdeOt3SzqH1DahgGRuXWYaMMl6/tT2tnV3RQIy61DUpprWFrtOdJeis+FLXQQ6AbKdzPoCAA=== -->

<!-- internal state end -->
<!-- finishing_touch_checkbox_start -->

<details open="true">
<summary>✨ Finishing Touches</summary>

- [ ] <!-- {"checkboxId": "7962f53c-55bc-4827-bfbf-6a18da830691"} --> 📝 Generate Docstrings

</details>

<!-- finishing_touch_checkbox_end -->
<!-- tips_start -->

---

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.

<details>
<summary>❤️ Share</summary>

- [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai)
- [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai)
- [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai)
- [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)

</details>

<details>
<summary>🪧 Tips</summary>

### Chat

There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=y-scope/spider&utm_content=119):

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

### Support

Need help? Create a ticket on our [support page](https://www.coderabbit.ai/contact-us/support) 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](https://docs.coderabbit.ai/finishing-touches/docstrings) for this PR.
- `@coderabbitai generate sequence diagram` to generate a sequence diagram of the changes in 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` 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](https://docs.coderabbit.ai/guides/configure-coderabbit) 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](https://docs.coderabbit.ai) for detailed information on how to use CodeRabbit.
- Join our [Discord Community](http://discord.gg/coderabbit) to get help, request features, and share feedback.
- Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.

</details>

<!-- tips_end -->

@sitaowang1998 sitaowang1998 changed the title Fix: Add data reference when getting data. fix(storage): Add data reference when getting data. May 1, 2025

@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: 2

🔭 Outside diff range comments (1)
src/spider/worker/FunctionManager.hpp (1)

269-276: ⚠️ Potential issue

Logical operator likely wrong – aborts only when BOTH checks fail

if (msgpack::type::ARRAY != object.type && object.via.array.size < 1)

The intent seems to be “type is not ARRAY or the array is empty”.
Using && means the error path is triggered only when both conditions are true, allowing an empty array to slip through if the type is ARRAY.
Replace && with ||:

- if (msgpack::type::ARRAY != object.type && object.via.array.size < 1) {
+ if (msgpack::type::ARRAY != object.type || object.via.array.size < 1) {
🧹 Nitpick comments (2)
src/spider/worker/FunctionManager.hpp (1)

300-324: Potential connection-leak / missing commit

get_storage_factory(...)->provide_storage_connection() returns a unique_ptr that is never explicitly commit()-ed or rollback()-ed on the success path.
While most DBs autocommit reads, relying on destructor side-effects is fragile and, if the connector starts an implicit transaction, may keep metadata locks longer than necessary.
Consider wrapping the connection usage in an RAII helper that calls commit() once the last argument is parsed.

src/spider/storage/mysql/MySqlStorage.cpp (1)

2030-2069: Missing commit() on successful read

get_data_with_locality returns after a successful SELECT without committing.
If the connector implicitly opens a transaction, the outer caller must remember to commit/rollback.
Safer pattern:

+ static_cast<MySqlConnection&>(conn)->commit();
  return StorageErr{};
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8f634bc and a1ce188.

📒 Files selected for processing (10)
  • src/spider/client/Driver.hpp (2 hunks)
  • src/spider/client/Job.hpp (4 hunks)
  • src/spider/client/TaskContext.hpp (2 hunks)
  • src/spider/storage/DataStorage.hpp (1 hunks)
  • src/spider/storage/mysql/MySqlStorage.cpp (1 hunks)
  • src/spider/storage/mysql/MySqlStorage.hpp (2 hunks)
  • src/spider/worker/FunctionManager.hpp (4 hunks)
  • src/spider/worker/task_executor.cpp (1 hunks)
  • tests/worker/test-FunctionManager.cpp (8 hunks)
  • tests/worker/test-TaskExecutor.cpp (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (4)
src/spider/client/Job.hpp (2)
src/spider/client/Driver.cpp (2)
  • Driver (24-65)
  • Driver (67-106)
src/spider/core/Task.hpp (5)
  • Task (176-179)
  • Task (176-176)
  • Task (181-185)
  • id (187-187)
  • id (187-187)
src/spider/client/Driver.hpp (3)
tests/integration/client.py (1)
  • Driver (43-44)
src/spider/client/Driver.cpp (2)
  • Driver (24-65)
  • Driver (67-106)
src/spider/core/Driver.hpp (2)
  • Driver (12-12)
  • Driver (12-12)
src/spider/worker/FunctionManager.hpp (2)
src/spider/core/TaskContextImpl.hpp (2)
  • task_id (16-23)
  • task_id (16-21)
src/spider/client/Job.hpp (4)
  • conn (193-211)
  • conn (193-193)
  • conn (214-376)
  • conn (214-214)
src/spider/storage/mysql/MySqlStorage.cpp (2)
src/spider/storage/mysql/MySqlStorage.hpp (16)
  • conn (38-38)
  • conn (39-39)
  • conn (40-40)
  • conn (41-42)
  • conn (43-48)
  • conn (49-55)
  • conn (56-57)
  • conn (58-59)
  • conn (60-61)
  • conn (62-66)
  • conn (67-68)
  • conn (69-73)
  • conn (74-74)
  • conn (75-75)
  • conn (76-77)
  • conn (78-79)
src/spider/core/Data.hpp (2)
  • locality (30-30)
  • locality (30-30)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: non-storage-unit-tests (ubuntu-22.04)
  • GitHub Check: non-storage-unit-tests (ubuntu-24.04)
  • GitHub Check: lint
🔇 Additional comments (25)
src/spider/worker/task_executor.cpp (1)

175-175: Function call updated to include task_id parameter.

This change passes the task ID to the function being executed, which is necessary for the new source-aware data retrieval system. This ensures the data accessed during function execution is properly associated with the task.

src/spider/client/TaskContext.hpp (2)

175-182: Job constructor now tracks task as the source.

Good implementation - the job is now explicitly initialized with the task as its source, along with the task ID. This ensures proper data reference tracking when retrieving data through this job.


234-241: Task source tracking added to Task Graph jobs.

Similar to the previous change, this ensures task graph jobs also track their source as a task with the appropriate task ID, maintaining consistency in the job source tracking implementation.

tests/worker/test-TaskExecutor.cpp (4)

22-23: Added necessary Task-related includes.

These additional includes are required for the Task and TaskGraph manipulation in the updated test.


184-195: Properly set up job with explicit task ID for testing.

This addition properly creates a job with a valid task ID before testing the task executor, which is essential for testing the new source-aware data retrieval functionality. The test now properly simulates the real-world job creation and execution flow.


206-206: Using explicit task ID in executor creation.

Using the same task ID that was used to create the job ensures that the test properly validates the source-aware data retrieval mechanism.


222-222: Added proper cleanup of the test job.

Good practice to clean up the job after the test, maintaining test isolation and preventing test data accumulation.

src/spider/storage/DataStorage.hpp (1)

35-49: Added source-specific data retrieval methods.

These new methods enhance the DataStorage interface to support retrieving data with source awareness (driver or task). This is the foundation for ensuring data references are properly maintained when data is retrieved, not just when it's created.

Both methods follow the established interface pattern and clearly specify their parameters.

src/spider/client/Driver.hpp (2)

231-232: Good enhancement to propagate source information!

These new parameters properly identify the job as originating from a Driver and pass the driver's UUID. This change enables tracking data references during retrieval operations and fixes the issue where data references were only registered during creation.


296-297: Consistent implementation for the TaskGraph version!

The same source identification parameters are correctly applied to this overloaded method, ensuring consistent behavior between both start methods. This maintains parity in how source tracking is implemented across the codebase.

src/spider/client/Job.hpp (6)

160-163: Good addition of JobSource enum!

This enum clearly identifies the origin of a job (Driver or Task), which is essential for the new data reference tracking system. It provides type safety and clear semantics for the source concept.


165-167: Appropriate constructor enhancement!

Updating the constructor to accept source type and ID ensures that every Job instance has the necessary context for proper data reference tracking. This is crucial for addressing the core issue where data references were missing when retrieved.


178-180: Consistent implementation in the overloaded constructor!

The same source parameters are correctly added to this constructor, ensuring consistent behavior regardless of how the Job is created.


258-272: Key implementation for source-aware data retrieval!

This conditional logic is the core of the fix - it uses the job's source information to call the appropriate data retrieval method, ensuring data references are registered within the same transaction as data retrieval. This directly addresses the issue where data returned to clients lacked references after job deletion.


332-346: Consistent implementation for non-tuple return types!

The same source-aware data retrieval logic is correctly implemented for the non-tuple return path, ensuring consistent behavior across all data retrieval scenarios. This maintains the fix for data reference tracking across different types of returned data.


381-382: Essential member variables for tracking source!

These member variables store the source information passed to the constructor, enabling the conditional logic in data retrieval methods. They're a necessary part of the solution for tracking data references.

tests/worker/test-FunctionManager.cpp (5)

18-20: Appropriate includes added!

Adding includes for Task.hpp and TaskGraph.hpp supports the new task creation and graph manipulation code in the tests, which is needed to validate the source-aware data reference tracking.


81-82: Good change to use consistent task ID!

Generating a single task ID per test case ensures consistency throughout the test and properly validates that source information is correctly propagated across function calls.


101-101: Updated function call with task ID parameter!

This change passes the task ID to the function, matching the updated signature and testing the propagation of source information through the function invocation path.


187-198: Excellent test setup for data reference validation!

This code properly creates a task with the test task ID, associates it with input data, builds a task graph, and submits it as a job. This comprehensive setup validates the end-to-end flow of the source-aware data reference tracking system, particularly ensuring that data is correctly associated with its source task.


214-214: Good test cleanup!

Adding cleanup code to remove the job ensures proper test isolation and prevents resource leakage between test cases.

src/spider/storage/mysql/MySqlStorage.hpp (2)

151-162: Excellent implementation of source-specific data retrieval!

These new methods implement the core storage functionality needed to fix the data reference issue. They retrieve data while registering references to either a driver or task within the same transaction, ensuring data references are properly maintained even when jobs are deleted.

The method signatures correctly take source IDs (driver_id or task_id) to associate with the data, which is essential for the source-aware data reference tracking.


202-204: Good helper method for code reuse!

This private helper method likely handles the common functionality needed by both source-specific retrieval methods, promoting code reuse while maintaining clear separation of concerns. It retrieves data with locality information, which is crucial for the storage implementation.

src/spider/worker/FunctionManager.hpp (2)

377-382: Placeholder order looks correct – nice catch

The extra _2 placeholder for task_id is inserted in the right spot, keeping the ABI stable for callers.


47-49:

Details

❓ Verification inconclusive

Verify all call-sites after changing the Function signature

Function now expects (TaskContext&, boost::uuids::uuid, ArgsBuffer const&).
Any older invocations that still pass only two arguments will fail to compile or, worse, be implicitly converted to an unintended overload.
Please do a quick grep across the repo to confirm every Function (and any std::function you create from it) is invoked with three parameters.

Run:


🏁 Script executed:

#!/bin/bash
rg -n "get_function(" | rg -v "task_id"

Length of output: 116


To avoid the regex error and reliably find all get_function( calls missing the task_id parameter, let’s search using a fixed-string match:


🏁 Script executed:

#!/bin/bash
# Search for get_function( without accidentally treating parentheses as regex
rg -n -F "get_function(" | rg -v "task_id"

Length of output: 892


We need to inspect how these functions are actually invoked. Let’s dump the surrounding lines in both the test and the executor:


🏁 Script executed:

#!/bin/bash
# Show context around get_function in the tests
rg -n -C3 "manager.get_function" tests/worker/test-FunctionManager.cpp
# Show context around get_function in task_executor
rg -n -C3 "get_function" src/spider/worker/task_executor.cpp

Length of output: 2210


Let’s inspect the actual invocation in task_executor.cpp to ensure it’s called with all three args:


🏁 Script executed:

#!/bin/bash
# Show more context around get_function in the executor
rg -n -C6 "get_function" src/spider/worker/task_executor.cpp
# Look for the actual call to (*function) there
rg -n -C6 "(*function)" src/spider/worker/task_executor.cpp

Length of output: 870


Verify all call-sites include the new task_id parameter

Automated grep confirms that in tests/worker/test-FunctionManager.cpp the calls to (*function) pass three arguments (context, task_id, args_buffers), but we couldn’t locate the actual invocation in the executor. Please manually inspect:

• src/spider/worker/task_executor.cpp – ensure the Function const* function = …; is invoked as
(*function)(context, task_id, args_buffer) (or equivalent) with all three parameters.
• Any other sites where a Function pointer or std::function is called, verify they’re updated to accept (TaskContext&, boost::uuids::uuid, ArgsBuffer const&).

Comment thread src/spider/storage/mysql/MySqlStorage.cpp
Comment thread src/spider/storage/mysql/MySqlStorage.cpp
@sitaowang1998
sitaowang1998 requested a review from davidlion May 1, 2025 03:25
Comment thread src/spider/storage/DataStorage.hpp Outdated
Comment thread src/spider/storage/DataStorage.hpp Outdated
Comment thread src/spider/storage/DataStorage.hpp Outdated
Comment thread src/spider/storage/DataStorage.hpp Outdated
Comment thread src/spider/worker/FunctionManager.hpp Outdated
Comment thread src/spider/client/Job.hpp Outdated
Comment thread src/spider/storage/mysql/MySqlStorage.hpp Outdated
Comment thread src/spider/storage/mysql/MySqlStorage.hpp Outdated
Comment thread src/spider/storage/mysql/MySqlStorage.cpp Outdated
Comment thread src/spider/storage/mysql/MySqlStorage.cpp Outdated
Co-authored-by: davidlion <davidlion2@protonmail.com>

@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

♻️ Duplicate comments (1)
src/spider/storage/mysql/MySqlStorage.cpp (1)

2163-2191: Consider handling duplicate key errors gracefully for task references

Similar to the driver references, the task reference insertion should handle duplicate keys gracefully to avoid unnecessary transaction rollbacks.

Consider modifying the SQL to use ON DUPLICATE KEY UPDATE or checking if the reference exists before inserting:

- std::unique_ptr<sql::PreparedStatement> statement{
-         static_cast<MySqlConnection&>(conn)->prepareStatement(
-                 "INSERT INTO `data_ref_task` (`id`, `task_id`) VALUES (?, ?)"
-         )
- };
+ std::unique_ptr<sql::PreparedStatement> statement{
+         static_cast<MySqlConnection&>(conn)->prepareStatement(
+                 "INSERT IGNORE INTO `data_ref_task` (`id`, `task_id`) VALUES (?, ?)"
+         )
+ };

Alternatively, in the catch block:

 } catch (sql::SQLException& e) {
     static_cast<MySqlConnection&>(conn)->rollback();
+    if (e.getErrorCode() == ErDupKey || e.getErrorCode() == ErDupEntry) {
+        // Reference already exists, this is fine
+        static_cast<MySqlConnection&>(conn)->commit();
+        return StorageErr{};
+    }
     return StorageErr{StorageErrType::OtherErr, e.what()};
 }
🧹 Nitpick comments (1)
src/spider/storage/mysql/MySqlStorage.cpp (1)

2133-2161: Consider handling duplicate key errors gracefully

The method correctly implements driver reference tracking, but it could handle the case where the same reference already exists more gracefully. Currently, a duplicate key error would cause a transaction rollback, which might be inefficient.

Consider modifying the SQL to use ON DUPLICATE KEY UPDATE or checking if the reference exists before inserting:

- std::unique_ptr<sql::PreparedStatement> statement{
-         static_cast<MySqlConnection&>(conn)->prepareStatement(
-                 "INSERT INTO `data_ref_driver` (`id`, `driver_id`) VALUES (?, ?)"
-         )
- };
+ std::unique_ptr<sql::PreparedStatement> statement{
+         static_cast<MySqlConnection&>(conn)->prepareStatement(
+                 "INSERT IGNORE INTO `data_ref_driver` (`id`, `driver_id`) VALUES (?, ?)"
+         )
+ };

Alternatively, in the catch block:

 } catch (sql::SQLException& e) {
     static_cast<MySqlConnection&>(conn)->rollback();
+    if (e.getErrorCode() == ErDupKey || e.getErrorCode() == ErDupEntry) {
+        // Reference already exists, this is fine
+        static_cast<MySqlConnection&>(conn)->commit();
+        return StorageErr{};
+    }
     return StorageErr{StorageErrType::OtherErr, e.what()};
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9132afa and aa994f5.

📒 Files selected for processing (6)
  • src/spider/client/Job.hpp (4 hunks)
  • src/spider/storage/DataStorage.hpp (1 hunks)
  • src/spider/storage/mysql/MySqlStorage.cpp (1 hunks)
  • src/spider/storage/mysql/MySqlStorage.hpp (2 hunks)
  • src/spider/worker/FunctionManager.hpp (4 hunks)
  • tests/worker/test-FunctionManager.cpp (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/spider/storage/mysql/MySqlStorage.hpp
  • tests/worker/test-FunctionManager.cpp
  • src/spider/storage/DataStorage.hpp
  • src/spider/client/Job.hpp
  • src/spider/worker/FunctionManager.hpp
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/spider/storage/mysql/MySqlStorage.cpp (3)
src/spider/storage/mysql/MySqlStorage.hpp (16)
  • conn (38-38)
  • conn (39-39)
  • conn (40-40)
  • conn (41-42)
  • conn (43-48)
  • conn (49-55)
  • conn (56-57)
  • conn (58-59)
  • conn (60-61)
  • conn (62-66)
  • conn (67-68)
  • conn (69-73)
  • conn (74-74)
  • conn (75-75)
  • conn (76-77)
  • conn (78-79)
src/spider/core/Task.hpp (6)
  • id (187-187)
  • id (187-187)
  • locality (156-158)
  • locality (156-156)
  • locality (160-162)
  • locality (160-160)
src/spider/core/Data.hpp (2)
  • locality (30-30)
  • locality (30-30)
🔇 Additional comments (2)
src/spider/storage/mysql/MySqlStorage.cpp (2)

2077-2116: Looks good: New helper method for data retrieval with locality

This helper method properly fetches data by ID and retrieves its associated localities in a structured way. It correctly handles the case where the data isn't found and appropriately populates the provided Data object.


2118-2131: Good refactoring of get_data to use the new helper

The refactoring of the existing get_data method to use the new helper is clean and maintains proper transaction handling.

@sitaowang1998

Copy link
Copy Markdown
Collaborator Author

@CodeRabbit. Please create an issue about cleaning up storage functions that are used only in testing. Please create another issue about moving the data fetching from FunctionManager into worker.

@coderabbitai

coderabbitai Bot commented May 9, 2025

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find storage-related files
echo "--- Storage-related files ---"
fd "Storage" --type f --extension hpp --extension cpp | grep -v test

# Look at DataStorage interface to understand the available functions
echo "--- DataStorage interface ---"
cat src/spider/storage/DataStorage.hpp

# Check for FunctionManager and related data fetching code
echo "--- FunctionManager code ---"
cat src/spider/worker/FunctionManager.hpp

# Find potential storage functions that might only be used in tests
echo "--- Looking for storage function usage patterns ---"
rg "Storage::" --files-with-matches tests/
rg "get_data" --files-with-matches tests/

Length of output: 19357


🏁 Script executed:

#!/bin/bash
# Find more details about storage functions usage in production code and tests

# Check usage of storage functions in production code
echo "--- Functions in DataStorage not used in production code ---"
for func in add_driver_data add_task_data get_data get_driver_data get_task_data set_data_locality remove_data add_task_reference remove_task_reference add_driver_reference remove_driver_reference remove_dangling_data add_client_kv_data add_task_kv_data get_client_kv_data get_task_kv_data; do
  echo "Checking usage of $func in production code:"
  rg "\->$func\\(" --files-without-match "tests/" src/ | wc -l
done

# Look for worker code to understand where data fetching should be moved
echo "--- Worker code structure ---"
fd "worker" --type d src/

echo "--- Task executor code ---"
cat src/spider/worker/task_executor.cpp

# Look for related PR objectives and issues to understand the context better
echo "--- Look for related issues ---"
gh issue list --repo y-scope/spider --search "storage function"
gh issue list --repo y-scope/spider --search "test function"
gh issue list --repo y-scope/spider --search "worker data"

Length of output: 15295


cpp
boost::uuids::uuid const data_id = arg.asboost::uuids::uuid();
std::unique_ptr data = std::make_unique();
err = data_store->get_task_data(*conn, task_id, data_id, data.get());


should be moved to the worker, which would then pass already-fetched data objects to the function.

## Benefits

- Better separation of concerns
- More maintainable code structure
- Clearer responsibility boundaries between components

## Related Work
- PR #119 (Data references when getting data)

/cc @sitaowang1998"

🏁 Script executed:

#!/bin/bash
# Create first issue about cleaning up storage functions used only in testing

echo "Creating issue for cleaning up storage functions used only in testing..."

gh issue create \
    --repo y-scope/spider \
    --title "Cleanup: Remove storage functions used only in testing" \
    --body "## Background

Based on the analysis of PR #119 which added proper data reference tracking, we noticed that several storage functions are only used in testing code but are part of the public DataStorage interface.

## Problem

Several functions in the DataStorage interface might only be used for testing purposes but are exposed in the public API. This creates unnecessary complexity in the interface and implementation.

Potential candidates include:
- Some key-value data functions
- Reference management functions
- Data locality functions that might only be used in tests

## Proposed Solution

1. Analyze all storage functions to identify which ones are only used in tests
2. Move these functions to test-specific interfaces or implement them as test helpers
3. Remove them from the public interface of DataStorage
4. Update tests to use the new test-specific interfaces

## Benefits

- Cleaner, more focused public API
- Reduced implementation burden for new storage backends
- Better separation between production and test code

## Related Work
- PR #119 (Data references when getting data)

/cc @sitaowang1998"

echo "Creating issue for moving data fetching from FunctionManager into worker..."

# Create second issue about moving data fetching from FunctionManager into worker
gh issue create \
    --repo y-scope/spider \
    --title "Refactor: Move data fetching from FunctionManager into worker" \
    --body "## Background

PR #119 added data reference tracking when retrieving data objects. As part of this work, we identified that the data fetching logic currently lives in the FunctionManager class but would be better placed in the worker.

## Problem

Currently, the \`FunctionInvoker<F>::apply\` method in \`FunctionManager\` is responsible for:
1. Parsing function arguments
2. Fetching data objects from storage
3. Registering references to the data
4. Executing the function with the fetched data

This creates a tight coupling between function management and data access, violating the single responsibility principle.

## Proposed Solution

1. Move the data fetching logic from \`FunctionInvoker<F>::apply\` to the task executor (\`task_executor.cpp\`)
2. Update the function manager to focus solely on function registration and invocation
3. Make the worker responsible for data access and reference management

## Implementation Notes

The data fetching code in \`FunctionInvoker<F>::apply\`:

Length of output: 1711


🏁 Script executed:

#!/bin/bash
# Create second issue about moving data fetching from FunctionManager into worker

echo "Creating issue for moving data fetching from FunctionManager into worker..."

gh issue create \
    --repo y-scope/spider \
    --title "Refactor: Move data fetching from FunctionManager into worker" \
    --body "## Background

PR #119 added data reference tracking when retrieving data objects. As part of this work, we identified that the data fetching logic currently lives in the FunctionManager class but would be better placed in the worker.

## Problem

Currently, the FunctionInvoker<F>::apply method in FunctionManager is responsible for:
1. Parsing function arguments
2. Fetching data objects from storage
3. Registering references to the data
4. Executing the function with the fetched data

This creates a tight coupling between function management and data access, violating the single responsibility principle.

## Proposed Solution

1. Move the data fetching logic from FunctionInvoker<F>::apply to the task executor (task_executor.cpp)
2. Update the function manager to focus solely on function registration and invocation
3. Make the worker responsible for data access and reference management

## Implementation Notes

The data fetching code in FunctionInvoker<F>::apply should be moved to the worker, which would then pass already-fetched data objects to the function.

## Benefits

- Better separation of concerns
- More maintainable code structure
- Clearer responsibility boundaries between components

## Related Work
- PR #119 (Data references when getting data)

/cc @sitaowang1998"

Length of output: 1620


@sitaowang1998 I've created both issues for you:

  1. Issue #133: Cleanup: Remove storage functions used only in testing

    • Focuses on identifying and moving storage functions that are only used in tests
    • Improves API clarity and reduces implementation burden for new storage backends
  2. Issue #134: Refactor: Move data fetching from FunctionManager into worker

    • Addresses the tight coupling between function management and data access
    • Proposes moving data fetching logic from FunctionInvoker to the task executor

Both issues have been tagged with your username for follow-up.

@sitaowang1998
sitaowang1998 requested a review from davidlion May 9, 2025 18:46
@davidlion davidlion changed the title fix(storage): Add data reference when getting data. fix(storage): Always create a reference when getting data from storage (fixes #132). May 9, 2025
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.

Potential dangling data reference in client.

2 participants