Skip to content

fix(fd,read): #806 live-console read faces — batch readiness peek, one-char deadline reads, ICRNL - #816

Merged
caomengxuan666 merged 3 commits into
masterfrom
fix/806-read-conpty
Oct 18, 2026
Merged

caomengxuan666 merged 3 commits into
masterfrom
fix/806-read-conpty

Conversation

@caomengxuan666

Copy link
Copy Markdown
Member

Closes #806.

Two-layer bisection first (the ticket's boundary note)

The ticket's two symptoms were bisected execution-level on a live ConPTY (pywinpty, keystroke-driven, marker-payload assertions) against three players: the engine standalone, the niubash product (installed host + engine), and GNU bash 5.3.0 under a WSL pty as oracle. Result:

  • The engine's no-\-t faces are GNU-conformant at 74e60b0. read -n1 with the key queued ahead (same write burst), with the key arriving while the read is blocked, with a key typed during a prior command's cooked window, and plain read a consuming a queued line with ONE Enter — all already match GNU (probes target/probe806b.py legs A/B/C/D/F/G: 12/12 PASS pre-fix, both ConPTY and winpty-agent backends, debug and release). No change was needed or made there.
  • The product-only faces (burst key never reaching read -n1; a queued line losing its first byte, `[ello]` for `hello`) reproduce on the installed niubash host and are HOST-side: the paste-signature lookahead (PasteChunkEditMode::cr_paste_partner) consumes the typeahead key from the kernel console queue at the submit Enter and parks it in the in-process pushback until the NEXT prompt — while the accepted command owns the terminal and its read reads the kernel queue. Proof: with read -n1 blocked after such a submit, a FRESH key completes the read (K=[z]) while the held key never does; a host-side patch that reinjects the probe's reads into the console queue at the submit boundary (drain-then-prepend, order-preserving) turns all product legs green while keeping the editor typeahead face (the key still lands in the next prompt's buffer when no command reads it). The proposal patch is archived at target/niu-host-reinject-806-proposal.patch on the branch host — niubash-side follow-up, out of this repo's scope, no engine change can recover keys a host thread consumed.

What this PR DOES fix in the engine are the three console-read defects the same bisection surfaced in the `-t`/deadline family (ticket hypothesis "-n 计数与行缓冲的交互 / read 消费路径"):

1. wait_readable starved on the head record (read.def:659 check_read_timeout family)

src/fd/windows_impl.rs peeked ONE record and required a key-down at the queue HEAD. The Enter that submitted the editing line leaves its key-RELEASE record queued; with it at the head, a consumable key-down right behind it never made the wait Ready — IFS= read -rn1 -t 2 k + key at t+0.15s burned the whole deadline and returned 142 with `k` empty, while GNU select fired on the same input in 0.20s (WSL 5.3.0, leg T1). Now the readiness peek looks at a batch of 16 and reports Ready when ANY record is one the following ReadFile would deliver (key-down with a character). Peek never consumes, so order is untouched; the niubash#280 protection (empty queue never reports Ready) is preserved (T4: deadline still fires at 1s).

2. Deadline line reads were split by conhost's cooked-ahead (ticket symptom 2's engine face)

The cooked line discipline and the raw input queue are two different buffers: the first cooked ReadFile(1) pulled the WHOLE typed line into conhost's pending read state (returning only its first byte), the raw-queue gate then saw an empty queue and timed out — read -t 3 a + typed `hello\r` returned 142 with `a=h`, and the orphaned `ello\r` leaked into the NEXT reader (verified: the following read b got `ello`). A console read with an armed deadline now takes the one-char path (read.def:570-590 ttfd_onechar; read.def:659 gates per byte; GNU never buffers ahead on a tty — read.def:736 reads -n/-d ttys byte-wise through zread). Every keystroke stays a raw record the gate can see, so the deadline cuts where GNU's select() would and the line stays atomic (legs T1b/T1c).

3. One-char reads lacked ICRNL (shtty.c:115)

tt_setonechar forces `c_iflag |= ICRNL\r ("make sure we get CR->NL on input"). ConPTY delivers VK_RETURN as a CR record in every console mode; without the translation a deadline line read hung past the typed Enter waiting for an LF that never comes, and `read -n1` + Enter stored the CR as data. One-char reads now translate CR→NL before the delimiter check; pipe/file reads keep raw CRs, exactly like GNU's non-tty path.

GNU oracle (WSL GNU bash 5.3.0 under a pty, 2026-10-13)

face GNU 5.3.0 rubash @74e60b01 rubash this PR
read -n1, key queued ahead (burst) K=[q] rc0 K=[q] rc0 K=[q] rc0
read -t 2 -n1, key in window (release at head) K=[q] rc0 in 0.20s RC=142 K=[] after 2s K=[q] rc0
read -t 3 a, line+Enter in window A=[hello] rc0 RC=142 A=[h] + orphan ello A=[hello] rc0, next read unaffected
read -t 2 a, partial line, no Enter RC=142 A=[] (line discipline holds the bytes) RC=142 A=[h] RC=142 A=[hello] (read.def:553 assigns the partial; the engine preserves what the user typed — GNU's empty record is a line-discipline artifact, the bytes are lost there too)
read -n1 + Enter (onechar ICRNL) delimiter break, 0 chars 0 chars (via Windows trailing-CR trim) 0 chars (delimiter break — shtty.c:115 parity)
plain read, queued line, one Enter consumed consumed consumed

Regressions

  • New tests/interactive (pywinpty ConPTY driver, marker assertions assembled from shell variables so the echoed command can never satisfy a check; skips cleanly where no console host exists): 10 legs across 6 tests. Negative control: at 74e60b0 the legs t-key-in-window / t-line-complete / line-atomic / t-partial-assign FAIL exactly as the ticket describes; all PASS here.
  • cargo test --lib: 690 passed. Read-family files green: issue275/276/277/279/280/282_stty_console/700/701/714, fd0_consumption_cursor_transport_units. cargo fmt --all --check clean.
  • Full-suite name-level diff, paired runs at 8ab35e8 vs this branch (--no-fail-fast, serial): base 14 failures, branch 13 — the sets are the known environment/timing band (cwd-shape, examples, sigpipe/snapshot timing); the one moving name (issue345_shell_writer_sigpipe) passes standalone on BOTH trees. No new failures; the existing read regressions (read builtin: empty from /dev/fd/N, and rc=0 at EOF under compound/fd redirection (while read off-by-one) #701 EOF rc face, [linux] read.tests: 'read -t 1' prints 'timeout 1: ok' where GNU prints the bare status line #238 -t face) stay green.
  • Existing ConPTY probes: scripts/smoke-read-tty-pty.py 7 PASS + 2 SKIP (unchanged), probe806b 12/12 legs PASS post-fix.

Boundary note for the niubash follow-up

While a foreground command owns the terminal, unread typeahead must live in the kernel console queue (GNU tty semantics — the host's own typeahead_guard.rs states this contract). The paste-signature lookahead violates it at the submit boundary by parking probe reads in process memory. Proposed host patch (verified against this engine: product legs A/C/G all green, editor typeahead face preserved): reinject at the typed-submit decision with drain-then-prepend ordering.

…e-char deadline reads, ICRNL

Three console-read defects bisected from the #806 ticket faces (GNU oracle:
WSL GNU bash 5.3.0 under a pty, 2026-10-13):

1. wait_readable (src/fd/windows_impl.rs) peeked ONE record and required a
   key-down at the queue HEAD. The Enter that submitted the editing line
   leaves its key-RELEASE record queued; with it at the head a consumable
   key-down right behind it never made the wait Ready, so `read -t 2 -n1`
   burned the whole deadline and returned 142 with the variable empty
   although GNU select fired on the same input in 0.2s. Peek a batch and
   report Ready when ANY record would feed a ReadFile (key-down with a
   character); peek never consumes, so order is untouched.

2. A deadline on a CONSOLE read now takes the one-char path
   (read.def:570-590 ttfd_onechar, shtty.c:103 tt_setonechar). The cooked
   line discipline and the raw input queue are two different buffers: the
   first cooked ReadFile(1) pulled the WHOLE typed line into conhost's
   pending read state (returning only its first byte), the raw-queue gate
   then saw an empty queue and timed out — `read -t 3 a` + typed
   `hello\r` returned 142 with a=`h` and the orphaned `ello\r`
   leaked into the NEXT reader. One-char mode keeps every keystroke a raw
   record the gate can see, so the deadline cuts where GNU's select() does
   and the line stays atomic. GNU never buffers ahead here either:
   read.def:736 reads a -n/-d tty byte-wise through zread and gates per
   byte (read.def:659 check_read_timeout at the top of every iteration).

3. One-char reads translate CR->NL (shtty.c:115 tt_setonechar forces
   ICRNL: "make sure we get CR->NL on input"). ConPTY delivers VK_RETURN
   as a CR record in every mode; without the translation a deadline line
   read hung past the typed Enter waiting for an LF that never comes.
   Pipe/file reads keep raw CRs, exactly like GNU's non-tty path.

Regressions: tests/interactive — a live-ConPTY suite (pywinpty driver,
marker-payload assertions, skips where no console host exists). Pre-fix
negative control on this suite: t-key-in-window / t-line-complete /
line-atomic / t-partial-assign all FAIL at 74e60b0; all PASS here.
cargo test --lib 690 green; read-family files (issue275/276/277/279/280/
282_stty_console/700/701/714, fd0_consumption) green.

@caomengxuan666 caomengxuan666 left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

独立代码评审(cr-816 worktree,基线 8ab35e8)

结论:APPROVE-WITH-NITS(不合并;nits 见下,均可跟进小改或随票备注)

逐项验证(全部实测)

  1. 批量 readiness 探测(src/fd/windows_impl.rs:827-846):PeekConsoleInputW 按文档不消费队列,read > 0 守卫保留,空队列 → consumable=false → 走 deadline → Timeout(niubash#280 语义端到端由 t-no-input 腿证明)。分类:key-RELEASE(key_down==0)不可消费 ✓(cooked ReadFile 不投递 release);MOUSE_EVENT 不可消费 ✓(ReadFile 路径永不出鼠标);unicode_char==0 的裸修饰键 key-down 不可消费 ✓(ReadFile 出不了字节,且比旧头 peek 更严)。深度 16 = 按键 down/up 对 + 窗口/焦点噪声的充分余量,peek 非消费故深队列只多一次 re-peek(2ms 轮询),合理。
  2. one-char deadline 读 + ICRNL:对照 vendored(bash.git @b4608166):read.def:553 retval=128+SIGALRM ✓;nchars>0||delim!='\n' + input_is_tty → ttfd_onechar(:570-601,调用点 :596)✓;check_read_timeout 预循环 :660 + 每迭代 :726(PR 注释引 :659 差一行,实质无误)✓;read.def:736 zread(fd,&c,1) 字节级 ✓;shtty.c tt_setonechar c_iflag |= ICRNL ✓。ICRNL 翻译门 onechar.is_some() 实为控制台门(enter_console_onechar_mode 对非控制台返回 None,windows_impl.rs:714/unix.rs:126)——管道/文件/管道+deadline 实测不翻译。
  3. 多行连续 read 独立验证(自写 ConPTY burst 探针 + WSL GNU 5.3.0 真 tty oracle,script -qec):
    • burst aaa\rbbb\r → read -t 3 a; read b ⇒ a=aaa b=bbb(修复);read -t 3 a; read -t 3 b 双 deadline 同过;midline CR 按 ICRNL 截行 ✓。
    • oracle:read -t 1 a+hello(无 Enter) ⇒ GNU RC=142 A=[](行纪律扣住字节),rubash RC=142 A=[hello]——有意的平台化分歧,驱动注释已声明;但 下一读者后果未文档化:GNU 在 Enter 后由下一个 read 续到 B=[hello],rubash 下一读者只见新输入(见 NIT-1)。
    • read -n1 只取 h、余 ello\r 留队 = GNU -n 语义本身(oracle K=[h] 同形),旧"a="h" 孤立 ello"症状在 deadline 行读上确已修好(非换形态)。
  4. 阴性对照(74e60b01 修复前二进制实测):t-key-in-window(142 K=[]) / t-line-complete(142 A=[]) / line-atomic / t-partial-assign(142 A=[]) 四腿全红,其余六腿双 binary 全绿——与 CHANGELOG 所列完全一致;修复后 6 测试 10 腿全绿(空载机器;并行重载下 conpty_deadline_contract_faces 曾一次时序抖动,单跑复绿——CI 2 核 runner 建议留意,见 NIT-3)。
  5. 回归:read 家族 #275(5)/#276(3)/#277(7)/#279(4)/#280(4)/#282-stty(4)/#700(5)/#701(6)/#714(8) 全绿;--lib 690/690 全绿(与 CHANGELOG 一致);cargo fmt --check 干净;diff 仅 7 个文件无夹带。
  6. 性能:12/25/28(pipe-read/yes|head-read/EOF-read 风暴)PR vs 74e60b0 best-of-3:1308/1346ms、1594/1765ms、60/57ms——噪声级,无回退;diff 结构上未触管道/文件热路径(改动均在 console 门后)。

Nits / findings

  • NIT-1(tests/interactive/support/conpty_read_probe.py:194-196 + CHANGELOG #806 条目):部分超时分歧只写了"记录内容"一半;GNU 里被扣住的部分行会在 Enter 后交给下一个读者(oracle B=[hello] 实证),rubash 则消费进 a、下一读者只见新输入。建议 CHANGELOG/注释补一句下一读者后果,避免后来者按"read.def:553 等价"理解。
  • NIT-2(src/executor/read_helpers.rs:499-500、read_io.rs 同形注释):"Pipe/file reads keep raw CRs" 只对翻译门为真;Windows 端到端记录尾部 CR 仍被 trim_read_input_literal 的 wave-2 弹出剥掉(实测 CRLF 管道 ${#x} 5 vs GNU 6,74e60b01 同 5——预先存在、有注释、非本 PR 引入)。建议注释指向 trim 层,防止误读为 CRLF 管道已 GNU 对齐。
  • NIT-3(时序抖动):conpty_deadline_contract_faces 在并行重载下出现过一次 FAIL(单跑复绿);腿内 0.3-0.5s 键入间隔对 2 核 CI 偏紧,7d739c04 已加宽过一轮,可再留意 CI 稳定性。
  • 观察(非阻塞):repeat_count>1 的 key-down 记录被 ReadFile(1) 消费首字节后,余量存于 conhost read-ahead 而非队列,紧随的 deadline 门可能提前超时——预先存在的暴露(旧头 peek 同样有),本 PR 未触碰。

边界确认

PasteChunkEditMode/pushback 在 niubash 宿主(本仓 grep 无此符号),引擎不可见宿主进程内存里的 pushback,drain-then-prepend 只能在宿主提交点做——本 PR 的 peek 保持非消费、deadline 契约(142)在"宿主已吃走"场景仍成立,未新增不可恢复性;宿主补丁(提交时写回控制台队列)与本修复可组合(重注入记录对批量 peek 可见)。边界画得对,随票提案进后续票正确。

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.

read on ConPTY active console: read -n1 hangs; plain read needs a second Enter to consume already-queued input

1 participant