haigou-web commented on PR #886:
URL: https://github.com/apache/burr/pull/886#issuecomment-6516418153

   Checked the current head (`2b30eb27`) against `main` and found two things 
the Copilot pass didn't cover. Both are in `examples/coding-agent/tools.py`.
   
   ### 1. `write_file` truncates the file before validating `contents` (High)
   
   `open(full, "w")` truncates the target file before `f.write(contents)` is 
reached. If the model calls the tool with `contents` as a list or dict — easy 
with a small local model — the `TypeError` fires **after** truncation, so the 
file is left empty. And `except (ValueError, OSError)` does not catch 
`TypeError`, so it escapes the tool and kills the run:
   
   ```
   TypeError: write() argument must be str, not list
   ```
   
   Net effect: silent data loss plus a crashed run. `run_bash` will happily 
`cat` the now-empty file on the next turn and the agent has no way to know it 
destroyed its own work.
   
   ```diff
    def write_file(path: str, contents: str) -> dict:
        """Writes text to a file in the workspace, creating or overwriting 
it."""
   +    if not isinstance(contents, str):
   +        return {"error": f"contents must be a string, got 
{type(contents).__name__}"}
        try:
            full = _resolve(path)
            os.makedirs(os.path.dirname(full), exist_ok=True)
   -        with open(full, "w") as f:
   +        with open(full, "w", encoding="utf-8") as f:
                f.write(contents)
            return {"path": path, "bytes_written": len(contents)}
        except (ValueError, OSError) as e:
            return {"error": str(e)}
   ```
   
   ### 2. `run_bash` timeout does not kill the command (Medium)
   
   `subprocess.run(..., shell=True, timeout=30)` kills the **shell**, not the 
process the shell started. With `shell=True` the direct child is `sh -c 
"<command>"`, so on timeout the real command survives:
   
   ```python
   >>> run_bash("sleep 300 & echo started")   # returns "timed out after 30s"
   >>> # the sleep is still alive afterwards
   ```
   
   Worse: after `TimeoutExpired`, `subprocess.run` calls `communicate()` again 
without a timeout, and the orphaned child still holds the stdout/stderr pipes — 
so the call blocks until the child exits and the 30s budget is not actually 
enforced. The existing tests don't catch this because nothing they run outlives 
the timeout.
   
   ```diff
   +import signal
    import subprocess
   
   +BASH_TIMEOUT_SECONDS = 30
   +
   +
    def run_bash(command: str) -> dict:
        """Runs a shell command in the workspace and returns its output."""
   -    try:
   -        proc = subprocess.run(
   -            command,
   -            shell=True,
   -            cwd=os.path.abspath(WORKSPACE),
   -            capture_output=True,
   -            text=True,
   -            timeout=30,
   -        )
   +    proc = subprocess.Popen(
   +        command,
   +        shell=True,
   +        cwd=os.path.abspath(WORKSPACE),
   +        stdout=subprocess.PIPE,
   +        stderr=subprocess.PIPE,
   +        text=True,
   +        start_new_session=(os.name != "nt"),
   +        creationflags=(subprocess.CREATE_NEW_PROCESS_GROUP if os.name == 
"nt" else 0),
   +    )
   +    try:
   +        stdout, stderr = proc.communicate(timeout=BASH_TIMEOUT_SECONDS)
   +    except subprocess.TimeoutExpired:
   +        _kill_tree(proc)
   +        stdout, stderr = proc.communicate()
            return {
   -            "exit_code": proc.returncode,
   -            "stdout": proc.stdout[-4000:],
   -            "stderr": proc.stderr[-4000:],
   +            "error": f"command timed out after {BASH_TIMEOUT_SECONDS}s",
   +            "stdout": (stdout or "")[-4000:],
   +            "stderr": (stderr or "")[-4000:],
            }
   -    except subprocess.TimeoutExpired:
   -        return {"error": "command timed out after 30s"}
   +    return {
   +        "exit_code": proc.returncode,
   +        "stdout": stdout[-4000:],
   +        "stderr": stderr[-4000:],
   +    }
   +
   +
   +def _kill_tree(proc: subprocess.Popen) -> None:
   +    """Kills the process and everything it spawned, then reaps it."""
   +    if proc.poll() is not None:
   +        return
   +    if os.name == "nt":
   +        subprocess.run(
   +            ["taskkill", "/F", "/T", "/PID", str(proc.pid)],
   +            capture_output=True,
   +            check=False,
   +        )
   +    else:
   +        try:
   +            os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
   +        except ProcessLookupError:
   +            pass
   +    try:
   +        proc.wait(timeout=5)
   +    except subprocess.TimeoutExpired:
   +        pass
   ```
   
   Regression tests worth pinning both fixes:
   
   ```python
   def test_write_file_rejects_non_string_without_truncating(tmp_path, 
monkeypatch):
       monkeypatch.setenv("CODING_AGENT_WORKSPACE", str(tmp_path))
       # ... rebuild the tool module here, as the other tests do ...
       write_file("notes.txt", "original")
       assert "error" in write_file("notes.txt", ["not", "a", "string"])
       assert (tmp_path / "notes.txt").read_text() == "original"
   
   
   def test_timeout_kills_child_processes(tmp_path, monkeypatch):
       monkeypatch.setenv("CODING_AGENT_WORKSPACE", str(tmp_path))
       # ...
       marker = tmp_path / "survivor"
       assert "error" in run_bash(f"sh -c 'sleep 60; touch {marker}' &")
       time.sleep(1)
       assert not marker.exists()
   ```
   
   `black --line-length=100` / `isort` / `flake8` stay clean with both patches, 
and the 10 existing tests still pass (the two `symlink`/`pwd` failures on 
Windows are platform limits that don't apply on CI).
   
   Happy to open a follow-up PR against this branch if that's easier than 
applying it here — just say the word.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to