Skip to content

[ESLint] Extract complex expressions (expression-complexity) + promote to error - #32381

Merged
ShaileshParmar11 merged 7 commits into
mainfrom
ShaileshParmar11/eslint-expression-complexity
Sep 4, 2026
Merged

ShaileshParmar11 merged 7 commits into
mainfrom
ShaileshParmar11/eslint-expression-complexity

Conversation

@ShaileshParmar11

@ShaileshParmar11 ShaileshParmar11 commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Part of rule 9 of the ESLint-cleanup epic (#30977, sub-issue #30984 — the sonarjs complexity family). Takes sonarjs/expression-complexity (SonarJS S1067, "too many conditional operators in one expression — max 3") to 0 violations and promotes it warn → error. The remaining complexity rules in #30984 (cyclomatic-complexity, cognitive-complexity) stay warn for follow-up PRs.

Stacked on #32364 (no-nested-functions), which is stacked on #32348 (no-nested-conditional). Base is #32364's branch so this diff shows only the 110 expression-complexity files; GitHub retargets automatically as the bases merge.

Approach — real refactors, short-circuit-safe

All 141 violations across 110 files fixed by extracting sub-expressions into named consts so no single expression has >3 &&/||/?: operators. The key hazard — naively splitting a short-circuit chain can eagerly evaluate a dereference out from behind its null-guard and throw — was avoided by:

  • extracting a contiguous leading same-operator run (a && b && c && d → const abc = a && b && c; abc && d) so evaluation order and short-circuiting are byte-for-byte identical;
  • keeping every null/undefined guard ahead of what it guards (or using optional chaining in the extracted const);
  • preserving TypeScript aliased-condition narrowing (no Boolean(...) wraps around narrowing guards; if-splits where a guard feeds later access).

Two heavy JSX subtrees (OntologyExplorer ~9 operators, AlertAiDestinationItem ~12) use a <> → <Fragment> boundary — identical render output — to isolate sibling conditionals where const extraction was impractical. Called out for reviewer visibility; no eslint-disable anywhere.

Verification

  • ESLint: eslint --quiet src with the rule at error → 0 errors tree-wide, 0 expression-complexity.
  • Types: full tsc diff vs the stacked base → 0 net-new errors in any of the 110 files (remaining diff signatures are union-member-ordering noise in unrelated files; branch has fewer total).
  • Tests: the 80 co-located suites for the changed files pass — 1639 tests.
  • organize-imports + prettier on the changed files → 0 diff.

Ratchet

- 'sonarjs/expression-complexity': 'warn', // 15
+ 'sonarjs/expression-complexity': 'error',

Tracker: does not close #30984 — clears only the expression-complexity sub-rule of the complexity family, leaving #30984 open for cyclomatic/cognitive. The PR-metadata gate is bypassed via the skip-pr-checks label for this reason.

@greptile-apps

greptile-apps Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Too many files changed for review (115 files, 100 file limit).

Bypass the limit by tagging @greptile-apps to review.

@github-actions

github-actions Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

❌ PR checklist incomplete

This PR cannot be merged until the following are addressed on its linked issue:

  • No GitHub issue is linked. Link an issue in the Development section of the PR (or add Fixes #12345 to the description). For a same-org cross-repo issue, add Fixes open-metadata/<repo>#123 to the description.

The fields live on the linked issue in the Shipping project (open the issue → right sidebar → Projects). After you set them, re-run this check (or push a commit) — issue/project changes do not re-trigger it automatically.

Maintainers can bypass this check by adding the skip-pr-checks label.

@ShaileshParmar11 ShaileshParmar11 added the skip-pr-checks Bypass PR metadata validation check label Sep 1, 2026
@github-actions github-actions Bot added safe to test Add this label to run secure Github workflows on PRs UI UI specific issues labels Sep 1, 2026
@github-actions

github-actions Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Jest test Coverage

UI tests summary

Lines Statements Branches Functions
Coverage: 69%
69.78% (92019/131869) 54.49% (57205/104969) 55.9% (17474/31255)

@github-actions

github-actions Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

✅ Playwright Results — workflow succeeded

Validated commit 38a9ada6a1d7250861451cd72479071ac57275e8 in Playwright run 33778356117, attempt 1.

✅ 4464 passed · ❌ 0 failed · 🟡 14 flaky · ⏭️ 1 skipped · 🧰 0 lifecycle flaky

Performance

Blocking targets: ✅ met · Optimization targets: 🟡 in progress

Shard-job maxima below are not the full workflow wall time; the linked run includes build, fixture, planning, and reporting.

🕒 Full workflow signal wall (to summary) 59m 1s

⏱️ Max setup 4m 37s · max shard execution 19m 26s · max shard-job elapsed before upload 23m 3s · reporting 38s

🌐 207.38 requests/attempt · 2.30 app boots/UI scenario · 27.87% common-shard skew

Optimization targets still in progress:

  • Common shard skew was 27.87% (convergence target: at most 15%).
  • Browser traffic was 207.38 requests per attempt (convergence target: fewer than 200).
  • Application boot ratio was 2.3 per UI scenario (10911 boots / 4742 scenarios; convergence target: at most 1).
Shard Passed Failed Flaky Skipped Lifecycle failed Lifecycle flaky
✅ Shard advanced-search-01 130 0 0 0 0 0
🟡 Shard chromium-01 180 0 1 0 0 0
✅ Shard chromium-02 148 0 0 0 0 0
🟡 Shard chromium-03 151 0 1 0 0 0
✅ Shard chromium-04 150 0 0 0 0 0
🟡 Shard chromium-05 155 0 1 0 0 0
✅ Shard chromium-06 145 0 0 0 0 0
🟡 Shard chromium-07 154 0 1 0 0 0
✅ Shard chromium-08 246 0 0 0 0 0
🟡 Shard chromium-09 170 0 1 0 0 0
✅ Shard chromium-10 163 0 0 0 0 0
🟡 Shard chromium-11 169 0 2 1 0 0
✅ Shard chromium-12 180 0 0 0 0 0
✅ Shard chromium-13 163 0 0 0 0 0
🟡 Shard chromium-14 187 0 1 0 0 0
✅ Shard chromium-15 151 0 0 0 0 0
✅ Shard chromium-16 161 0 0 0 0 0
🟡 Shard chromium-17 207 0 1 0 0 0
✅ Shard chromium-18 203 0 0 0 0 0
🟡 Shard chromium-19 171 0 1 0 0 0
✅ Shard chromium-20 195 0 0 0 0 0
🟡 Shard chromium-21 162 0 1 0 0 0
✅ Shard chromium-22 167 0 0 0 0 0
🟡 Shard chromium-23 137 0 1 0 0 0
✅ Shard data-asset-rules-01 65 0 0 0 0 0
✅ Shard domain-isolation-01 16 0 0 0 0 0
✅ Shard global-state-01 34 0 0 0 0 0
✅ Shard import-export-01 36 0 0 0 0 0
🟡 Shard import-export-02 113 0 1 0 0 0
✅ Shard ingestion-01 43 0 0 0 0 0
🟡 Shard ingestion-02 43 0 1 0 0 0
✅ Shard reindex-01 28 0 0 0 0 0
✅ Shard search-01 12 0 0 0 0 0
✅ Shard search-rbac-01 29 0 0 0 0 0
🟡 14 flaky test(s) (passed on retry)
  • Features/ContextCenterArticles.spec.ts › Article list cards, recently viewed widget, and pagination work (shard chromium-01, 1 retry)
  • Pages/Lineage/LineageFilters.spec.ts › Verify lineage schema filter selection (shard chromium-03, 1 retry)
  • Pages/ExplorePageRightPanel.spec.ts › Should verify deleted user not visible in owner selection for table (shard chromium-05, 1 retry)
  • Pages/Lineage/LineageInteraction.spec.ts › Verify node panel opens on click (shard chromium-07, 1 retry)
  • VersionPages/ServiceEntityVersionPage.spec.ts › Storage Service (shard chromium-09, 1 retry)
  • Pages/ExplorePageRightPanel_KnowledgeCenter.spec.ts › Should remove user owner for knowledgeCenter (shard chromium-11, 1 retry)
  • Pages/Tag.spec.ts › Add and Remove Assets (shard chromium-11, 1 retry)
  • Features/Workflows/WorkflowOssRestrictions.spec.ts › trigger-type-select is disabled in OSS (shard chromium-14, 1 retry)
  • Pages/InputOutputPorts.spec.ts › Tab renders with empty state when no ports exist (shard chromium-17, 1 retry)
  • Pages/TasksUIFlow.spec.ts › Create and reject tag task for Dashboard via UI (shard chromium-19, 1 retry)
  • Features/PersonaAIContextRules.spec.ts › knowledge entity type forces Fully rendered on and disables it (shard chromium-21, 1 retry)
  • Pages/Glossary.spec.ts › Glossary & terms creation for reviewer as team (shard chromium-23, 1 retry)
  • Features/ClassificationImportExport.spec.ts › export starts a CSV export job for the classification (shard import-export-02, 1 retry)
  • Features/DataQuality/DataQuality.spec.ts › Pagination functionality in test cases list (shard ingestion-02, 1 retry)

📦 Download artifacts

How to debug locally
# Download playwright-test-results-<shard> artifact and unzip
npx playwright show-trace path/to/trace.zip    # view trace

@ShaileshParmar11
ShaileshParmar11 force-pushed the ShaileshParmar11/eslint-no-nested-functions branch from 0a64340 to 75843ba Compare September 2, 2026 05:11
…atch 1/2

Partial: 49 of 110 files with sonarjs/expression-complexity (S1067)
violations refactored by extracting sub-expressions into named consts,
preserving short-circuit/lazy evaluation. Committed to protect against
the workspace-sync reset; remaining 61 files follow in batch 2.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
karanh37
karanh37 previously approved these changes Sep 2, 2026
@github-actions

github-actions Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

🚦 Removed from the merge queue — merge_conflict (2026-09-02T19:08:02Z)

The entry left the queue before it was built, so no checks ran against it.

Conflicts:
- DestinationSelectItemV2.tsx: accepted main's deletion (#32078).
- DestinationSelectItem.tsx: took main's react-hook-form rewrite wholesale —
  this branch's refactor targeted the AntD implementation main replaced — then
  re-applied expression extraction to its new JSX so the promoted rule holds.
- AlertsUtil.tsx: accepted main's removal of getConnectionTimeoutField,
  getReadTimeoutField and getDestinationConfigField; no references remain.
- TableV2.tsx: kept this branch's showCustomPagination/showClientPagination
  extraction, updated the client-pagination condition to main's serverTotal
  form, and added main's rest.footer block.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@gitar-bot

gitar-bot Bot commented Sep 3, 2026

Copy link
Copy Markdown
Code Review ⚠️ Changes requested 1 resolved / 4 findings

Extracts 141 complex expressions across 110 files to eliminate expression-complexity violations and promotes the rule to error. However, three issues must be resolved before merge:

Important: TableV2 uses internalCurrentPage for row indices but currentPage for data slicing; when client-side pagination is controlled externally, indices will be off by a page, causing wrong row keys and incorrect indices passed to renderers.

Minor: CreateMemoryModal replaced a memoized remove handler with an inline closure created per render, allocating a new function for every asset on every render instead of using a stable callback reference.

Minor: Several hunks add unrelated functional changes—theme persistence semantics in theme-provider.tsx, UI component swaps in KnowledgePageListComponent.tsx and DomainTreeView.tsx—that go beyond mechanical expression extraction and should be split out or clearly documented, as regressions here would be masked by the surrounding refactor churn.

⚠️ Bug: flatRows uses internalCurrentPage while slicing uses currentPage

📄 openmetadata-ui/src/main/resources/ui/src/components/common/Table/TableV2.tsx:677-678 📄 openmetadata-ui/src/main/resources/ui/src/components/common/Table/TableV2.tsx:848-862

pagedDataSource slices with currentPage = clientPagination?.controlledCurrent ?? internalCurrentPage, but flatRows computes actualIndex as (internalCurrentPage - 1) * pageSize + idx. When a call site drives client-side pagination with a controlled pagination.current (a number, with total <= rowCount so serverTotal is undefined), internalCurrentPage stays at 1 while controlledCurrent selects the visible page. The rows shown are page N, but actualIndex — and therefore getRowKey(record, actualIndex) and the index passed to onRow, onCell and cell renderers — is computed as if on page 1. This yields wrong indices and, when rowKey falls back to the index, duplicate/incorrect row keys across pages. Use currentPage in flatRows (and its dependency array) to match the slice.

Compute actualIndex from currentPage (controlledCurrent ?? internalCurrentPage), matching pagedDataSource's slice.
      return pagedDataSource.map((record, idx) => {
        const actualIndex = clientPagination
          ? (currentPage - 1) * clientPagination.pageSize + idx
          : idx;
// ...and replace `internalCurrentPage` with `currentPage` in the deps array below
💡 Quality: Unrelated behavior/scope changes bundled into refactor PR

📄 openmetadata-ui/src/main/resources/ui/src/context/UntitledUIThemeProvider/theme-provider.tsx:270-284 📄 openmetadata-ui/src/main/resources/ui/src/components/KnowledgeCenter/KnowledgePageListComponent/KnowledgePageListComponent.tsx:487-501

Several hunks go well beyond mechanical expression extraction for a PR scoped to expression-complexity: theme-provider.tsx adds new system-preference detection, a matchMedia change listener, and changes theme persistence semantics (light theme now persists, previously it was removed from storage); KnowledgePageListComponent.tsx and DomainTreeView.tsx replace ErrorPlaceHolder with EmptyPlaceholder and change empty-state UI. These functional changes are harder to review inside a large no-op refactor and should ideally be split out or at least called out, since a regression here would be masked by the surrounding churn.

💡 Performance: CreateMemoryModal: memoized remove handler replaced with inline closure

📄 openmetadata-ui/src/main/resources/ui/src/components/ContextCenter/CreateMemoryModal/CreateMemoryModal.component.tsx:854-868

The refactor deleted the handleRemoveLinkedAsset useCallback and the getLinkedAssetKey helper, inlining the remove logic as onRemove={(fqn) => setLinkedAssets(...)} inside the linkedAssets.map render. This creates a new function for every asset on every render, which contradicts the project's frontend-performance guidance on stable callback references. Restore a useCallback-wrapped handler (and keep a shared key helper) and pass it down instead of allocating a closure per row.

✅ 1 resolved
✅ Quality: expression-complexity fix un-ratchets two other sonarjs rules

📄 openmetadata-ui/src/main/resources/ui/eslint.config.mjs:344-346
This commit demotes sonarjs/no-nested-conditional and sonarjs/no-nested-functions from error back to warn (now annotated // 16 and // 18), removing the "backlog is zero / ratchets it" comments. This is contradictory in a PR stacked on #32364 (no-nested-functions) and directly undoes that parent's promotion. The cause is that the expression-complexity refactor replaced extracted consts with deeply nested inline JSX ternaries (e.g. the Button color/data-testid/iconLeading triple ternaries in TaskDetailPanel.tsx, the owner/link/tier ternary chains in EntitySummaryDetails.tsx, and the banner/label ternaries in BulkEntityImportPage.tsx), re-introducing 16 nested-conditional violations. Consider extracting these back into intermediate variables or if/helper functions so both rules can stay at error, rather than trading one clean rule for the regression of two.

🤖 Prompt for agents
Code Review: Extracts 141 complex expressions across 110 files to eliminate `expression-complexity` violations and promotes the rule to error. However, three issues must be resolved before merge:
  
  **Important:** TableV2 uses `internalCurrentPage` for row indices but `currentPage` for data slicing; when client-side pagination is controlled externally, indices will be off by a page, causing wrong row keys and incorrect indices passed to renderers.
  
  **Minor:** CreateMemoryModal replaced a memoized remove handler with an inline closure created per render, allocating a new function for every asset on every render instead of using a stable callback reference.
  
  **Minor:** Several hunks add unrelated functional changes—theme persistence semantics in theme-provider.tsx, UI component swaps in KnowledgePageListComponent.tsx and DomainTreeView.tsx—that go beyond mechanical expression extraction and should be split out or clearly documented, as regressions here would be masked by the surrounding refactor churn.

1. 💡 Quality: Unrelated behavior/scope changes bundled into refactor PR
   Files: openmetadata-ui/src/main/resources/ui/src/context/UntitledUIThemeProvider/theme-provider.tsx:270-284, openmetadata-ui/src/main/resources/ui/src/components/KnowledgeCenter/KnowledgePageListComponent/KnowledgePageListComponent.tsx:487-501

   Several hunks go well beyond mechanical expression extraction for a PR scoped to `expression-complexity`: theme-provider.tsx adds new system-preference detection, a matchMedia change listener, and changes theme persistence semantics (light theme now persists, previously it was removed from storage); KnowledgePageListComponent.tsx and DomainTreeView.tsx replace `ErrorPlaceHolder` with `EmptyPlaceholder` and change empty-state UI. These functional changes are harder to review inside a large no-op refactor and should ideally be split out or at least called out, since a regression here would be masked by the surrounding churn.

2. 💡 Performance: CreateMemoryModal: memoized remove handler replaced with inline closure
   Files: openmetadata-ui/src/main/resources/ui/src/components/ContextCenter/CreateMemoryModal/CreateMemoryModal.component.tsx:854-868

   The refactor deleted the `handleRemoveLinkedAsset` `useCallback` and the `getLinkedAssetKey` helper, inlining the remove logic as `onRemove={(fqn) => setLinkedAssets(...)}` inside the `linkedAssets.map` render. This creates a new function for every asset on every render, which contradicts the project's frontend-performance guidance on stable callback references. Restore a `useCallback`-wrapped handler (and keep a shared key helper) and pass it down instead of allocating a closure per row.

3. ⚠️ Bug: flatRows uses internalCurrentPage while slicing uses currentPage
   Files: openmetadata-ui/src/main/resources/ui/src/components/common/Table/TableV2.tsx:677-678, openmetadata-ui/src/main/resources/ui/src/components/common/Table/TableV2.tsx:848-862

   `pagedDataSource` slices with `currentPage = clientPagination?.controlledCurrent ?? internalCurrentPage`, but `flatRows` computes `actualIndex` as `(internalCurrentPage - 1) * pageSize + idx`. When a call site drives client-side pagination with a controlled `pagination.current` (a number, with `total <= rowCount` so `serverTotal` is undefined), `internalCurrentPage` stays at 1 while `controlledCurrent` selects the visible page. The rows shown are page N, but `actualIndex` — and therefore `getRowKey(record, actualIndex)` and the index passed to `onRow`, `onCell` and cell renderers — is computed as if on page 1. This yields wrong indices and, when `rowKey` falls back to the index, duplicate/incorrect row keys across pages. Use `currentPage` in `flatRows` (and its dependency array) to match the slice.

   Fix (Compute actualIndex from currentPage (controlledCurrent ?? internalCurrentPage), matching pagedDataSource's slice.):
         return pagedDataSource.map((record, idx) => {
           const actualIndex = clientPagination
             ? (currentPage - 1) * clientPagination.pageSize + idx
             : idx;
   // ...and replace `internalCurrentPage` with `currentPage` in the deps array below

Options

Display: compact → Showing less information.

Comment with these commands to change the behavior for this request:

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

A few refactors introduced/retained stale-closure risks via incomplete useMemo dependency arrays that can cause incorrect UI state until fixed.

Review details

Suppressed comments (3)

openmetadata-ui/src/main/resources/ui/src/components/common/QueryBuilderWidgetV1/QueryBuilderWidgetV1.tsx:217

  • showFilteredResourceCount depends on searchResults, but it isn't included in the useMemo dependency list. This can leave the boolean stale (e.g., when setSearchResults(undefined) runs without changing any listed deps), causing the count preview UI to render inconsistently.
    openmetadata-ui/src/main/resources/ui/src/components/Settings/Team/TeamDetails/TeamsHeaderSection/TeamsHeadingLabel.component.tsx:193
  • teamHeadingRender's useMemo reads values/functions (hasAccess, isCurrentTeamOwner, handleClose, onHeadingSave, t) that are not in its dependency array. If permissions/user/locale change, the memoized JSX can be stale (e.g., edit button not appearing/disappearing).
    openmetadata-ui/src/main/resources/ui/src/components/Settings/Team/TeamDetails/TeamDetailsV1.tsx:967
  • teamActionButton's useMemo reads isOrganization, currentTeam.isJoinable, and t, but they are not listed in the dependency array. If the selected team changes (or joinable/org flags change), the memo can render the wrong Join/Leave button state.
  • Files reviewed: 115/115 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

@sonarqubecloud

sonarqubecloud Bot commented Sep 3, 2026

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

🚦 Removed from the merge queue — manual (2026-09-03T15:36:15Z)

Blocked the queue: playwright-summary

  • Postgresql PR Playwright E2E Tests — playwright-summary, playwright / playwright-ci (chromium-19), playwright / playwright-ci (chromium-22), playwright / playwright-ci (chromium-15)

@ShaileshParmar11

Copy link
Copy Markdown
Contributor Author

✅ Full Playwright suite — green on 38a9ada6

The merge-queue run 33767728012 failed three tests. I re-ran the complete suite against this PR's head to check whether they were real regressions.

Run: 33778356117 — conclusion: success

event:              workflow_dispatch (full_suite=true)
PW_EXECUTION_MODE:  full
head_sha:           38a9ada6a1d7250861451cd72479071ac57275e8
shards:             34   (non-success: 0)
jobs:               43 success · 2 skipped · 0 failure
tests:              4472 passed · 14 flaky · 0 failed

This is the full suite, not the targeted subset — the PR-level check ran 18 shards, this ran 34. ExploreTree.spec.ts in particular was never selected at PR level, so this is its first run against these changes.

The three merge-queue failures all pass here

✓  70 [chromium] › LargeGlossaryPerformance.spec.ts:379:7 › should handle drag and drop for term reordering (19.9s)
✓  16 [chromium] › TestLibrary.spec.ts:106:9              › should create, edit, and delete a test definition (17.2s)
✓ 164 [Basic]    › ExploreTree.spec.ts:186:7             › Verify Tags navigation via Governance tree ... (9.8s)

None of the three appear in the flaky list either — they passed outright, first attempt.

Why the queue run was not this PR

  • All three tests had already passed in this PR's earlier merge-queue run 33764330212 (success), on the same PR content.
  • The whole 14:35 queue batch failed — 32506 → 32445 → 32381 → 32211 → 32472 — each on a different random set of tests. 32506 and 32445 sit upstream of this PR and do not contain it.
  • The PR touches none of the three features: no ExploreTree files; TestCaseFormBody.tsx is the test case form, while the spec drives test-definition-form-body; and the one Glossary file changed, GlossaryTermTab.component.tsx, is a 2-hunk semantically-inert extraction.
  • Every failure signature was timing — element was detached from the DOM, element is not stable, click performed then 60s timeout, modal never appearing — not an assertion on a wrong value.

14 flaky (passed on retry) across unrelated specs: ServiceEntityVersionPage, TasksUIFlow, Tag, LineageInteraction, LineageFilters, InputOutputPorts, Glossary, ExplorePageRightPanel, WorkflowOssRestrictions, PersonaAIContextRules, DataQuality, ContextCenterArticles, ClassificationImportExport.

@github-actions

github-actions Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

🚦 Removed from the merge queue — manual (2026-09-04T05:12:27Z)

The entry left the queue before it was built, so no checks ran against it.

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

safe to test Add this label to run secure Github workflows on PRs skip-pr-checks Bypass PR metadata validation check UI UI specific issues

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[ESLint 9/10] sonarjs complexity

3 participants