Skip to content

Feat: support local provider for code exec component & remove some outdated models - #14637

Merged
yingfeng merged 5 commits into
infiniflow:mainfrom
Magicbook1108:main
May 7, 2026
Merged

yingfeng merged 5 commits into
infiniflow:mainfrom
Magicbook1108:main

Conversation

@Magicbook1108

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Feat: support local provider for code exec component & remove some outdated models

Type of change

  • New Feature (non-breaking change which adds functionality)

@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label May 7, 2026
@Magicbook1108 Magicbook1108 added the ci Continue Integration label May 7, 2026
@dosubot dosubot Bot added 🌈 python Pull requests that update Python code 💞 feature Feature request, pull request that fullfill a new feature. 🧪 test Pull requests that update test cases. labels May 7, 2026
@coderabbitai

coderabbitai Bot commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR introduces LocalProvider, a new local sandbox execution provider that runs user code as subprocesses with resource constraints, refactors provider configuration loading to support environment overrides, establishes a shared execution result protocol for structured output capture, and updates existing providers to use the protocol. The JSON configuration changes are structural and unrelated to the feature.

Changes

LocalProvider Sandbox with Configuration & Integration

Layer / File(s) Summary
Exception Types
agent/sandbox/providers/base.py
New SandboxProviderConfigError exception signals provider misconfiguration/unusability.
Shared Execution Result Protocol
agent/sandbox/result_protocol.py
New module exports RESULT_MARKER_PREFIX, build_python_wrapper(), build_javascript_wrapper(), and extract_structured_result() to standardize structured-result capture from Python/JavaScript subprocesses.
LocalProvider Implementation
agent/sandbox/providers/local.py
Complete LocalProvider class with instance management, code execution via subprocess, POSIX resource/timeout limits, and artifact collection from an artifacts/ directory with extension/size/count enforcement.
Provider Registration
agent/sandbox/providers/__init__.py
LocalProvider added to module imports and __all__ exports.
Provider Configuration Loading
agent/sandbox/client.py
_load_provider_from_settings() refactored to resolve provider type from SANDBOX_PROVIDER_TYPE env, load merged system+env config, and raise SandboxProviderConfigError for misconfigured local or env-selected providers.
Provider Integration
agent/sandbox/providers/aliyun_codeinterpreter.py, agent/tools/code_exec.py
Aliyun provider delegates wrapper/result extraction to shared protocol functions; CodeExec adds specific error handling for provider config failures and conditional fallback to HTTP sandbox.
Tests & Configuration
test/unit_test/agent/sandbox/test_local_provider.py, docker/.env
Docker env template restructured for provider-based sandbox config with shared and per-provider sections; comprehensive unit tests cover LocalProvider initialization, code execution, artifact collection, and timeout enforcement.
Preserved API
agent/sandbox/client.py
Public functions get_provider_manager(), reload_provider(), execute_code(), health_check(), get_provider_info() unchanged in signature and behavior.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 A local sandbox hops into place,
Wrapped results flow through shared space,
Config helpers sort each provider type,
Artifacts collected, timeouts tight,
Error handling crisp—a fluffy delight! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the two main changes: adding local provider support for code execution and removing outdated models.
Description check ✅ Passed The description includes the required template sections (problem statement and type of change) but lacks detail about implementation context, testing approach, or breaking changes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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.

@Magicbook1108
Magicbook1108 marked this pull request as draft May 7, 2026 09:59
@Magicbook1108
Magicbook1108 marked this pull request as ready for review May 7, 2026 09:59

@coderabbitai coderabbitai 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.

Actionable comments posted: 6

🧹 Nitpick comments (2)
agent/tools/code_exec.py (1)

380-382: ⚡ Quick win

Add a log on explicit provider-config failures

Line 380–382 returns immediately with _ERROR but does not log server-side context, which makes provider misconfiguration incidents harder to diagnose.

Proposed patch
             except SandboxProviderConfigError as provider_error:
+                logging.warning(f"[CodeExec]: Provider configuration error: {provider_error}")
                 self.set_output("_ERROR", str(provider_error))
                 return self.output()
As per coding guidelines `**/*.py`: Add logging for new flows.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@agent/tools/code_exec.py` around lines 380 - 382, The except block catching
SandboxProviderConfigError currently sets self.set_output("_ERROR",
str(provider_error)) and returns self.output() without server-side logging;
update the handler in the method containing this except to also log the failure
(e.g., use logger.error or self.logger.error) including the exception and any
relevant context (provider name/config vars) before returning, while preserving
the existing set_output("_ERROR", ...) and return self.output() behavior so
diagnostics are recorded server-side for SandboxProviderConfigError.
test/unit_test/agent/sandbox/test_local_provider.py (1)

23-23: ⚡ Quick win

Fail fast in test helper when provider initialization fails

Line 23 ignores the boolean return from initialize, which can make downstream test failures less precise.

Proposed patch
-    provider.initialize(config)
+    assert provider.initialize(config), "LocalProvider failed to initialize in test setup"
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/unit_test/agent/sandbox/test_local_provider.py` at line 23, The test
helper currently calls provider.initialize(config) and ignores its boolean
result; update the helper to fail fast by checking the return value of
provider.initialize and raising or asserting when it returns False (e.g., assert
provider.initialize(config), "provider.initialize failed for <provider>") so
tests stop immediately with a clear message; locate the call to
provider.initialize in test_local_provider.py and replace the ignored call with
a return-value check that fails the test on initialization failure.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@agent/sandbox/providers/local.py`:
- Around line 69-86: The new Local sandbox provider lacks lifecycle logging: add
structured start/finish/error logs around initialize, execute, and destroy flows
to aid tracing without logging user code/PII. In the initialize method (and
similarly in execute and destroy), before and after key steps (e.g., entering
initialize, after setting python_bin/node_bin/work_dir/limits, after
self._validate_limits(), after work_dir.mkdir(), and when setting
self._initialized) emit structured logs via the module logger (include function
name like initialize/execute/destroy and non-sensitive config keys), and add
exception handling to log errors with context before re-raising; follow existing
logger conventions used elsewhere in the codebase for message format and log
level.
- Line 117: Replace direct dict indexing of self._instances with a guarded
lookup: before assigning instance_dir = self._instances[instance_id], check if
instance_id in self._instances (or use self._instances.get(instance_id)) and if
missing raise the provider's controlled error (e.g., raise ProviderError /
KeyedLookupError with a clear message) instead of allowing a raw KeyError;
update both places that set instance_dir from self._instances (the occurrences
referencing instance_dir and instance_id) to use this guarded pattern so callers
receive a predictable, descriptive error when an unknown/stale instance_id is
provided.
- Line 120: Compute and validate the effective timeout (exec_timeout) so it
cannot be non-positive before calling process.communicate: when calculating
exec_timeout (currently exec_timeout = min(int(timeout or self.timeout),
self.timeout)) clamp it to a positive value (e.g., exec_timeout = max(1, ...))
or explicitly check if exec_timeout <= 0 and raise a clear provider error (use
the provider's existing error type or a ValueError) with a descriptive message;
perform this validation just before the call to
process.communicate(timeout=exec_timeout) to ensure invalid inputs (like -1)
produce a clear, controlled failure.
- Around line 79-80: The assignment to self.max_artifacts uses a truthy fallback
which treats an explicit 0 as falsy and prevents zero from being configured;
update the logic around self.max_artifacts (and similarly
self.max_artifact_bytes if necessary) to check for None explicitly (e.g., use
config.get("max_artifacts") is not None) before falling back to os.environ or
the default so that 0 is preserved, and ensure subsequent lower-bound checks
against self.max_artifacts still behave correctly.

In `@agent/sandbox/result_protocol.py`:
- Around line 69-73: The code currently decodes and parses RESULT_MARKER_PREFIX
payloads into structured_result without guarding against malformed input; update
the block that handles lines starting with RESULT_MARKER_PREFIX to wrap
base64.b64decode(...) and json.loads(...) in a try/except, catch (ValueError,
binascii.Error, json.JSONDecodeError) (or a broad Exception if those types
aren't available), log the error using the module logger (create logger =
logging.getLogger(__name__) if none exists), skip the malformed marker (leave
structured_result unchanged) and continue processing instead of letting the
exception propagate. Reference the RESULT_MARKER_PREFIX check and the assignment
to payload_b64/payload/structured_result when making the change.

In `@agent/tools/base.py`:
- Line 60: Restore safe logging for tool invocation by truncating and sanitizing
inputs/results before logging: in the invoke function (where logging.info uses
name, arguments) call a sanitize helper (e.g., sanitize_arguments(arguments))
that redacts sensitive keys (patterns like *key, *token, *secret, password) and
then truncate the sanitized string to ~200 characters before logging; do the
same for the response (resp) logging path (the other logging.info at the resp
line) using sanitize_response(resp) then truncate. Ensure helpers are reusable
and clearly referenced in the invoke code so both the arguments and resp log
calls use sanitized+truncated values rather than raw payloads.

---

Nitpick comments:
In `@agent/tools/code_exec.py`:
- Around line 380-382: The except block catching SandboxProviderConfigError
currently sets self.set_output("_ERROR", str(provider_error)) and returns
self.output() without server-side logging; update the handler in the method
containing this except to also log the failure (e.g., use logger.error or
self.logger.error) including the exception and any relevant context (provider
name/config vars) before returning, while preserving the existing
set_output("_ERROR", ...) and return self.output() behavior so diagnostics are
recorded server-side for SandboxProviderConfigError.

In `@test/unit_test/agent/sandbox/test_local_provider.py`:
- Line 23: The test helper currently calls provider.initialize(config) and
ignores its boolean result; update the helper to fail fast by checking the
return value of provider.initialize and raising or asserting when it returns
False (e.g., assert provider.initialize(config), "provider.initialize failed for
<provider>") so tests stop immediately with a clear message; locate the call to
provider.initialize in test_local_provider.py and replace the ignored call with
a return-value check that fails the test on initialization failure.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: fc13af08-4ecd-4bc4-8517-8540d24f6656

📥 Commits

Reviewing files that changed from the base of the PR and between bb10b83 and c882f2d.

📒 Files selected for processing (11)
  • agent/sandbox/client.py
  • agent/sandbox/providers/__init__.py
  • agent/sandbox/providers/aliyun_codeinterpreter.py
  • agent/sandbox/providers/base.py
  • agent/sandbox/providers/local.py
  • agent/sandbox/result_protocol.py
  • agent/tools/base.py
  • agent/tools/code_exec.py
  • conf/llm_factories.json
  • docker/.env
  • test/unit_test/agent/sandbox/test_local_provider.py
💤 Files with no reviewable changes (1)
  • conf/llm_factories.json

Comment on lines +69 to +86
def initialize(self, config: Dict[str, Any]) -> bool:
if not _env_enabled("SANDBOX_LOCAL_ENABLED"):
raise SandboxProviderConfigError("Local code execution is disabled. Set SANDBOX_LOCAL_ENABLED=true to enable it.")

self.python_bin = str(config.get("python_bin") or os.environ.get("SANDBOX_LOCAL_PYTHON_BIN", "python3"))
self.node_bin = str(config.get("node_bin") or os.environ.get("SANDBOX_LOCAL_NODE_BIN", "node"))
self.work_dir = Path(config.get("work_dir") or os.environ.get("SANDBOX_LOCAL_WORK_DIR", "/tmp/ragflow-codeexec")).resolve()
self.timeout = int(config.get("timeout") or os.environ.get("SANDBOX_LOCAL_TIMEOUT", 30))
self.max_memory_mb = int(config.get("max_memory_mb") or os.environ.get("SANDBOX_LOCAL_MAX_MEMORY_MB", 512))
self.max_output_bytes = int(config.get("max_output_bytes") or os.environ.get("SANDBOX_LOCAL_MAX_OUTPUT_BYTES", 1024 * 1024))
self.max_artifacts = int(config.get("max_artifacts") or os.environ.get("SANDBOX_LOCAL_MAX_ARTIFACTS", 20))
self.max_artifact_bytes = int(config.get("max_artifact_bytes") or os.environ.get("SANDBOX_LOCAL_MAX_ARTIFACT_BYTES", 10 * 1024 * 1024))

self._validate_limits()
self.work_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
self._initialized = True
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.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Add lifecycle/execution logs for the new provider flow

New critical flows (initialize, execute, destroy) currently have no logging, which makes operational debugging and incident tracing difficult. Add structured logs at start/end/error boundaries (without logging user code/PII).

As per coding guidelines, **/*.py: "Add logging for new flows".

Also applies to: 105-167, 168-174

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@agent/sandbox/providers/local.py` around lines 69 - 86, The new Local sandbox
provider lacks lifecycle logging: add structured start/finish/error logs around
initialize, execute, and destroy flows to aid tracing without logging user
code/PII. In the initialize method (and similarly in execute and destroy),
before and after key steps (e.g., entering initialize, after setting
python_bin/node_bin/work_dir/limits, after self._validate_limits(), after
work_dir.mkdir(), and when setting self._initialized) emit structured logs via
the module logger (include function name like initialize/execute/destroy and
non-sensitive config keys), and add exception handling to log errors with
context before re-raising; follow existing logger conventions used elsewhere in
the codebase for message format and log level.

Comment thread agent/sandbox/providers/local.py Resolved
raise RuntimeError("Provider not initialized. Call initialize() first.")

normalized_lang = self._normalize_language(language)
instance_dir = self._instances[instance_id]

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Guard unknown instance IDs instead of leaking KeyError

Lines 117 and 172 directly index self._instances[...]. If an invalid/stale instance_id is provided, the API raises raw KeyError instead of a controlled provider error, which hurts reliability and error handling.

Suggested fix
-        instance_dir = self._instances[instance_id]
+        instance_dir = self._instances.get(instance_id)
+        if instance_dir is None:
+            raise RuntimeError(f"Sandbox instance not found: {instance_id}")
...
-        instance_dir = self._instances.pop(instance_id)
+        instance_dir = self._instances.pop(instance_id, None)
+        if instance_dir is None:
+            raise RuntimeError(f"Sandbox instance not found: {instance_id}")

Also applies to: 172-172

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@agent/sandbox/providers/local.py` at line 117, Replace direct dict indexing
of self._instances with a guarded lookup: before assigning instance_dir =
self._instances[instance_id], check if instance_id in self._instances (or use
self._instances.get(instance_id)) and if missing raise the provider's controlled
error (e.g., raise ProviderError / KeyedLookupError with a clear message)
instead of allowing a raw KeyError; update both places that set instance_dir
from self._instances (the occurrences referencing instance_dir and instance_id)
to use this guarded pattern so callers receive a predictable, descriptive error
when an unknown/stale instance_id is provided.

Comment thread agent/sandbox/providers/local.py Resolved
Comment on lines +69 to +73
if line.startswith(RESULT_MARKER_PREFIX):
payload_b64 = line[len(RESULT_MARKER_PREFIX) :].strip()
payload = base64.b64decode(payload_b64, validate=True).decode("utf-8")
structured_result = json.loads(payload)
continue

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Do not hard-fail on malformed result-marker lines

Line 69–73 decodes/parses marker payload without a guard. If user stdout contains an invalid __RAGFLOW_RESULT__: line, execution can fail with an exception instead of returning normal stdout.

Proposed patch
+import logging
 import base64
 import json
 from typing import Any
 
+logger = logging.getLogger(__name__)
+
@@
     for line in str(stdout).splitlines():
         if line.startswith(RESULT_MARKER_PREFIX):
             payload_b64 = line[len(RESULT_MARKER_PREFIX) :].strip()
-            payload = base64.b64decode(payload_b64, validate=True).decode("utf-8")
-            structured_result = json.loads(payload)
+            try:
+                payload = base64.b64decode(payload_b64, validate=True).decode("utf-8")
+                structured_result = json.loads(payload)
+            except Exception as e:
+                logger.warning(f"Invalid structured result marker payload ignored: {e}")
+                cleaned_lines.append(line)
             continue
         cleaned_lines.append(line)
As per coding guidelines `**/*.py`: Add logging for new flows.
📝 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
if line.startswith(RESULT_MARKER_PREFIX):
payload_b64 = line[len(RESULT_MARKER_PREFIX) :].strip()
payload = base64.b64decode(payload_b64, validate=True).decode("utf-8")
structured_result = json.loads(payload)
continue
if line.startswith(RESULT_MARKER_PREFIX):
payload_b64 = line[len(RESULT_MARKER_PREFIX) :].strip()
try:
payload = base64.b64decode(payload_b64, validate=True).decode("utf-8")
structured_result = json.loads(payload)
except Exception as e:
logger.warning(f"Invalid structured result marker payload ignored: {e}")
cleaned_lines.append(line)
continue
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@agent/sandbox/result_protocol.py` around lines 69 - 73, The code currently
decodes and parses RESULT_MARKER_PREFIX payloads into structured_result without
guarding against malformed input; update the block that handles lines starting
with RESULT_MARKER_PREFIX to wrap base64.b64decode(...) and json.loads(...) in a
try/except, catch (ValueError, binascii.Error, json.JSONDecodeError) (or a broad
Exception if those types aren't available), log the error using the module
logger (create logger = logging.getLogger(__name__) if none exists), skip the
malformed marker (leave structured_result unchanged) and continue processing
instead of letting the exception propagate. Reference the RESULT_MARKER_PREFIX
check and the assignment to payload_b64/payload/structured_result when making
the change.

Comment thread agent/tools/base.py Outdated
async def tool_call_async(self, name: str, arguments: dict[str, Any]) -> Any:
assert name in self.tools_map, f"LLM tool {name} does not exist"
logging.info(f"[ToolCall] invoke name={name} arguments={str(arguments)[:200]}")
logging.info(f"[ToolCall] invoke name={name} arguments={str(arguments)}")

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Risk: Unbounded logging may expose sensitive data and cause operational issues.

Removing the 200-character truncation on arguments and resp introduces two concerns:

  1. Privacy/compliance risk: Tool arguments and results may contain sensitive data (API keys, credentials, PII, user inputs). Logging them in full could violate privacy regulations or leak secrets.
  2. Operational risk: Large payloads (e.g., file contents, bulk data) can bloat log files, degrade performance, and make logs difficult to analyze.

Consider re-adding truncation and sanitizing sensitive fields before logging.

🔒 Suggested fix with truncation and sanitization placeholder
-        logging.info(f"[ToolCall] invoke name={name} arguments={str(arguments)}")
+        # Truncate and sanitize arguments before logging
+        safe_args = str(arguments)[:500]  # Adjust limit as needed
+        logging.info(f"[ToolCall] invoke name={name} arguments={safe_args}")
-        logging.info(f"[ToolCall] done name={name} elapsed={elapsed:.2f}s result={str(resp)}")
+        # Truncate result to prevent log bloat
+        safe_result = str(resp)[:500]  # Adjust limit as needed
+        logging.info(f"[ToolCall] done name={name} elapsed={elapsed:.2f}s result={safe_result}")

For production use, also implement sanitization to redact sensitive fields (e.g., keys matching patterns like *key, *token, *secret, password).

Also applies to: 84-84

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@agent/tools/base.py` at line 60, Restore safe logging for tool invocation by
truncating and sanitizing inputs/results before logging: in the invoke function
(where logging.info uses name, arguments) call a sanitize helper (e.g.,
sanitize_arguments(arguments)) that redacts sensitive keys (patterns like *key,
*token, *secret, password) and then truncate the sanitized string to ~200
characters before logging; do the same for the response (resp) logging path (the
other logging.info at the resp line) using sanitize_response(resp) then
truncate. Ensure helpers are reusable and clearly referenced in the invoke code
so both the arguments and resp log calls use sanitized+truncated values rather
than raw payloads.

@codecov

codecov Bot commented May 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (12f80f1) to head (5ec48ce).
⚠️ Report is 12 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14637   +/-   ##
=======================================
  Coverage   94.16%   94.16%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          662      662           
  Misses         25       25           
  Partials       16       16           

☔ 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.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai 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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@agent/sandbox/providers/local.py`:
- Around line 141-147: The except block handling subprocess.TimeoutExpired
currently calls os.killpg(process.pid, signal.SIGKILL) which can raise
ProcessLookupError if the child already exited, preventing process.communicate()
and causing a leaked pipe and wrong exception; update the TimeoutExpired handler
in local.py to wrap the posix os.killpg call in a try/except ProcessLookupError
(ignore or log and continue), ensure process.communicate() is always invoked
(e.g., place it after the kill call or in a finally-like flow inside the except
block), and then raise the intended TimeoutError(f"Execution timed out after
{exec_timeout} seconds"); reference the symbols: process, exec_timeout,
os.killpg, signal.SIGKILL, process.communicate, and TimeoutError.
- Around line 258-287: The symlink check in _collect_artifacts is
TOCTOU-vulnerable; instead of relying on path.is_symlink() +
path.read_bytes()/path.stat(), open the file with O_NOFOLLOW and read via the
resulting fd so the open and read are atomic: use os.open(path, os.O_RDONLY |
os.O_NOFOLLOW), call os.fstat(fd) to get size (and enforce max_artifact_bytes),
read the content from the fd, then close it (handle OSError from os.open and
convert to the same RuntimeError messages used now). You may keep the initial
path.is_symlink() fast-path but make the O_NOFOLLOW open the authoritative
guard; preserve use of path.relative_to(artifacts_dir).as_posix() and
mimetypes.guess_type(path.name) when building the artifact dict.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 682705d0-eeb9-4cbf-bf0b-e08f734f625f

📥 Commits

Reviewing files that changed from the base of the PR and between c882f2d and 5ec48ce.

📒 Files selected for processing (2)
  • agent/sandbox/providers/local.py
  • agent/sandbox/result_protocol.py
✅ Files skipped from review due to trivial changes (1)
  • agent/sandbox/result_protocol.py

Comment on lines +141 to +147
except subprocess.TimeoutExpired:
if os.name == "posix":
os.killpg(process.pid, signal.SIGKILL)
else:
process.kill()
process.communicate()
raise TimeoutError(f"Execution timed out after {exec_timeout} seconds")

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

os.killpg can raise ProcessLookupError, swallowing TimeoutError and leaking the pipe

If the child process exits naturally between TimeoutExpired being raised and os.killpg executing, the process group is already gone and os.killpg raises ProcessLookupError. At that point process.communicate() is never called (pipe stays open → potential zombie), and raise TimeoutError(...) is never reached — the caller receives ProcessLookupError instead.

🐛 Proposed fix
         except subprocess.TimeoutExpired:
             if os.name == "posix":
-                os.killpg(process.pid, signal.SIGKILL)
+                try:
+                    os.killpg(process.pid, signal.SIGKILL)
+                except ProcessLookupError:
+                    pass  # process group already gone; still need to drain pipes
             else:
                 process.kill()
             process.communicate()
             raise TimeoutError(f"Execution timed out after {exec_timeout} seconds")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@agent/sandbox/providers/local.py` around lines 141 - 147, The except block
handling subprocess.TimeoutExpired currently calls os.killpg(process.pid,
signal.SIGKILL) which can raise ProcessLookupError if the child already exited,
preventing process.communicate() and causing a leaked pipe and wrong exception;
update the TimeoutExpired handler in local.py to wrap the posix os.killpg call
in a try/except ProcessLookupError (ignore or log and continue), ensure
process.communicate() is always invoked (e.g., place it after the kill call or
in a finally-like flow inside the except block), and then raise the intended
TimeoutError(f"Execution timed out after {exec_timeout} seconds"); reference the
symbols: process, exec_timeout, os.killpg, signal.SIGKILL, process.communicate,
and TimeoutError.

Comment on lines +258 to +287
def _collect_artifacts(self, artifacts_dir: Path) -> list[dict[str, Any]]:
artifacts: list[dict[str, Any]] = []
for path in sorted(artifacts_dir.rglob("*")):
if path.is_symlink():
raise RuntimeError(f"Artifact symlinks are not allowed: {path.name}")
if path.is_dir():
continue
if not path.is_file():
raise RuntimeError(f"Unsupported artifact entry: {path.name}")

if len(artifacts) >= self.max_artifacts:
raise RuntimeError(f"Local execution produced more than {self.max_artifacts} artifacts.")

size = path.stat().st_size
if size > self.max_artifact_bytes:
raise RuntimeError(f"Artifact exceeds {self.max_artifact_bytes} bytes: {path.name}")

ext = path.suffix.lower()
if ext not in ALLOWED_ARTIFACT_EXTENSIONS:
raise RuntimeError(f"Unsupported artifact type: {path.name}")

artifacts.append(
{
"name": path.relative_to(artifacts_dir).as_posix(),
"content_b64": base64.b64encode(path.read_bytes()).decode("ascii"),
"mime_type": mimetypes.guess_type(path.name)[0] or "application/octet-stream",
"size": size,
}
)
return artifacts

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

TOCTOU: symlink check in _collect_artifacts can be raced to read arbitrary host files

path.is_symlink() (Line 261) is a stat-then-use pattern. A child process can atomically replace (rename) a regular file with a symlink between is_symlink() returning False and the subsequent path.stat() / path.read_bytes() calls, which both follow symlinks. This bypasses the guard and allows the child to exfiltrate arbitrary host-fs content (e.g., /etc/passwd, private keys) through the artifact channel.

The fix is to open each file with O_NOFOLLOW so the guard and the read are atomic:

🔒 Proposed fix
-            size = path.stat().st_size
-            if size > self.max_artifact_bytes:
-                raise RuntimeError(f"Artifact exceeds {self.max_artifact_bytes} bytes: {path.name}")
-
             ext = path.suffix.lower()
             if ext not in ALLOWED_ARTIFACT_EXTENSIONS:
                 raise RuntimeError(f"Unsupported artifact type: {path.name}")

+            try:
+                fd = os.open(str(path), os.O_RDONLY | os.O_NOFOLLOW)
+            except OSError:
+                raise RuntimeError(f"Artifact symlinks are not allowed: {path.name}")
+            try:
+                raw = os.read(fd, self.max_artifact_bytes + 1)
+            finally:
+                os.close(fd)
+            size = len(raw)
+            if size > self.max_artifact_bytes:
+                raise RuntimeError(f"Artifact exceeds {self.max_artifact_bytes} bytes: {path.name}")
+
             artifacts.append(
                 {
                     "name": path.relative_to(artifacts_dir).as_posix(),
-                    "content_b64": base64.b64encode(path.read_bytes()).decode("ascii"),
+                    "content_b64": base64.b64encode(raw).decode("ascii"),
                     "mime_type": mimetypes.guess_type(path.name)[0] or "application/octet-stream",
                     "size": size,
                 }
             )

The os.O_NOFOLLOW flag causes os.open to fail with OSError if path is a symlink at open time, making the check and the read atomic from the kernel's perspective. The early is_symlink() guard on Line 261 can be retained as a fast-path for clearly named symlinks, but the O_NOFOLLOW open is the authoritative safety net.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@agent/sandbox/providers/local.py` around lines 258 - 287, The symlink check
in _collect_artifacts is TOCTOU-vulnerable; instead of relying on
path.is_symlink() + path.read_bytes()/path.stat(), open the file with O_NOFOLLOW
and read via the resulting fd so the open and read are atomic: use os.open(path,
os.O_RDONLY | os.O_NOFOLLOW), call os.fstat(fd) to get size (and enforce
max_artifact_bytes), read the content from the fd, then close it (handle OSError
from os.open and convert to the same RuntimeError messages used now). You may
keep the initial path.is_symlink() fast-path but make the O_NOFOLLOW open the
authoritative guard; preserve use of path.relative_to(artifacts_dir).as_posix()
and mimetypes.guess_type(path.name) when building the artifact dict.

@yingfeng
yingfeng merged commit c29335c into infiniflow:main May 7, 2026
1 check passed
pekar9781 pushed a commit to pekar9781/ragflow that referenced this pull request May 8, 2026
…tdated models (infiniflow#14637)

### What problem does this PR solve?

Feat: support local provider for code exec component & remove some
outdated models

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
@coderabbitai coderabbitai Bot mentioned this pull request Jun 7, 2026
1 task done
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
…tdated models (infiniflow#14637)

### What problem does this PR solve?

Feat: support local provider for code exec component & remove some
outdated models

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. 🌈 python Pull requests that update Python code size:XL This PR changes 500-999 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants