Skip to content

Token storage chunking fixes - #22

Closed
evgenyk wants to merge 5 commits into
mainfrom
ev/token_storage_chunking
Closed

Token storage chunking fixes#22
evgenyk wants to merge 5 commits into
mainfrom
ev/token_storage_chunking

Conversation

@evgenyk

@evgenyk evgenyk commented Aug 14, 2025

Copy link
Copy Markdown
Contributor

Explain your changes

Fixed issues with unbound counts for token chinks

@coderabbitai

coderabbitai Bot commented Aug 14, 2025

Copy link
Copy Markdown

Walkthrough

Refactors CLI token storage to support dynamic multi-chunk tokens with a helper for chunk count retrieval, updates GetRawToken to concatenate chunks with a legacy fallback, adjusts SetRawToken for dynamic cleanup on save/delete, removes obsolete parsing, and updates one test’s expected error message.

Changes

Cohort / File(s) Summary of changes
CLI session chunked token storage refactor
frameworks/cli/cliSession.go
Added getChunkCount helper; GetRawToken now reads chunk_count, concatenates chunk_* data, and falls back to legacy single-key parsing; SetRawToken cleans up existing chunks based on count; removed Sscanf parsing and unused errors import; refined chunk slicing and countKey handling.
Test expectation update
frameworks/cli/cliSession_test.go
Updated TestCliSession_GetRawToken_ChunkCountParseError to assert new error string reflecting keyring not found instead of parse error.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant CliSession
  participant Keyring

  Caller->>CliSession: GetRawToken()
  CliSession->>Keyring: Read chunk_count
  alt chunk_count available and parsed
    loop for i in 0..count-1
      CliSession->>Keyring: Read chunk_i
    end
    CliSession->>CliSession: Concatenate chunks
    CliSession->>CliSession: Unmarshal oauth2.Token
    CliSession-->>Caller: Token
  else fallback
    CliSession->>Keyring: Read legacy token key
    CliSession->>CliSession: Unmarshal oauth2.Token
    CliSession-->>Caller: Token or error
  end
Loading
sequenceDiagram
  participant Caller
  participant CliSession
  participant Keyring

  Caller->>CliSession: SetRawToken(token or nil)
  alt token == nil (delete)
    CliSession->>Keyring: Read chunk_count (if exists)
    loop for i in 0..count-1
      CliSession->>Keyring: Delete chunk_i
    end
    CliSession->>Keyring: Delete chunk_count
    CliSession-->>Caller: Done
  else save token
    CliSession->>Keyring: Read chunk_count (if exists)
    loop for i in 0..count-1
      CliSession->>Keyring: Delete chunk_i
    end
    CliSession->>CliSession: Marshal token bytes and chunk
    loop for each new chunk_i
      CliSession->>Keyring: Write chunk_i
    end
    CliSession->>Keyring: Write chunk_count
    CliSession-->>Caller: Done
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Possibly related PRs

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch ev/token_storage_chunking

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
🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (1)
frameworks/cli/cliSession.go (1)

112-124: Fix compile errors in chunk-saving loop (range over int, undefined min).

  • for i := range chunks does not compile because chunks is an int.
  • min is not defined anywhere in this package.

Apply this diff to fix both issues:

-	for i := range chunks {
-		start := i * chunkSize
-		end := min(start+chunkSize, len(t))
+	for i := 0; i < chunks; i++ {
+		start := i * chunkSize
+		end := start + chunkSize
+		if end > len(t) {
+			end = len(t)
+		}
🧹 Nitpick comments (6)
frameworks/cli/cliSession.go (5)

101-110: Avoid shadowing and improve cleanup robustness when removing existing chunks.

Shadowing chunks makes the code harder to read. Also, breaking on the first removal error may leave stale keys behind.

Apply this diff:

-	// Try to get chunk count
-	if chunks, err := c.getChunkCount(countKey); err == nil {
-		// Remove any existing chunks
-		for i := 0; i < chunks; i++ {
+	// Try to get existing chunk count for cleanup
+	if prevChunks, err := c.getChunkCount(countKey); err == nil {
+		// Remove any existing chunks (best-effort)
+		for i := 0; i < prevChunks; i++ {
 			chunkKey := fmt.Sprintf("%s_chunk_%d", key, i)
-			if err := c.keyring.Remove(chunkKey); err != nil {
-				break
-			}
+			_ = c.keyring.Remove(chunkKey) // ignore errors to maximize cleanup
 		}
 	}

81-87: Use best-effort cleanup during deletion instead of breaking on first error.

Breaking on the first error can leave leftover chunks; prefer continuing the loop.

-			if err := c.keyring.Remove(chunkKey); err != nil {
-				break
-			}
+			_ = c.keyring.Remove(chunkKey) // ignore errors to continue best-effort cleanup

22-33: Parsing chunk count works, but consider using strconv and validating > 0.

fmt.Sscanf is fine, but strconv.Atoi(strings.TrimSpace(...)) is simpler and avoids partial matches. Also consider rejecting non-positive counts to prevent empty concatenations.

Example diff (plus imports for strconv/strings):

-	var chunks int
-	if _, err := fmt.Sscanf(string(countItem.Data), "%d", &chunks); err != nil {
-		return 0, fmt.Errorf("failed to parse chunk count: %w", err)
-	}
+	s := strings.TrimSpace(string(countItem.Data))
+	chunks, err := strconv.Atoi(s)
+	if err != nil {
+		return 0, fmt.Errorf("failed to parse chunk count: %w", err)
+	}
+	if chunks <= 0 {
+		return 0, fmt.Errorf("invalid chunk count: %d", chunks)
+	}

Outside this hunk, add imports:

import (
    "encoding/json"
    "fmt"
    "strconv"
    "strings"
    // ...
)

126-126: Redundant re-assignment of countKey.

countKey is already defined earlier; reassigning it to the same computed value adds noise.

-	countKey = fmt.Sprintf("%s_chunk_count", key)

73-136: Optional: also write the legacy single-key token to preserve fallback behavior.

Currently, saving writes only chunked data. If the chunk count key ever becomes unreadable, the fallback will look for the legacy "kinde_token", which could be stale or missing. Consider also setting the legacy key with the full JSON for resilience:

// After saving chunks and chunk count:
_ = c.keyring.Set(keyring.Item{Key: key, Data: t}) // ignore error or handle as needed

Or, if you prefer to avoid duplicating storage, explicitly remove the legacy key during save to prevent stale fallback:

_ = c.keyring.Remove(key)
frameworks/cli/cliSession_test.go (1)

113-113: Relax brittle assertion to avoid coupling to keyring’s exact error string.

Asserting the full propagated message ties the test to keyring’s wording. Prefer asserting the high-level prefix and/or using assert.ErrorIs.

-	assert.Contains(err.Error(), "failed to get token: The specified item could not be found in the keyring")
+	assert.Contains(err.Error(), "failed to get token")
+	assert.ErrorIs(err, keyring.ErrKeyNotFound)
📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these settings in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 6567762 and 40fb4d0.

📒 Files selected for processing (2)
  • frameworks/cli/cliSession.go (4 hunks)
  • frameworks/cli/cliSession_test.go (1 hunks)
🔇 Additional comments (2)
frameworks/cli/cliSession.go (2)

41-53: LGTM: Fallback to legacy token on chunk-count error is sensible.

Gracefully falling back to the legacy single-key token when chunked storage isn't available or count parsing fails is a good compatibility choice and matches the updated test.


127-133: No action needed — repo declares Go >= 1.20 (fmt.Appendf is supported)

Verified that the repository's go directives are >= 1.20 (root go.mod and examples declare go 1.24.4), so fmt.Appendf usage is supported.

  • go.mod files checked: go.mod, examples/cli/go.mod, examples/gin-chat/go.mod — all: go 1.24.4
  • Files using fmt.Appendf:
    • frameworks/cli/cliSession.go (countData := fmt.Appendf(nil, "%d", chunks) at ~line 127)
    • kinde/kinde_test.go (test usage at line 78)

@evgenyk

evgenyk commented Aug 14, 2025

Copy link
Copy Markdown
Contributor Author

closing as some commits ended-up not signed

@evgenyk evgenyk closed this Aug 14, 2025
@evgenyk
evgenyk deleted the ev/token_storage_chunking branch September 6, 2025 04:27
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.

1 participant