Skip to content

feat(spider-storage): Implement the task instance management gRPC service and migrate it to Status-based errors. - #354

Merged
LinZhihao-723 merged 1 commit into
y-scope:mainfrom
LinZhihao-723:task-instance-management-impl
Jun 24, 2026
Merged

feat(spider-storage): Implement the task instance management gRPC service and migrate it to Status-based errors.#354
LinZhihao-723 merged 1 commit into
y-scope:mainfrom
LinZhihao-723:task-instance-management-impl

Conversation

@LinZhihao-723

@LinZhihao-723 LinZhihao-723 commented Jun 23, 2026

Copy link
Copy Markdown
Member

Description

Summary

This PR implements the storage server's TaskInstanceManagementService end-to-end and brings it in line with the JobOrchestrationService error model: the RPCs now return flat success payloads and propagate failures through gRPC Status codes instead of an in-body oneof error. It also replaces the bincode-serialized execution context with a typed protobuf message, threads the storage session into the stale-session error, and updates the execution-manager client to match.

The scope is TaskInstanceManagementService and its execution-manager client. The other services are unchanged.

Protocol changes (storage.proto + regenerated bindings)

These are wire-breaking changes to TaskInstanceManagementService; the server and the execution-manager client are updated together in this branch.

  • RegisterTaskInstanceResponse no longer wraps a oneof result { bytes execution_context; TaskInstanceManagementError error }. It now carries a typed ExecutionContext execution_context.
  • Added ExecutionContext, TdlContext, and TimeoutPolicy messages that mirror the spider_core types, replacing the opaque bincode-serialized bytes. serialized_inputs stays bytes (an already-serialized payload).
  • TaskInstanceOperationResponse (used by ReportTaskSuccess / ReportTaskFailure) collapses from oneof result { Void ok; error } to an empty message — success is an empty acknowledgement, errors travel over Status.
  • Removed the TaskInstanceManagementError message and its ErrCode enum.
  • Regenerated components/spider-proto-rust/src/generated/storage.rs accordingly.

Request unpacking (spider-proto-rust/src/unpack/storage.rs)

Added RequestUnpack implementations for RegisterTaskInstanceRequest, ReportTaskSuccessRequest, and ReportTaskFailureRequest, each unpacking into the spider-native tuple its ServiceState method consumes. A shared unpack_task_id helper performs the only fallible step — converting the protobuf TaskId into the core TaskId (INVALID_ARGUMENT on a missing or unrepresentable task id). Each unpack logs failures with its own source context (request kind, execution manager id, and the relevant job / task-instance ids) so a malformed request can be traced to the originating execution manager.

Typed execution context (spider-proto-rust/src/io.rs, new)

Replaced the bincode round-trip with impl TryFrom<storage::ExecutionContext> for ExecutionContext. This lives in spider-proto-rust because storage::ExecutionContext is local there, which satisfies the orphan rule (the same pattern as the existing TaskId / JobState conversions). The conversion fails with the new Error::TdlContextMissing / Error::TimeoutPolicyMissing variants if a nested message is absent on the wire. Added pub mod io to the crate.

Storage server handlers (spider-storage/src/grpc.rs)

  • Implemented register_task_instance (unpack the request, call create_task_instance, build the typed ExecutionContext response), and report_task_success / report_task_failure (unpack, call the service, return the empty acknowledgement). Errors are surfaced as Status.
  • Added task_instance_management_service_error_handler, which maps a StorageServerError onto a Status and logs it: a fatal cache-internal error and any other unexpected error fire the cancellation token (the service restarts) and return INTERNAL; a stale session returns UNAVAILABLE; a stale cache state returns FAILED_PRECONDITION; malformed input returns INVALID_ARGUMENT.

Error-model changes

  • StorageServerError::StaleSession now carries the current SessionId. ServiceState::validate_session constructs it from self.inner.session_id, and the gRPC handler threads that value into the Status message so the client learns storage's current session.
  • cache/error.rs removes the CacheError::Db variant; a DbError now converts into CacheError::Internal(InternalError::Db(_)) via a manual From. As a result, a database error encountered inside a cache operation is treated as a fatal cache-internal error and restarts the service (a DB failure is taken to mean the cache may be inconsistent).

spider-core

Implemented Display for TaskId so it renders readably in logs and error messages (the task index for an index task, and commit / cleanup for the termination tasks).

Execution-manager client (spider-execution-manager)

  • client/grpc/storage.rs is rewired to the new protocol: register_task_instance reads the typed execution_context and runs it through ExecutionContext::try_from; report_task_success / report_task_failure succeed on the empty response; and a status_to_error helper maps Status codes back to StorageResponseError (UNAVAILABLEStaleSession, FAILED_PRECONDITIONCacheStale, INVALID_ARGUMENTInvalidInput, otherwise Server). The in-body error decoding and the local execution-context conversion are removed.
  • StorageResponseError::StaleSession changes from { storage_session: SessionId } to StaleSession(String), since a Status carries the storage session only as text (the server's session number arrives inside the message). runtime.rs and the test_runtime integration tests are updated for the new shape.

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

  • Ensure all workflows pass.

Summary by CodeRabbit

  • New Features

    • Task instance management operations (register, report success/failure) are now fully implemented.
  • Bug Fixes

    • Improved error messaging for session validation and storage operations.
  • Refactor

    • Simplified protobuf schema for task execution context and operation responses; streamlined error handling in storage operations.

@LinZhihao-723
LinZhihao-723 requested review from a team and sitaowang1998 as code owners June 23, 2026 22:38
@coderabbitai

coderabbitai Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

This PR implements the task instance management gRPC service endpoints in the storage server. The proto schema is refactored to use structured ExecutionContext, TdlContext, and TimeoutPolicy messages in place of raw bytes and oneof error unions. Matching conversion utilities, RequestUnpack implementations, and StorageServerError::StaleSession carrying a typed session value are added across the storage, proto-Rust, and execution-manager layers.

Changes

Task Instance Management gRPC Implementation

Layer / File(s) Summary
Proto schema: structured ExecutionContext and simplified responses
components/spider-proto/storage/storage.proto
RegisterTaskInstanceResponse now carries a typed ExecutionContext with TdlContext and TimeoutPolicy submessages; TaskInstanceOperationResponse is emptied and TaskInstanceManagementError is removed.
StaleSession error variant carries SessionId / String
components/spider-storage/src/state/error.rs, components/spider-execution-manager/src/client/storage.rs, components/spider-storage/src/state/service.rs
StorageServerError::StaleSession now carries SessionId; StorageResponseError::StaleSession now carries String; validate_session populates the session value.
Proto-Rust ExecutionContext conversion and unpack impls
components/spider-proto-rust/src/error.rs, components/spider-proto-rust/src/io.rs, components/spider-proto-rust/src/lib.rs, components/spider-proto-rust/src/unpack/storage.rs
Adds TdlContextMissing/TimeoutPolicyMissing error variants, TryFrom<storage::ExecutionContext> conversion, RequestUnpack impls for task instance request types, and a shared unpack_task_id helper.
Storage server task instance service implementation
components/spider-core/src/types/id.rs, components/spider-storage/src/cache/error.rs, components/spider-storage/src/grpc.rs
Adds Display for TaskId, fixes CacheError::Db wrapping, introduces task_instance_management_service_error_handler, and replaces todo! stubs in register_task_instance, report_task_success, and report_task_failure. Updates StaleStateError::JobAlreadyTerminated message to include job state.
Execution-manager gRPC client: tonic Status-based error mapping
components/spider-execution-manager/src/client/grpc/storage.rs
Replaces proto result-oneof parsing with status_to_error tonic Code mapping in all three task instance methods; removes old protobuf operation response helpers and updates tests.
Runtime and integration test updates for StaleSession shape
components/spider-execution-manager/src/runtime.rs, components/spider-storage/src/state/service.rs, tests/huntsman/em-runtime/tests/test_runtime.rs
Updates StaleSession match arms and test constructions to use the new tuple payload forms throughout.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • y-scope/spider#340: Modifies the same execution-manager gRPC storage client and storage.proto task-instance operation contracts that this PR further refactors.
  • y-scope/spider#343: Directly precedes this PR's changes to spider-execution-manager/src/client/grpc/storage.rs, StorageResponseError::StaleSession, and TaskId formatting in spider-core.
  • y-scope/spider#346: Modifies the same report_task_success/report_task_failure gRPC paths in spider-execution-manager/src/client/grpc/storage.rs that this PR refactors for tonic Status mapping.

Suggested reviewers

  • sitaowang1998
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main objective of the PR: implementing the TaskInstanceManagementService gRPC service and migrating to Status-based error handling.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

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

🧹 Nitpick comments (2)
components/spider-execution-manager/src/client/grpc/storage.rs (1)

165-178: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Expand test coverage for all status mapping branches.

The tests cover UNAVAILABLE and INVALID_ARGUMENT, but don't test FAILED_PRECONDITION → CacheStale or the default catch-all case that maps to Server.

🧪 Suggested additional tests
+    #[test]
+    fn status_maps_failed_precondition_to_cache_stale() {
+        match status_to_error(&Status::failed_precondition("job already terminated")) {
+            StorageResponseError::CacheStale(message) => assert!(message.contains("terminated")),
+            error => panic!("unexpected error: {error:?}"),
+        }
+    }
+
+    #[test]
+    fn status_maps_other_codes_to_server_error() {
+        match status_to_error(&Status::internal("internal error")) {
+            StorageResponseError::Server(message) => assert!(message.contains("internal")),
+            error => panic!("unexpected error: {error:?}"),
+        }
+    }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@components/spider-execution-manager/src/client/grpc/storage.rs` around lines
165 - 178, The status_to_error function test coverage is incomplete and missing
tests for two branches. Add two new test functions: one that tests when
Status::failed_precondition is passed to status_to_error and verifies it maps to
StorageResponseError::CacheStale, and another that tests the default catch-all
case (e.g., using Status::ok or another unmapped status code) to verify it maps
to StorageResponseError::Server. Follow the same pattern as the existing
status_maps_unavailable_to_stale_session and
status_maps_invalid_argument_to_invalid_input tests.
components/spider-proto-rust/src/io.rs (1)

65-82: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add test coverage for missing timeout policy.

The tests cover the successful conversion case and the missing TDL context case, but there's no test verifying that TimeoutPolicyMissing is returned when timeout_policy is None.

🧪 Suggested test case
+    #[test]
+    fn execution_context_rejects_missing_timeout_policy() {
+        let proto = storage::ExecutionContext {
+            task_instance_id: 7,
+            tdl_context: Some(storage::TdlContext {
+                package: "pkg".to_owned(),
+                task_func: "func".to_owned(),
+            }),
+            timeout_policy: None,
+            serialized_inputs: Vec::new(),
+        };
+
+        assert!(matches!(
+            ExecutionContext::try_from(proto),
+            Err(Error::TimeoutPolicyMissing)
+        ));
+    }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@components/spider-proto-rust/src/io.rs` around lines 65 - 82, Add a new test
function after execution_context_rejects_missing_tdl_context that creates an
ExecutionContext proto with timeout_policy set to None (while providing valid
tdl_context) and assert that ExecutionContext::try_from(proto) returns
Err(Error::TimeoutPolicyMissing) to verify the conversion properly validates
that timeout_policy is present.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@components/spider-execution-manager/src/client/grpc/storage.rs`:
- Around line 165-178: The status_to_error function test coverage is incomplete
and missing tests for two branches. Add two new test functions: one that tests
when Status::failed_precondition is passed to status_to_error and verifies it
maps to StorageResponseError::CacheStale, and another that tests the default
catch-all case (e.g., using Status::ok or another unmapped status code) to
verify it maps to StorageResponseError::Server. Follow the same pattern as the
existing status_maps_unavailable_to_stale_session and
status_maps_invalid_argument_to_invalid_input tests.

In `@components/spider-proto-rust/src/io.rs`:
- Around line 65-82: Add a new test function after
execution_context_rejects_missing_tdl_context that creates an ExecutionContext
proto with timeout_policy set to None (while providing valid tdl_context) and
assert that ExecutionContext::try_from(proto) returns
Err(Error::TimeoutPolicyMissing) to verify the conversion properly validates
that timeout_policy is present.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 0606e858-0c7b-44e9-aa29-ccd6853e3fe1

📥 Commits

Reviewing files that changed from the base of the PR and between 3d97992 and b8b43eb.

⛔ Files ignored due to path filters (1)
  • components/spider-proto-rust/src/generated/storage.rs is excluded by !**/generated/**
📒 Files selected for processing (14)
  • components/spider-core/src/types/id.rs
  • components/spider-execution-manager/src/client/grpc/storage.rs
  • components/spider-execution-manager/src/client/storage.rs
  • components/spider-execution-manager/src/runtime.rs
  • components/spider-proto-rust/src/error.rs
  • components/spider-proto-rust/src/io.rs
  • components/spider-proto-rust/src/lib.rs
  • components/spider-proto-rust/src/unpack/storage.rs
  • components/spider-proto/storage/storage.proto
  • components/spider-storage/src/cache/error.rs
  • components/spider-storage/src/grpc.rs
  • components/spider-storage/src/state/error.rs
  • components/spider-storage/src/state/service.rs
  • tests/huntsman/em-runtime/tests/test_runtime.rs

@LinZhihao-723 LinZhihao-723 changed the title feat(spider-storage): Implement the task-instance management gRPC service and migrate it to Status-based errors. feat(spider-storage): Implement the task instance management gRPC service and migrate it to Status-based errors. Jun 24, 2026
@LinZhihao-723
LinZhihao-723 merged commit 1870856 into y-scope:main Jun 24, 2026
16 checks passed
@LinZhihao-723
LinZhihao-723 deleted the task-instance-management-impl branch June 24, 2026 02:52
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