Skip to content

CONSOLE-5307: Add knip-based dead code detection in CI - #16523

Merged
openshift-merge-bot[bot] merged 2 commits into
openshift:mainfrom
logonoff:knip
Jun 1, 2026
Merged

CONSOLE-5307: Add knip-based dead code detection in CI#16523
openshift-merge-bot[bot] merged 2 commits into
openshift:mainfrom
logonoff:knip

Conversation

@logonoff

@logonofflogonoff commented Jun 1, 2026

Copy link
Copy Markdown
Member

Follow up on #16513

Solution description:

Adds knip-based static analysis to identify unused exports and dependencies across the monorepo.

A custom knip compiler for console-extensions.json handles console-specific patterns that standard analysis tools cannot trace:

  • $codeRef values are detected uing isEncodedCodeRef and parsed with parseEncodedCodeRefValue from the SDK's coderef-resolver, then resolved via exposedModules in each plugin's package.json
  • Plugin packages are resolved once via resolvePluginPackages and reused for both the compiler lookup and workspace extension detection
  • Dynamic plugin SDK exports are excluded from reporting since they may be consumed by external plugins
  • Workspace configs are auto-discovered from the packages/ directory

Knip cannot natively trace which specific export is accessed from dynamic import().then(m => m.X) or CJS require('path').X patterns in TypeScript files. Without help, it marks the entire dynamically-imported module as used, hiding genuinely unused exports.

Add a compileScript compiler for ts/tsx/js/jsx that uses @babel/core parseSync to build an AST and extract:

  • import('./mod').then(m => m.X)import { X } from './mod'
  • require('pkg/mod').Ximport { X } from 'pkg/mod'

Matched patterns are surgically removed from the source using AST node positions, so knip no longer treats the entire module as used. The static named imports give knip export-level granularity while keeping each module in the dependency graph for transitive import tracing.

AST-based detection avoids the fragility of regex comment/string stripping (which broke on /* inside JSX string attributes like path="/api-resource/:plural/*").

Test cases:

  • Code that is exported but not used should be flagged
  • Unused files should be flagged
  • Duplicate exports (e.g., named and default) should be flagged
  • Dead code should be flagged
  • Exception for any code in console-dynamic-plugin-sdk because plugins could consume some code in some path which is dead to us but not for them

Summary by CodeRabbit

  • Chores
    • Removed unused internal components and hooks to streamline codebase.
    • Added new tooling for export analysis and dependency tracking.
    • Updated frontend CI pipeline to include additional code quality checks.
    • Cleaned up internal constant exports and removed commented-out code.

Adds knip-based static analysis to identify unused exports and dependencies across the monorepo.
A custom knip compiler for console-extensions.json handles console-specific patterns that standard analysis tools cannot trace:
- $codeRef values are detected uing isEncodedCodeRef and parsed with parseEncodedCodeRefValue from the SDK's coderef-resolver, then resolved via exposedModules in each plugin's package.json
- Plugin packages are resolved once via resolvePluginPackages and reused for both the compiler lookup and workspace extension detection
- Dynamic plugin SDK exports are excluded from reporting since they may be consumed by external plugins
- Workspace configs are auto-discovered from the packages/ directory
Knip cannot natively trace which specific export is accessed from dynamic `import().then(m => m.X)` or CJS `require('path').X` patterns in TypeScript files. Without help, it marks the entire dynamically-imported module as used, hiding genuinely unused exports.
Add a compileScript compiler for ts/tsx/js/jsx that uses @babel/core parseSync to build an AST and extract:
- `import('./mod').then(m => m.X)` → `import { X } from './mod'`
- `require('pkg/mod').X` → `import { X } from 'pkg/mod'`
Matched patterns are surgically removed from the source using AST node positions, so knip no longer treats the entire module as used. The static named imports give knip export-level granularity while keeping each module in the dependency graph for transitive import tracing.
AST-based detection avoids the fragility of regex comment/string stripping (which broke on `/*` inside JSX string attributes like `path="/api-resource/:plural/*"`).
@openshift-ci-robotopenshift-ci-robot added the jira/valid-reference Indicates that this PR references a valid Jira ticket of any type. label Jun 1, 2026
@openshift-ci-robot

openshift-ci-robot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

@logonoff: This pull request references CONSOLE-5037 which is a valid jira issue.

Warning: The referenced jira issue has an invalid target version for the target branch this PR targets: expected the story to target the "5.0.0" version, but no target version was set.

Details

In response to this:

Solution description:

Adds knip-based static analysis to identify unused exports and dependencies across the monorepo.

A custom knip compiler for console-extensions.json handles console-specific patterns that standard analysis tools cannot trace:

  • $codeRef values are detected uing isEncodedCodeRef and parsed with parseEncodedCodeRefValue from the SDK's coderef-resolver, then resolved via exposedModules in each plugin's package.json
  • Plugin packages are resolved once via resolvePluginPackages and reused for both the compiler lookup and workspace extension detection
  • Dynamic plugin SDK exports are excluded from reporting since they may be consumed by external plugins
  • Workspace configs are auto-discovered from the packages/ directory

Knip cannot natively trace which specific export is accessed from dynamic import().then(m => m.X) or CJS require('path').X patterns in TypeScript files. Without help, it marks the entire dynamically-imported module as used, hiding genuinely unused exports.

Add a compileScript compiler for ts/tsx/js/jsx that uses @babel/core parseSync to build an AST and extract:

  • import('./mod').then(m => m.X)import { X } from './mod'
  • require('pkg/mod').Ximport { X } from 'pkg/mod'

Matched patterns are surgically removed from the source using AST node positions, so knip no longer treats the entire module as used. The static named imports give knip export-level granularity while keeping each module in the dependency graph for transitive import tracing.

AST-based detection avoids the fragility of regex comment/string stripping (which broke on /* inside JSX string attributes like path="/api-resource/:plural/*").

Test cases:

  • Code that is exported but not used should be flagged
  • Unused files should be flagged
  • Duplicate exports (e.g., named and default) should be flagged
  • Dead code should be flagged
  • Exception for any code in console-dynamic-plugin-sdk because plugins could consume some code in some path which is dead to us but not for them

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the openshift-eng/jira-lifecycle-plugin repository.

@coderabbitai

coderabbitaiBot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

Walkthrough

This PR introduces knip, an unused exports detection tool, with custom compilers to trace exports across a monorepo. The knip configuration handles dynamic imports and scans console-extensions.json. Knip is integrated into the CI pipeline and identifies several unused components and hooks that are then removed.

Changes

Knip Configuration and Unused Exports Cleanup

Layer / File(s)Summary
Knip configuration with custom compilers
frontend/scripts/knip.ts
Defines JSON compiler to extract $codeRef from console-extensions.json and generate static imports. Implements script compiler using Babel to detect require(x).Y and import(x).then(m => m.Y) patterns and rewrite them as static named imports. Discovers workspace packages under frontend/packages and auto-configures knip for monorepo structure.
Knip integration into build and CI
frontend/package.json, test-frontend.sh
Adds knip as dev dependency at version ^6.14.2 and creates knip npm script. CI test pipeline runs knip after cycle detection and before linting.
Unused exports cleanup
frontend/packages/console-app/src/components/cluster-configuration/ClusterConfigurationField.tsx, frontend/packages/console-app/src/components/data-view/ConsoleDataView.tsx
Removes WIP commented field-type entries for text and checkbox from ClusterConfigurationField dispatch. Makes SELECTION_COLUMN_WIDTH constant non-exported in ConsoleDataView. Deletes unused components ClusterConfigurationCheckboxField, ClusterConfigurationTextField, the useSelectList hook and its tests, and useDebounceCallback re-export from cluster-configuration hooks.

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 15
✅ Passed checks (15 passed)
Check nameStatusExplanation
Title check✅ PassedThe title clearly and specifically describes the main change: adding knip-based dead code detection to CI. It directly matches the primary objective of the changeset.
Docstring Coverage✅ PassedNo functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.
Stable And Deterministic Test Names✅ PassedPR involves only frontend/JavaScript changes; no Ginkgo Go tests are present, created, or modified, making this check not applicable.
Test Structure And Quality✅ PassedPR contains no Ginkgo test code changes; check is not applicable as all modifications are TypeScript/JavaScript frontend files and configuration scripts.
Microshift Test Compatibility✅ PassedPR does not add any Ginkgo e2e tests; all changes are frontend code and configuration. MicroShift test compatibility check does not apply.
Single Node Openshift (Sno) Test Compatibility✅ PassedPR does not add new Ginkgo e2e tests; it removes dead code and adds knip static analysis tooling. SNO test compatibility check is not applicable.
Topology-Aware Scheduling Compatibility✅ PassedPR contains only frontend TypeScript/React code and build tooling changes, not Kubernetes manifests, operator code, or deployment-related infrastructure.
Ote Binary Stdout Contract✅ PassedThe OTE Binary Stdout Contract check is for Go test binaries. This PR contains only frontend TypeScript/JavaScript/React code with no Go test files, making the check not applicable.
Ipv6 And Disconnected Network Test Compatibility✅ PassedThis PR contains no Ginkgo e2e tests. All changes are frontend TypeScript/JavaScript files, configuration files, and CI scripts. The check is not applicable.
No-Weak-Crypto✅ PassedNo weak cryptography patterns (MD5, SHA1, DES, RC4, 3DES, Blowfish, ECB), custom crypto implementations, or non-constant-time secret comparisons found in PR changes.
Container-Privileges✅ PassedPR contains no K8s manifests or container specs - only frontend code cleanup and static analysis tooling. Container-privileges check not applicable.
No-Sensitive-Data-In-Logs✅ PassedNo logging statements exposing sensitive data (passwords, tokens, API keys, PII, etc.) found in PR files, including the new knip.ts configuration.
Description check✅ PassedThe pull request description comprehensively covers the solution, technical implementation details, and test cases required for the changes.

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

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

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

@logonoff

Copy link
Copy Markdown
MemberAuthor

/label px-approved
/label docs-approved
/verified by CI

@openshift-ci
openshift-ciBot requested review from rhamilto and spadgettJune 1, 2026 12:45
@openshift-ciopenshift-ciBot added component/core Related to console core functionality component/shared Related to console-shared px-approved Signifies that Product Support has signed off on this PR docs-approved Signifies that Docs has signed off on this PR labels Jun 1, 2026
@logonofflogonoff changed the title CONSOLE-5037: Remove even more dead codeCONSOLE-5037: Add knip-based dead code detection in CIJun 1, 2026
@openshift-ci-robotopenshift-ci-robot added the verified Signifies that the PR passed pre-merge verification criteria label Jun 1, 2026
@openshift-ci-robot

Copy link
Copy Markdown
Contributor

@logonoff: This PR has been marked as verified by CI.

Details

In response to this:

/label px-approved
/label docs-approved
/verified by CI

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the openshift-eng/jira-lifecycle-plugin repository.

@openshift-ci-robot

openshift-ci-robot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

@logonoff: This pull request references CONSOLE-5037 which is a valid jira issue.

Warning: The referenced jira issue has an invalid target version for the target branch this PR targets: expected the story to target the "5.0.0" version, but no target version was set.

Details

In response to this:

Solution description:

Adds knip-based static analysis to identify unused exports and dependencies across the monorepo.

A custom knip compiler for console-extensions.json handles console-specific patterns that standard analysis tools cannot trace:

  • $codeRef values are detected uing isEncodedCodeRef and parsed with parseEncodedCodeRefValue from the SDK's coderef-resolver, then resolved via exposedModules in each plugin's package.json
  • Plugin packages are resolved once via resolvePluginPackages and reused for both the compiler lookup and workspace extension detection
  • Dynamic plugin SDK exports are excluded from reporting since they may be consumed by external plugins
  • Workspace configs are auto-discovered from the packages/ directory

Knip cannot natively trace which specific export is accessed from dynamic import().then(m => m.X) or CJS require('path').X patterns in TypeScript files. Without help, it marks the entire dynamically-imported module as used, hiding genuinely unused exports.

Add a compileScript compiler for ts/tsx/js/jsx that uses @babel/core parseSync to build an AST and extract:

  • import('./mod').then(m => m.X)import { X } from './mod'
  • require('pkg/mod').Ximport { X } from 'pkg/mod'

Matched patterns are surgically removed from the source using AST node positions, so knip no longer treats the entire module as used. The static named imports give knip export-level granularity while keeping each module in the dependency graph for transitive import tracing.

AST-based detection avoids the fragility of regex comment/string stripping (which broke on /* inside JSX string attributes like path="/api-resource/:plural/*").

Test cases:

  • Code that is exported but not used should be flagged
  • Unused files should be flagged
  • Duplicate exports (e.g., named and default) should be flagged
  • Dead code should be flagged
  • Exception for any code in console-dynamic-plugin-sdk because plugins could consume some code in some path which is dead to us but not for them

Summary by CodeRabbit

  • Chores
  • Removed unused internal components and hooks to streamline codebase.
  • Added new tooling for export analysis and dependency tracking.
  • Updated frontend CI pipeline to include additional code quality checks.
  • Cleaned up internal constant exports and removed commented-out code.

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the openshift-eng/jira-lifecycle-plugin repository.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
frontend/scripts/knip.ts (1)

99-104: ⚡ Quick win

Avoid any in the AST walker.

(n as any)[key] turns off the type checking in the new compiler right where the node-shape assumptions matter most. A typed dictionary cast keeps the dynamic lookup without dropping back to any.

♻️ Proposed fix
- const child = (n as any)[key];+ const child = (n as Record<string, unknown>)[key];

As per coding guidelines, "Flag use of any type and suggest proper type definitions instead".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@frontend/scripts/knip.ts` around lines 99 - 104, The walker uses (n as
any)[key] which disables type checking; replace it with a typed index lookup
like (n as Record<string, unknown>)[key] or (n as t.Node & Record<string,
unknown>)[key] in the loop where t.VISITOR_KEYS, walk, and n are used, then
treat the result as unknown (const child) and keep the existing Array.isArray
and t.isNode guards (and type the array iterator param as unknown) so you don't
rely on any while preserving the runtime checks.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@frontend/package.json`:
- Line 294: Update the frontend package.json devDependency for "knip" to use an
exact version instead of a semver range: locate the "knip" entry under
devDependencies (devDependencies.knip) and replace "^6.14.2" with "6.14.2" so
the dependency is pinned exactly.
---
Nitpick comments:
In `@frontend/scripts/knip.ts`:
- Around line 99-104: The walker uses (n as any)[key] which disables type
checking; replace it with a typed index lookup like (n as Record<string,
unknown>)[key] or (n as t.Node & Record<string, unknown>)[key] in the loop where
t.VISITOR_KEYS, walk, and n are used, then treat the result as unknown (const
child) and keep the existing Array.isArray and t.isNode guards (and type the
array iterator param as unknown) so you don't rely on any while preserving the
runtime checks.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: openshift/coderabbit/.coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 4dd30ef5-46b9-447b-9b2f-e5e6bc4a0215

📥 Commits

Reviewing files that changed from the base of the PR and between 377ea54 and 27cd18d.

⛔ Files ignored due to path filters (1)
  • frontend/yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (10)
  • frontend/package.json
  • frontend/packages/console-app/src/components/cluster-configuration/ClusterConfigurationCheckboxField.tsx
  • frontend/packages/console-app/src/components/cluster-configuration/ClusterConfigurationField.tsx
  • frontend/packages/console-app/src/components/cluster-configuration/ClusterConfigurationTextField.tsx
  • frontend/packages/console-app/src/components/cluster-configuration/hooks.ts
  • frontend/packages/console-app/src/components/data-view/ConsoleDataView.tsx
  • frontend/packages/console-shared/src/hooks/__tests__/useSelectList.ts
  • frontend/packages/console-shared/src/hooks/useSelectList.ts
  • frontend/scripts/knip.ts
  • test-frontend.sh
💤 Files with no reviewable changes (6)
  • frontend/packages/console-app/src/components/cluster-configuration/hooks.ts
  • frontend/packages/console-shared/src/hooks/useSelectList.ts
  • frontend/packages/console-shared/src/hooks/tests/useSelectList.ts
  • frontend/packages/console-app/src/components/cluster-configuration/ClusterConfigurationField.tsx
  • frontend/packages/console-app/src/components/cluster-configuration/ClusterConfigurationTextField.tsx
  • frontend/packages/console-app/src/components/cluster-configuration/ClusterConfigurationCheckboxField.tsx

Comment threadfrontend/package.json
@openshift-ci

Copy link
Copy Markdown
Contributor

@logonoff: all tests passed!

Full PR test history. Your PR dashboard.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository. I understand the commands that are listed here.

@TheRealJonTheRealJon left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

/lgtm

@openshift-ciopenshift-ciBot added the lgtm Indicates that a PR is ready to be merged. label Jun 1, 2026
@openshift-ci

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: logonoff, TheRealJon

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@openshift-ciopenshift-ciBot added the approved Indicates a PR has been approved by an approver from all required OWNERS files. label Jun 1, 2026
@openshift-merge-bot
openshift-merge-botBot merged commit 07a33c7 into openshift:mainJun 1, 2026
9 checks passed
@logonoff
logonoff deleted the knip branch June 1, 2026 19:47
@logonofflogonoff changed the title CONSOLE-5037: Add knip-based dead code detection in CICONSOLE-5307: Add knip-based dead code detection in CIJun 12, 2026
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approvedIndicates a PR has been approved by an approver from all required OWNERS files.component/coreRelated to console core functionalitycomponent/sharedRelated to console-shareddocs-approvedSignifies that Docs has signed off on this PRjira/valid-referenceIndicates that this PR references a valid Jira ticket of any type.lgtmIndicates that a PR is ready to be merged.px-approvedSignifies that Product Support has signed off on this PRverifiedSignifies that the PR passed pre-merge verification criteria

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

@logonoff@openshift-ci-robot@TheRealJon