Skip to content

fix(term): reject DECSTBM when the top margin is not above the bottom (bitty#3261) - #3264

Merged
Xuepoo merged 1 commit into
mainfrom
ctx-1908/fix-decstbm
Nov 19, 2026
Merged

Xuepoo merged 1 commit into
mainfrom
ctx-1908/fix-decstbm

Conversation

@Xuepoo

@Xuepoo Xuepoo commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Priority: P2 | Area: term | Labels: fix,P2,area:term | Milestone: v0.1.0 | RFC: none | Task: CTX-1908

Closes #3261

Problem

set_scroll_region accepted DECSTBM with top == bottom, i.e. a one-row region. xterm and ghostty reject that pair: the margins are only applied when the top margin sits strictly above the bottom one, and the whole sequence is ignored otherwise. Bitty honoured it, producing a scroll region no reference terminal would ever enter — the shape that turns a leaked margin into a pane reduced to a single scrolling row instead of merely a misplaced one.

Found while fixing #3259 (per-screen scroll margins, divergence D-1), whose reproductions originally used CSI 1;1r; that fix moved them to a five-row region and left this compatibility change to be reviewed on its own.

Fix

crates/bitty-term-state/src/state.rs, set_scroll_region: the validity check goes from t > b to t >= b.

A rejected pair is still ignored wholesale — no margin write, no cursor home — the same path the inverted pair already took. self.home_cursor() stays inside the accepted branch.

Reference behaviour

  • xterm (charproc.c, CASE_DECSTBM): applies the pair only when top < bottom; otherwise the sequence has no effect, cursor included.
  • ghostty (set_scroll_region): same rule, bottom > top required.

No deliberate deviation: bitty now matches both exactly.

One consequence worth naming in review: on a transient 1-row viewport (a divider drag can solve a pane to a single row) CSI r is now ignored as well, because 0 >= 0 there. That is xterm's behaviour too, and a 1-row grid's region can only ever be 0..0, so no observable state differs — tests/resize_reflow_2529.rs::transient_one_row_height_never_squashes_output still passes untouched.

Shapes covered

shape sequence (24-row grid) result
top == bottom, one row CSI 5;5r rejected: margins untouched, cursor not homed
top > bottom, inverted CSI 15;6r rejected: margins untouched, cursor not homed
top + 1 == bottom, accepted boundary CSI 6;7r rows 5..=6, two rows, cursor homed
default pair CSI r full-screen region restored

Tests

crates/bitty-term-state/src/state/tests.rs:

  • decstbm_rejects_a_one_row_region — sets a live 4..9 region, parks the cursor at row 6 col 2 inside it, feeds CSI 6;6r, asserts the margins are still 4..9 and the cursor did not move (proving wholesale ignore, not a silent re-home).
  • decstbm_rejects_an_inverted_region — the top > bottom shape over a live 3..19 region, same assertions, so the older branch keeps its coverage through the parser.
  • decstbm_accepts_a_two_row_region — the accepted boundary: rows 5..6 scroll as a unit while rows 4 and 7 stay put, the cursor homes to (0, 0), and CSI r then restores the full screen.

The one-row regression is load-bearing: run against the pre-fix t > b check it fails with left: (5, 5) vs right: (4, 9).

Fixture audit

Nothing in the tree depended on a one-row region, so no test or fixture was changed to make this pass:

  • grep -rn '1;1r' across the whole worktree: no hits.
  • Every other DECSTBM site is a multi-row region: \x1b[5;12r in crates/bitty-render/tests/paint_diff.rs, \x1b[1;10r / \x1b[1;5r in state/tests.rs, \x1b[2;10r in crates/bitty-vt/tests/replay.rs and in crates/bitty-vt/src/parser/tests.rs, \x1b[4;20r / \x1b[5;10r in the new tests.
  • Narrower regions already in the suite are two rows or more (scroll_region_per_screen.rs, clear_residue.rs), so they stay on the accepted side of the boundary.

bitty-vt was re-run because it owns the DECSTBM parse path.

Gates

Run from the worktree with CARGO_TARGET_DIR=/mnt/data/Workspace/Projects/bitty-terminal/.targets/ctx-1908, offline:

rustfmt +stable --edition 2024 --check (state.rs, state/tests.rs)   exit 0
cargo clippy -p bitty-term-state --all-targets --offline -- -D warnings   clean
cargo test -p bitty-term-state --offline   275 lib + 2 + 19 + 3 + 4 + 8 + 1
                                           + 4 + 5 + 19 + 4 + 4 + 3 + 4 + 4
                                           + 22 + 16 + 2, 0 failed
cargo +1.85 check -p bitty-term-state --tests --offline   clean (no let-chains, no if-let guards)
RUSTFLAGS=-D warnings cargo check -p bitty-term-state --tests \
  --target x86_64-pc-windows-gnu --offline                clean
cargo test -p bitty-vt --offline            297 + 8 + 1 + 5 + 1, 0 failed

just ci-local was not run: github.com HTTPS is unreachable from this host, so act cannot clone its Nix action. The workspace-wide nextest/doc gates from #3259's checklist were therefore not re-run here; the crate-scoped gates above are the ones that cover this change.

Docs

No compatibility-matrix or spec page asserts the old behaviour: bitty-terminal-docs has no DECSTBM validity row (grep -rn 'top == bottom\|one-row region' over it returns nothing), and crates/bitty-term-state/src/lib.rs documents only the per-screen margins divergence D-1, which this change does not touch. The new rule is recorded in the set_scroll_region doc comment, so no docs-only follow-up is needed.

Summary by CodeRabbit

  • Bug Fixes
    • Invalid scroll-region settings, including ranges with identical or reversed boundaries, now leave the current margins unchanged and do not move the cursor.
    • Valid two-row scroll regions continue to work as expected, and the standard reset command restores scrolling across the full screen.

@Xuepoo Xuepoo added this to the v0.1.0 milestone Nov 19, 2026
@Xuepoo Xuepoo added fix Bug fix area:term Area: terminal state / VT P2 Priority: medium labels Nov 19, 2026
@coderabbitai

coderabbitai Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

set_scroll_region now rejects DECSTBM requests with equal or inverted margins without changing the existing margins or cursor position. Tests cover both rejected cases, an accepted two-row region, scrolling within it, and restoring full-screen margins.

Changes: DECSTBM Validation

Layer / File(s) Summary
Validate margins and test region behavior
crates/bitty-term-state/src/state.rs, crates/bitty-term-state/src/state/tests.rs
set_scroll_region rejects requests when the top margin is greater than or equal to the bottom margin. Tests check that rejected requests preserve margins and cursor position, and that adjacent margins are accepted, constrain scrolling, and can be reset to full-screen margins.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: Minimal · up to 04284

This change makes the terminal ignore one-row scroll-region requests, matching xterm and ghostty, and adds tests for the boundary cases. No actionable merge-blocking risk remains.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the DECSTBM fix in the terminal state crate, which matches the changeset: set_scroll_region now rejects top >= bottom, so one-row regions are rejected along with inverted ones. It is s…
Linked Issues check Passed Issue #3261 requires three coding outcomes. (1) Reject DECSTBM with top == bottom while keeping the wholesale ignore for top > bottom. The PR description and the AI-generated summary both state that t…
Out of Scope Changes check Passed The change set, as described by the PR description and the AI summary, touches only crates/bitty-term-state/src/state.rs (the validity check and doc comment in set_scroll_region) and `crates/bitty…
Full details: Title check

Explanation

The title names the DECSTBM fix in the terminal state crate, which matches the changeset: set_scroll_region now rejects top >= bottom, so one-row regions are rejected along with inverted ones. It is specific and relevant. The title says the top margin must be above the bottom, which covers the one-row case and the inverted case. It also includes the linked issue reference, which is acceptable.

Full details: Linked Issues check

Explanation

Issue #3261 requires three coding outcomes. (1) Reject DECSTBM with top == bottom while keeping the wholesale ignore for top > bottom. The PR description and the AI-generated summary both state that the set_scroll_region validity check changes from t &gt; b to t &gt;= b, and that rejected pairs leave margins unchanged and do not home the cursor. (2) Regression tests for both rejected shapes. decstbm_rejects_a_one_row_region and decstbm_rejects_an_inverted_region are described in state/tests.rs, and the summary confirms both assert unchanged margins and an unmoved cursor. (3) A test for the accepted boundary (top + 1 == bottom). decstbm_accepts_a_two_row_region covers it. The issue also asks for an audit of fixtures that depend on a one-row region. The PR description reports that audit: no hits for 1;1r, and all other DECSTBM sites use multi-row regions. Limit: the repository diff tool returned no text for state.rs or tests.rs, so the code was verified only through the PR description and the AI summary. The test results were not re-run.

Full details: Out of Scope Changes check

Explanation

The change set, as described by the PR description and the AI summary, touches only crates/bitty-term-state/src/state.rs (the validity check and doc comment in set_scroll_region) and crates/bitty-term-state/src/state/tests.rs (three DECSTBM tests). Both directly implement issue #3261. The PR description states that no other test or fixture was edited to make the change pass. No unrelated change is identified. Limit: the diff itself could not be read, so this verdict rests on the reported file list and summary.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI (base), Organization UI (inherited)
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 2e50459a-a131-4503-b636-a598fab0af12
Commits

Reviewing files that changed from the base of the PR and between 83fda62 and 04284a9.

Files selected for processing: 2

  • crates/bitty-term-state/src/state.rs
  • crates/bitty-term-state/src/state/tests.rs

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

@Xuepoo Xuepoo left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Independent review — head 04284a933df2dfe62dae776164667c0b8cb837a4

Reviewed SHA: 04284a93 (ctx-1908/fix-decstbm, base 83fda62f). Read-only on the lane worktree; every probe and the revert proof ran in separate git archive copies under my own scratch dir with their own CARGO_TARGET_DIR (rev-3264/{head,rev,base,probe}), so no artifact was shared between the fix and the reverted tree.

1. Semantics — PASS

crates/bitty-term-state/src/state.rs:3932-3952. The early return at state.rs:3944 sits before both margin writes (:3947-3948) and home_cursor() (:3949), so a rejected pair performs no partial write: t/b are locals, nothing else in the function mutates state before the guard. Confirmed behaviourally, not just by reading: after a live 4..9 region and the cursor parked at (6,2), CSI 6;6r leaves margins (4,9) and the cursor at (6,2); with DECOM set the rejected pair also leaves the cursor where it was (probe: origin=true, cursor (9,2) unchanged).

CSI r (no params) still restores full screen: parser dispatch.rs:999-1007 sets bottom = Row::SENTINEL when params.len() <= 1, set_scroll_region maps that to last — probe from a live (4,9) region lands on (0,23) on a 24-row grid; pinned by tests.rs:382.

2. Reference parity — FAIL (validity rule matches; parameter defaults do not)

Rule parity is exact. xterm charproc.c:4778-4787 (ThomasDickey/xterm-snapshots, rev 1.2134) applies the pair only inside if (bot > top), with set_tb_margins + CursorSet(0,0) both inside that branch. ghostty src/terminal/Terminal.zig:3330-3340 (setTopAndBottomMargin, main) has if (top >= bottom) return; with setCursorPos(1,1) after it. t >= b on 0-based rows is the same predicate as both, and rejection is wholesale in all three. 5;5r is correctly ignored (probe: margins survive a live 4..9 region); 0;24r and 1;2r are accepted.

The failure is parameter resolution, and it is pre-existing (crates/bitty-vt/src/parser/dispatch.rs:250-256 lead_value, :264-266 resolved_coordinate): a bottom parameter of 0 or an empty field resolves to Row(1), not to the screen bottom.

sequence xterm / ghostty base 83fda62f this PR
CSI r full screen (0,23) (0,23)
CSI 0;0r full screen (xterm bot == 0 → MaxRows, ghostty bottom_req == 0 → self.rows) (0,0) one-row region ignored, previous region kept
CSI 1;0r full screen (0,0) ignored
CSI ;r full screen (0,0) ignored
CSI 5;5r ignored (4,4) ignored

So 0;0r does not resolve to full screen before or after this change. It is not a regression — the base wrote the exact degenerate 0..0 region this PR exists to eliminate, and the new outcome is strictly safer — but the "bitty now matches both exactly" claim holds for the validity predicate only, not for defaults. See residual R1.

3. Discrimination — PASS

Scratch copy, one character reverted (state.rs:3944 >= → >), separate target dir, no shared artifacts:

  • reverted: decstbm_rejects_a_one_row_region FAILS at tests.rs:322 — left: (5, 5), right: (4, 9) (exactly the values the PR body predicts); full crate run on the reverted tree is 274 passed / 1 failed, i.e. this test is the only thing that moves.
  • head: same three tests pass (3 passed; 272 filtered out), and the crate is 275 lib tests green.

Not tautological. decstbm_rejects_an_inverted_region and decstbm_accepts_a_two_row_region pass on both trees by design — the former pins the older branch, the latter the accepted boundary — and the body does not claim otherwise.

4. Boundary — PASS

tests.rs:355-386. CSI 6;7r on a 24-row grid → margins (5,6), cursor (0,0). CSI S then gives row7 at row 5, blank at row 6, row5 untouched at row 4 and row8 untouched at row 7 — the two-row region scrolls as a unit with its neighbours intact. CSI r afterwards restores (0, GRID_ROWS-1). Only nit: the test does not assert the cursor after that final CSI r (minor, R3).

5. Collateral — PASS

  • Only two call sites exist: state.rs:2005 (the TerminalAction::SetScrollRegion arm) and state.rs:3932. Nothing else writes scroll_region_top/bottom from a DECSTBM path; the other writers are resets (:774, :4022, :4133, :4412, :4433), the DECSTBM-independent save/clamp paths (:844-845, :4196-4197) and invariants.rs:211 which asserts top <= bottom.
  • Every DECSTBM sequence in the tree is multi-row: paint_diff.rs:491 \x1b[5;12r, bitty-vt/tests/replay.rs:205 \x1b[2;10r, bitty-vt/src/parser/tests.rs:253, state/tests.rs:222,242,245, clear_residue.rs:132 rows 5..20, scroll_region_per_screen.rs (whose header already documents the multi-row constraint).
  • Suites run: bitty-term-state full (275 + 2 + 19 + 3 + 4 + 8 + 1 + 4 + 5 + 19 + 4 + 4 + 3 + 4 + 4 + 22 + 16 + 2), bitty-term-state --test {clear_residue,scroll_region_per_screen,resize_reflow_2529 (incl. transient_one_row_height_never_squashes_output),tui_reference_grid_2873}, bitty-vt full (297 + 8 + 1 + 5 + 1), bitty-render --test paint_diff (3, exercises \x1b[5;12r … \x1b[r through parser+state). All green.

6. Gates — PASS

  • cargo test -p bitty-term-state --offline → all suites ok, 0 failed.
  • cargo test -p bitty-vt --offline → 297 + 8 (1 ignored) + 1 + 5 + 1, 0 failed.
  • cargo clippy -p bitty-term-state --all-targets --offline -- -D warnings → exit 0, no diagnostics.
  • cargo +1.85 check -p bitty-term-state --tests --offline → exit 0 (no let-chains, no if-let guards).

7. PR body accuracy — PASS

git show 04284a93 --stat → exactly 2 files (state.rs +11/−2, state/tests.rs +78), no fixture or snapshot touched. grep -rn '1;1r' over the worktree → no hits; my wider sweep (\\x1b\[[0-9;]*r plus SetScrollRegion in fixtures) finds no other one-row region. The claimed pre-fix failure values match my revert run byte for byte.

CI at review time: macOS, MSRV 1.85, codeql, both compat matrices, Wayland/X11, supply chain, VM tier green; Windows check and test and Quality gates (1) still pending, so this verdict does not stand in for those legs.

Residual findings

  • R1 (pre-existing, parser-level, not introduced here). A bottom parameter of 0/empty resolves to Row(1) (dispatch.rs:250-256, 264-266) instead of "screen bottom", so CSI 0;0r, CSI 1;0r and CSI ;r are now ignored rather than restoring the full screen, where xterm (charproc.c:4779-4782, bot == 0 → MaxRows) and ghostty (Terminal.zig:3334, bottom_req == 0 → self.rows) both reset. The change still improves the base's degenerate 0..0 region, so it should not block this PR; worth a follow-up that maps an absent/zero bottom to Row::SENTINEL in the b'r' arm, with the same probe matrix above as the acceptance check.
  • R2 (body precision). "a 1-row grid's region can only ever be 0..0" understates reachability: the clamp paths at state.rs:845 and state.rs:4196-4197 can also produce top == bottom on a taller grid when a stored region starts at the new last row (invariants.rs:211 deliberately allows <=, so nothing breaks). The sentence is a note, not a guarantee the code now relies on — but it reads like one.
  • R3 (nit). decstbm_accepts_a_two_row_region verifies the margins after the final CSI r but not that the cursor homed; one assertion would close the only accepted-path behaviour the new tests don't pin.

None of these contradict the fix: the validity predicate matches both references, the rejection path is atomic, the pinning test genuinely discriminates, and nothing in the tree depended on a one-row region.

VERDICT: APPROVE

@Xuepoo
Xuepoo merged commit 47e721c into main Nov 19, 2026
21 checks passed
@Xuepoo
Xuepoo deleted the ctx-1908/fix-decstbm branch November 19, 2026 20:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:term Area: terminal state / VT fix Bug fix P2 Priority: medium

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[term-state] DECSTBM accepts top == bottom, which xterm and ghostty reject

1 participant