Skip to content

Conversation

@sudhakartag1
Copy link

Adds support for analyzing initContainers alongside regular containers for all workload types.

Changes

  • Updated container extraction for all 9 workload types (Deployment, StatefulSet, DaemonSet, Job, CronJob, GroupedJob, Rollout, StrimziPodSet, DeploymentConfig)
  • Added _get_init_containers() helper to handle both init_containers (standard API) and initContainers (CustomObjectsApi)
  • Added 23 unit tests

Testing

  • All 78 tests passing
  • Verified with kind cluster + Prometheus
  • Tested both Deployment (standard API) and Rollout (CustomObjectsApi) paths

Fixes #426

@CLAassistant
Copy link

CLAassistant commented Dec 16, 2025

CLA assistant check
All committers have signed the CLA.

@coderabbitai
Copy link

coderabbitai bot commented Dec 16, 2025

Walkthrough

Adds support for reading Kubernetes pod init containers (both snake_case and camelCase) and includes them alongside regular containers in ClusterLoader extraction, grouping, and listing paths; introduces _get_init_containers(spec) and comprehensive tests covering workloads and edge cases.

Changes

Cohort / File(s) Summary
Core implementation
robusta_krr/core/integrations/kubernetes/__init__.py
Added _get_init_containers(spec: Any) -> list to read init_containers or initContainers. Updated ClusterLoader and related extraction paths to append init containers to regular containers across deployments, statefulsets, daemonsets, jobs, cronjobs, strimzi podsets, rollouts, deploymentconfigs, grouped-job logic, and other container-extraction points. Small whitespace/formatting cleanups and improved continue-token handling in batched listing.
Tests
tests/test_initcontainers.py
New test module exercising init container handling for Deployments, Jobs, CronJobs, StrimziPodSets, Rollouts, DeploymentConfigs, grouped jobs, snake_case vs camelCase precedence, empty/multiple init containers, and custom-object scenarios.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20–30 minutes

  • Inspect _get_init_containers() implementation for correct precedence and empty-case behavior.
  • Review all ClusterLoader extraction methods updated to ensure init containers are consistently concatenated and named.
  • Verify grouping/LightweightJobInfo changes correctly include init containers in template hashing/group keys.
  • Check batched listing/continue-token handling changes, especially 410 token propagation and error paths.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 63.79% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Add initContainer support (#426)' clearly and concisely summarizes the main objective of the changeset.
Description check ✅ Passed The description directly relates to the changeset, detailing the updated container extraction, helper function, and test additions for initContainer support.
Linked Issues check ✅ Passed The PR fully addresses issue #426 by implementing initContainer analysis across all workload types with dual API compatibility and comprehensive testing.
Out of Scope Changes check ✅ Passed All code changes are directly aligned with the objective of adding initContainer support; no unrelated modifications detected.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

❤️ Share

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

Copy link

@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 (2)
tests/test_initcontainers.py (1)

65-65: Update type hints to use explicit Optional or union syntax.

The init_containers parameter should use explicit optional typing per PEP 484.

Apply this diff:

-def create_mock_deployment(name: str, namespace: str, containers: list, init_containers: list = None):
+def create_mock_deployment(name: str, namespace: str, containers: list, init_containers: list | None = None):
-def create_mock_job(name: str, namespace: str, containers: list, init_containers: list = None):
+def create_mock_job(name: str, namespace: str, containers: list, init_containers: list | None = None):
-def create_mock_cronjob(name: str, namespace: str, containers: list, init_containers: list = None):
+def create_mock_cronjob(name: str, namespace: str, containers: list, init_containers: list | None = None):

Also applies to: 80-80, 93-93

robusta_krr/core/integrations/kubernetes/__init__.py (1)

691-691: Minor cleanup opportunity: unused exception variable.

The exception variable e is assigned but never used since exc_info=True already logs the exception details.

Apply this diff:

-        except Exception as e:
+        except Exception:
             logger.error(
                 "Failed to run grouped jobs discovery",
                 exc_info=True,
             )
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c149d0b and be10c48.

📒 Files selected for processing (2)
  • robusta_krr/core/integrations/kubernetes/__init__.py (25 hunks)
  • tests/test_initcontainers.py (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
tests/test_initcontainers.py (4)
robusta_krr/core/integrations/kubernetes/__init__.py (3)
  • ClusterLoader (60-829)
  • namespaces (80-113)
  • _list_namespaced_or_global_objects_batched (301-363)
robusta_krr/core/models/config.py (2)
  • Config (20-211)
  • get_kube_client (183-193)
robusta_krr/utils/object_like_dict.py (1)
  • ObjectLikeDict (1-29)
robusta_krr/core/models/objects.py (1)
  • selector (76-83)
robusta_krr/core/integrations/kubernetes/__init__.py (2)
robusta_krr/utils/object_like_dict.py (1)
  • items (28-29)
robusta_krr/core/models/objects.py (2)
  • selector (76-83)
  • K8sObjectData (38-107)
🪛 Ruff (0.14.8)
tests/test_initcontainers.py

65-65: PEP 484 prohibits implicit Optional

Convert to T | None

(RUF013)


80-80: PEP 484 prohibits implicit Optional

Convert to T | None

(RUF013)


93-93: PEP 484 prohibits implicit Optional

Convert to T | None

(RUF013)


229-229: Unused function argument: args

(ARG001)


229-229: Unused function argument: kwargs

(ARG001)


254-254: Unused function argument: args

(ARG001)


254-254: Unused function argument: kwargs

(ARG001)


282-282: Unused function argument: args

(ARG001)


282-282: Unused function argument: kwargs

(ARG001)

robusta_krr/core/integrations/kubernetes/__init__.py

234-234: Do not call getattr with a constant attribute value. It is not any safer than normal property access.

Replace getattr with attribute access

(B009)


238-238: Do not call getattr with a constant attribute value. It is not any safer than normal property access.

Replace getattr with attribute access

(B009)


348-348: Consider moving this statement to an else block

(TRY300)


607-607: Consider moving this statement to an else block

(TRY300)


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

Remove assignment to unused variable e

(F841)

🔇 Additional comments (14)
tests/test_initcontainers.py (6)

1-14: LGTM!

Clear module documentation and appropriate imports for a comprehensive test suite.


17-52: LGTM!

Well-structured fixtures that properly mock the configuration and ClusterLoader dependencies needed for testing.


126-214: LGTM!

Comprehensive test coverage for Deployment and CronJob init container extraction, including edge cases like None, empty lists, and multiple init containers.


217-296: LGTM!

The async tests correctly verify Job and GroupedJob init container handling. The unused args and kwargs parameters in the mock functions (lines 229, 254, 282) are acceptable patterns for matching function signatures in tests.


299-390: LGTM!

Excellent test coverage for the _get_init_containers helper function, including precedence rules, empty vs None handling, and both naming conventions.


392-487: LGTM!

Thorough validation of CustomObjectsApi workloads with camelCase initContainers support. The tests correctly simulate real-world ObjectLikeDict behavior and verify all three custom resource types (Rollout, StrimziPodSet, DeploymentConfig).

robusta_krr/core/integrations/kubernetes/__init__.py (8)

27-42: LGTM!

Excellent helper function that elegantly handles the dual snake_case/camelCase naming convention discrepancy between the standard Kubernetes Python client and CustomObjectsApi. The precedence logic (snake_case first) is correct, and the docstring clearly explains the rationale.


441-442: LGTM!

Consistent implementation of init container support for Deployment, StatefulSet, and DaemonSet workloads using the standard Python client pattern with proper None handling.

Also applies to: 550-551, 559-560


446-491: LGTM!

Correct implementation of init container support for CustomObjectsApi workloads (Rollout, StrimziPodSet, DeploymentConfig) using the new helper function. The Rollout implementation properly handles both the template path (CustomObjectsApi with camelCase) and the workloadRef path (standard API with snake_case).

Also applies to: 514-516, 540-542


621-622: LGTM!

Correct implementation for CronJob init containers, properly navigating the nested job_template.spec.template.spec structure.


599-602: LGTM!

Correct inline loop implementation for Jobs that processes both regular containers and init containers, with proper None handling.


709-725: LGTM!

Comprehensive GroupedJob implementation that correctly handles init containers by:

  1. Collecting all container names (regular + init) from the template job
  2. Searching both regular and init containers when looking up the template container by name

This ensures init containers are properly represented in grouped job results.


177-190: LGTM!

The GroupedJob pod listing correctly applies the job_grouping_limit, and the selector building logic appropriately uses getattr to handle optional camelCase attributes from CRDs (despite the static analysis warning, this usage is correct for attributes that may not exist on all objects).

Also applies to: 230-239


350-363: LGTM!

Proper error handling for expired continue tokens (HTTP 410), extracting the new token from the error response body and continuing the batched loading.

@sudhakartag1
Copy link
Author

The docstring coverage warning is pre-existing (the main kubernetes/init.py has 27.5% coverage in the existing codebase). Our new code (_get_init_containers helper and all test functions) includes proper docstrings. Happy to add more if needed,

Copy link

@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 (2)
tests/test_initcontainers.py (2)

217-266: LGTM! Job extraction tests validate full integration flow.

The async tests properly mock the batched listing method and verify that both regular and init containers are extracted through the full _list_all_jobs() flow.

Optional: To satisfy the linter warnings about unused parameters in the mock async functions (lines 229 and 254), you could prefix them with underscores:

-        async def mock_batched_method(*args, **kwargs):
+        async def mock_batched_method(*_args, **_kwargs):

This preserves the signature while indicating the parameters are intentionally unused.


268-297: LGTM! GroupedJob extraction tests validate grouping with init containers.

The test correctly validates that init containers are extracted and grouped separately when job grouping is enabled, resulting in distinct GroupedJob objects per container.

Optional: Same linter warning as above—consider prefixing unused parameters with underscores on line 282:

-        async def mock_batched_method(*args, **kwargs):
+        async def mock_batched_method(*_args, **_kwargs):
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between be10c48 and ccb9607.

📒 Files selected for processing (1)
  • tests/test_initcontainers.py (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
tests/test_initcontainers.py (3)
robusta_krr/core/integrations/kubernetes/__init__.py (1)
  • _get_init_containers (27-41)
robusta_krr/core/models/config.py (1)
  • get_kube_client (183-193)
robusta_krr/utils/object_like_dict.py (1)
  • ObjectLikeDict (1-29)
🪛 Ruff (0.14.8)
tests/test_initcontainers.py

229-229: Unused function argument: args

(ARG001)


229-229: Unused function argument: kwargs

(ARG001)


254-254: Unused function argument: args

(ARG001)


254-254: Unused function argument: kwargs

(ARG001)


282-282: Unused function argument: args

(ARG001)


282-282: Unused function argument: kwargs

(ARG001)

🔇 Additional comments (7)
tests/test_initcontainers.py (7)

1-52: LGTM! Well-structured test fixtures.

The imports, module documentation, and fixtures are well-organized. The mock_cluster_loader fixture appropriately mocks all necessary Kubernetes API clients and the executor for async operations.


55-123: LGTM! Excellent helper functions.

The helper functions reduce duplication and make tests readable. The extract container helpers correctly mirror the lambda patterns used in the production code, properly handling None values with the or [] idiom.


126-186: LGTM! Comprehensive Deployment extraction tests.

The tests thoroughly cover Deployment container extraction scenarios: with init containers, without (None), empty list, and multiple init containers. The assertions correctly verify both count and container names.


188-215: LGTM! CronJob extraction tests cover the job_template path.

The tests correctly validate init container extraction through the CronJob-specific job_template path, covering both presence and absence scenarios.


299-338: LGTM! Focused unit tests for extraction lambda patterns.

The tests validate the container extraction logic for different workload types independently, covering both the standard pattern and specialized paths for CronJob and StrimziPodSet.


340-390: LGTM! Excellent tests for the dual-case helper function.

The tests comprehensively validate _get_init_containers behavior across all scenarios. The test on lines 382-389 is particularly valuable—it ensures that an explicit empty list from init_containers (snake_case) is returned without falling back to initContainers (camelCase), which correctly matches the is not None check in the implementation.


392-487: LGTM! Thorough CustomObjectsApi camelCase tests.

The tests validate init container extraction for CustomObjectsApi workloads (Rollout, StrimziPodSet, DeploymentConfig) using ObjectLikeDict to simulate the raw JSON response with camelCase fields. The final test (lines 479-487) provides valuable documentation of ObjectLikeDict behavior—returning None for missing attributes—which explains why the dual-case _get_init_containers helper is necessary.

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.

Support analysis of initContainers

2 participants