shellctl: non-UTF-8 bytes in output.log stall ReadOutputWindow at unchanged offset with truncated=true and drop TailOutputWindow output

Open
#47,039 2 comments 1 reaction 0 assignees View on GitHub

Maintainers usually reply within 1 day

@Max-Reisinger is already working on this.

Since Nov 24, 2026.

  • #47040 by @Max-Reisinger — open
  • #47041 by @jimmyallinai — open

Assessment

Difficulty
3/5
Estimated time
Half a day
Newbie friendliness
25/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
go, python
Domain
backend

Research direction

The bug lives in dify-agent-runtime/internal/server/output.go: advanceToUTF8Boundary, validUTF8PrefixLen and firstCompleteRuneLen decide the offset, and ReadOutputWindow and TailOutputWindow use them. Start by running the repro test described in the issue to see offset stay at 6 on page 2. Done means that paging through prefix\xe9suffix\n reaches Offset == len(content) with Truncated: false, and the tail keeps bytes after an invalid byte. Two open pull requests (#47040, #47041) already target this, so check them first.

Written by the indexing model from the issue text.

Description

Self Checks
  • I have read the Contributing Guide and Language Policy.
  • This is only for bug report, if you would like to ask a question, please head to Discussions.
  • I have searched for existing issues search for existing issues, including closed ones.
  • I confirm that I am using English to submit this report, otherwise it will be closed.
  • 【中文用户 & Non English User】请使用英语提交,否则会被关闭 :)
  • Please do not modify this template :) and fill in all the required fields.
Dify version

1.20.0 (main at 6a4584511090b39254b45eb4eec8e22483e41725), dify-agent-runtime component (verified locally with Go 1.27.1 on darwin/arm64).

Cloud or Self Hosted

Self Hosted (Source)

Steps to reproduce

When a shellctl job's output.log contains an invalid UTF-8 non-continuation byte (0xC0–0xFF, e.g., Latin-1 0xE9 or binary 0xFF—written directly by stdio mode via io.Copy in runStdio), ReadOutputWindow stalls with Output: "", an unchanged Offset, and Truncated: true, while TailOutputWindow drops all output from the first invalid byte onward.

Downstream in dify-agent, run_shellctl_control_command (mode="stdio", no overall loop deadline) spins indefinitely calling wait at the same offset because output is empty and never triggers the byte limit, and execute_complete_with_commands (mode="stdio") tight-loops read_output until the command timeout expires, falsely reporting incomplete_reason="timeout" and losing all subsequent output.

Minimal component-level reproduction against dify-agent-runtime/internal/server/output.go (no Docker/API/tmux required):

  1. Add a temporary test file dify-agent-runtime/internal/server/repro_output_test.go:
package server

import (
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func TestReproNonUTF8StallsReadOutputWindow(t *testing.T) {
	path := filepath.Join(t.TempDir(), "output.log")
	if err := os.WriteFile(path, []byte("prefix\xe9suffix\n"), 0600); err != nil {
		t.Fatal(err)
	}

	w1, err := ReadOutputWindow(path, 0, 16384)
	if err != nil {
		t.Fatal(err)
	}
	w2, err := ReadOutputWindow(path, w1.Offset, 16384)
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("page 1: output=%q offset=%d truncated=%v", w1.Output, w1.Offset, w1.Truncated)
	t.Logf("page 2: output=%q offset=%d truncated=%v", w2.Output, w2.Offset, w2.Truncated)
}

func TestReproNonUTF8DropsTailOutputWindow(t *testing.T) {
	path := filepath.Join(t.TempDir(), "output.log")
	content := append([]byte{0xff}, []byte(strings.Repeat("a", 100)+"\n")...)
	if err := os.WriteFile(path, content, 0600); err != nil {
		t.Fatal(err)
	}

	w, err := TailOutputWindow(path, 1024)
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("tail: output=%q (len=%d) offset=%d truncated=%v", w.Output, len(w.Output), w.Offset, w.Truncated)
}
  1. Run cd dify-agent-runtime && go test -v internal/server/output.go internal/server/errors.go internal/server/repro_output_test.go.
Root Cause & Suggested Direction
  • In output.go, advanceToUTF8Boundary only skips continuation bytes (0x80–0xBF). Both validUTF8PrefixLen (L145-L157) and firstCompleteRuneLen (L160-L167) require utf8.Valid(data[:end]), so any non-continuation invalid UTF-8 byte at data[0] yields startShift=0 and consumed=0, leaving newOffset == offset while truncated = newOffset < size remains true. (validUTF8PrefixLen also scans backward calling utf8.Valid on every decrement, making stalled 16 KiB reads O(N²).)
  • In service.go, WaitJob returns immediately whenever view.Done or window.Truncated, amplifying the stalled window into tight retry loops in callers.
  • Suggested fix: Decode data forward in a single O(N) pass with utf8.DecodeRune—preserving valid multi-byte rune boundaries at budget (so split valid runes across pages remain intact) while replacing genuinely invalid UTF-8 bytes with U+FFFD and advancing the raw file Offset by the exact number of input bytes consumed. Both ReadOutputWindow and TailOutputWindow will then always produce valid UTF-8 and guarantee strict forward offset progress. Existing behavior for valid UTF-8 files is unchanged. Optionally, dify-agent replay loops can also guard against non-advancing offsets when truncated=True.
✔️ Expected Behavior
  • ReadOutputWindow strictly advances Offset whenever offset < size, returning valid UTF-8 (replacing invalid bytes with U+FFFD) and allowing callers to paginate through "suffix\n" to Offset == len(content) with Truncated: false.
  • TailOutputWindow returns the tail window as valid UTF-8 (with invalid bytes replaced by U+FFFD) instead of truncating the tail at the first invalid byte.
❌ Actual Behavior

Observed test output:

=== RUN   TestReproNonUTF8StallsReadOutputWindow
    repro_output_test.go:26: page 1: output="prefix" offset=6 truncated=true
    repro_output_test.go:33: page 2: output="" offset=6 truncated=true
--- PASS: TestReproNonUTF8StallsReadOutputWindow (0.00s)
=== RUN   TestReproNonUTF8DropsTailOutputWindow
    repro_output_test.go:58: tail: output="" (len=0) offset=0 truncated=false
--- PASS: TestReproNonUTF8DropsTailOutputWindow (0.00s)
  • ReadOutputWindow returns output="", offset=6 (unchanged), truncated=true on every subsequent call, making "suffix\n" unreachable and causing pagination loops in dify-agent to spin.
  • TailOutputWindow returns output="", offset=0, dropping all 101 valid bytes following 0xff.
Dominant language
Python
Stars
162k
Forks
25.6k
Avg merge
15h 9m
Merged PRs (30d)
606

Getting set up

Open in Codespaces

Starts the project's dev container in your browser, under your own GitHub account.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from langgenius/dify

All issues in langgenius/dify

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.