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

Release/v1.2.0 #5306

Merged
merged 267 commits into from
Dec 20, 2024
Merged

Release/v1.2.0 #5306

merged 267 commits into from
Dec 20, 2024

Conversation

findtopher
Copy link
Member

@findtopher findtopher commented Dec 20, 2024

What changes are proposed in this pull request?

release version 1.2.0

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced documentation for Data Lens integration with Databricks.
    • New Error and ErrorIcon components for improved error handling in model evaluations.
    • Instance segmentation support in dataset import/export processes.
    • Added support for AWS session tokens in cloud credential configurations.
    • Improved functionality in the EvaluationPanel class for handling binary classification and segmentation evaluations.
    • New method for managing sidebar groups in the DatasetAppConfig class.
    • New fetchWithLinearBackoff function for enhanced HTTP request handling.
  • Bug Fixes

    • Improved error handling in the ImageElement and VideoElement classes.
    • Fixed visibility checks in grid tagging tests.
    • Addressed a bug that could lead to StopIteration errors during long-running operations with API connections.
  • Documentation

    • Expanded sections in the user guide for instance segmentation and dynamic attributes.
    • Updated API documentation to reflect new method signatures and functionalities.
    • New release note sections for "FiftyOne Teams 2.3.0" and "FiftyOne Teams 2.2.0".
  • Tests

    • Added unit tests for instance segmentation functionality and the TableView class.
    • Enhanced test coverage for detection masks and histogram panels.
  • Chores

    • Updated dependency versions in requirements/common.txt and setup.py.

findtopher and others added 30 commits November 8, 2024 16:13
bump mongoengine, motor, and pymongo
…canvas

performance: use offscreen canvas to decode on-disk masks
Merge `release/v1.1.0` to `develop`
Merge `release/v1.1.0` to `develop`
Merge `release/v1.1.0` to `develop`
Copy link
Contributor

coderabbitai bot commented Dec 20, 2024

Walkthrough

This pull request introduces comprehensive changes across multiple components of the FiftyOne project, focusing on enhancing mask handling, improving error management, and refining various system utilities. The modifications span workflow configurations, core functionality, and testing infrastructure, with significant updates to how detection and segmentation masks are processed, stored, and referenced. Key areas of improvement include mask path handling, workflow optimization, and expanded support for different label types.

Changes

File/Group Change Summary
.github/workflows/ Updated workflow configurations for build, documentation, end-to-end testing, and pull request processes
app/packages/core/src/ Enhanced component rendering, error handling, and routing logic
fiftyone/core/labels.py Added new _HasMedia mixin, introduced mask path handling for Detection and Segmentation classes
fiftyone/utils/ Updated utility functions for handling masks, labels, and data import/export
requirements/common.txt Updated dependency versions for mongoengine, motor, and pymongo
setup.py Incremented package version to 1.2.0 and updated dependency specifications

Suggested labels

documentation

Suggested reviewers

  • benjaminpkane

Poem

🐰 Hop, hop, through the code we go,
Masks and paths now start to flow
Workflows dance, dependencies sing
FiftyOne spreads its digital wing! 🚀


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.

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

🔭 Outside diff range comments (1)
fiftyone/utils/ultralytics.py (1)

Inconsistent mask access patterns found in the codebase

The verification reveals mixed usage of direct mask access and getter methods across the codebase:

  • Direct access (detection.mask) still present in:
    • fiftyone/utils/labels.py
    • fiftyone/utils/data/importers.py
    • fiftyone/core/labels.py (multiple instances)
  • Getter method (get_mask()) is used in:
    • fiftyone/utils/labelstudio.py
    • fiftyone/utils/labelbox.py
    • fiftyone/utils/eval/segmentation.py
    • fiftyone/utils/eta.py

Consider updating the remaining direct mask access patterns to use the getter method for consistency.

🔗 Analysis chain

Line range hint 599-599: LGTM! Verify consistent mask access patterns across the codebase.

The change from direct mask access to using get_mask() aligns with encapsulation best practices. This change is part of a broader effort to standardize mask handling across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining direct mask access patterns
# that might need to be updated for consistency

# Search for direct mask access patterns
rg -A 2 'detection\.mask\b|\.mask\s*='

# Search for the new getter method usage
rg -A 2 'get_mask\(\)'

Length of output: 4007

🧹 Nitpick comments (57)
app/packages/state/src/recoil/sidebar.ts (1)

764-773: LGTM! Consider adding JSDoc documentation.

The implementation efficiently uses Set for collapsed paths and correctly filters list fields based on unsupported filter types.

Add JSDoc documentation to explain the purpose and behavior of this selector:

+/**
+ * Selector that returns a Set of paths that should be collapsed in the sidebar.
+ * This includes dictionary fields and list fields with unsupported filter types.
+ * @returns {Set<string>} Set of paths to be collapsed
+ */
 export const collapsedPaths = selector<Set<string>>({
fiftyone/core/odm/dataset.py (2)

642-646: Potential duplication check is good, but consider performance in large lists
The loop removes the path from every group that contains it, ensuring each path appears only once. For large numbers of groups, a single pass is fine, but if performance becomes an issue, consider optimizing.


653-661: Insert logic is clear but may benefit from error handling
If “after_group” is a value not found in the list, the code appends at the end. This is valid logic, but consider logging a message so the user knows the insertion point couldn’t be located.

app/packages/looker/src/worker/decorated-fetch.ts (2)

1-4: Consider adding 429 (Too Many Requests) to the non-retryable list or special-casing it.
HTTP 429 indicates rate limits; depending on your requirements, you may wish to handle it with exponential backoff rather than immediate failure or ignoring it as retryable.


17-24: Validate default retry parameters against fetch constraints.
Your chosen default of 10 retries × 200ms each yields a maximum ~2 second delay, not counting request time. If the environment is prone to slow connections or API throttling, consider whether a more flexible strategy (like exponential backoff) is more suitable.

app/packages/looker/src/worker/canvas-decoder.ts (1)

53-71: Consider error logging or fallback for createImageBitmap issues.
In certain browser contexts, createImageBitmap might be unavailable or throw unexpected errors (e.g., memory constraints). Adding a guarded fallback approach or more detailed logs could enhance troubleshooting.

app/packages/looker/src/worker/disk-overlay-decoder.ts (1)

83-112: Ensure fetch fallback for overlay path.
If overlayImageUrl is invalid or missing, and fetching fails, code logs an error and returns. This is correct for skipping decoding. Consider whether you need partial or fallback overlays in some workflows.

app/packages/looker/src/overlays/heatmap.ts (1)

9-18: Keep consistent naming for color utility imports.
Imports like getColor, getRGBA, getRGBAColor, and get32BitColor are functionally separate yet thematically related. Ensure they remain consistent across all overlays for readability.

app/packages/looker/src/overlays/segmentation.ts (1)

260-266: Intuitive memory & resource cleanup
Introducing getSizeBytes() to estimate memory usage is very helpful for performance monitoring, and the cleanup method properly closes the bitmap resource.

Consider logging or otherwise surfacing the estimated size bytes for debugging or performance optimization in production.

app/packages/looker/src/worker/index.ts (5)

97-104: Straightforward, stepwise documentation
Providing a clear top-level comment describing each step in mask and overlay processing is extremely helpful for maintainers.


140-151: Robust decodeOverlayOnDisk usage
Accumulating decode promises (lines 140-151) centralizes the overlay decoding approach into one function. This is more modular and maintainable.

Consider adding error-handling or retry logic in decodeOverlayOnDisk for more resilience.


252-253: Helper for bitmap creation
Clear function naming and separation of concerns. This encourages reusability and simpler testing.


350-356: Accumulating partial results
You push new promises into imageBitmapPromises and buffers into maskTargetsBuffers. This matches your approach in processLabels.

Consider using spread operators carefully to avoid potential performance overhead in extremely large arrays.


Line range hint 485-509: Granular label filtering
This conditional logic ensures you can filter and flatten various classification/detection scenarios neatly. It’s fairly verbose, but logically consistent.

Consider extracting repeated filter steps to a helper function to reduce method size and improve readability.

fiftyone/operators/builtins/panels/model_evaluation/__init__.py (2)

9-9: Import usage
The usage of defaultdict and Counter from “collections” is straightforward and ideal for tallying or grouping metrics.


485-509: Complex multi-conditional logic
Although lengthy, the if-else structure is explicit for each scenario (class, matrix, field), making it straightforward, if somewhat repetitive.

Consider a small refactor or pattern-based approach to reduce repeated lines.

app/packages/looker/src/lookers/abstract.ts (4)

499-499: Font size update merges properly with existing options.

Looks good. The approach to pass fontSize via the options object is consistent. Validate possible overrides in the future for dynamic font resizing.


524-560: Detach buffer checks.

This logic to handle possibly detached ArrayBuffers for overlay data is quite helpful. Consider robust logging or error reporting whenever you skip an update so that diagnosing performance or data issues is easier.

 // check for detached buffer (happens if user is switching colors too fast)
+ // Optional: Add a debug log to help track data flow issues
 if (typeof buffer.detached !== "undefined") {
     ...
}

744-749: Cleaning up overlays remains straightforward.

This is an important housekeeping method. Just ensure that overlay cleanup is safe to call multiple times. It might be worth a defensive check to avoid potential double cleanup calls.


Line range hint 750-798: Handling dataCloneError.

The retry logic to send data without transferring buffers is a safety net. Implementing extremely granular logging or metrics about how often this path is triggered can help debug user experiences with detached buffers.

fiftyone/utils/labels.py (5)

214-225: Static analysis suggests combining branches.

While combining branches might reduce code duplication, ensure clarity doesn’t suffer. If the logic remains more readable in separate conditionals, keep them separate. Otherwise, a logical OR approach can reduce repetition.

🧰 Tools
🪛 Ruff (0.8.2)

214-225: Combine if branches using logical or operator

Combine if branches

(SIM114)


288-299: Consider merging if statements.

Same suggestion from static analysis about combining these if branches. Evaluate if that simplification remains readable without sacrificing clarity.

🧰 Tools
🪛 Ruff (0.8.2)

288-299: Combine if branches using logical or operator

Combine if branches

(SIM114)


309-310: Static analysis suggests merging nested checks.

Proceed carefully with combining if statements. It's often beneficial, but ensure that clarity is preserved.

🧰 Tools
🪛 Ruff (0.8.2)

309-310: Use a single if statement instead of nested if statements

(SIM102)


494-496: Handle overwrite carefully if output directory is large.

Deleting the entire output_dir can be destructive. Ensure the user’s aware or prompt for confirmation in a UI scenario.


Line range hint 513-560: Generating detections from segmentation masks with optional image exports.

Clear logic is used to convert segmentation data into detection labels, exporting instance masks if requested. Logging the file path for debugging might help diagnosing issues, but this is not mandatory.

app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/Evaluation.tsx (1)

1147-1149: Difference column for class performance.

Consistent approach across all tables. Keep an eye on large differences and how they are displayed. Possibly consider highlighting significant changes more strongly.

fiftyone/core/labels.py (3)

44-47: Consider clarifying usage for _HasMedia.
The new "_HasMedia" mixin sets a pattern for classes that have a media path. It might be helpful to expand the docstring to indicate that if the subclass redefines "_MEDIA_FIELD", it should ensure consistency in any get/import/export methods.


448-462: Potential performance overhead when importing masks.
Repeated reading of large masks from disk can be costly if used frequently. If performance becomes an issue, consider caching or lazy loading the mask to reduce repeated I/O.


653-653: Verify the intended user experience of skipping detections without a mask.
The warning "Skipping detection(s) with no instance mask" might be beneficial to detail how many detections were skipped, or inform the user more comprehensively if missing masks are expected.

fiftyone/utils/data/exporters.py (4)

15-17: Unused imports or potential re-usage of imports.
Currently, "json_util" and "pydash" are imported together. If "json_util" is only used within certain sections or is replaceable, consider verifying it is needed. This is merely a suggestion to reduce potential clutter.


1897-1897: Renaming blacklist.
"blacklist" has recently been replaced with more descriptive terms like "denylist" in many contexts. Consider updating the parameter for clarity and modern conventions.


2047-2050: Apply ternary operator for cleaner code.
The static analysis suggests using a ternary expression for readability.

Use the following diff to refactor:

-if key is not None:
-    _value = _d.get(key, None)
-else:
-    _value = _d
+_value = _d.get(key, None) if key is not None else _d
🧰 Tools
🪛 Ruff (0.8.2)

2047-2050: Use ternary operator _value = _d.get(key, None) if key is not None else _d instead of if-else-block

Replace if-else-block with _value = _d.get(key, None) if key is not None else _d

(SIM108)


2355-2358: Replicate the same ternary operator improvement here.
Following the prior suggestion, you can likewise simplify this if-else to a one-liner.

Use the following diff to refactor:

-if key is not None:
-    _value = _d.get(key, None)
-else:
-    _value = _d
+_value = _d.get(key, None) if key is not None else _d
🧰 Tools
🪛 Ruff (0.8.2)

2355-2358: Use ternary operator _value = _d.get(key, None) if key is not None else _d instead of if-else-block

Replace if-else-block with _value = _d.get(key, None) if key is not None else _d

(SIM108)

app/packages/looker/src/lookers/utils.ts (1)

3-7: Validate frameNumber within buffers.
This function works as intended, but be mindful of negative or invalid frame numbers. Depending on usage, you could throw an error or return false if frameNumber < 0 or if buffers is empty.

app/packages/looker/src/worker/shared.ts (1)

14-21: Consider simplifying the switch statement.
Since there's only one specialized case (HEATMAP) and a default fallback, a simple dictionary lookup or an inline ternary might reduce code size. However, your current approach is perfectly readable and explicit.

app/packages/looker/src/lookers/utils.test.ts (1)

11-13: Add edge case tests for buffer boundaries

While the test covers basic scenarios, consider adding edge cases:

  • Test with empty buffers array
  • Test with overlapping buffer ranges
  • Test with single-frame buffers ([5,5])
app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/Evaluate.tsx (1)

7-8: Enhance type safety for permissions object

Consider defining a specific type for permissions instead of using Record<string, boolean>.

-  permissions: Record<string, boolean>;
+  permissions: {
+    can_evaluate: boolean;
+    // add other permission flags as needed
+  };
app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/Error.tsx (1)

38-40: Update type name to match component

Update the type name to match the renamed component.

-type ErrorProps = {
+type EvaluationErrorProps = {
   onBack: () => void;
 };
tests/unittests/operators/tableview_tests.py (2)

7-15: Add docstring to describe test cases

The test method would benefit from a docstring describing the test scenarios and expected outcomes.

 def test_table_view_basic(self):
+    """
+    Test basic TableView operations:
+    - Adding columns with unique names
+    - Verifying duplicate column prevention
+    - Testing row actions and tooltips
+    """
     table = TableView()

42-46: Consider adding edge case tests for tooltips

The current tests verify basic tooltip functionality. Consider adding edge cases such as:

  • Invalid row/column indices
  • Empty tooltip text
  • Special characters in tooltip text
e2e-pw/src/oss/specs/grid-tagging.spec.ts (1)

47-50: Extract repeated visibility checks into helper function

Both loops perform similar visibility checks. Consider extracting this logic into a reusable helper function to improve maintainability.

async function verifyGridItems(grid: GridPom, startIndex: number, endIndex: number, checkTag = false) {
  for (let i = startIndex; i <= endIndex; i++) {
    const locator = grid.locator.getByText(`/tmp/${i}.png`);
    await expect(locator).toBeVisible();
    if (checkTag) {
      await expect(
        locator.locator("..").getByTestId("tag-tags-grid-test")
      ).toBeVisible();
    }
  }
}

Usage:

await verifyGridItems(grid, 31, 54);
// After tagging
await verifyGridItems(grid, 31, 54, true);

Also applies to: 58-64

app/packages/spaces/src/components/AddPanelItem.tsx (2)

22-24: Consider using early return pattern

The conditional modification of showNew could be clearer using an early return pattern in a separate effect or useMemo.

const showNewLabel = useMemo(() => {
  return showNew && !showBeta;
}, [showNew, showBeta]);

45-45: Extract common styles to constants

The margin adjustments and width styles could be extracted to constants or theme variables for consistency.

const styles = {
  container: {
    width: "100%",
  },
  label: {
    marginLeft: "5px",
  },
} as const;

// Usage in sx prop
sx={{
  ...styles.container,
  cursor: "pointer",
  // ...
}}

// Usage in style prop
style={{
  ...styles.label,
  color: theme.custom.primarySoft,
  fontSize: "11px",
}}

Also applies to: 64-64, 75-75

app/packages/looker/src/elements/image.ts (1)

48-49: Consider extracting the retry delay base as a constant

The magic number 1000 (milliseconds) in the timeout calculation could be extracted as a named constant for better maintainability.

+const BASE_RETRY_DELAY_MS = 1000;
 // ...
-          }, 1000 * this.retryCount);
+          }, BASE_RETRY_DELAY_MS * this.retryCount);
app/packages/core/src/plugins/SchemaIO/components/ContainerizedComponent.tsx (1)

Line range hint 12-44: Consider memoizing the container component selection

The component logic is sound, but consider memoizing the container selection logic to optimize performance when the schema prop changes frequently.

+ const Container = useMemo(() => 
+   container ? containersByName[container.name] : null,
+   [container?.name]
+ );

- const Container = containersByName[container.name];
app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/ErrorIcon.tsx (1)

1-33: Add accessibility attributes to the SVG icon

While the implementation is clean, consider enhancing accessibility by adding aria labels and role attributes.

 <SvgIcon 
   width="54" 
   height="61" 
   viewBox="0 0 54 61" 
   fill="none" 
+  aria-label="Error icon"
+  role="img"
   {...props}
 >
.github/workflows/test.yml (1)

Line range hint 90-94: Consider adding fail-fast option to codecov upload

The codecov-action upgrade to v5 is good, but consider adding fail-fast option to prevent workflow failures due to coverage upload issues.

 uses: codecov/codecov-action@v5
 with:
   token: ${{ secrets.CODECOV_TOKEN }}
   files: ./coverage.xml
   flags: python
+  fail_ci_if_error: false
.github/workflows/pr.yml (1)

15-15: Fix trailing whitespace

There are trailing spaces that should be removed to maintain consistent formatting.

-  
+
-          (needs.test.result == 'success' || needs.test.result == 'skipped') && 
+          (needs.test.result == 'success' || needs.test.result == 'skipped') &&

Also applies to: 93-93

🧰 Tools
🪛 yamllint (1.35.1)

[error] 15-15: trailing spaces

(trailing-spaces)

app/packages/looker/src/worker/decorated-fetch.test.ts (1)

46-46: Use regex literal instead of RegExp constructor

Replace new RegExp("Max retries for fetch reached") with /Max retries for fetch reached/ for better readability and to avoid unnecessary string escaping.

🧰 Tools
🪛 Biome (1.9.4)

[error] 46-46: Use a regular expression literal instead of the RegExp constructor.

Regular expression literals avoid some escaping required in a string literal, and are easier to analyze statically.
Safe fix: Use a literal notation instead.

(lint/complexity/useRegexLiterals)

e2e-pw/src/oss/specs/overlays/detection-mask.spec.ts (1)

Line range hint 54-90: Comprehensive test coverage for mask scenarios

The test cases effectively cover three important scenarios:

  1. Bad detection mask (empty mask)
  2. Good detection mask (filled mask)
  3. Good detection mask path (mask on disk)

Consider adding assertions for each mask type's specific characteristics:

 test("should load all masks fine", async ({ grid, modal }) => {
   await grid.assert.isEntryCountTextEqualTo("3 samples");
+  // Verify bad mask
   await grid.openFirstSample();
   await modal.waitForSampleLoadDomAttribute();
+  await expect(modal.getDetectionMask()).toBeFalsy();
   await modal.close();
+
+  // Verify good mask
+  await grid.openSampleAtIndex(1);
+  await modal.waitForSampleLoadDomAttribute();
+  await expect(modal.getDetectionMask()).toBeTruthy();
+  await modal.close();
+
+  // Verify mask path
+  await grid.openSampleAtIndex(2);
+  await modal.waitForSampleLoadDomAttribute();
+  await expect(modal.getDetectionMask()).toBeTruthy();
+  await modal.close();

   await expect(grid.getForwardSection()).toHaveScreenshot(
app/packages/looker/src/worker/disk-overlay-decoder.test.ts (1)

35-204: Comprehensive test coverage with edge cases!

The test suite thoroughly covers:

  • Early returns for existing overlays
  • Successful fetch and decode scenarios
  • HEATMAP class handling
  • Recursive DETECTIONS processing
  • Error handling for failed fetches

However, consider adding tests for:

  • Concurrent decoding of multiple overlays
  • Memory usage patterns during large overlay processing
fiftyone/server/metadata.py (1)

442-445: LGTM: Improved path retrieval

Replaced custom deep get implementation with pydash's get function, which is more robust and well-tested.

Consider adding error handling for the path retrieval:

-        path = get(sample, field)
+        try:
+            path = get(sample, field)
+        except Exception as e:
+            logger.debug(f"Failed to get path for field {field}: {e}")
+            continue
fiftyone/utils/torch.py (1)

576-578: LGTM! Consider adding a docstring.

The null check before calling __exit__ on _no_grad is a good defensive programming practice. Consider adding a docstring explaining why this check is necessary.

 def __exit__(self, *args):
+    # Check if _no_grad context manager was initialized before attempting to exit
     if self._no_grad is not None:
         self._no_grad.__exit__(*args)
         self._no_grad = None
fiftyone/utils/data/importers.py (1)

2155-2171: Refactor suggestion: Combine nested if statements

The nested if statements can be combined using and for better readability.

-        if value is None:
-            continue
-
-        if isinstance(value, dict):
+        if value is not None and isinstance(value, dict):
🧰 Tools
🪛 Ruff (0.8.2)

2168-2169: Use a single if statement instead of nested if statements

Combine if statements using and

(SIM102)

docs/source/user_guide/using_datasets.rst (1)

2542-2561: LGTM! Consider clarifying the mask value ranges.

The implementation provides good flexibility by supporting both in-database and on-disk storage of masks. The documentation is clear, but could be enhanced by explicitly stating the valid range for non-zero pixel values in on-disk masks.

Consider adding:

-value indicates the object.
+value (1-255) indicates the object.
fiftyone/utils/cvat.py (1)

Line range hint 4-7: Add tests and documentation

The function needs unit tests and documentation to explain its purpose and parameters.

Would you like me to:

  1. Generate unit tests for this function?
  2. Add docstring documentation?
  3. Create a GitHub issue to track these tasks?
fiftyone/core/collections.py (1)

Line range hint 10665-10711: Improved media field filtering with blacklist support

The changes enhance the flexibility of media field filtering by:

  1. Adding a blacklist parameter to exclude specific fields
  2. Simplifying filepath handling by making it always included
  3. Properly handling app media fields

The blacklist handling code can be simplified using a ternary operator:

- if etau.is_container(blacklist):
-     blacklist = set(blacklist)
- else:
-     blacklist = {blacklist}
+ blacklist = set(blacklist) if etau.is_container(blacklist) else {blacklist}
🧰 Tools
🪛 Ruff (0.8.2)

10702-10705: Use ternary operator blacklist = set(blacklist) if etau.is_container(blacklist) else {blacklist} instead of if-else-block

Replace if-else-block with blacklist = set(blacklist) if etau.is_container(blacklist) else {blacklist}

(SIM108)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a035528 and e5cd1bd.

⛔ Files ignored due to path filters (6)
  • app/package.json is excluded by !**/*.json
  • app/packages/looker/package.json is excluded by !**/*.json
  • app/yarn.lock is excluded by !**/yarn.lock, !**/*.lock, !**/*.lock
  • e2e-pw/src/oss/specs/overlays/detection-mask.spec.ts-snapshots/grid-detections-chromium-darwin.png is excluded by !**/*.png, !**/*.png
  • e2e-pw/src/oss/specs/overlays/detection-mask.spec.ts-snapshots/grid-detections-chromium-linux.png is excluded by !**/*.png, !**/*.png
  • e2e-pw/yarn.lock is excluded by !**/yarn.lock, !**/*.lock, !**/*.lock
📒 Files selected for processing (75)
  • .github/workflows/build-docs.yml (1 hunks)
  • .github/workflows/e2e.yml (1 hunks)
  • .github/workflows/pr.yml (3 hunks)
  • .github/workflows/test.yml (1 hunks)
  • app/packages/app/src/routing/RouterContext.ts (1 hunks)
  • app/packages/core/src/components/Grid/Grid.tsx (1 hunks)
  • app/packages/core/src/components/ImageContainerHeader.tsx (1 hunks)
  • app/packages/core/src/plugins/SchemaIO/components/ContainerizedComponent.tsx (1 hunks)
  • app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/Error.tsx (1 hunks)
  • app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/ErrorIcon.tsx (1 hunks)
  • app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/Evaluate.tsx (1 hunks)
  • app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/Evaluation.tsx (33 hunks)
  • app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/Overview.tsx (1 hunks)
  • app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/Status.tsx (3 hunks)
  • app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/utils.ts (1 hunks)
  • app/packages/looker/src/elements/common/error.ts (1 hunks)
  • app/packages/looker/src/elements/image.ts (2 hunks)
  • app/packages/looker/src/elements/video.ts (1 hunks)
  • app/packages/looker/src/lookers/abstract.ts (8 hunks)
  • app/packages/looker/src/lookers/frame-reader.ts (1 hunks)
  • app/packages/looker/src/lookers/utils.test.ts (1 hunks)
  • app/packages/looker/src/lookers/utils.ts (1 hunks)
  • app/packages/looker/src/lookers/video.ts (4 hunks)
  • app/packages/looker/src/numpy.ts (2 hunks)
  • app/packages/looker/src/overlays/base.ts (4 hunks)
  • app/packages/looker/src/overlays/detection.ts (3 hunks)
  • app/packages/looker/src/overlays/heatmap.ts (4 hunks)
  • app/packages/looker/src/overlays/segmentation.ts (6 hunks)
  • app/packages/looker/src/worker/canvas-decoder.ts (1 hunks)
  • app/packages/looker/src/worker/decorated-fetch.test.ts (1 hunks)
  • app/packages/looker/src/worker/decorated-fetch.ts (1 hunks)
  • app/packages/looker/src/worker/deserializer.ts (0 hunks)
  • app/packages/looker/src/worker/disk-overlay-decoder.test.ts (1 hunks)
  • app/packages/looker/src/worker/disk-overlay-decoder.ts (1 hunks)
  • app/packages/looker/src/worker/index.ts (11 hunks)
  • app/packages/looker/src/worker/painter.ts (2 hunks)
  • app/packages/looker/src/worker/pooled-fetch.test.ts (1 hunks)
  • app/packages/looker/src/worker/pooled-fetch.ts (1 hunks)
  • app/packages/looker/src/worker/shared.ts (2 hunks)
  • app/packages/operators/src/state.ts (3 hunks)
  • app/packages/plugins/src/index.ts (1 hunks)
  • app/packages/spaces/src/components/AddPanelButton.tsx (2 hunks)
  • app/packages/spaces/src/components/AddPanelItem.tsx (4 hunks)
  • app/packages/state/src/recoil/atoms.ts (1 hunks)
  • app/packages/state/src/recoil/filters.ts (2 hunks)
  • app/packages/state/src/recoil/sidebar.test.ts (2 hunks)
  • app/packages/state/src/recoil/sidebar.ts (3 hunks)
  • app/packages/utilities/src/fetch.ts (2 hunks)
  • docs/source/teams/data_lens.rst (4 hunks)
  • docs/source/user_guide/using_datasets.rst (5 hunks)
  • e2e-pw/src/oss/specs/grid-tagging.spec.ts (1 hunks)
  • e2e-pw/src/oss/specs/overlays/detection-mask.spec.ts (4 hunks)
  • e2e-pw/src/oss/specs/plugins/histograms.spec.ts (1 hunks)
  • fiftyone/__public__.py (1 hunks)
  • fiftyone/constants.py (1 hunks)
  • fiftyone/core/collections.py (4 hunks)
  • fiftyone/core/dataset.py (2 hunks)
  • fiftyone/core/labels.py (6 hunks)
  • fiftyone/core/odm/dataset.py (1 hunks)
  • fiftyone/core/stages.py (1 hunks)
  • fiftyone/operators/builtins/panels/model_evaluation/__init__.py (8 hunks)
  • fiftyone/operators/types.py (4 hunks)
  • fiftyone/server/metadata.py (8 hunks)
  • fiftyone/utils/coco.py (2 hunks)
  • fiftyone/utils/cvat.py (1 hunks)
  • fiftyone/utils/data/exporters.py (5 hunks)
  • fiftyone/utils/data/importers.py (2 hunks)
  • fiftyone/utils/eta.py (1 hunks)
  • fiftyone/utils/labels.py (10 hunks)
  • fiftyone/utils/torch.py (1 hunks)
  • fiftyone/utils/ultralytics.py (1 hunks)
  • requirements/common.txt (1 hunks)
  • setup.py (3 hunks)
  • tests/unittests/import_export_tests.py (1 hunks)
  • tests/unittests/operators/tableview_tests.py (1 hunks)
💤 Files with no reviewable changes (1)
  • app/packages/looker/src/worker/deserializer.ts
✅ Files skipped from review due to trivial changes (3)
  • app/packages/core/src/components/ImageContainerHeader.tsx
  • app/packages/spaces/src/components/AddPanelButton.tsx
  • fiftyone/core/stages.py
🧰 Additional context used
📓 Path-based instructions (44)
app/packages/looker/src/lookers/utils.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/elements/common/error.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/lookers/utils.test.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/ErrorIcon.tsx (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/spaces/src/components/AddPanelItem.tsx (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/core/src/plugins/SchemaIO/components/ContainerizedComponent.tsx (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/worker/decorated-fetch.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/Evaluate.tsx (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/worker/shared.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

e2e-pw/src/oss/specs/grid-tagging.spec.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/Error.tsx (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/Overview.tsx (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/numpy.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/worker/disk-overlay-decoder.test.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

e2e-pw/src/oss/specs/plugins/histograms.spec.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/worker/canvas-decoder.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/worker/disk-overlay-decoder.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/lookers/video.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/utilities/src/fetch.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/worker/pooled-fetch.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/plugins/src/index.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/Status.tsx (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/core/src/components/Grid/Grid.tsx (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/overlays/base.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

e2e-pw/src/oss/specs/overlays/detection-mask.spec.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/worker/painter.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/operators/src/state.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/state/src/recoil/atoms.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/state/src/recoil/sidebar.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/elements/image.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/utils.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/lookers/abstract.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/lookers/frame-reader.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/overlays/detection.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/app/src/routing/RouterContext.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/state/src/recoil/filters.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/overlays/heatmap.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/state/src/recoil/sidebar.test.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/overlays/segmentation.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/worker/index.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/Evaluation.tsx (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/elements/video.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/worker/decorated-fetch.test.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/worker/pooled-fetch.test.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

🪛 Ruff (0.8.2)
tests/unittests/operators/tableview_tests.py

16-16: Do not assign a lambda expression, use a def

Rewrite mock_on_click as a def

(E731)

fiftyone/utils/data/importers.py

2168-2169: Use a single if statement instead of nested if statements

Combine if statements using and

(SIM102)

fiftyone/utils/labels.py

214-225: Combine if branches using logical or operator

Combine if branches

(SIM114)


233-234: Use a single if statement instead of nested if statements

Combine if statements using and

(SIM102)


288-299: Combine if branches using logical or operator

Combine if branches

(SIM114)


309-310: Use a single if statement instead of nested if statements

(SIM102)

fiftyone/core/collections.py

10702-10705: Use ternary operator blacklist = set(blacklist) if etau.is_container(blacklist) else {blacklist} instead of if-else-block

Replace if-else-block with blacklist = set(blacklist) if etau.is_container(blacklist) else {blacklist}

(SIM108)

fiftyone/utils/data/exporters.py

2047-2050: Use ternary operator _value = _d.get(key, None) if key is not None else _d instead of if-else-block

Replace if-else-block with _value = _d.get(key, None) if key is not None else _d

(SIM108)


2355-2358: Use ternary operator _value = _d.get(key, None) if key is not None else _d instead of if-else-block

Replace if-else-block with _value = _d.get(key, None) if key is not None else _d

(SIM108)

fiftyone/__public__.py

226-226: .core.stages.Shuffle imported but unused

Remove unused import

(F401)

🪛 Biome (1.9.4)
app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/Error.tsx

[error] 6-6: Do not shadow the global "Error" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)

app/packages/looker/src/worker/disk-overlay-decoder.ts

[error] 64-65: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/utils.ts

[error] 38-38: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/Evaluation.tsx

[error] 45-45: Do not shadow the global "Error" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)

app/packages/looker/src/worker/decorated-fetch.test.ts

[error] 46-46: Use a regular expression literal instead of the RegExp constructor.

Regular expression literals avoid some escaping required in a string literal, and are easier to analyze statically.
Safe fix: Use a literal notation instead.

(lint/complexity/useRegexLiterals)

🪛 yamllint (1.35.1)
.github/workflows/pr.yml

[error] 15-15: trailing spaces

(trailing-spaces)


[error] 93-93: trailing spaces

(trailing-spaces)

🔇 Additional comments (174)
app/packages/state/src/recoil/filters.ts (2)

9-9: LGTM!

Clean import of the extendedSelection atom.


111-114: LGTM! Extended selection check is properly implemented.

The modification to include extended selection in the hasFilters selector is well-structured:

  • Correctly guards the selection check with !modal
  • Properly handles the optional selection array
app/packages/state/src/recoil/atoms.ts (1)

389-392: LGTM! Well-structured atom definition.

The editingFieldAtom is properly defined with appropriate typing and default value.

app/packages/state/src/recoil/sidebar.test.ts (2)

5-5: LGTM!

Clean addition of required field type imports.


570-588: LGTM! Well-structured test case.

The test case for collapsedPaths resolution:

  • Properly tests the edge case for list fields with primitive subfields
  • Has clear setup and expectations
  • Uses appropriate mocking strategy
app/packages/state/src/recoil/sidebar.ts (1)

Line range hint 885-889: LGTM! Robust handling of edge cases.

The implementation correctly handles null/undefined expanded states and efficiently uses Set.has() for path lookups.

app/packages/operators/src/state.ts (3)

854-854: LGTM! Clean and clear state management.

The editingField state is correctly retrieved using useRecoilValue hook.


917-918: LGTM! Enhanced keyboard event handling.

The condition correctly prevents default behavior only when not in an editing state, improving user experience with input fields.


927-927: LGTM! Improved operator palette toggle behavior.

The condition correctly prevents operator palette toggling when in an editing state, avoiding accidental toggles during text input.

fiftyone/__public__.py (1)

226-226: LGTM! Note about import reordering in a release.

The reordering of the Shuffle import aligns with its restructuring in the core stages module. While the change is safe, please ensure this reordering is documented in the release notes if it could affect any downstream imports.

Note: The static analysis warning about unused import can be safely ignored as this is a public interface file explicitly designed to export these entities for external use.

Let's verify if this import is actually used by downstream code:

✅ Verification successful

Import reordering is safe and the class is actively used

The Shuffle class is a legitimate and actively used component of FiftyOne:

  • Implemented as a ViewStage in core/stages.py for randomly shuffling samples
  • Referenced in documentation and tutorials
  • Used in data manipulation workflows as shown in the user guide

The reordering in __public__.py maintains the public API and won't impact downstream users.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage of Shuffle from fiftyone's public interface
rg "from fiftyone import.*Shuffle" -A 2

Length of output: 41


Script:

#!/bin/bash
# Let's try a broader search for Shuffle usage
rg "Shuffle" -l

# Also check if Shuffle is imported from a more specific module
rg "from fiftyone\..*Shuffle" -l

# Let's also look at the actual implementation to understand its usage
ast-grep --pattern 'class Shuffle'

Length of output: 507


Script:

#!/bin/bash
# Let's check the actual implementation in stages.py and its usage in documentation
cat fiftyone/core/stages.py | rg -A 10 "class Shuffle"

# Check documentation references to understand its usage pattern
rg -A 3 "Shuffle" docs/source/user_guide/groups.rst

Length of output: 470

🧰 Tools
🪛 Ruff (0.8.2)

226-226: .core.stages.Shuffle imported but unused

Remove unused import

(F401)

fiftyone/core/dataset.py (2)

48-48: General import usage looks straightforward
This new import ensures access to the DatasetAppConfig class. There is no immediate correctness or security concern with this import.


1868-1873: Good use of the new App config helper, but verify non-null arguments
The call to “_add_path_to_sidebar_group” is clear. However, if “sidebar_group” is invalid or None, the code doesn’t explicitly handle the error, so consider adding a check or default fallback.

fiftyone/core/odm/dataset.py (2)

627-637: Null check returning early may hide issues
If “sidebar_groups” is None and “dataset” is also None, it simply returns. Consider logging a warning or raising an exception so the caller is aware that no action was taken.


662-664: Appending the path only if missing looks clean
Checking “if path not in index_group.paths:” before appending prevents duplication. No further improvements necessary here.

app/packages/looker/src/worker/decorated-fetch.ts (2)

6-15: The error handling structure looks good.
The custom error class "NonRetryableError" is a clear approach for categorizing immediate failures. Its naming accurately conveys its purpose.


25-58: Good linear backoff approach with proper non-retryable checks.
The code gracefully handles both retryable and non-retryable scenarios, ensuring that errors are propagated and that your loop respects the maximum retries. The immediate throw on non-retryable errors is straightforward.

app/packages/looker/src/worker/canvas-decoder.ts (4)

3-7: Well-documented PNG signature and header logic.
The inline comments explaining how the PNG signature and IHDR chunk data works are clear and helpful for future maintenance.


8-30: Check for additional PNG edge cases.
While the logic correctly identifies the PNG signature and color type, test and confirm behavior if the PNG is malformed or lacks a standard IHDR chunk. Ensure that partial or corrupted images do not cause uncaught errors.


32-50: Good dynamic channel handling.
You're properly differentiating grayscale from color PNGs here—this is a neat optimization for memory usage.


72-78: Final data structure is clear and consistent with OverlayMask usage.
Returning the image data along with channel info and shape aligns well with your overlay logic.

app/packages/looker/src/worker/disk-overlay-decoder.ts (2)

116-121: Decoding errors are handled gracefully.
When decoding fails, the function logs and returns, preventing data corruption. Good approach for non-blocking failures.


125-137: Memory usage is correctly managed by pushing buffer references.
The maskTargetsBuffers.push(overlayMask.buffer); usage is a sensible design for later transfer or usage.

app/packages/looker/src/overlays/heatmap.ts (5)

27-27: LabelMask alignment is cohesive with other overlays.
Switching from a custom HeatMap interface to map?: LabelMask unifies the approach to overlay management.


42-42: Readonly label field helps maintain immutability.
Marking the label field as readonly is a good approach to ensure overlay data remains consistent after construction.


80-85: Bitmap usage in draw method is straightforward.
Drawing the heatmap via a bitmap is memory-efficient. Good approach for large images or repeated draws.


204-207: getSizeBytes() fits well for memory usage debugging.
Offering a straightforward estimate of heatmap memory usage is handy for performance monitoring.


209-211: Cleanup method is essential for releasing resources.
Explicitly closing the bitmap is crucial to free resources. This aligns with best practices to avoid memory leaks.

app/packages/looker/src/overlays/segmentation.ts (6)

5-6: Dependency usage is consistent
These import statements cleanly bring in utility functions and types, aligning well with the rest of your codebase.


11-11: Good to see the LabelMask import
The newly introduced "LabelMask" import will provide a clearer type for mask representations.


20-20: Updated mask property improves consistency
Changing the mask property to "mask?: LabelMask" clarifies usage and ensures consistent type enforcement across overlays.


33-33: readonly label
Making the label property readonly is a suitable choice to guard against unintended modifications of critical data.


52-52: Check for valid mask dimension
This line properly verifies height and width from the mask data. Ensure external callers always provide valid shape data.


80-85: Alpha channel usage
These lines correctly handle the globalAlpha property to respect the overlay’s transparency setting. Great job preserving the original alpha value after usage.

app/packages/looker/src/worker/painter.ts (4)

116-116: Conditional channels
Introducing numChannels allows more flexible handling of grayscale and multi-channel masks. This is a clean solution.


123-137: One-pass approach for masked overlays
Well-structured approach to iterating with a stride of numChannels to decide whether to color a pixel. The early bailouts on grayscale vs. color scenarios further optimize loops.


138-141: Fallback for no mask_path
This fallback loop clarifies that the simple approach only checks a single channel for the mask presence. This is a neat fallback.


282-289: RGB channels guard
The extra verification that prevents errors if the RGBA mask frame is already reduced to grayscale helps avoid data corruption. Good job guarding overlay transformations.

app/packages/looker/src/worker/index.ts (16)

116-120: Return type updated
Switching from returning just ArrayBuffer[] to a tuple that also includes Promise<ImageBitmap[]>[] properly structures asynchronous overlay processing. Good improvement.


122-122: Bulk decode & paint approach
The top-level logic sets up decoding promises before painting, ensuring efficient concurrency.


130-133: Key detection for dense labels
This check ensures you only decode overlay data for recognized dense label types, avoiding extraneous overhead.


Line range hint 160-186: Recursive label processing logic
The recursive call to processLabels for embedded documents is carefully implemented, pushing newly gathered promises upwards. Nicely done to avoid partial labeling.


188-189: Graceful fallback on decoding errors
Using Promise.allSettled ensures that any errors in decode promises do not break the entire pipeline.


Line range hint 190-230: Painter loop
Separating the painting step from decoding is a strong design, ensuring no partial painting occurs if decoding fails.


224-225: Promise concurrency
Awaiting painterPromises ensures painting has completed before any further processing. This is correct.


319-319: processSample is now async
Marking processSample as async is crucial to align with the awaited calls. Good consistency in return usage.


332-333: Better separation of imageBitmap and maskTargets
Splitting the result arrays for bitmaps vs. mask target buffers clarifies code usage of each resource.


338-348: Conditional path
This block effectively handles 3D vs. standard images with a straightforward “else” branch for normal processing.


359-390: Frame loop
Providing a separate label processing path for frames is essential for handling multi-frame data. The code properly awaits all frame-based tasks.


406-406: Transferring results
Collecting and sending all bitmaps and mask buffers as transferables is correct for worker concurrency.


Line range hint 461-462: Passing view options
Exposing user-specified or system-defined view options aligns well with dynamic filtering or other runtime decisions.


Line range hint 464-465: Fallback logic for eval_key
Graceful fallback ensures that the view can load with or without an explicit eval_key in the provided view options.


Line range hint 470-478: Second evaluation key
Allowing a compareKey to generate differential or comparative views is a valuable feature. This improves advanced use cases.


Line range hint 482-483: Handling 'missing'
Storing a special state for the “missing” field clarifies how you match incorrectly predicted items in the matrix.

fiftyone/operators/builtins/panels/model_evaluation/__init__.py (14)

13-14: NumPy integration
Importing numpy is necessary for the newly introduced mask or classification calculations. Well done.


19-19: operators.types import
Ensures typed fields or definitions are consistently used throughout the evaluation panel logic.


35-35: Supported evaluation types extended
Including “segmentation” in SUPPORTED_EVALUATION_TYPES is a step forward. Verify your UI or other code now accommodates segmentation seamlessly.


110-134: Binary classification & object detection logic
Great approach using np.count_nonzero to compute TP/FP/FN. The distinctions between classification vs. detection are handled elegantly.


Line range hint 250-299: Enhanced confusion matrix generation
This block is a thorough approach to produce multiple matrix versions. Sorting classes in different ways is excellent for interpretability.


312-321: get_mask_targets
This new helper method is a welcome improvement to unify dataset-level mask lookup logic.


334-347: Segmentation gating
Conditionally calling get_mask_targets is a good approach, avoiding extraneous calls for non-segmentation evaluations.


355-355: Calculation of (tp, fp, fn)
Your function call to retrieve tp/fp/fn ensures consistent usage of your get_tp_fp_fn logic. Clear for debugging.


360-363: mask_targets included in evaluation_data
Storing mask_targets in the same object as metrics and confusion matrices provides a single structure for all results, improving clarity.


365-365: Exposing 'missing'
The panel state for “missing” across detection or classification aids in consistent matrix-based filtering.


461-462: Surfaces shared view options
Allows advanced control paths or improved expansions in the future. Good for reusability.


464-465: Preserve user-chosen key
Retaining the previously loaded evaluation key if the updated “options” do not define it ensures continuity of user context.


470-478: CompareKey usage
Allows direct comparison between two different model evaluation results, a powerful addition for advanced analyses.


482-483: Missing label handling
Proper reference to the missing state from the panel ensures consistent view filtering for edge cases.

app/packages/looker/src/lookers/abstract.ts (3)

26-26: Importing LabelMask introduced for mask overlay handling.

Nice addition to the import statement. This helps leverage the newly introduced LabelMask functionality for improved overlay management.


472-476: Expanded attach method signature.

The newly added optional fontSize parameter is a convenient way to set text size during attachment. Make sure all invocation sites are updated accordingly.


482-483: Use short-circuiting when updating disabled state.

The code looks fine. Just ensure that the conditions for re-enabling the looker are well tested.

app/packages/looker/src/elements/video.ts (1)

68-72: Conditional rendering improvement.

The new logic that checks if rendering of the loader bar is necessary helps prevent unnecessary re-renders. Good performance optimization.

fiftyone/utils/labels.py (8)

158-159: Docstring updated to reflect new label types.

The mention of Detection/Detections in the docstring for export_segmentations fosters clarity. Great job updating the docstrings to keep them in sync with code changes.


167-169: Expanding supported label types.

Export function now supports Detection/Detections in addition to Segmentation and Heatmap. This broadens utility usage. Looks good.


188-190: Validation checks for additional label types.

Ensuring input fields can be Segmentation/Detection/Detections/Heatmap is consistent with the docstring changes. This is properly validated.


248-249: Docstring updated for new label types in import_segmentations.

Accurate reflection of the newly supported label types. Nicely done.


257-259: Covering detection fields in import_segmentations.

This update ensures that detection masks can also be imported properly. Good consistency with the export pipeline.


269-271: Ensure label fields are validated consistently.

Again, the synergy with the docstring. The code updates confirm that import_segmentations now handles all the label types.


430-431: segmentations_to_detections now accepts optional output_dir.

This feature boosts usability by letting users store instance segmentation images outside the database. Great addition.


467-478: Docstring clarifies new optional arguments.

Notably, output_dir, rel_dir, and overwrite provide more control of exporting instance segmentation images. The thorough explanation is helpful for integrators.

app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/Evaluation.tsx (30)

54-54: NONE_CLASS constant declared.

Symbolic references for no-label or missing classes is beneficial. This is consistent with the newly introduced segmentation/detection logic across the codebase.


95-98: Compute evaluationError from data.

Conditionally rendering an Error component is a user-friendly approach. Just ensure that the final string from data is always a string or relevant object for the Error UI.


99-102: Handle compareEvaluationError similarly.

Parallels the approach in evaluationError, effectively ensuring the user sees an error message if compareEvaluation data is invalid.


103-108: Retrieve mask_targets from evaluations.

This helps unify how we handle segmentation or detection masks across the evaluation. Good job pulling out mask targets to pass them into confusion matrix logic.


110-115: Confusion matrix for current evaluation.

We call getMatrix, passing the new confusionMatrixConfig and evaluationMaskTargets. This is consistent with the broader changes for mask-based data. Nice approach.


119-123: Confusion matrix for compare evaluation.

Similarly, bridging the compareEvaluation’s confusion matrix with the same getMatrix approach ensures parallel treatment of main vs. compare sets.


163-163: Use of setRecoilState for editingFieldAtom.

Enables toggling editing states for user input. Ensure the rest of the code is consistent about resetting or unsubscribing from this state if no longer needed.


175-177: Rendering error fallback.

If evaluationError is present, it immediately returns the Error component, preventing further UI confusion. Straightforward approach.


200-200: evaluationMethod usage.

Used to differentiate between binary classification and other classification tasks. Great for toggling UI elements based on method specifics.


210-211: Check classification method for binary tasks.

Combining the type (“classification”) and method (“binary”) is an easy read. Just keep an eye on possible expansions for multi-label or multi-class classification.


261-261: Hide IoU threshold row for non-object detection evaluations.

An effectively toggled row. This ensures minimal confusion for other evaluation types.


302-302: Hide IoU threshold for non-object detection.

Same row-level check repeated. Perfect for consistency in summary or info sections.


336-336: Avoid storing average confidence for segmentation.

Makes sense to hide this if segmentation doesn’t produce a typical confidence measure. Good dynamic approach.


429-429: True Positives row for detection/binary.

We only show TP, FP, FN in these contexts. Great job restricting the UI to relevant metrics.


444-444: False Positives row.

Same approach for FP is consistent. Nicely done.


459-459: False Negatives row.

Again consistent with the approach for bounding boxes or binary classification.


473-474: Mapping maskTarget for each class.

This allows more descriptive labeling in the UI for each class performance row, which is a nice user-friendly approach.


616-620: Conditional editing of evaluation notes.

Preventing unauthorized users from editing the notes is a crucial check. Great job setting user feedback with a tooltip or a disabled cursor.


623-634: Triggering the note dialog.

The icon button leads to the note editing. The code is clear; it respects can_edit_note. All good here.


656-665: Summary table layout.

Properly sets up color-coded columns for the main evaluation vs. comparison. Implementation is quite user-friendly.


688-690: Displaying difference in a separate column.

A nice approach. This extra difference column immediately visualizes the performance gap. Good UI design.


903-904: Plot comparing x-axis property vs. y-axis value.

For the metric chart, the histogram approach is straightforward. Good usage of the color-coded series.


913-914: Compare series data.

Similarly pulling from compareValue ensures a direct comparison is plotted. The name is color-coded as well. Good job.


929-938: Metric table layout.

Same approach as summary. The differences are clearly displayed side by side. Overall, a consistent approach across the UI.


960-963: Difference column in the metric table.

Extended from the summary approach, showing numeric differences side-by-side for clarity.


1089-1092: Handling compareProperty for the second dataset.

Ensuring the label for the second dataset is drawn from either compare or main property to avoid blank or undefined labels.


1115-1124: Class performance table layout.

Maintaining consistent style: a color-coded column for main vs compare, plus difference if present. Straightforward design.


1251-1252: Enforcing reversed Y-axis in confusion matrix.

This is typical for confusion matrices so that the first entry is top-left. Good to see it explicitly set.


1662-1683: Enhanced getMatrix function.

Now supporting compareMaskTargets and re-labelling classes. The logic is concise. The conditional noneIndex handling is a bit specialized. Confirm that this is thoroughly tested if multiple unknown classes appear.


1703-1708: Analyzing FilterLabels stage for labeling.

We parse the eq operator to decide which label or metric is in use. This is quite a specialized approach. Ensure no unexpected stage combos break this logic.

fiftyone/core/labels.py (1)

429-433: Ensure consistent checks for has_mask.
This property checks for both in-memory masks and mask files. Confirm that any external references (e.g., other modules or UI components) also handle scenarios where either is set but not the other, to avoid unexpected edge cases.

requirements/common.txt (1)

12-13: Verify MongoDB stack version compatibility

The updates to MongoDB-related dependencies involve major version changes that could introduce breaking changes:

  • mongoengine: ~0.29.1
  • motor: ~3.6.0
  • pymongo: ~4.9.2

Also applies to: 19-19

✅ Verification successful

Let me gather more information about the codebase usage of these MongoDB dependencies.


MongoDB stack version updates appear compatible

The version updates are safe to proceed with because:

  • Motor 3.x is compatible with PyMongo 4.x as per the changelog
  • The codebase uses standard MongoDB patterns through mongoengine and motor async clients
  • The main MongoDB integration is abstracted through ODM layer in fiftyone/core/odm/
  • No deprecated APIs or breaking changes from Motor 3.0 are used in the codebase

The tilde (~) version specifier ensures minor version compatibility while allowing patch updates, which is appropriate for these dependencies.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check compatibility matrix and changelog for breaking changes

# Check mongoengine changelog for breaking changes
curl -s https://raw.githubusercontent.com/MongoEngine/mongoengine/master/CHANGELOG.rst | grep -A 10 "0.29.0"

# Check motor changelog for breaking changes
curl -s https://raw.githubusercontent.com/mongodb/motor/master/doc/changelog.rst | grep -A 10 "Motor 3.0"

# Check if these versions are commonly used together
gh search code "mongoengine~=0.29 motor~=3.6 pymongo~=4.9" --language=python

Length of output: 1153


Script:

#!/bin/bash
# Search for MongoDB-related imports and usage patterns
rg -A 3 "from mongoengine import|from motor import|import motor|import mongoengine" 

# Check if there are any MongoDB-specific configurations
fd -e py -e yaml -e json | xargs rg -l "mongo"

# Look for any MongoDB connection setup code
ast-grep --pattern 'MongoClient($$$)'

Length of output: 3887

tests/unittests/operators/tableview_tests.py (1)

1-6: LGTM!

The test class setup and imports are clean and well-structured.

app/packages/looker/src/elements/image.ts (2)

9-9: LGTM: Retry mechanism implementation looks solid

The retry mechanism with linear backoff is well-implemented. The constants and state variables are properly defined.

Also applies to: 15-16


13-13: Verify inheritance requirements for protected visibility

The imageSource property visibility has been changed from private to protected. Please ensure this change is required for inheritance purposes.

✅ Verification successful

Protected visibility for imageSource is required

The change from private to protected visibility is justified as the imageSource property is accessed by the parent abstract class through this.lookerElement.children[0].imageSource in app/packages/looker/src/lookers/abstract.ts. Additionally, other element classes in the same directory (ThreeDElement, VideoElement, FrameElement, ImaVidElement) also implement this property with various visibility levels, suggesting it's part of a common interface or pattern.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for classes that extend ImageElement
ast-grep --pattern 'class $_ extends ImageElement {
  $$$
}'

Length of output: 62


Script:

#!/bin/bash
# First, let's find the file containing ImageElement definition
fd "image.ts" --type f

# Then, let's check for any class that inherits from this class using ripgrep
# as ast-grep might have issues with the class name
rg "extends\s+ImageElement" -l

Length of output: 179


Script:

#!/bin/bash
# Let's check if there are any references to imageSource from other files
rg "imageSource" -A 2 -B 2

# Also check the ImageElement class definition and its usage
cat "app/packages/looker/src/elements/image.ts"

Length of output: 7654

app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/Status.tsx (2)

7-7: LGTM: Permission handling is well implemented

The combination of readOnly and canEdit props provides clear control over the component's edit state. The permission message is informative and user-friendly.

Also applies to: 10-10, 25-30


72-73: LGTM: Props type changes improve type safety

Making setStatusEvent required and adding the optional readOnly flag improves the component's type safety and API clarity.

e2e-pw/src/oss/specs/plugins/histograms.spec.ts (1)

62-62: LGTM: Test coverage extended for mask path field

The addition of "detections.detections.mask_path" to the field verification list appropriately extends test coverage for the mask handling functionality.

app/packages/core/src/plugins/SchemaIO/components/ContainerizedComponent.tsx (1)

4-4: LGTM! Good practice using PropsWithChildren

The explicit import of PropsWithChildren from React is a good practice for type safety.

.github/workflows/test.yml (1)

Line range hint 100-104: LGTM! Good practice running isolated tests independently

The use of success() || failure() condition ensures isolated tests run regardless of previous test results, which is a good practice for comprehensive testing.

fiftyone/constants.py (1)

45-45: Verify version compatibility range for v1.2.0 release

The compatibility range has been extended to "<1.3" which is appropriate for the v1.2.0 release. This ensures that datasets from versions >=0.19 remain compatible while preparing for future releases.

✅ Verification successful

Let me run one more verification to check for any version-related configuration or compatibility checks in the Python files:


Version compatibility range change is appropriate

The change to extend compatibility to "<1.3" is correct for the v1.2.0 release. The codebase scan shows:

  • The main version is being updated to "1.2.0" in setup.py
  • Version compatibility checks in the codebase (plugins, utils, etc.) use dynamic version comparison and will work correctly with the new range
  • No hardcoded version checks that would conflict with the new compatibility range were found
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify version compatibility across codebase
# Look for any hardcoded version checks that might need updating
rg -g '!{package-lock.json,yarn.lock}' '(?i)(version|compatible).*(1\.2|1\.3)'

Length of output: 7463


Script:

#!/bin/bash
# Check for version-related checks in Python files
rg -t py "(?i)(version|compatible).*(check|require|depend)"

Length of output: 958

.github/workflows/build-docs.yml (1)

54-54: Security improvement: Using read-only token for docs build

Good security practice to use a read-only token (RO_FOT_FG_PAT) for the documentation build workflow instead of the previous TEAMS_GITHUB_PAT.

.github/workflows/pr.yml (3)

12-14: Good addition: Concurrency control for workflow efficiency

The concurrency configuration helps prevent redundant workflow runs and optimizes CI resources by canceling outdated runs.


17-41: Well-structured change detection system

The modified-files job effectively categorizes changes into app, e2e-pw, and fiftyone components, enabling selective execution of downstream jobs. The file patterns are comprehensive and logically grouped.


91-94: Improved success criteria with skipped state handling

Good enhancement to consider both 'success' and 'skipped' states as valid outcomes, making the workflow more flexible while maintaining reliability.

🧰 Tools
🪛 yamllint (1.35.1)

[error] 93-93: trailing spaces

(trailing-spaces)

app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/Overview.tsx (1)

100-100: LGTM: Adding readOnly prop improves component behavior

The addition of the readOnly prop to the Status component is appropriate for this overview context where status should only be displayed, not edited.

app/packages/looker/src/overlays/base.ts (3)

43-46: LGTM: Well-defined LabelMask type

The LabelMask type properly defines the structure for bitmap and overlay mask data with appropriate optional properties.


70-70: LGTM: Enhanced Overlay interface with cleanup support

The addition of optional label and cleanup method improves resource management capabilities of overlays.

Also applies to: 77-77


86-86: LGTM: Protected label property with readonly modifier

Making the label property readonly prevents accidental mutations and improves type safety.

app/packages/looker/src/elements/common/error.ts (1)

106-109: LGTM: Proper cleanup of error element

The added cleanup logic properly removes the error element from DOM and resets the reference when error is cleared, preventing memory leaks.

app/packages/looker/src/worker/decorated-fetch.test.ts (1)

1-116: Well-structured and comprehensive test suite!

The test suite thoroughly covers all important scenarios including:

  • Success cases
  • Retry behavior
  • Error handling
  • Linear backoff implementation
  • HTTP status code handling

Good use of vi.useFakeTimers() for testing time-dependent behavior.

🧰 Tools
🪛 Biome (1.9.4)

[error] 46-46: Use a regular expression literal instead of the RegExp constructor.

Regular expression literals avoid some escaping required in a string literal, and are easier to analyze statically.
Safe fix: Use a literal notation instead.

(lint/complexity/useRegexLiterals)

app/packages/looker/src/worker/pooled-fetch.test.ts (2)

7-15: Well-designed helper function!

The createDeferredPromise helper function is elegantly implemented, providing good control over promise resolution/rejection for testing async behavior.


17-110: Excellent test coverage for concurrent request handling!

The test suite effectively validates:

  • Request queuing behavior
  • Concurrency limits
  • Error handling
  • Retry mechanisms
  • Request ordering

Good use of deferred promises to control async flow in tests.

setup.py (2)

16-16: Version bump to 1.2.0 looks good

The version increment follows semantic versioning principles.


49-50: Verify compatibility between MongoDB-related dependencies

The updates to MongoDB-related packages involve significant version jumps:

  • mongoengine: ~0.29.1
  • motor: ~3.6.0
  • pymongo: ~4.9.2

These packages are tightly coupled and need to be verified for compatibility.

Consider documenting the MongoDB version requirements in the README.md to help users avoid compatibility issues.

Also applies to: 58-58, 77-77

✅ Verification successful

Let me analyze the pymongo version in setup.py to ensure it meets both mongoengine (pymongo<5.0,>=3.4) and motor (pymongo<4.10,>=4.9) requirements, and check if MongoDB version requirements are documented.


MongoDB-related dependencies are compatible

The specified versions are compatible:

  • mongoengine 0.29.1 requires pymongo>=3.4,<5.0
  • motor 3.6.0 requires pymongo>=4.9,<4.10
  • pymongo 4.9.2 satisfies both requirements
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check compatibility between MongoDB packages
echo "Checking mongoengine compatibility..."
curl -s https://pypi.org/pypi/mongoengine/0.29.1/json | jq -r '.info.requires_dist[] | select(contains("pymongo"))'

echo "Checking motor compatibility..."
curl -s https://pypi.org/pypi/motor/3.6.0/json | jq -r '.info.requires_dist[] | select(contains("pymongo"))'

Length of output: 720


Script:

#!/bin/bash
# Check the actual pymongo version specified in setup.py
echo "Checking pymongo version in setup.py..."
rg "pymongo.*[0-9]" setup.py

# Check if there are any MongoDB connection configurations or version requirements in README
echo "Checking README for MongoDB version info..."
fd -t f "README" -X cat {} 

Length of output: 53953

e2e-pw/src/oss/specs/overlays/detection-mask.spec.ts (1)

26-40: Good use of Promise.all for parallel image creation

The parallel creation of test images improves test efficiency.

app/packages/looker/src/numpy.ts (1)

12-12: Good addition of Uint8ClampedArray support

The addition of Uint8ClampedArray is appropriate for handling image data, particularly for canvas operations. This type ensures pixel values are always clamped between 0 and 255.

Also applies to: 24-24

app/packages/looker/src/lookers/frame-reader.ts (1)

55-63: Improved memory management in frame disposal!

The enhanced dispose callback now properly cleans up overlay resources before removing the frame, which helps prevent memory leaks.

app/packages/core/src/components/Grid/Grid.tsx (1)

75-78: Enhanced font size handling in looker attachment!

The addition of dynamic font size support through getFontSize() improves the component's adaptability to different display contexts.

app/packages/looker/src/worker/disk-overlay-decoder.test.ts (2)

1-29: Well-structured test setup with comprehensive mocking!

The test file has a clean setup with proper mocking of external dependencies and type definitions.


30-34: Good test hygiene with beforeEach cleanup!

The test suite follows best practices by clearing mocks before each test.

app/packages/looker/src/overlays/detection.ts (3)

9-15: LGTM! Type definitions are well-structured

The updated imports and simplified mask type in DetectionLabel interface improve type safety and maintainability.

Also applies to: 19-19


Line range hint 146-160: Improved mask rendering performance

The changes optimize mask rendering by:

  1. Directly using bitmap instead of creating intermediate canvas
  2. Disabling image smoothing for crisp mask edges

264-266: Verify bitmap cleanup integration

The cleanup method properly releases bitmap resources. Ensure it's called during component unmount to prevent memory leaks.

app/packages/app/src/routing/RouterContext.ts (2)

Line range hint 63-66: LGTM! Improved routing for different environments

The history creation now properly handles both notebook and browser environments.


1-14: Verify impact on bundle size

While the import organization is improved, let's ensure these additional imports don't significantly impact the bundle size.

✅ Verification successful

Let me gather more specific information about the actual usage of these imports in the RouterContext.ts file.


Import changes are justified and well-utilized

The imported utilities (viewsAreEqual, NotFoundError, Resource, isNotebook) are actively used throughout the RouterContext.ts file for core routing functionality:

  • Resource class is used extensively for managing route entries and loading states
  • isNotebook() determines the history type
  • viewsAreEqual is used for route reusability checks
  • NotFoundError handles invalid routes

These imports are essential for the router's functionality and not just organizational changes.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage of imported utilities
rg -l "viewsAreEqual|NotFoundError|Resource|isNotebook" --type ts

Length of output: 1064


Script:

#!/bin/bash
# Check specific usage of imported utilities in RouterContext.ts
rg "viewsAreEqual|NotFoundError|Resource|isNotebook" app/packages/app/src/routing/RouterContext.ts -A 2

Length of output: 2808

app/packages/utilities/src/fetch.ts (2)

113-113: LGTM! Added retry backoff delay

Adding a 500ms delay between retries is a good practice to prevent overwhelming the server during retries.


21-21: Verify impact of retryCodes type change

The simplified type might affect existing code using "arrayBuffer" as retryCodes.

✅ Verification successful

Type change to retryCodes is safe

The codebase only uses retryCodes as a number array with default values [502, 503, 504]. No instances of "arrayBuffer" usage were found. The type simplification from number[] | "arrayBuffer" to number[] is safe to proceed with.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for existing usage of retryCodes
rg 'retryCodes.*arrayBuffer' --type ts

Length of output: 40


Script:

#!/bin/bash
# Let's first check all usages of retryCodes to understand the impact
rg 'retryCodes' -A 3 --type ts

# Also search for any type definitions involving retryCodes
ast-grep --pattern 'interface $_ {
  $$$
  retryCodes$_
  $$$
}'

Length of output: 839

app/packages/looker/src/lookers/video.ts (2)

22-22: LGTM: Utility function extraction

The hasFrame function has been appropriately moved to a utility file, following the principle of separation of concerns.


55-55: LGTM: Buffer initialization during detachment

Proper cleanup of state by resetting buffers to their initial state when detaching the reader.

fiftyone/server/metadata.py (3)

35-36: LGTM: Added support for Detection types

Appropriate extension of _ADDITIONAL_MEDIA_FIELDS to support both single and multiple detections with mask paths.


Line range hint 467-490: Verify field schema handling

The modified _get_additional_media_fields function now handles detection fields separately. Ensure that all field types are properly handled.

✅ Verification successful

Let me gather more information about the field schema handling by checking the implementation and usage of _get_additional_media_fields.


Let me check the _ADDITIONAL_MEDIA_FIELDS definition and the field types it handles to ensure complete coverage.


Field schema handling is properly implemented

The modified _get_additional_media_fields function correctly handles all field types defined in _ADDITIONAL_MEDIA_FIELDS. The implementation:

  • Properly separates detection fields into a dedicated list
  • Correctly handles OrthographicProjectionMetadata fields
  • Maintains handling of other field types (Detection, Heatmap, Segmentation) in the additional fields list
  • Uses appropriate type checking with isinstance and document_type comparison

The changes maintain the expected behavior while improving the organization of different field types.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for field schema test coverage
rg -A 10 "def test.*field_schema" tests/

Length of output: 2267


Script:

#!/bin/bash
# Search for _get_additional_media_fields usage and implementation
rg -A 10 "_get_additional_media_fields" 

# Search for field schema handling in metadata.py
rg -A 10 "get_field_schema" fiftyone/server/metadata.py

Length of output: 1703


Script:

#!/bin/bash
# Search for _ADDITIONAL_MEDIA_FIELDS definition
rg -B 5 -A 5 "_ADDITIONAL_MEDIA_FIELDS\s*=" fiftyone/server/metadata.py

# Search for all field types in the codebase
ast-grep --pattern 'class $_ (extends|implements)? $$$Field'

Length of output: 416


408-424: Verify detection fields processing logic

The new detection fields processing logic needs verification for edge cases:

  1. Nested detections access
  2. Empty or null detections handling
✅ Verification successful

Detection fields processing logic is properly handled

Based on the codebase analysis:

  1. The code correctly handles nested detections by using the get() function for safe access to both the detection field and its nested detections list
  2. Empty/null cases are properly handled with explicit checks:
    • if not detections: continue
    • if not detections_list or len(detections_list) == 0: continue
  3. The implementation is consistent with test cases in tests/unittests/import_export_tests.py which verify mask_path handling for detections
  4. The field is properly registered in the metadata types mapping: fol.Detection: "mask_path" and fol.Detections: "mask_path"
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for test cases covering detection fields processing
rg -A 5 "def test.*detection.*mask" tests/

Length of output: 44


Script:

#!/bin/bash
# Search for test files related to detections and metadata
fd "test.*metadata.*py|test.*detection.*py" tests/

# Search for detection field usage patterns in tests
rg -A 10 "detections.*mask_path|mask_path.*detection" tests/

Length of output: 4600


Script:

#!/bin/bash
# Search for similar detection field processing patterns in the codebase
ast-grep --pattern 'detections = get($_, $_)
            if not detections:
                $_
            detections_list = get($_, "detections")'

Length of output: 149


Script:

#!/bin/bash
# Look for related metadata processing functions
rg -A 10 "def.*metadata.*detection" fiftyone/server/

Length of output: 54


Script:

#!/bin/bash
# Search for the get function implementation and its usage
rg -A 5 "def get\(" fiftyone/

# Look for detection field handling in the codebase
rg -A 10 "detections_fields.*for.*field" fiftyone/

Length of output: 5520


Script:

#!/bin/bash
# Search for mask_path related processing
rg -A 5 "mask_path" fiftyone/server/

Length of output: 891

fiftyone/utils/eta.py (1)

599-599: LGTM! Consistent with mask access changes.

The change to use get_mask() is consistent with the standardization of mask access patterns seen in other files.

docs/source/teams/data_lens.rst (4)

597-607: Well-structured documentation with clear examples.

The Databricks connector documentation is well-organized and includes comprehensive examples. The introduction clearly states the purpose and context of the integration.


733-739: Good security practice using secrets for credentials.

The example properly demonstrates secure credential handling using the execution context's secret management functionality.


807-847: Robust pagination handling with proper error checking.

The code example demonstrates proper handling of Databricks' chunked responses and includes appropriate error checking and retry logic.


1134-1208: Excellent addition of dynamic user inputs documentation.

The new section on dynamic user inputs provides valuable guidance on creating intuitive and context-sensitive search experiences. The traffic light example effectively illustrates the practical application.

fiftyone/utils/coco.py (2)

1307-1307: LGTM! Improved mask presence check.

Using has_mask property instead of directly accessing mask is a better practice as it properly encapsulates the internal representation of mask data.


2119-2121: LGTM! Consistent mask presence check.

The mask presence check is now consistent with the earlier change, using has_mask property.

fiftyone/operators/types.py (4)

1830-1840: LGTM! Improved type safety by making name required.

Making name a required parameter in the constructor improves type safety and prevents potential runtime errors.


1851-1861: LGTM! Improved type safety by making row and column required.

Making row and column required parameters in the constructor improves type safety and prevents potential runtime errors.


1883-1886: LGTM! Added duplicate checks for better error handling.

Added validation to prevent duplicate columns, row actions, and tooltips, which improves error handling and user experience.

Also applies to: 1894-1897, 1910-1914


1925-1928: LGTM! Fixed tooltip map cloning.

Properly rebuilding the tooltip map during cloning ensures that the cloned instance maintains the correct tooltip lookup functionality.

fiftyone/utils/data/importers.py (2)

17-17: LGTM: Added pydash import for safer dictionary access

The addition of pydash provides safer dictionary access with fallback values, which helps prevent KeyError exceptions.


2173-2191: LGTM: Well-structured helper function for parsing nested media fields

The new _parse_nested_media_field helper function:

  • Cleanly encapsulates the logic for handling nested media fields
  • Properly handles error cases with informative logging
  • Uses safe dictionary access with pydash
tests/unittests/import_export_tests.py (3)

2221-2226: LGTM: Added test for instance segmentation with FiftyOne dataset format

The test method properly validates instance segmentation functionality with the current FiftyOne dataset format.


2227-2232: LGTM: Added test for instance segmentation with legacy format

The test method ensures backward compatibility by testing instance segmentation with the legacy FiftyOne dataset format.


2233-2329: LGTM: Comprehensive test helper for instance segmentation

The helper function _test_instance_segmentation_fiftyone_dataset thoroughly tests:

  • Export/import of in-database instance segmentations
  • Conversion to on-disk instance segmentations
  • Path validation for exported segmentations
  • Import/export without media
docs/source/user_guide/using_datasets.rst (3)

2574-2576: LGTM! Proper mask generation and storage.

The code correctly generates and saves binary masks using appropriate data types (uint8) and image format (PNG).


2620-2621: LGTM! Clear documentation of custom attributes.

The documentation effectively explains the extensibility of instance segmentation labels through dynamic attributes.


2647-2647: LGTM! Clear example output.

The example output effectively demonstrates the structure of a Detection object with a mask_path attribute.

fiftyone/utils/cvat.py (2)

Line range hint 1-2: LGTM!

The subtraction function is correctly implemented with proper parameter naming and logic.


6430-6432: ⚠️ Potential issue

Critical API change: Detection mask check updated

The change from det.mask to det.has_mask represents a significant API change in mask handling. This new property provides more robust mask detection by checking both in-memory and on-disk masks, but may break existing code that relies on the old mask property.

Let's verify the usage of this API change:

✅ Verification successful

API change is valid and properly implemented

The change from det.mask to det.has_mask is a valid improvement in the codebase. The has_mask property is a well-defined method in the Detection class (fiftyone/core/labels.py) that properly checks for both in-memory masks (self.mask) and on-disk masks (self.mask_path). This change makes the code more robust by considering both storage locations, and it's consistent with the class's design.

Key findings from the codebase:

  • The has_mask property is properly defined in the Detection class
  • It checks both self.mask and self.mask_path
  • The implementation is used consistently throughout the codebase
  • The change aligns with the mask handling architecture in the FiftyOne framework
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any other uses of det.mask or det.has_mask in the codebase
rg -A 2 "det\.(mask|has_mask)"

# Search for tests that need to be updated
rg -A 5 "test.*mask.*detection" "tests/"

Length of output: 213


Script:

#!/bin/bash
# Let's search for the broader context of this change
rg -B 5 -A 5 "det\.has_mask" fiftyone/utils/cvat.py

# Let's also look for any Detection class definitions or imports
ast-grep --pattern 'class Detection'

# Search for mask-related properties in Detection class
ast-grep --pattern 'class Detection {
  $$$
  mask
  $$$
}'

# Let's check if there are any imports of Detection class
rg "from.*import.*Detection"

Length of output: 2411


Script:

#!/bin/bash
# Let's look for the Detection class in the core modules
rg -B 5 -A 10 "class.*Detection.*:" fiftyone/core/

# Check for any recent changes to Detection class
git log -p --grep="Detection" -- "fiftyone/core/"

# Look for mask-related methods in the codebase
rg -B 2 -A 2 "def.*mask" fiftyone/core/

Length of output: 27887

fiftyone/core/collections.py (1)

Line range hint 10715-10740: Enhanced media field parsing with improved return values

The renamed _parse_media_field() method provides better functionality by:

  1. Properly handling app media fields
  2. Returning both the resolved media field and any associated list field
  3. Improved detection of list fields in the path

The rename from _resolve_media_field() to _parse_media_field() better reflects the method's purpose of parsing and extracting media field information.

Comment on lines +64 to +65
label[overlayField] &&
label[overlayField].bitmap &&
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

Use optional chaining to simplify code.
Applying the static analysis hint helps avoid potential TypeError issues and reduces complexity.

Below is a possible fix:

-    if (
-      label[overlayField] &&
-      label[overlayField].bitmap &&
-      !label[overlayField].image
-    ) {
+    if (
+      label[overlayField]?.bitmap &&
+      !label[overlayField]?.image
+    ) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
label[overlayField] &&
label[overlayField].bitmap &&
label[overlayField]?.bitmap &&
!label[overlayField]?.image
🧰 Tools
🪛 Biome (1.9.4)

[error] 64-65: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

Comment on lines +226 to +250
// bitmap generation loop
for (const field in sample) {
let labels = sample[field];

if (!Array.isArray(labels)) {
labels = [labels];
}

const cls = getCls(`${prefix ? prefix : ""}${field}`, schema);

if (!cls) {
continue;
}

for (const label of labels) {
if (!label) {
continue;
}

collectBitmapPromises(label, cls, bitmapPromises);
}
}

return [bitmapPromises, maskTargetsBuffers];
};
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

Final bitmap generation
By collecting bitmapPromises, you finalize the pipeline in three phases (decode, paint, generate). This pipeline is easy to follow and debug.

Ensure that large sequences of samples with high-resolution images don’t consume excessive memory before final disposal or streaming. Possibly chunk the tasks or add streaming logic.

Comment on lines +296 to +300
if (this.state.destroyed && this.sampleOverlays) {
// close all current overlays
this.pluckedOverlays.forEach((overlay) => overlay.cleanup?.());
}

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

Ensure overlays are null-checked before cleanup.

If this.state.destroyed occurs without valid overlays, we might encounter unexpected errors. Consider adding a defensive null check for this.pluckedOverlays to avoid potential runtime exceptions.

296-300
 if (this.state.destroyed && this.sampleOverlays) {
   // close all current overlays
-  this.pluckedOverlays.forEach((overlay) => overlay.cleanup?.());
+  this.pluckedOverlays?.forEach((overlay) => overlay.cleanup?.());
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (this.state.destroyed && this.sampleOverlays) {
// close all current overlays
this.pluckedOverlays.forEach((overlay) => overlay.cleanup?.());
}
if (this.state.destroyed && this.sampleOverlays) {
// close all current overlays
this.pluckedOverlays?.forEach((overlay) => overlay.cleanup?.());
}

Comment on lines +44 to +45
import { useRecoilState, useSetRecoilState } from "recoil";
import Error from "./Error";
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

Potential collision with global “Error” object.

You’re importing Error from a custom module, overshadowing the built-in Error constructor. Consider renaming it, e.g., “EvaluationError,” to prevent confusion.

- import Error from "./Error";
+ import EvaluationError from "./Error";
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import { useRecoilState, useSetRecoilState } from "recoil";
import Error from "./Error";
import { useRecoilState, useSetRecoilState } from "recoil";
import EvaluationError from "./Error";
🧰 Tools
🪛 Biome (1.9.4)

[error] 45-45: Do not shadow the global "Error" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)

Comment on lines +10 to +22
<Box
title={canEvaluate ? "" : "You do not have permission to evaluate model"}
sx={{ cursor: canEvaluate ? "pointer" : "not-allowed" }}
>
<MuiButton
onClick={onEvaluate}
startIcon={<Add />}
variant="contained"
disabled={!canEvaluate}
>
Evaluate Model
</MuiButton>
</Box>
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

Improve accessibility for disabled state

The component should have improved accessibility for screen readers:

 <Box
   title={canEvaluate ? "" : "You do not have permission to evaluate model"}
-  sx={{ cursor: canEvaluate ? "pointer" : "not-allowed" }}
+  sx={{ cursor: canEvaluate ? "pointer" : "not-allowed" }}
+  role="region"
+  aria-label="Model evaluation controls"
 >
   <MuiButton
     onClick={onEvaluate}
     startIcon={<Add />}
     variant="contained"
     disabled={!canEvaluate}
+    aria-disabled={!canEvaluate}
   >
     Evaluate Model
   </MuiButton>
 </Box>
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<Box
title={canEvaluate ? "" : "You do not have permission to evaluate model"}
sx={{ cursor: canEvaluate ? "pointer" : "not-allowed" }}
>
<MuiButton
onClick={onEvaluate}
startIcon={<Add />}
variant="contained"
disabled={!canEvaluate}
>
Evaluate Model
</MuiButton>
</Box>
<Box
title={canEvaluate ? "" : "You do not have permission to evaluate model"}
sx={{ cursor: canEvaluate ? "pointer" : "not-allowed" }}
role="region"
aria-label="Model evaluation controls"
>
<MuiButton
onClick={onEvaluate}
startIcon={<Add />}
variant="contained"
disabled={!canEvaluate}
aria-disabled={!canEvaluate}
>
Evaluate Model
</MuiButton>
</Box>

Comment on lines +42 to +46
.catch((error) => {
activeRequests--;
reject(error);
});
};
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

Improve error handling in queue processing

The catch block decrements activeRequests but doesn't continue processing the queue, which could lead to stuck requests if an error occurs.

Apply this diff:

     .catch((error) => {
       activeRequests--;
       reject(error);
+      processFetchQueue();
     });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
.catch((error) => {
activeRequests--;
reject(error);
});
};
.catch((error) => {
activeRequests--;
reject(error);
processFetchQueue();
});
};

Comment on lines +6 to +36
export default function Error(props: ErrorProps) {
const { onBack } = props;
return (
<Stack sx={{ height: "100%", p: 2 }} spacing={1}>
<Box>
<Button onClick={onBack} startIcon={<West />} color="secondary">
Back to Model Evaluation
</Button>
</Box>
<Card
sx={{
display: "flex",
justifyContent: "center",
alignItems: "center",
height: "100%",
}}
>
<Stack spacing={2} sx={{ alignItems: "center" }}>
<ErrorIcon sx={{ fontSize: 64 }} />
<Typography color="secondary">
Analyze and improve models collaboratively with your team
</Typography>
<Typography sx={{ fontWeight: 600 }}>
The Model Evaluation panel currently supports only classification,
detection, and segmentation evaluations
</Typography>
</Stack>
</Card>
</Stack>
);
}
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

Rename component and improve accessibility

  1. Component name shadows the global Error type
  2. Missing accessibility attributes
  3. Hard-coded strings should be externalized for i18n

Suggested improvements:

-export default function Error(props: ErrorProps) {
+export default function EvaluationError(props: ErrorProps) {
   const { onBack } = props;
   return (
     <Stack sx={{ height: "100%", p: 2 }} spacing={1}>
       <Box>
         <Button 
           onClick={onBack} 
           startIcon={<West />} 
           color="secondary"
+          aria-label="Return to model evaluation"
         >
-          Back to Model Evaluation
+          {t('modelEvaluation.backButton')}
         </Button>
       </Box>
       {/* ... rest of the component ... */}
     </Stack>
   );
 }

Consider creating a separate translations file for all text strings.

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

🧰 Tools
🪛 Biome (1.9.4)

[error] 6-6: Do not shadow the global "Error" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)

Comment on lines +16 to +41
mock_on_click = lambda: None

table.add_row_action(
"action1",
on_click=mock_on_click,
icon="icon1",
color="primary",
tooltip="Action 1",
)
table.add_row_action(
"action2",
on_click=mock_on_click,
icon="icon2",
color="secondary",
tooltip="Action 2",
)

with self.assertRaises(ValueError):
table.add_row_action(
"action1",
on_click=mock_on_click,
icon="icon3",
color="primary",
tooltip="Action 3",
)

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

Replace lambda with proper function definition

Using lambda for assignment violates Python style guidelines (PEP 8 - E731). Define a proper function instead.

-mock_on_click = lambda: None
+def mock_on_click():
+    return None
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
mock_on_click = lambda: None
table.add_row_action(
"action1",
on_click=mock_on_click,
icon="icon1",
color="primary",
tooltip="Action 1",
)
table.add_row_action(
"action2",
on_click=mock_on_click,
icon="icon2",
color="secondary",
tooltip="Action 2",
)
with self.assertRaises(ValueError):
table.add_row_action(
"action1",
on_click=mock_on_click,
icon="icon3",
color="primary",
tooltip="Action 3",
)
def mock_on_click():
return None
table.add_row_action(
"action1",
on_click=mock_on_click,
icon="icon1",
color="primary",
tooltip="Action 1",
)
table.add_row_action(
"action2",
on_click=mock_on_click,
icon="icon2",
color="secondary",
tooltip="Action 2",
)
with self.assertRaises(ValueError):
table.add_row_action(
"action1",
on_click=mock_on_click,
icon="icon3",
color="primary",
tooltip="Action 3",
)
🧰 Tools
🪛 Ruff (0.8.2)

16-16: Do not assign a lambda expression, use a def

Rewrite mock_on_click as a def

(E731)

Comment on lines +74 to +77
# Use this until https://github.com/federicocarboni/setup-ffmpeg/pull/23
# is merged or the maintainer addresses the root issue.
- name: Setup FFmpeg (with retries)
uses: afoley587/setup-ffmpeg@main
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Pin the FFmpeg action to commit f8748f5b0c83db7d0adb3b874893a8c5ff39bda4

The current @main reference points to a stable commit from December 10, 2024, which specifically adds retry functionality. Pin to this specific commit SHA for better stability while waiting for the upstream issue to be resolved.

  • Update the action reference in .github/workflows/e2e.yml from afoley587/setup-ffmpeg@main to afoley587/setup-ffmpeg@f8748f5b0c83db7d0adb3b874893a8c5ff39bda4
🔗 Analysis chain

Consider pinning the FFmpeg action to a specific version

While this is a temporary solution, using @main tag for GitHub Actions can be risky as it may lead to unexpected breaking changes. Consider pinning to a specific commit SHA for better stability until the upstream issue is resolved.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the action repository has recent commits that might affect stability
gh api repos/afoley587/setup-ffmpeg/commits --jq '.[0:5] | .[] | {sha: .sha, date: .commit.author.date, message: .commit.message}'

Length of output: 816

@@ -384,7 +384,7 @@ type PanelOptions = {
*
* Defaults to `false`.
*/
isNew?: boolean;
isNew: boolean;
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

Breaking Change: isNew property is now required

The isNew property in PanelOptions has been changed from optional to required. This is a breaking change that will affect all existing plugin registrations.

Please ensure that:

  1. All existing plugins are updated to include the isNew property
  2. The change is documented in the migration guide
  3. The major version is bumped according to semver

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

🧹 Nitpick comments (4)
docs/source/teams/data_lens.rst (4)

748-764: Consider enhancing warehouse selection logic.

The current warehouse selection logic could be improved to:

  1. Handle the case when no warehouses are available
  2. Add timeout for warehouse startup
  3. Add retry logic for warehouse startup failures
 def _start_warehouse(self) -> str:
     """Start a SQL warehouse and return its ID."""
+    MAX_RETRIES = 3
+    STARTUP_TIMEOUT = 300  # 5 minutes
+    start_time = time.time()
 
     last_warehouse_id = None
 
     # If any warehouses are already running, use the first available
     for warehouse in self.client.warehouses.list():
         last_warehouse_id = warehouse.id
         if warehouse.health.status is not None:
             return warehouse.id
 
     # Otherwise, manually start the last available warehouse
     if last_warehouse_id is not None:
+        for attempt in range(MAX_RETRIES):
+            try:
                 self.client.warehouses.start(last_warehouse_id)
+                while time.time() - start_time < STARTUP_TIMEOUT:
+                    warehouse = self.client.warehouses.get(last_warehouse_id)
+                    if warehouse.health.status is not None:
+                        return last_warehouse_id
+                    time.sleep(5)
+            except Exception as e:
+                if attempt == MAX_RETRIES - 1:
+                    raise ValueError(f"Failed to start warehouse: {e}")
+                time.sleep(5)
+
+    raise ValueError("No warehouses available")
-    return last_warehouse_id

820-830: Consider making polling interval configurable.

The sleep duration in the polling loop is hardcoded to 2.5 seconds. Consider making this configurable to allow for different Databricks environments and workloads.

+    POLL_INTERVAL = 2.5  # seconds
     while (
             statement_response.status.state in
             (StatementState.PENDING, StatementState.RUNNING)
     ):
         statement_response = self.client.statement_execution.get_statement(
             statement_response.statement_id
         )
 
-        time.sleep(2.5)
+        time.sleep(POLL_INTERVAL)

917-936: Enhance error handling with more specific error types.

The current error handling uses generic ValueError. Consider creating custom exception types for different error scenarios to help with error handling upstream.

+class DatabricksConnectorError(Exception):
+    """Base exception for Databricks connector errors."""
+    pass
+
+class DatabricksResponseError(DatabricksConnectorError):
+    """Exception for Databricks response errors."""
+    pass
+
+class DatabricksStatementError(DatabricksConnectorError):
+    """Exception for Databricks statement errors."""
+    pass
+
 def _check_for_error(self, response: StatementResponse):
     if response is None:
-        raise ValueError("received null response from databricks")
+        raise DatabricksResponseError("received null response from databricks")
 
     if response.status is not None:
         if response.status.error is not None:
-            raise ValueError("databricks error: ({0}) {1}".format(
+            raise DatabricksStatementError("databricks error: ({0}) {1}".format(
                 response.status.error.error_code,
                 response.status.error.message
             ))
 
         if response.status.state in (
                 StatementState.CLOSED,
                 StatementState.FAILED,
                 StatementState.CANCELED,
         ):
-            raise ValueError(
+            raise DatabricksStatementError(
                 f"databricks error: response state = {response.status.state}"
             )

1131-1210: Consider adding performance and validation best practices.

The dynamic user inputs section is well-documented but could benefit from additional information about:

  1. Performance considerations when using dynamic inputs (e.g., caching strategies for expensive operations)
  2. Best practices for validating dynamic inputs
  3. Error handling recommendations for invalid combinations of inputs

Example addition:

Performance and Validation Best Practices
---------------------------------------

When implementing dynamic inputs, consider the following best practices:

1. Cache expensive operations that determine available options
2. Validate interdependent fields (e.g., ensure remapped field names don't conflict)
3. Provide clear error messages when invalid combinations are selected
4. Consider the impact of frequent input changes on backend resources
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e5cd1bd and 45a8a28.

📒 Files selected for processing (2)
  • docs/source/release-notes.rst (3 hunks)
  • docs/source/teams/data_lens.rst (5 hunks)
🔇 Additional comments (3)
docs/source/release-notes.rst (2)

6-24: LGTM! The recent release notes are well-structured and informative.

The release notes for v1.2.0 are properly formatted and contain clear descriptions of changes across different components (App, Core, Brain, etc.). The information is organized logically and provides good context for users.


Line range hint 25-2738: Skip reviewing historical release notes.

These are historical release notes from v0.7.0 to v1.1.0 that serve as documentation of past changes. As they represent historical records, they don't require active review.

docs/source/teams/data_lens.rst (1)

15-18: LGTM!

The text changes appropriately include Databricks in the list of supported data sources.

@findtopher findtopher requested a review from a team December 20, 2024 15:25
@findtopher findtopher merged commit aa3a500 into main Dec 20, 2024
15 checks passed
@findtopher findtopher deleted the release/v1.2.0 branch December 20, 2024 22:41
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.