Skip to content

Conversation

@everettbu
Copy link

@everettbu everettbu commented Jul 26, 2025

Test 6

Summary by CodeRabbit

  • New Features

    • Added comprehensive support and testing for dual write mode 3 across file, unified, and etcd storage backends in playlist API integration tests.
    • Implemented the List operation for dual write mode 3.
  • Improvements

    • Enhanced dual write mode 3 with structured logging, timing metrics, and improved error handling for all major operations.
    • Standardized logging for better traceability of storage operations.
  • Tests

    • Introduced an extensive suite of unit tests for dual write mode 3, covering all CRUD operations and various success and failure scenarios.

* Dual writer: mode 3

* Add integration tests for playlits in mode 3

* Remove todo

* Update pkg/apiserver/rest/dualwriter_mode3.go

Co-authored-by: Arati R. <33031346+suntala@users.noreply.github.com>

* Admin: Fixes an issue where user accounts could not be enabled (#88117)

Fix: unable to enable user

* [REVIEW] FInish mode 3 and add tests

* Improve logging

* Update dependencies

* Update pkg/apiserver/rest/dualwriter_mode3_test.go

Co-authored-by: maicon <maiconscosta@gmail.com>

* remove test assertion

* Use mode log when dual writer is initiated

---------

Co-authored-by: Arati R. <33031346+suntala@users.noreply.github.com>
Co-authored-by: gonvee <gonvee@qq.com>
Co-authored-by: maicon <maiconscosta@gmail.com>
@coderabbitai
Copy link

coderabbitai bot commented Jul 26, 2025

Walkthrough

The changes introduce extensive enhancements to the dual writer "Mode3" implementation, including structured logging, timing metrics, and asynchronous legacy operations. Comprehensive unit tests for Mode3 are added, covering all CRUD operations and error scenarios. Integration tests are expanded to include Mode3 across multiple storage backends. Minor test code cleanup is also performed.

Changes

File(s) Change Summary
pkg/apiserver/rest/dualwriter_mode3.go Refactored Mode3 dual writer: added logging, timing metrics, async legacy ops, standardized error handling, implemented List.
pkg/apiserver/rest/dualwriter_mode3_test.go Replaced stub with full unit test suite for Mode3, covering CRUD operations and error cases using mocks.
pkg/tests/apis/playlist/playlist_test.go Added integration test cases for dual write Mode3 with file, unified, and etcd storage backends.
pkg/apiserver/rest/dualwriter_mode1_test.go Simplified test to use shared Prometheus registry instead of instantiating a new one per test.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant DualWriterMode3
    participant Storage
    participant LegacyStorage
    participant Logger
    participant Metrics

    Client->>DualWriterMode3: Create/Get/List/Delete/Update/DeleteCollection
    DualWriterMode3->>Logger: Log method, kind, context
    DualWriterMode3->>Metrics: Start timer for Storage
    DualWriterMode3->>Storage: Perform operation
    Storage-->>DualWriterMode3: Result or error
    DualWriterMode3->>Metrics: Record Storage duration/status
    alt Success or Error
        DualWriterMode3->>LegacyStorage: (async, with timeout) Perform operation
        LegacyStorage-->>DualWriterMode3: Result or error (ignored by client)
        DualWriterMode3->>Metrics: Record Legacy duration/status
    end
    DualWriterMode3-->>Client: Return Storage result/error
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Poem

In burrows deep, where logs now gleam,
Mode3 emerges—metrics stream!
Async calls and tests abound,
With mocks and checks all tightly wound.
Storage sings in harmony,
While rabbits code in jubilee!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch dual-storage-enhanced

🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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.

@everettbu
Copy link
Author

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Jul 27, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

🧹 Nitpick comments (4)
pkg/apiserver/rest/dualwriter_mode3_test.go (2)

119-120: Use the shared Prometheus registry for consistency.

The test creates a new Prometheus registry instead of using the shared p variable that's used in other tests.

-			p := prometheus.NewRegistry()
-			dw := NewDualWriter(Mode3, ls, us, p)
+			dw := NewDualWriter(Mode3, ls, us, p)

17-356: Consider adding verification for asynchronous legacy operations.

The tests verify that the unified storage operations work correctly but don't verify that legacy operations are actually called asynchronously. Since Mode3 runs legacy operations in goroutines with timeouts, consider adding assertions to verify:

  1. Legacy methods are eventually called
  2. The main operation doesn't wait for legacy completion

You could use mock's AssertExpectations with a timeout or channels to verify async behavior.

pkg/apiserver/rest/dualwriter_mode3.go (2)

55-55: Use consistent error variable naming.

The error variable is named errObjectSt in some places, which is inconsistent with the simple err used elsewhere.

-		_, errObjectSt := d.Legacy.Create(ctx, obj, createValidation, options)
-		d.recordLegacyDuration(errObjectSt != nil, mode3Str, options.Kind, method, startLegacy)
+		_, err := d.Legacy.Create(ctx, obj, createValidation, options)
+		d.recordLegacyDuration(err != nil, mode3Str, options.Kind, method, startLegacy)
-		_, _, errObjectSt := d.Legacy.Update(ctx, name, objInfo, createValidation, updateValidation, forceAllowCreate, options)
-		d.recordLegacyDuration(errObjectSt != nil, mode3Str, options.Kind, method, startLegacy)
+		_, _, err := d.Legacy.Update(ctx, name, objInfo, createValidation, updateValidation, forceAllowCreate, options)
+		d.recordLegacyDuration(err != nil, mode3Str, options.Kind, method, startLegacy)

Also applies to: 139-139


51-57: Consider adding error logging for legacy operations.

While storage operations have error logging, the asynchronous legacy operations don't log their errors. This could make debugging issues with legacy storage difficult.

Example for Create method:

 		startLegacy := time.Now()
-		_, errObjectSt := d.Legacy.Create(ctx, obj, createValidation, options)
-		d.recordLegacyDuration(errObjectSt != nil, mode3Str, options.Kind, method, startLegacy)
+		_, err := d.Legacy.Create(ctx, obj, createValidation, options)
+		if err != nil {
+			log.Error(err, "failed to create object in legacy storage")
+		}
+		d.recordLegacyDuration(err != nil, mode3Str, options.Kind, method, startLegacy)

Also applies to: 108-114, 134-141, 161-167

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5e3a5b3 and 67b74e1.

⛔ Files ignored due to path filters (1)
  • go.work.sum is excluded by !**/*.sum
📒 Files selected for processing (4)
  • pkg/apiserver/rest/dualwriter_mode1_test.go (0 hunks)
  • pkg/apiserver/rest/dualwriter_mode3.go (2 hunks)
  • pkg/apiserver/rest/dualwriter_mode3_test.go (1 hunks)
  • pkg/tests/apis/playlist/playlist_test.go (3 hunks)
💤 Files with no reviewable changes (1)
  • pkg/apiserver/rest/dualwriter_mode1_test.go
🔇 Additional comments (1)
pkg/tests/apis/playlist/playlist_test.go (1)

132-145: LGTM! Test coverage for Mode3 is comprehensive.

The integration tests for Mode3 are well-structured and consistent with the existing test patterns for other dual writer modes. They properly cover all three storage backends (file, unified storage, and etcd).

Also applies to: 191-205, 287-312

created, err := d.Storage.Create(ctx, obj, createValidation, options)
if err != nil {
log.Error(err, "unable to create object in storage")
d.recordLegacyDuration(true, mode3Str, options.Kind, method, startStorage)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix incorrect metric recording on storage error.

When storage operations fail, the code incorrectly records legacy duration instead of storage duration.

-		d.recordLegacyDuration(true, mode3Str, options.Kind, method, startStorage)
+		d.recordStorageDuration(true, mode3Str, options.Kind, method, startStorage)

Also applies to: 129-129

🤖 Prompt for AI Agents
In pkg/apiserver/rest/dualwriter_mode3.go at lines 45 and 129, the code
incorrectly calls recordLegacyDuration when a storage operation fails, but it
should call recordStorageDuration instead. Update these lines to call
d.recordStorageDuration with the appropriate parameters to correctly record the
storage duration metric on storage errors.

func (d *DualWriterMode3) Delete(ctx context.Context, name string, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions) (runtime.Object, bool, error) {
var method = "delete"
log := d.Log.WithValues("name", name, "kind", options.Kind, "method", method)
ctx = klog.NewContext(ctx, d.Log)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use the local logger variable consistently.

The Delete method creates a local log variable but then uses d.Log when creating the context.

-	ctx = klog.NewContext(ctx, d.Log)
+	ctx = klog.NewContext(ctx, log)
📝 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
ctx = klog.NewContext(ctx, d.Log)
- ctx = klog.NewContext(ctx, d.Log)
+ ctx = klog.NewContext(ctx, log)
🤖 Prompt for AI Agents
In pkg/apiserver/rest/dualwriter_mode3.go at line 97, the code uses d.Log
instead of the local log variable when creating the new context. Replace d.Log
with the local log variable to ensure consistent use of the local logger
throughout the Delete method.

d.recordStorageDuration(true, mode3Str, options.Kind, method, startStorage)
return res, async, err
}
d.recordStorageDuration(false, mode3Str, name, method, startStorage)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use consistent metric parameters.

The Delete method uses name instead of options.Kind for metric recording, which is inconsistent with other methods.

-	d.recordStorageDuration(false, mode3Str, name, method, startStorage)
+	d.recordStorageDuration(false, mode3Str, options.Kind, method, startStorage)
📝 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
d.recordStorageDuration(false, mode3Str, name, method, startStorage)
d.recordStorageDuration(false, mode3Str, options.Kind, method, startStorage)
🤖 Prompt for AI Agents
In pkg/apiserver/rest/dualwriter_mode3.go at line 106, the Delete method calls
recordStorageDuration with the parameter 'name' for metrics, which is
inconsistent with other methods that use 'options.Kind'. Update the call to use
'options.Kind' instead of 'name' to maintain consistency in metric parameters.

ctx, cancel := context.WithTimeoutCause(ctx, time.Second*10, errors.New("legacy deletecollection timeout"))
defer cancel()
_, err := d.Legacy.DeleteCollection(ctx, deleteValidation, options, listOptions)
d.recordStorageDuration(err != nil, mode3Str, options.Kind, method, startLegacy)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix metric recording for legacy operations.

The DeleteCollection method incorrectly calls recordStorageDuration for legacy operations instead of recordLegacyDuration.

-		d.recordStorageDuration(err != nil, mode3Str, options.Kind, method, startLegacy)
+		d.recordLegacyDuration(err != nil, mode3Str, options.Kind, method, startLegacy)
📝 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
d.recordStorageDuration(err != nil, mode3Str, options.Kind, method, startLegacy)
d.recordLegacyDuration(err != nil, mode3Str, options.Kind, method, startLegacy)
🤖 Prompt for AI Agents
In pkg/apiserver/rest/dualwriter_mode3.go at line 166, the DeleteCollection
method incorrectly calls recordStorageDuration for legacy operations. Replace
the call to recordStorageDuration with recordLegacyDuration, passing the
appropriate parameters to correctly record the duration for legacy operations.

@github-actions
Copy link
Contributor

This pull request has been automatically marked as stale because it has not had activity in the last 30 days. It will be closed in 2 weeks if no further activity occurs. Please feel free to give a status update or ping for review. Thank you for your contributions!

@github-actions github-actions bot added the stale label Aug 27, 2025
@github-actions
Copy link
Contributor

This pull request has been automatically closed because it has not had any further activity in the last 2 weeks. Thank you for your contributions!

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants