Skip to content

chore: restore reverted test suites, folder structure, logic optimizations, and security patches (v3)#200

Closed
sheepdestroyer wants to merge 11 commits into
masterfrom
chore/restore-reversions-final-v3
Closed

chore: restore reverted test suites, folder structure, logic optimizations, and security patches (v3)#200
sheepdestroyer wants to merge 11 commits into
masterfrom
chore/restore-reversions-final-v3

Conversation

@sheepdestroyer

@sheepdestroyer sheepdestroyer commented Jul 2, 2026

Copy link
Copy Markdown
Owner

This PR comprehensively restores all files, directory organization, logic optimizations, container dependencies, and security patches that were mistakenly deleted or reverted during recent automated merge conflict resolutions on master.

1. Folder Structure & Reorganization Restored

  • Moved 23 test and utility files currently at the root back to their reorganized directories (tests/, scripts/, scripts/verification/, and router/tests/) matching PR Refactor: Reorganize repository structure #181.
  • Removed duplicate test files (e.g. removing router/test_memory_mcp.py and consolidating tests in router/tests/test_memory_mcp.py).

2. Missing Test and Utility Files Recovered

Checked out and restored the following 10 files from past commits in the repository history:

3. Logic Optimizations Re-applied in router/main.py

  • Async Cache: Restored the async annotations caching logic (_read_annotations_async and deepcopy offloading) to prevent blocking the event loop.
  • Token Heuristics: Restored the regex-based _count_tokens_heuristic and updated estimate_prompt_tokens to use it (bringing token estimation accuracy within ±11% of prose, code, and CJK).
  • Valkey URL Connection: Restored URL-based Redis/Valkey client initialization in get_redis to handle client configuration properly.

4. Security & Configuration Patches Restored

  • Category Injection: Restored input sanitization (urllib.parse.quote(category) and unquote) in router/memory_mcp.py to prevent parameter-injection vulnerabilities.
  • Password Placeholders: Restored pod.yaml and start-stack.sh back to secure, placeholder-based credential configurations (avoiding hardcoded default passwords in git).
  • Version Upgrades: Restored LiteLLM v1.90.2 and newer container tags (ClickHouse, Valkey, pgvector, MinIO, and Langfuse).
  • Container Dependencies: Fixed router/Dockerfile to include aiofiles.

5. CI Workflow & Test Collection Fixes

  • Dependency List: Added aiofiles to the pip install action in .github/workflows/test.yml.
  • Path Targets: Updated workflow execution steps to reference corrected tests/ and scripts/ pathways.
  • Import-time Execution: Wrapped tests/test_agy_behavior.py in a __main__ block to prevent immediate execution at import-time during test collection (resolving CI collection crash).

6. Agent Guidelines & Post-Mortem Documentation

  • Added Git Rebase and Conflict Resolution Rules to .agents/AGENTS.md to prevent automated bots from re-introducing folder and logic regressions.
  • Saved the complete post-mortem regression report to .agents/jules_regression_analysis.md.

Verification: All 176 unit and integration tests compile, collect, and pass successfully.

7. Review & Bot Reversion Updates Applied (v2)

  • Fixed missing comma in start-stack.sh python wrapper list rendering.
  • Restored performance-sensitive async _is_quota_exhausted log reader in router/agy_proxy.py and converted tests to async.
  • Restored parallel ThreadPoolExecutor optimization in scripts/benchmark_classifier.py.
  • Fixed test_detect_active_tool.py to import from module level main instead of router.main.
  • Defensively handled potential null statusCheckRollup in scripts/get_pr_status.py and added a regression unit test.
  • Expanded early openssl check in start-stack.sh to prevent command-not-found failures on unset env parameters.
  • Restored Prisma datetime/RobustDatetime serialization patch in litellm/entrypoint.py to fix spend logs serialization failures.
  • Restored complete environment-driven placeholders relocation in pod.yaml and start-stack.sh (for LITELLM_MASTER_KEY, POSTGRES_PASSWORD, OLLAMA_API_KEY, LANGFUSE_PUBLIC_KEY, and LANGFUSE_SECRET_KEY) together with dynamic fallback key generation.
  • Restored offload-aa-scores-sync optimization from PR ⚡ Offload synchronous AA scores loading to thread #98 to offload blocking synchronous disk operations to a background thread pool inside sync_adaptive_router_roster and get_best_free_model.
  • Added a comprehensive branch audit report at .agents/branch_audit_plan.md to track and prevent any future merge conflict regressions.
  • Optimized _is_quota_exhausted in router/agy_proxy.py to use binary mode, seeking to the end, and reading only the last 1KB chunk of cli.log asynchronously, avoiding loading large log files in memory and bypassing the blocking synchronous os.path.exists check.

@sourcery-ai sourcery-ai Bot 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.

Sorry @sheepdestroyer, you have reached your weekly rate limit of 500000 diff characters.

Please try again later or upgrade to continue using Sourcery

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request introduces several optimizations, security enhancements, and robust testing infrastructure. Key changes include restoring the lost asynchronous offloading of AA scores loading, replacing naive character-count token estimation with a regex-based weighted heuristic, transitioning file reads to asynchronous operations using aiofiles, securing configurations by replacing hardcoded credentials with dynamically generated placeholders, and mitigating category injection vulnerabilities in memory_mcp.py by URL-encoding category names. Feedback from the reviewer suggests optimizing the asynchronous log reading in router/agy_proxy.py to read only the last 1KB chunk of the file rather than loading the entire log into memory, which avoids potential performance and memory overhead as the log grows.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread router/agy_proxy.py Outdated
Comment on lines 155 to 160
if os.path.exists(log_path):
with open(log_path, "r") as f:
for line in f.readlines()[-5:]:
async with aiofiles.open(log_path, "r") as f:
lines = await f.readlines()
for line in lines[-5:]:
if "RESOURCE_EXHAUSTED" in line or "code 429" in line:
return True

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.

high

Reading the entire log file into memory with await f.readlines() can cause significant performance and memory overhead if cli.log grows large. Additionally, os.path.exists is a blocking synchronous call that can block the event loop.

Instead, we can open the file in binary mode ("rb"), seek to the end of the file to read only the last 1KB chunk, and decode it. This avoids both the blocking os.path.exists check (by catching FileNotFoundError implicitly) and loading the entire file into memory.

Suggested change
if os.path.exists(log_path):
with open(log_path, "r") as f:
for line in f.readlines()[-5:]:
async with aiofiles.open(log_path, "r") as f:
lines = await f.readlines()
for line in lines[-5:]:
if "RESOURCE_EXHAUSTED" in line or "code 429" in line:
return True
async with aiofiles.open(log_path, "rb") as f:
try:
await f.seek(0, 2)
file_size = await f.tell()
await f.seek(max(0, file_size - 1024))
except OSError:
pass
content_bytes = await f.read()
content = content_bytes.decode("utf-8", errors="ignore")
for line in content.splitlines()[-5:]:
if "RESOURCE_EXHAUSTED" in line or "code 429" in line:
return True

@sheepdestroyer

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

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.

@coderabbitai

coderabbitai Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@sheepdestroyer, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 23 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 8918cc54-7900-4db4-9850-0eb0a716694f

📥 Commits

Reviewing files that changed from the base of the PR and between c304f3d and b0a8605.

⛔ Files ignored due to path filters (1)
  • debug-homepage.png is excluded by !**/*.png
📒 Files selected for processing (51)
  • .agents/AGENTS.md
  • .agents/branch_audit_plan.md
  • .agents/jules_regression_analysis.md
  • .github/workflows/test.yml
  • README.md
  • get_pr_status.py
  • litellm/entrypoint.py
  • pod.yaml
  • router/Dockerfile
  • router/agy_proxy.py
  • router/main.py
  • router/memory_mcp.py
  • router/test_memory_mcp.py
  • router/tests/test_agy_proxy.py
  • router/tests/test_detect_active_tool.py
  • router/tests/test_estimate_prompt_tokens.py
  • router/tests/test_get_gemini_oauth_status.py
  • router/tests/test_get_goose_sessions.py
  • router/tests/test_get_redis.py
  • router/tests/test_load_persisted_stats.py
  • router/tests/test_memory_mcp.py
  • scripts/README.md
  • scripts/benchmark_classifier.py
  • scripts/benchmark_tokens.py
  • scripts/get_pr_status.py
  • scripts/host_agy_daemon.py
  • scripts/sync_gemini_token.py
  • scripts/test_quota_reset.sh
  • scripts/verification/verify_breaker.py
  • scripts/watch_quota.sh
  • start-stack.sh
  • test_memory_mcp.py
  • tests/test_a2_verify.py
  • tests/test_agy_behavior.py
  • tests/test_agy_tiers.py
  • tests/test_antigravity.py
  • tests/test_atomic_write.py
  • tests/test_check_http_endpoint.py
  • tests/test_circuit_breaker.py
  • tests/test_classifier_accuracy.py
  • tests/test_compute_free_model_score.py
  • tests/test_get_pr_status.py
  • tests/test_host_agy_daemon.py
  • tests/test_map_tool_to_category.py
  • tests/test_models_proxy.py
  • tests/test_pie_chart_gradient.py
  • tests/test_read_annotations_async.py
  • tests/test_record_tool_usage.py
  • tests/test_src_badge.py
  • tests/test_stream_latency.py
  • tests/test_sync_gemini_token.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch chore/restore-reversions-final-v3

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.

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