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

Fix execute_operator() with delegation #5180

Merged
merged 3 commits into from
Nov 23, 2024
Merged

Conversation

swheaton
Copy link
Contributor

@swheaton swheaton commented Nov 22, 2024

resolve_type_with_context() had morphed since introduction and was now recreating the Context even though we already have it. The bug was that when scheduled from the SDK, operator_uri is not a part of request_params. When scheduled from the UI, it is, plus a whole bunch of other attributes. Introduced sometime pre-v1.0

What changes are proposed in this pull request?

Repurpose/refactor resolve_type_with_context() to be more what the name implies it's gonna do. Then make resolve_type() use that also.
If we reuse the ExecutionContext we already had (which was properly created), it is cleaner plus has a valid operator_uri which fixes this particular bug.

How is this patch tested? If it is not, please explain why.

I tried to make some exposing tests but I was getting frustrated and I have limited hours before going out for a week. So ended up scrapping it.
We definitely need more testing in this area of the code.

Here's @brimoor's manual test that works now (no error on resolving output schema).

import fiftyone as fo
import fiftyone.operators as foo
import fiftyone.zoo as foz

dataset = foz.load_zoo_dataset("quickstart")
compute_metadata = foo.get_operator("@voxel51/utils/compute_metadata")

# Schedule a delegated operation to (re)compute metadata
compute_metadata(dataset, overwrite=True, delegate=True)
$ fiftyone delegated launch
Running operation xyz (@voxel51/utils/compute_metadata)
Computing metadata...
 100% |██████████████████████████| 200/200 [50.6ms elapsed, 0s remaining, 4.0K samples/s] 

Operation xyz complete

Summary by CodeRabbit

  • New Features

    • Enhanced error handling for output schema resolution, now logging warnings instead of raising exceptions.
    • Simplified type resolution process with improved error management.
  • Documentation

    • Updated comments and docstrings for clarity on method functionality.

Copy link
Contributor

coderabbitai bot commented Nov 22, 2024

Walkthrough

The changes introduced in this pull request primarily focus on refining the error handling and request parameter management within the DelegatedOperationService class in fiftyone/operators/delegated.py and the resolve_type and resolve_type_with_context functions in fiftyone/operators/executor.py. The modifications streamline the process of resolving output types and enhance clarity in error management by logging warnings instead of raising exceptions. Additionally, minor adjustments to comments and method signatures improve the overall documentation and organization of the code.

Changes

File Path Change Summary
fiftyone/operators/delegated.py Modified _execute_operator in DelegatedOperationService to set target and results in ctx.request_params directly; updated error handling to log warnings instead of raising exceptions; clarified comments.
fiftyone/operators/executor.py Simplified resolve_type by removing try-except block; updated resolve_type_with_context to handle errors internally; minor comment and docstring updates. Method signatures for resolve_type_with_context and resolve_type updated to include new parameters.

Possibly related PRs

Suggested reviewers

  • swheaton
  • ritch
  • imanjra

🐰 In the code, we hop and play,
With requests and types, we find our way.
Errors now logged, no more dismay,
Clarity blooms, brightening the day!
Let's refine and structure, come what may! 🎉


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.

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
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)
fiftyone/operators/delegated.py (2)

Line range hint 522-532: Improve error handling specificity and message formatting.

Consider these improvements to the error handling:

  1. Be more specific about which AttributeError you're catching
  2. Use string formatting instead of concatenation for the warning message
-        except (AttributeError, Exception):
-            logger.warning(
-                "Failed to resolve output schema for the operation."
-                + traceback.format_exc(),
-            )
+        except (AttributeError, Exception) as e:
+            logger.warning(
+                "Failed to resolve output schema for the operation: %s\n%s",
+                str(e),
+                traceback.format_exc(),
+            )

Line range hint 518-532: Add tests to prevent regression.

The PR mentions that tests were not added due to time constraints. Given the critical nature of this fix, we should add tests to:

  1. Verify context reuse works correctly
  2. Ensure output schema resolution handles errors gracefully
  3. Validate the fix for operations scheduled from SDK

Would you like me to help create these tests? I can generate test cases that cover these scenarios.

fiftyone/operators/executor.py (1)

394-399: Improve error handling

The error handling could be enhanced by including the exception details in the error traceback.

-    except Exception as e:
-        return ExecutionResult(error=traceback.format_exc())
+    except Exception as e:
+        return ExecutionResult(
+            error=traceback.format_exc(),
+            error_message=str(e)
+        )
🧰 Tools
🪛 Ruff (0.7.0)

398-398: Local variable e is assigned to but never used

Remove assignment to unused variable e

(F841)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1b52f51 and d621680.

📒 Files selected for processing (2)
  • fiftyone/operators/delegated.py (1 hunks)
  • fiftyone/operators/executor.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.7.0)
fiftyone/operators/executor.py

398-398: Local variable e is assigned to but never used

Remove assignment to unused variable e

(F841)

🔇 Additional comments (3)
fiftyone/operators/delegated.py (1)

518-521: LGTM! Verify impact on existing operations.

The changes correctly reuse the existing context by setting parameters directly in ctx.request_params. This fixes the bug where context was being unnecessarily recreated.

Let's verify the impact on existing operations:

✅ Verification successful

The search results show that resolve_type_with_context is only used in two places:

  1. In fiftyone/operators/executor.py where it's defined and exported
  2. In fiftyone/operators/delegated.py where we're modifying its usage

Let me verify if there are any other places where the execution context or operator types are being manipulated:


Changes are safe and properly integrated with the codebase

The verification confirms that the changes are safe because:

  1. resolve_type_with_context is only used in two places: its definition in executor.py and our modified usage in delegated.py
  2. The request_params["target"] and request_params["results"] are only set in this specific location
  3. The output schema resolution follows the same pattern used elsewhere in the codebase, as seen in the test files
  4. The error handling aligns with similar schema resolution code in executor.py
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other places where resolve_type_with_context is called
rg -A 5 "resolve_type_with_context"

# Search for places where request_params["target"] or request_params["results"] are set
rg -A 5 'request_params\["(?:target|results)"\]'

Length of output: 2002


Script:

#!/bin/bash
# Search for ExecutionContext usage
rg -A 5 "class ExecutionContext"

# Search for places where operator types are resolved
rg -A 5 "(?:input|output)s?_schema"

Length of output: 10813

fiftyone/operators/executor.py (2)

382-382: LGTM: Simplified resolve_type implementation

The function now correctly delegates to resolve_type_with_context, which aligns with the PR objective of reusing the existing context instead of recreating it.


385-392: LGTM: Improved function signature

The new signature explicitly accepts operator and context parameters, which:

  • Makes dependencies clearer
  • Enables context reuse
  • Fixes the bug where context was being unnecessarily recreated

Copy link
Contributor

@brimoor brimoor left a comment

Choose a reason for hiding this comment

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

LGTM

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

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d621680 and be38d26.

📒 Files selected for processing (2)
  • fiftyone/operators/delegated.py (1 hunks)
  • fiftyone/operators/executor.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • fiftyone/operators/delegated.py
🧰 Additional context used
🪛 Ruff (0.7.0)
fiftyone/operators/executor.py

401-401: Local variable e is assigned to but never used

Remove assignment to unused variable e

(F841)

🔇 Additional comments (2)
fiftyone/operators/executor.py (2)

381-382: LGTM! Clean refactor of resolve_type()

The function has been simplified by delegating to resolve_type_with_context(), which improves code maintainability.


385-396: LGTM! Improved function signature

The function signature has been updated to take more specific parameters (operator and context) instead of raw request parameters, which improves clarity and type safety.

Comment on lines +397 to +402
try:
return operator.resolve_type(
context, context.request_params.get("target", "inputs")
)
except Exception as e:
return ExecutionResult(error=traceback.format_exc())
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance error handling

The error handling could be improved in two ways:

  1. The caught exception 'e' is unused
  2. The error message from the exception is not included in the ExecutionResult

Consider this improvement:

     try:
         return operator.resolve_type(
             context, context.request_params.get("target", "inputs")
         )
-    except Exception as e:
-        return ExecutionResult(error=traceback.format_exc())
+    except Exception as e:
+        return ExecutionResult(
+            error=traceback.format_exc(),
+            error_message=str(e)
+        )

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

🧰 Tools
🪛 Ruff (0.7.0)

401-401: Local variable e is assigned to but never used

Remove assignment to unused variable e

(F841)

@brimoor brimoor merged commit 03c4e84 into release/v1.1.0 Nov 23, 2024
13 checks passed
@brimoor brimoor deleted the fix/do-from-sdk branch November 23, 2024 01:08
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