Skip to content

Feature: Replay from HistoryStore Cache.#204

Open
bryannolen wants to merge 15 commits intobeelzebub-labs:mainfrom
bryannolen:future
Open

Feature: Replay from HistoryStore Cache.#204
bryannolen wants to merge 15 commits intobeelzebub-labs:mainfrom
bryannolen:future

Conversation

@bryannolen
Copy link
Contributor

@bryannolen bryannolen commented Jul 21, 2025

Extension to HistoryStore, and new (optional) config flag for SSH strategy.

New Service Config flag enableCacheReplay - default false: When enabled, the SSH strategy will prefer to use previous successful responses stored in the HistoryStore instead of asking the LLM for a response. This significantly reduces the number of calls needed to be made to the LLM and reduces costs.

Currently only supported by SSH strategy.

There are also a number of small incremental improvements to the HistoryStore, inproving efficiency and speed.

Code changes have been tested in a local honeypot for the last few weeks.

New Feature Submissions:

  1. [Yes] Does your submission pass tests?
  2. [Yes] Have you lint your code locally before submission?

Changes to Core Features:

  • [Yes] Have you added an explanation of what your changes do and why you'd like us to include them?
  • [Yes] Have you written new tests for your core changes, as applicable?
  • [Yes] Have you successfully run tests with your changes locally?

Summary by CodeRabbit

  • New Features

    • Introduced support for caching and replaying SSH command outputs when enabled in the service configuration.
    • Added a new configuration option to toggle cache replay functionality.
    • Enhanced conversation history tracking by storing input-output message pairs.
  • Bug Fixes

    • Improved handling of conversation history to prevent duplicate entries.
  • Tests

    • Added tests for conversation storage, duplicate handling, session initialization, and conversation querying.

This feature will use a previously observed reply, rather than ask the
LLM for a new response if the input command has already been seen and is
present in the HistoryStore.
Only used by SSH strategy currently, enables replying to requests from
HistoryStore instead of asking the LLM again, significantly saving costs.
@coderabbitai
Copy link

coderabbitai bot commented Jul 21, 2025

Walkthrough

The changes introduce structured conversation tracking to the history store, including new methods for appending and querying conversations. Caching logic is integrated into the SSH protocol handler, enabling replay of cached command outputs when configured. The configuration parser and its tests are updated to support a new EnableCacheReplay flag.

Changes

File(s) Change Summary
historystore/history_store.go Added Conversation struct and Conversations field to HistoryEvent. Introduced AppendConversation and QueryConversations methods. Marked Append as deprecated.
historystore/history_store_test.go Added tests for conversation appending, deduplication, nil session handling, and querying conversations.
parser/configurations_parser.go Added EnableCacheReplay boolean field to BeelzebubServiceConfiguration struct.
parser/configurations_parser_test.go Added assertion to test default value of EnableCacheReplay in configuration parsing.
protocols/strategies/SSH/ssh.go Integrated cache replay logic for SSH commands, using structured conversations and updating event tracing accordingly.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant SSHHandler
    participant HistoryStore
    participant Cache
    participant LLM

    User->>SSHHandler: Send command input
    SSHHandler->>Cache: Check EnableCacheReplay & lookup input
    alt Cache hit
        Cache-->>SSHHandler: Return cached output
        SSHHandler->>HistoryStore: AppendConversation(input, cached output)
        SSHHandler-->>User: Return cached output
    else Cache miss
        SSHHandler->>LLM: Process input (if plugin specified)
        LLM-->>SSHHandler: Return output
        SSHHandler->>HistoryStore: AppendConversation(input, output)
        SSHHandler-->>User: Return output
    end
Loading

Estimated code review effort

3 (30–60 minutes)

Suggested reviewers

  • mariocandela

Poem

In the warren where histories leap,
Now conversations are easy to keep.
SSH commands may replay,
If the cache has its say—
With new fields and tests, the code runs deep!
🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1f9687c and 3191842.

📒 Files selected for processing (1)
  • parser/configurations_parser_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • parser/configurations_parser_test.go
✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • 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 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.

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

♻️ Duplicate comments (1)
protocols/strategies/SSH/ssh.go (1)

155-177: Same code duplication issue as inline commands.

This is the same LLM invocation logic that appears in the inline command handler. The previously suggested helper method would eliminate this duplication.

🧹 Nitpick comments (2)
historystore/history_store.go (1)

57-57: Consider using a more visible deprecation approach.

While the comment deprecation is clear, consider using Go's conventional // Deprecated: format for better tooling support.

-// DEPRECATED: Use AppendConversation() instead.
+// Deprecated: Use AppendConversation() instead.
protocols/strategies/SSH/ssh.go (1)

62-85: Extract LLM invocation logic to reduce code duplication.

The LLM plugin invocation logic is duplicated between inline commands and interactive sessions. Consider extracting this into a helper method.

func (sshStrategy *SSHStrategy) invokeLLMPlugin(servConf parser.BeelzebubServiceConfiguration, histories []plugins.Message, commandInput string) (string, error) {
	llmProvider, err := plugins.FromStringToLLMProvider(servConf.Plugin.LLMProvider)
	if err != nil {
		log.Errorf("error: %s, fallback OpenAI", err.Error())
		llmProvider = plugins.OpenAI
	}
	llmHoneypot := plugins.LLMHoneypot{
		Histories:    histories,
		OpenAIKey:    servConf.Plugin.OpenAISecretKey,
		Protocol:     tracer.SSH,
		Host:         servConf.Plugin.Host,
		Model:        servConf.Plugin.LLMModel,
		Provider:     llmProvider,
		CustomPrompt: servConf.Plugin.Prompt,
	}
	llmHoneypotInstance := plugins.InitLLMHoneypot(llmHoneypot)
	return llmHoneypotInstance.ExecuteModel(commandInput)
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 67caadc and 1c86692.

📒 Files selected for processing (5)
  • historystore/history_store.go (3 hunks)
  • historystore/history_store_test.go (2 hunks)
  • parser/configurations_parser.go (1 hunks)
  • parser/configurations_parser_test.go (1 hunks)
  • protocols/strategies/SSH/ssh.go (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
historystore/history_store_test.go (2)
historystore/history_store.go (4)
  • NewHistoryStore (34-38)
  • Conversation (29-31)
  • HistoryStore (16-19)
  • HistoryEvent (22-26)
plugins/llm-integration.go (2)
  • Message (60-63)
  • Role (65-65)
historystore/history_store.go (1)
plugins/llm-integration.go (1)
  • Message (60-63)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Analyze (go)
🔇 Additional comments (9)
parser/configurations_parser.go (1)

77-77: LGTM! Configuration field properly added.

The EnableCacheReplay field is correctly added with appropriate YAML tagging and follows the existing struct pattern.

historystore/history_store.go (3)

28-31: LGTM! Well-structured conversation type.

The Conversation struct appropriately pairs input and output messages, providing a clean abstraction for conversation tracking.


23-26: LGTM! HistoryEvent extension looks good.

The addition of the Conversations field maintains backward compatibility while adding the new conversation tracking capability.


103-114: LGTM! Query method is well-implemented.

The QueryConversations method properly handles thread safety and follows a clear search pattern. The logic correctly returns a pointer to the found conversation or nil if not found.

protocols/strategies/SSH/ssh.go (4)

45-58: LGTM! Cache checking logic is well-implemented.

The cache replay logic correctly checks for existing conversations before proceeding with command execution. The implementation properly handles the case when no cached answer exists.


113-113: LGTM! Good code organization.

The comment clearly marks the end of the raw command handler block, improving code readability.


145-152: LGTM! Consistent caching logic in interactive sessions.

The cache checking logic for interactive sessions mirrors the inline command logic correctly, maintaining consistency across both execution paths.


186-189: LGTM! Consistent handler name modification.

The handler name modification to append " cached" when using cached responses is consistent with the inline command implementation and provides good traceability.

historystore/history_store_test.go (1)

99-134: LGTM! Comprehensive query testing.

Excellent test coverage for the QueryConversations method, including all edge cases:

  • Found conversation
  • Not found conversation
  • Non-existent key
  • Empty conversations list

The test structure using subtests is clean and well-organized.

@bryannolen
Copy link
Contributor Author

Embarrasing typo fixed in commit 1f9687c 😄

@mariocandela
Copy link
Collaborator

Welcome back mate 🙂 I'll watch it in the next few days

@codecov
Copy link

codecov bot commented Aug 9, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 84.02%. Comparing base (fa38891) to head (8f30d9c).

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #204      +/-   ##
==========================================
+ Coverage   82.94%   84.02%   +1.08%     
==========================================
  Files           7        7              
  Lines         428      457      +29     
==========================================
+ Hits          355      384      +29     
  Misses         63       63              
  Partials       10       10              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@mariocandela
Copy link
Collaborator

mariocandela commented Aug 11, 2025

Great job, @bryannolen , I really like the new codebase.
However, this cache implementation isn’t quite right, you should use the entire chat history as the cache key (you could use something like hash([]plugins.Message) as the cache key 🙂).

Below is a use case that shows the honeypot with rather low interaction(missing test-1 from second ls):

root@ubuntu:~$ ls
Desktop  Documents  Downloads  Music  Pictures  Public  Templates  Videos
root@ubuntu:~$ touch test-1
root@ubuntu:~$ ls
Desktop  Documents  Downloads  Music  Pictures  Public  Templates  Videos

Anyway, while testing your branch, I noticed you’re working on a rate limit feature, fantastic, this could be really useful 🙂

Thanks again for your time and effort.

Cheers

Mario

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