Skip to content

feat(mysql): add rtk mysql output filter (parity with rtk psql) - #3153

Open
henit-chobisa wants to merge 11 commits into
rtk-ai:developfrom
henit-chobisa:feat/mysql-cmd
Open

henit-chobisa wants to merge 11 commits into
rtk-ai:developfrom
henit-chobisa:feat/mysql-cmd

Conversation

@henit-chobisa

@henit-chobisa henit-chobisa commented Jul 22, 2026 •

Copy link
Copy Markdown

Summary

Adds an rtk mysql filter that compacts MySQL query output, closing the psql/mysql parity gap flagged in #3130.

  • Table mode (-t / interactive): strips box borders, cell padding, and the (N.NN sec) footer → tab-separated rows (≥60% token savings).
image
  • Batch mode (-B) and vertical (\G): already compact / different shape → passed through unchanged.
image
  • Credential-safe: every arg is forwarded to mysql untouched (so --defaults-file and auth work), but the label sent to tracking/logging is scrubbed — inline -p<pw> / --password=<pw> never hit the SQLite DB or verbose stderr.
image

Design — alternatives considered

psql's table filter is ~85% of what mysql needs, so the real question was how
to share
, not whether:

  1. Copy psql's filter into mysql_cmd — rejected: two near-identical files, classic copy-paste rot (a fix in one silently skips the other).
  2. Extract a shared module — chosen. Two sub-options weighed: a sql_table helper local to cmds/cloud/, vs. a generic one in core/. Landed on core/ascii_table: by keeping it SQL-agnostic (borders, padding, outer-pipe handling, row cap — nothing MySQL/psql-specific) it's a general text primitive that belongs next to strip_ansi/truncate in core. The dialect-specific bits (footer regex, \G vertical) stay in each command module.

Why this is safe

psql was refactored to consume ascii_table — and its existing tests pass
unchanged
, proving the extraction is behavior-preserving before mysql depends
on it.

Commits

  • refactor(core): add shared ascii_table de-formatter
  • refactor(psql): delegate table filtering to ascii_table
  • feat(mysql): add mysql output filter with credential-safe logging

Test plan

  • cargo fmt --all --check && cargo clippy --all-targets && cargo test (2538 pass)
  • Unit + snapshot + ≥60% savings; table / batch / vertical / NULL / credential-scrub cases
  • Manual: rtk mysql -t -e "SELECT …" against a live DB

@CLAassistant

CLAassistant commented Jul 22, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@henit-chobisa
henit-chobisa marked this pull request as ready for review July 22, 2026 14:53
@adam-msjc

Copy link
Copy Markdown

This is fantastic — thank you for jumping on it so fast! I went through the PR and the approach is exactly what I was hoping for.

A few things I especially appreciated:

  • Credential handling is spot on — forwarding every arg untouched so --defaults-file and auth still work, while scrubbing inline -p/--password= from anything logged or persisted. That's precisely the property we needed (a lot of our usage relies on --defaults-file so passwords never touch the CLI), and I love that you added tests for it.
  • Extracting core::ascii_table and refactoring psql onto it (tests still green) is a much cleaner call than duplicating the filter.
  • Passing -B and \G through untouched makes sense.

For context, this came out of using rtk in a real MySQL-heavy reporting workflow, so it'll get immediate real-world mileage. Happy to test it against live result sets if that'd help. Thanks again! 🙌

@henit-chobisa

Copy link
Copy Markdown
Author

Thank you @adam-msjc for this wonderful feedback, looking forward to your review further. 🙏🏼

@pszymkowiak

Copy link
Copy Markdown
Collaborator

Really clean PR — the shared ascii_table.rs extraction avoids psql/mysql duplication, the credential redaction is careful and well-tested (-pSECRET/--password=SECRET scrubbed from the label while the raw args still reach mysql), and I confirmed locally that it builds, the 39 psql+mysql+ascii_table tests pass, and clippy is clean. -B/\G passthrough respecting user intent is exactly right, and the ... +N more rows cap + tee for recovery is a nice touch.

One blocker with a proposed fix, plus two smaller notes.

🔴 Cells containing | get split into extra columns. strip_ascii_table does trimmed.split('|'), so any | inside a cell value is treated as a column separator. Real filter output:

IN   | 1 | mode=a|b|c | ^(foo|bar|baz)$ |
OUT  1	mode=a	b	c	^(foo	bar	baz)$

mode=a|b|c (a config value) and ^(foo|bar|baz)$ (a stored regex) each explode into 3 columns → the row ends up with more fields than the header and the agent reads misaligned data with no error. Pipe-containing values (feature flags, validation patterns, enums) are common in real tables, so this trips the "never-worse" guarantee.

Fix: derive column boundaries from the + positions in the border row and slice each data row there, instead of splitting on |:

fn separator_offsets(body: &str) -> Vec<usize> {
    body.lines()
        .find(|l| { let t = l.trim(); BORDER.is_match(t) && t.contains('+') })
        .map(|b| b.match_indices('+').map(|(i, _)| i).collect())
        .unwrap_or_default()
}

// A well-formed row has '|' at every separator offset; if not (e.g. unicode
// width shifts the bytes), fall back to the current split('|').
fn split_by_columns(line: &str, seps: &[usize]) -> Option<Vec<String>> {
    if seps.len() < 2 || !seps.iter().all(|&i| line.as_bytes().get(i) == Some(&b'|')) {
        return None;
    }
    Some(seps.windows(2).map(|w| line[w[0] + 1..w[1]].trim().to_string()).collect())
}

For | 1 | mode=a|b|c | the separators sit at fixed offsets, so mode=a|b|c is sliced out intact; the interior pipes never match a separator position. Unicode-heavy rows shift the byte offsets → split_by_columns returns None → graceful fallback to today's behavior (which already handles unicode without interior pipes). Since it's in the shared module, psql benefits too (just add virtual bounds at 0 and line.len() for its has_outer_pipes: false case). If you'd rather keep it minimal, detecting cells.len() > expected_columns and passing the table through raw also satisfies never-worse.

🟡 Test coverage has one telling gap. It's otherwise solid (batch/vertical passthrough, footer variants, interior NULL, credentials all covered), but nothing exercises a cell that contains | — which is exactly why the split bug slipped through. The fix should land with that as a regression test (| 1 | a|b|c | → two columns, not four), plus a unicode-cell assertion since the refactor touches that path.

🟡 savings_pct: 75.0 is optimistic. Measured against the real BPE tokenizer (cl100k_base) on the actual filter output: a realistic 12-column table is ~58%, a dense one ~54%; only very repetitive/sparse tables reach ~90%. rtk's whitespace token-count overstates here because it charges each stripped |/border as a full token, which BPE merges nearly for free. ~60 would match the realistic case — and the savings test currently uses only a small sparse table, so a wider one would keep that number honest.

🔵 Consider a real captured fixture (include_str! from tests/fixtures/) for the table cases — MySQL's box format is format-sensitive enough that inline strings drift; the checklist calls for it.

Substance and code quality are good — the pipe-splitting is the one thing I'd fix before merge, since it can silently feed the agent wrong data.

@henit-chobisa

Copy link
Copy Markdown
Author

Really clean PR — the shared ascii_table.rs extraction avoids psql/mysql duplication, the credential redaction is careful and well-tested (-pSECRET/--password=SECRET scrubbed from the label while the raw args still reach mysql), and I confirmed locally that it builds, the 39 psql+mysql+ascii_table tests pass, and clippy is clean. -B/\G passthrough respecting user intent is exactly right, and the ... +N more rows cap + tee for recovery is a nice touch.

One blocker with a proposed fix, plus two smaller notes.

🔴 Cells containing | get split into extra columns. strip_ascii_table does trimmed.split('|'), so any | inside a cell value is treated as a column separator. Real filter output:

IN   | 1 | mode=a|b|c | ^(foo|bar|baz)$ |
OUT  1	mode=a	b	c	^(foo	bar	baz)$

mode=a|b|c (a config value) and ^(foo|bar|baz)$ (a stored regex) each explode into 3 columns → the row ends up with more fields than the header and the agent reads misaligned data with no error. Pipe-containing values (feature flags, validation patterns, enums) are common in real tables, so this trips the "never-worse" guarantee.

Fix: derive column boundaries from the + positions in the border row and slice each data row there, instead of splitting on |:

fn separator_offsets(body: &str) -> Vec<usize> {
    body.lines()
        .find(|l| { let t = l.trim(); BORDER.is_match(t) && t.contains('+') })
        .map(|b| b.match_indices('+').map(|(i, _)| i).collect())
        .unwrap_or_default()
}

// A well-formed row has '|' at every separator offset; if not (e.g. unicode
// width shifts the bytes), fall back to the current split('|').
fn split_by_columns(line: &str, seps: &[usize]) -> Option<Vec<String>> {
    if seps.len() < 2 || !seps.iter().all(|&i| line.as_bytes().get(i) == Some(&b'|')) {
        return None;
    }
    Some(seps.windows(2).map(|w| line[w[0] + 1..w[1]].trim().to_string()).collect())
}

For | 1 | mode=a|b|c | the separators sit at fixed offsets, so mode=a|b|c is sliced out intact; the interior pipes never match a separator position. Unicode-heavy rows shift the byte offsets → split_by_columns returns None → graceful fallback to today's behavior (which already handles unicode without interior pipes). Since it's in the shared module, psql benefits too (just add virtual bounds at 0 and line.len() for its has_outer_pipes: false case). If you'd rather keep it minimal, detecting cells.len() > expected_columns and passing the table through raw also satisfies never-worse.

🟡 Test coverage has one telling gap. It's otherwise solid (batch/vertical passthrough, footer variants, interior NULL, credentials all covered), but nothing exercises a cell that contains | — which is exactly why the split bug slipped through. The fix should land with that as a regression test (| 1 | a|b|c | → two columns, not four), plus a unicode-cell assertion since the refactor touches that path.

🟡 savings_pct: 75.0 is optimistic. Measured against the real BPE tokenizer (cl100k_base) on the actual filter output: a realistic 12-column table is ~58%, a dense one ~54%; only very repetitive/sparse tables reach ~90%. rtk's whitespace token-count overstates here because it charges each stripped |/border as a full token, which BPE merges nearly for free. ~60 would match the realistic case — and the savings test currently uses only a small sparse table, so a wider one would keep that number honest.

🔵 Consider a real captured fixture (include_str! from tests/fixtures/) for the table cases — MySQL's box format is format-sensitive enough that inline strings drift; the checklist calls for it.

Substance and code quality are good — the pipe-splitting is the one thing I'd fix before merge, since it can silently feed the agent wrong data.

Hey there @pszymkowiak, thank you so much for taking the time and reviewing it. I really appreciate your feedback and I completely agree, the cells with | separator is actually something that I missed, and I completely agree with the solution that you proposed as well, for deriving a column boundary with +, calculating the offset and then splitting the values according to those offsets, column boundary. Completely on it with you. I wish to try it out again though with different types of psql and mysql outputs, now that you mentioned it, with json and also yaml columns, in case it breaks those by any chance. I will share a detailed test report and also add those in the coverage. I will consider the remaining points as well.

Honestly, thank you so much again, for taking the time to review. I thought it might or might not get a review this soon. Really appreciated 🙏

@henit-chobisa

henit-chobisa commented Jul 23, 2026 •

Copy link
Copy Markdown
Author

Hey @pszymkowiak, I've pushed the changes, with your suggestions for using a column boundary instead of just simply splitting with the | operator, with that here, even the psql implementation is now more robust. I also toned the saving_pct to 60 as you mentioned. 🙏

I also considered making the junction character provided by the caller, but as of now, I think it's sufficient. Please let me know your suggestions on this, if you think we should make it configurable I'm up for it and completely align as there can be someone in the future, who wish to use the module, but the table format is different. Thanks. 🙌

@pszymkowiak

Copy link
Copy Markdown
Collaborator

The filter itself looks great — I ran ~30 end-to-end cases on a compiled build: config values (mode=a|b|c), stored regexes (^(foo|bar|baz)$) and multi-pipe cells now all stay in a single column, \G/batch/status output passes through byte-exact, and credential redaction is confirmed in the actual tracking DB (no plaintext -p/--password leak). psql/mysql/ascii_table unit tests are all green. The junction-based column slicing resolves the pipe-splitting blocker cleanly. 🎉

One thing worth revisiting before merge: savings_pct: 75.0 should be re-estimated with a real (BPE) tokenizer. rtk's own metric is whitespace/byte-based, which overstates table savings — it charges every stripped |/-/+ as a full token, whereas a BPE tokenizer merges those runs nearly for free. Measured on actual filter output:

  • whitespace/byte count (what rtk reports): ~46% on a dense 4-col × 10-row table
  • BPE cl100k_base: ~54–58% on realistic wide tables; ~90% only on very sparse/repetitive ones

So 75.0 is optimistic for the common case. I'd re-measure with tiktoken (or whichever tokenizer rtk targets) on a couple of representative tables and set it around ~60, and ideally point the savings unit test at a wider table so the number stays honest.

Everything else LGTM.

@henit-chobisa

Copy link
Copy Markdown
Author

Hey there @pszymkowiak, thank you for testing this throughly with me. Actually in my last commit, I've also tuned down the saving_pct to 60, as you mentioned. image

@adam-msjc

Copy link
Copy Markdown

Checking in on this one — looks like the savings_pct re-estimate was the last open item, and @henit-chobisa pushed that (75 → 60) shortly after the review. With the end-to-end testing, credential-redaction verification, and green tests already confirmed, is there anything else needed before this can merge?

Happy to help validate against real MySQL result sets if another data point would be useful. Thanks to you both for the thorough work on this one.

@henit-chobisa

Copy link
Copy Markdown
Author

Hey @pszymkowiak & @adam-msjc, I hit a merge conflict with recent change of replacing lazy static by @TaKO8Ki. I've resolve that and moved this PR to LazyLock as well, changing

  • src/core/ascii_table.rs - BORDER
  • src/cmds/cloud/mysql_cmd.rs - TABLE_BORDER & FOOTER

psql_cmd.rs was already on LazyLock, with a SEPARATOR declaration unused, as we now have moved to ascii_table for that, I removed that.

All test green. ✅
Build Successful ✅

Please have a look. Thanks.

@adam-msjc

Copy link
Copy Markdown

Thanks for turning that around so quickly @henit-chobisa — good catch adopting LazyLock to match the upstream change.

One procedural thing that might be what's actually holding this up: GitHub still shows this as REVIEW_REQUIRED with 0 formal reviews submitted and no reviewers requested, so branch protection is blocking the merge even though the PR itself is MERGEABLE. @pszymkowiak — your "everything else LGTM" came through as a regular comment rather than a submitted Approve, so it isn't registering as an approval. Would you be able to submit it as a formal review (or tag whoever the right approver is)?

Worth doing sooner rather than later — the PR has already had to absorb one upstream conflict while waiting, and that risk grows the longer it sits. Thanks both.

@henit-chobisa

henit-chobisa commented Jul 29, 2026 •

Copy link
Copy Markdown
Author

Hey there, @adam-msjc. Thanks. Actually I cannot really request for a formal review, as of course I'm an external contributor. As a maintainer myself, for plane.so, https://github.com/makeplane/plane, I can understand, it can be quite a pain, to manage these many open PRs and reviews, especially when you're gaining this much popularity, while working on your everyday task. I'm sure, this will soon get a review and get merged. 🔥

Thanks again. 🙏

@henit-chobisa

henit-chobisa commented Aug 3, 2026 •

Copy link
Copy Markdown
Author

Hey there @pszymkowiak, reminder to check this. In case you missed. Thanks!

@pszymkowiak

Copy link
Copy Markdown
Collaborator

Found a data-loss bug in filter_table (src/cmds/cloud/mysql_cmd.rs). Verified against a compiled build of this branch, both via unit test and a live MySQL server.

FOOTER is unanchored (\(\d+[.,]\d+ sec\), matched with is_match) and is applied to every line of table output, not just the trailing summary line:

let body = output
    .lines()
    .filter(|line| !FOOTER.is_match(line.trim()))
    .collect::<Vec<_>>()
    .join("\n");

Any data row whose cell content happens to contain a (N.NN sec)-shaped substring gets silently dropped — not truncated with the ... +N more rows marker, just gone, before strip_ascii_table ever sees it.

Repro against a real MySQL server (table mode):

CREATE TABLE notes (id INT, note VARCHAR(255));
INSERT INTO notes VALUES
  (1, 'backup done (12.34 sec) ok'),
  (2, 'second row');
$ rtk mysql -h 127.0.0.1 -u root -t -e "SELECT * FROM notes"
id	note
2	second row

Row 1 vanishes. rtk proxy mysql ... (unfiltered) shows both rows correctly, confirming the drop happens in the filter.

Minimal unit-test repro (drop into mod tests):

#[test]
fn repro_footer_eats_data_row() {
    let input = "\
+----+------------------------------+
| id | note                         |
+----+------------------------------+
|  1 | backup done (12.34 sec) ok   |
|  2 | second row                   |
+----+------------------------------+
2 rows in set (0.00 sec)";
    let out = filter_mysql_output(input);
    assert!(out.contains("backup done"), "row 1 was dropped:\n{}", out);
}

psql_cmd.rs's equivalent (ROW_COUNT) is anchored to the full line (^\(\d+ rows?\)$), which is why it doesn't have this issue. Suggested fix — either anchor FOOTER the same way, or (more robust, since real footers never contain | and real table rows always do):

.filter(|line| line.trim().contains('|') || !FOOTER.is_match(line.trim()))

@henit-chobisa

Copy link
Copy Markdown
Author

Hey @pszymkowiak. Thank you so much for jumping back on this. That was a crucial one, I've pushed a fix and also added tests for checking the same. Thanks again. 🙌

@pszymkowiak

Copy link
Copy Markdown
Collaborator

Tested at current head (7746e72). The FOOTER-anchoring fix holds up, thanks for that. Found several more issues, some verified against a compiled build with a stub mysql binary, some via read-through.

1. Bundled short-option password leak (mysql_cmd.rs) — redact_credentials only catches -p/--password when it's the leading text of the arg token.

rtk mysql -tpSecret123 -uroot -e "SELECT 1"

mysql's getopt-style parser reads -tpSecret123 as -t + -p Secret123 (standard short-option bundling), but arg.starts_with("-p") is false for -tpSecret123 (starts with -t). Verified: Secret123 ends up in plaintext in the SQLite tracking DB (original_cmd column) and on stderr in verbose mode — contradicts the module's own doc comment about inline passwords never hitting the DB.

2. stdin never forwarded (mysql_cmd.rs) — mysql db < dump.sql / piped imports silently do nothing.

echo "SELECT 1;" | rtk mysql testdb

Exit 0, no error, but the mysql client's stdin is closed before it can read anything (RunOptions::stdout_only() chain never calls .inherit_stdin()). Verified with a stub mysql that echoes what it reads on stdin — it gets nothing.

3. Multi-statement 2nd result set silently swallowed / column offsets can corrupt it (ascii_table.rs) — junction_offsets locks onto the first border row in the whole body and reuses those byte offsets for every later row, including a second table from a multi-statement query.

rtk mysql testdb -e "SELECT ...; SELECT ...;"

Verified with two fake result sets: the entire second table (header + data) disappeared with no trace, replaced by ... +2 more rows on the first table's row count. Depending on column widths this can also silently corrupt the second table's rows (merge/truncate columns) instead of just miscounting them, since the only safety check in split_by_offsets is "is there a | byte at this stale offset" — a coincidental match on narrower columns passes that check.

4. Truncated rows on a successful query are unrecoverable (ascii_table.rs/mysql_cmd.rs) — the row cap (CAP_LIST=20) appends ... +N more rows, but mysql_cmd::run only sets .tee("mysql") with the default TeeMode::Failures, so tee never writes on exit 0. ~10 other filters in this repo (go_cmd, pytest_cmd, cargo_cmd, etc.) call tee::force_tee_hint/force_tee_tail_hint specifically to bypass that check for successful-command truncation, per src/core/README.md's documented pattern. Here, the truncation note implies more rows exist, but there's no way to get them.

5. Footer stripping deletes a DML statement's own confirmation when batched with a SELECT — mysql -t -e "UPDATE t SET x=1; SELECT * FROM t;": the UPDATE's own output has no border, but because the SELECT elsewhere in the same body has one, is_table_format returns true for the whole thing, and is_footer_line matches and deletes Query OK, 1 row affected (0.01 sec) even though that statement never rendered a table.

Smaller points:

  • naive_split's outer-pipe branch (cells[1..cells.len()-1]) returns an empty string instead of the row's content when a malformed row has exactly one interior | (cells.len()==2) — silent content drop on the fallback path meant to be the safe one.
  • redact_credentials is a new bespoke implementation with no shared helper — dotnet/binlog.rs already has scrub_sensitive_env_vars for a similar purpose; worth consolidating so a future command doesn't copy-paste a third variant with the same bundled-flag gap.
  • filter_mysql_output/filter_table walk the output ~4 separate times (format-check, footer-filter+rejoin, junction_offsets, main loop) with an extra full-body allocation from the rejoin — the old psql path did this in one borrowed-&str pass.

Three defects found in review, all in the shared stripper, all silent.

1. `junction_offsets` locked onto the first `+`-bearing border in the
   whole body and reused those byte offsets for every later row. A
   multi-statement query returns one table per statement, so a second,
   narrower result set failed the "is there a `|` at this offset" check,
   fell through to `naive_split`, and had every interior `|` promoted to
   a column break. Where the widths happened to line up the check passed
   instead, and the row was sliced on the wrong boundaries with nothing
   to detect it. Row accounting carried the same single-table
   assumption: CAP_LIST was counted across the body, so a second result
   set following a long first one disappeared into the first table's
   `... +N more rows`.

   A border whose junction layout differs now starts a new table:
   offsets are re-derived, the header/cap counters restart, and the
   overflow marker closes the table it belongs to. Repeated identical
   borders (mysql draws three per table) are not a boundary. Two
   adjacent tables of identical width still merge, which is harmless
   because the offsets are correct for both.

2. mysql pads cells to display width while the offsets are counted in
   bytes, so a single wide character drops a row into `naive_split`.
   That fallback splits on every `|`, which is correct only when no cell
   contains one: `| 1 | a|b<coffee> |` came back as three fields instead
   of two, reported as data with nothing to signal it was wrong. The
   split now learns the column count from the border and returns the row
   unsplit rather than guessing where the boundaries are. Display-width
   slicing is the proper fix, but it needs a unicode-width dependency.

3. `naive_split`'s outer-pipe branch sliced a malformed row carrying
   exactly one bar to an empty string, dropping its content on the path
   that exists to be the safe fallback.

Also adds `strip_ascii_table_with_stats`, which reports how many rows the
cap hid so a caller can offer a recovery path for them.
`strip_ascii_table` remains as a wrapper, so psql is unaffected.
Bundled short-option passwords were not redacted. `my_getopt` reads
`-tpSecret123` as `-t` plus `-p Secret123`, but the check only matched
`-p` at the head of a token, so the password reached the label rtk
persists: `original_cmd`/`rtk_cmd` in the tracking DB, verbose stderr,
and `rtk gain --history`. It can also leave the machine, because
`low_savings_commands` sends the first three whitespace tokens of
`rtk_cmd` in the telemetry ping and the password is token three. The scan
now walks the cluster, stopping at the short options that consume a value
so a `p` inside `-uroot` or `-hprimary` is not mistaken for a flag. The
parse lives in `core::args_utils` so the next client filter does not grow
a third variant of it.

stdin was never forwarded. `RunOptions::stdout_only()` leaves
`inherit_stdin` false, so `mysql db < dump.sql` read EOF immediately:
nothing imported, no error, exit 0. It is now inherited when stdin is not
a terminal, covering pipes and redirects. Forwarding on a TTY would trade
that for a different break, since output is captured and printed after
exit, leaving an interactive REPL looking frozen.

A batched `UPDATE ...; SELECT ...;` lost the UPDATE's confirmation.
`is_table_format` inspects the whole body, so that statement's output
went down the table path even though it rendered no table, and FOOTER
matched any line ending in a timing parenthesis. FOOTER now names the two
result-set status lines and is anchored at both ends. Pinning the head
also subsumes the previous `|` guard: a table row starts with a bar and
can no longer match whatever its cells contain, so an unfamiliar footer
dialect leaks one cosmetic line instead of deleting a row.

Detection itself was too loose. Any body holding a line matching
`^\+[-+]+\+$` counted as a table, so batch (`-B`) output whose value is
`+----+` was routed into the stripper, which skips border lines, and that
row vanished with no marker. Detection now requires the pair a real table
always prints: a border immediately followed by a bar-wrapped row.

Truncated rows had no recovery path. `.tee("mysql")` only writes on a
non-zero exit, but a truncated SELECT succeeds, so `... +N more rows`
named rows that nothing could produce and the caller had to re-run the
query with LIMIT/OFFSET. `force_tee_hint` now emits `[full output: ...]`
when the stripper reports hidden rows, per src/core/README.md.

The footer pass also assembles its body in a single walk instead of
collecting a `Vec<&str>` and re-joining it.
@henit-chobisa

Copy link
Copy Markdown
Author

Hey @pszymkowiak, thank you so much for going this deep on it. The bundled -p one especially — that was a nasty catch, and I would not have found it on my own. All 5 points and the smaller ones are addressed now.

Heads up before anything else: I squashed and force-pushed the branch, so your inline comments will show as outdated. Nothing was dropped — the tree is identical to what you reviewed, it is just two commits now instead of a long chain. Sorry for the noise.

473d477 — ascii_table.rs

  • (3) multi-statement result sets. junction_offsets locked onto the first +-bearing border in the whole body and reused those byte offsets for every later row, so a second, narrower table failed the junction check and got shredded by naive_split. Row accounting had the same assumption, which is why the second table vanished into the first one's ... +N more rows. A border with a different layout now starts a new table — offsets re-derived, header/cap counters restarted, overflow marker closing the table it belongs to. Repeated identical borders (mysql draws three per table) are not a boundary.
  • (smaller) naive_split empty string. Fixed — cells.len() == 2 no longer slices to nothing.
  • One more of the same family I hit while checking your cases: mysql pads to display width but the offsets are counted in bytes, so a single wide char drops the row into naive_split, and if that row also has a | in a cell it was split wrongly. | 1 | a|b☕ | came back as three fields instead of two. It now returns the row unsplit instead of guessing the boundaries.

882dbad — mysql_cmd.rs

  • (1) bundled short-option password. my_getopt reads -tpSecret123 as -t + -p Secret123, so the scan now walks into the cluster and stops at value-taking shorts, and -uroot / -hprimary are left alone. You were right that this reaches the DB, and it is a bit worse than that — low_savings_commands keeps the first three tokens of rtk_cmd for the telemetry ping, and the password is token three.
  • (2) stdin. Now forwarded, but only when stdin is not a TTY. Forwarding unconditionally would leave an interactive REPL looking frozen, since we capture output and print it after exit.
  • (4) truncation recovery. force_tee_hint now emits [full output: ...] when rows were actually hidden, per src/core/README.md. Used the plain hint rather than force_tee_tail_hint because a multi-statement body has several sections and no single offset covers the gap.
  • (5) DML confirmation. FOOTER now names the two result-set status lines and is anchored at both ends, so a batched UPDATE's Query OK ... survives. Anchoring the head also made the | guard redundant — a row starts with a bar and can no longer match whatever is in its cells.
  • (smaller) shared helper. The cluster parse lives in core::args_utils now so the next client filter does not grow a third copy.
  • (smaller) extra passes. The footer pass builds its body in one walk instead of collect + join. Small note on that one — psql_cmd.rs:77-81 has the same Vec + join, so the two were actually even; mysql is the leaner one now.
  • Another sniffing bug I found while testing: is_table_format accepted any body containing a +----+ line, so -B output whose value happens to be +----+ was routed into the stripper and that row got deleted silently. Detection now requires a border immediately followed by a bar-wrapped row.

Two I deliberately left out, happy to take either if you would rather have them here:

  1. psql connection URI. psql_cmd.rs:33,39 passes args.join(" ") unredacted, so psql "postgresql://user:pw@host/db" writes the password to the tracking DB today. Different mechanism from mysql — psql's -p is --port, so the same helper must not be reused there — which is why it felt like its own issue rather than more scope on this PR.
  2. Display-width slicing. The proper fix for the wide-char case, but it needs a unicode-width dependency, and adding one to a PR that is already waiting felt like inviting a second debate. The change above removes the corruption without it.

All green ✅ — clippy clean, 2611 tests passing. I verified the redaction and the stdin forwarding end-to-end against a stub mysql binary; the table-mode ones are covered by unit tests, since I do not have a live server on this machine.

Please have a look when you get a chance. Thanks again 🙌

@pszymkowiak

Copy link
Copy Markdown
Collaborator

Verified all of this against a compiled build — re-ran the exact repros from the original review (stdin via a stub mysql, bundled -tpSecret123 redaction, the multi-statement two-table case) plus the new ascii_table/mysql_cmd tests. All green, clippy clean, 40 tests passing. The multi-statement fix in particular is solid — the second table (id/email) now shows up intact instead of vanishing into ... +2 more rows.

On the two you left out — agreed with your call on both, would keep them separate:

  1. psql URI redaction — different enough mechanism (as you said, -p means something else there) that folding it into this PR's redaction helper would risk the same kind of accidental coupling this PR just moved away from. Worth its own issue so it doesn't get lost, but not blocking this one.
  2. Display-width slicing — agree on not pulling in unicode-width here. The fix you shipped (return the row unsplit instead of guessing) is the right conservative behavior for now; a dependency add is a separate discussion.

Nice catch on the three you found while testing (the low_savings_commands telemetry token-3 exposure, the is_table_format false-positive on literal +----+ in -B output, and the wide-char+interior-pipe corruption) — none of those were in the original review, good that testing surfaced them.

LGTM — thanks for the thorough turnaround.

@pszymkowiak pszymkowiak left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-verified all fixes against a compiled build — see comment above for details. LGTM.

@henit-chobisa

Copy link
Copy Markdown
Author

Thank you soook much @pszymkowiak for your review and the time that you put in. To be honest, it's not too long I've started contributing within rust projects. All thanks to you, I learnt a lot. Looking forward to contributing further! 🙏🏼🙏🏼

@KuSh KuSh left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Mostly LGTM, but ascii_table.rs contains a bug and a regression that would be worth fixing before merging.

Also, the new command should be added to RUST_HANDLED_COMMANDS

Comment on lines +203 to +211
let mut body = String::with_capacity(output.len());
let mut first = true;
for line in output.lines().filter(|line| !is_footer_line(line)) {
if !first {
body.push('\n');
}
body.push_str(line);
first = false;
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
let mut body = String::with_capacity(output.len());
let mut first = true;
for line in output.lines().filter(|line| !is_footer_line(line)) {
if !first {
body.push('\n');
}
body.push_str(line);
first = false;
}
let body = output
.lines()
.filter(|line| !is_footer_line(line))
.fold(String::with_capacity(output.len()), |mut acc, line| {
if !acc.is_empty() {
acc.push('\n');
}
acc.push_str(line);
acc
});

}

if verbose > 0 {
eprintln!("Running: psql {}", args.join(" "));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

No password redaction here?

Comment thread src/core/ascii_table.rs
Comment on lines +127 to +129
/// Two adjacent tables with *identical* column widths are indistinguishable
/// here and merge into one. That is harmless: the offsets are correct for
/// both, so only the row count and the header/data split are affected.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

They also share a single CAP_LIST budget, so second table could completely be truncated

// to get them back. `force_tee_hint` writes regardless of exit code; the
// plain "full output" form is the one to use here because a multi-statement
// body has several sections and no single line offset covers the gap.
match tee::force_tee_hint(output, "mysql-rows") {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

this loads Config and writes a file as a side effect, including from unit tests that trip the cap, in an otherwise pure filter. Should perhaps be split in two (pure filter and encapsulation)

Comment thread src/core/ascii_table.rs
continue;
}

if trimmed.contains('|') {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Any non-row line containing two or more | is classified as a row here, and naive_split then unconditionally drops cells[0] and cells[last] as outer-bar edges when has_outer_pipes is true. The line loses its first and last segment silently, with no marker.

Reachable from a single client invocation, e.g. mysql -t -e "SELECT id FROM t; SELECT x FROM u\G" — the \G block follows the -t table in the same output:

+----+
| id |
+----+
| 1  |
+----+
1 row in set (0.00 sec)

*** 1. row ***
 note: a|b|c

note: a|b|c comes out as just b. The expected_columns guard does not fire, because the truncated result (1 field) is under the column count rather than over it.

Requiring a row to both start and end with | when shape.has_outer_pipes would let these lines pass through untouched.

Comment thread src/core/ascii_table.rs
/// across every result set in the body. A caller that shows `... +N more rows`
/// needs the count to decide whether to offer a recovery path for them.
pub fn strip_ascii_table_with_stats(body: &str, shape: TableShape) -> (String, usize) {
let mut junctions = junction_offsets(body);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Offsets are seeded once from the first border found in the body, and only re-derived at a subsequent border (line 154). psql prints its header above its border, so in a multi-result-set body every header after the first is split with the previous table's offsets — it is consumed at line 167 before the border that would have updated them.

This is a regression against the filter_table this replaces, which split each pipe-bearing line independently and so had no offsets to go stale. Running both on the same input:

 id | name
----+------
  1 | foo
(1 row)

 ab | c | d
----+---+---
  1 | 2 | 3
(1 row)
line before after
ab | c | d ab⇥c⇥d (3 fields) ab⇥c | d (2 fields)
1 | 2 | 3 1⇥2⇥3 (3 fields) 1⇥2⇥3 (3 fields)

A 2-field header over a 3-field data row. Depending on where the stale | lands the header is either mis-split like this or returned unsplit. psql -c "SELECT …; SELECT …" and psql -f script.sql both hit it.

Re-deriving the offsets for the row preceding a border, or buffering the header and re-slicing it once the border is seen, would restore the old behaviour.

@KuSh KuSh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Round 2 of 3 — CHANGES REQUESTED

Claim: rtk mysql filters MySQL client output to parity with rtk psql, extracting the shared table de-formatter into core::ascii_table.

Scope: accept if narrowed to "mysql output filter, without credential redaction". Credential redaction is not an OSS feature, and psql_cmd on develop has none — so the redaction surface here should come out rather than be fixed. That cut is clean: the whole +91 in src/core/args_utils.rs is redact_clustered_password plus its six tests, so reverting that file to its develop state removes it entirely, and in mysql_cmd.rs it is the module-doc paragraph, VALUE_TAKING_SHORTS, redact_credentials, its one call site, and four tests. Removing it also drops two findings I would otherwise be raising here, so it shrinks the PR in every direction.

Ran: PostgreSQL 16 and MySQL 5.7.44 / 8.0.46 / 8.4.11 / 9.7.2 in Docker, through the real clients rather than fixtures. Two-result-set psql -c … -c …; mysql -t with a trailing \G; multi-line TEXT values; 200-row results in every psql output mode; bare -p under a PTY. cargo fmt --all --check, cargo clippy --all-targets (0 warnings) and cargo test --all are green on the head and on the head merged onto current develop — the branch is 578 commits behind, and the merge is clean.

CI @882dbad: never run. Only license/cla is present; run 33533028352 is still action_required. Both approvals on this PR were given on a head CI has never built.

Blocks merge (2)

  1. ascii_table.rs treats every physical line as a whole row. Three arms, one class. Two of them I have fixes and regression tests ready for and can push on request: non-row lines with interior bars losing their first and last segment ( note: a|b|c → b), and psql's second-and-later headers being sliced with the previous result set's junction offsets (ab<TAB>c | d, two fields, over a three-field data row — a regression against the filter_table this replaces). The third arm is open and needs your design call, because a TEXT column containing newlines makes a row span several physical lines — see the inline comment.

  2. rules.rs advertises 60% for every ^mysql(\s|$) and rewrites all of them, but the form that rule will mostly match measures 0.0% against the 20% floor. See the inline comment.

Plus your own two open threads, which I am counting as blocking rather than optional because both are content loss in new code: the shared CAP_LIST budget between adjacent same-width tables, and force_tee_hint inside an otherwise pure filter.

Checked and correct — no need to re-verify

  • The (\s|$) terminator: mysqldump, mysqladmin, mysqlcheck and mysql_upgrade are all correctly left alone.
  • \G vertical output and -B batch output pass through untouched; exit codes and stderr propagate on failure; forward_stdin imports correctly and leaves terminal stdin closed.
  • The registration walk — main.rs routing, discover/rules.rs, the cloud README.md, the pipe dispatch — is consistent with psql. RUST_HANDLED_COMMANDS is the one gap, and it is a one-line addition.
  • The psql side beyond arm 2: aligned output, single-column tables, NULL cells, the (N rows) footer, non-table lines, psql's + continuation marker and \dt title lines are all byte-identical to the deleted filter_table.

Filed as follow-ups — not this PR's job

  • #4022 — the filters only fire on the decorated shape, so psql -A/--csv/-t and mysql batch output pass through uncapped at any size. Pre-existing on the psql side; this PR inherits the shape rather than introducing it. It is also where the real unrealised value is for both commands.
  • #4023 — categorize_command buckets psql (and now mysql) as "other" rather than "cloud".

Hypotheses built and dropped

  • Bare -p hangs because rtk captures the prompt. Refuted by execution: MySQL's my_getpass writes to /dev/tty, not stdout — with stdout redirected to a file the prompt still reached the terminal and the file stayed empty, and end to end under a PTY rtk mysql -u root -p prompts, reads and returns.
  • This filter drops the child's stderr on success. True on this head in isolation, but already fixed on develop by #3772; with develop merged the warning is forwarded.
  • The multi-line-cell bug is a regression. It is not — psql pads continuation lines so they never match ^[-+]+$, and develop, this PR and this PR plus my fixes are byte-identical there. It is new-surface content loss on the mysql path only.

Next

Cut the redaction surface, then arm 3 of finding 1 and the rule claim in finding 2. Say the word and I will push the two ascii_table fixes with their tests so you only have the design call left. After that this needs its first CI run before anyone can honestly approve it.

Comment thread src/core/ascii_table.rs
}

// Skip border lines: `----+----` (psql) and `+----+----+` (mysql).
if BORDER.is_match(trimmed) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

BORDER (^[-+]+$) is tested against every line, but with a TEXT column containing newlines a single row spans several physical lines — so cell content reaches this check. Two ways it goes wrong, both reproduced against a real mysql -t:

  • a value line that is only dashes matches and is dropped, with no ... +N more rows marker and hidden left at 0, so filter_table's recovery hint never fires either;
  • a value line shaped like +----+ matches and contains +, so the branch below treats it as a new result set: junctions is overwritten with the bogus layout and every later row of the same table is sliced against it.
INSERT INTO ml VALUES (1,'head\n----\ntail'),(2,'x\n+----+\ny'),(3,'ok');
raw mysql -t                    through rtk
|    1 | head                   |    1 | head
----                            tail
tail |                          |    2 | x
|    2 | x                      y     |
+----+                          3	ok
y     |
|    3 | ok             |

head, ----, x and +----+ are gone, and rows 1 and 2 are no longer tab-separated.

The underlying assumption is that one physical line is one logical row, which a multi-line cell breaks. For this dialect the row boundary is knowable — a row opens with | and closes on the line that ends with | — so tracking that state would let the border check skip continuation lines. But how a multi-line cell should then be represented in tab-separated output is a design call, which is why I am handing this back rather than patching it.

Worth noting psql escapes this: it pads continuation lines ( | ---- +), so they never match ^[-+]+$. Verified develop, this PR, and this PR plus fixes are byte-identical on the psql path.

Comment thread src/discover/rules.rs
..RtkRule::DEFAULT
},
RtkRule {
pattern: r"^mysql(\s|$)",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This advertises 60% for every ^mysql(\s|$) command and rewrites all of them, but the form it will mostly match saves nothing.

The mysql client switches to batch mode — tab-separated, no box — whenever stdout is not a tty, and rtk always captures stdout through a pipe. So is_table_format returns false and the output is passed through. Measured on a 200-row table with an isolated RTK_DB_PATH:

result
raw mysql -e 'SELECT * FROM big', piped 201 lines / 4288 B
rtk mysql -e 'SELECT * FROM big' 202 lines / 4289 B

The extra byte is a trailing newline — all 200 rows, no cap, no hint, 0.0% against the 20% floor in CONTRIBUTING.md.

This is not version-specific. Same query, only stdout differing, on 5.7.44, 8.0.46, 8.4.11 and 9.7.2 — all four identical:

stdout = TTY        stdout = PIPE
+---+---+           a	b
| a | b |           1	2
+---+---+
| 1 | 2 |
+---+---+

Since an agent's shell pipes stdout with or without rtk, the decorated shape this filter targets never appears where rtk runs; the table path is reachable only when someone explicitly passes -t (which does measure 64.5%).

So either narrow the rule to the form that benefits, or set savings_pct from a measurement of the form it actually matches. The broader fix — capping the undecorated path, which is where the value would be for both this and psql — is #4022 and not this PR's job.

Incidentally the rule will not match modern MariaDB at all: mariadb:11 ships no mysql binary, the compatibility symlinks having been dropped.

Comment thread src/core/args_utils.rs
/// bare `-p` that prompts interactively, or a bundle whose value swallowed the
/// rest). The bias is deliberate: an unrecognized value-taking option leads to
/// *over*-redaction of a label, never to a leaked secret.
pub fn redact_clustered_password(arg: &str, value_taking: &str) -> Option<String> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Credential redaction is not an OSS feature, so this should come out rather than be corrected — psql_cmd on develop has none, which is the consistent behaviour.

The cut is clean here: this function plus its six tests are the entire +91 this PR adds to the file, so reverting args_utils.rs to its develop state removes it exactly. On the mysql_cmd.rs side it is the module-doc paragraph, VALUE_TAKING_SHORTS, redact_credentials, its single call site, and four tests.

Removing it also retires two findings rather than leaving them open:

  • the hand-written VALUE_TAKING_SHORTS scan is the kind of getopt re-implementation .claude/rules/rust-patterns.md rule 6 rules out for a new command, and arg_tokenizer landed on develop after this branch forked, so the rule now applies here. Its omission of -# is already visible: rtk -v mysql '-#d:t:o,/tmp/trace' -uroot -e q prints mysql -#d:t:o,/tmp*** …, the scan having walked into the debug spec and stopped at the p in /tmp.
  • the module header states credentials are "never persisted", but only the auth flags are scrubbed — the -e argument is stored verbatim, so rtk mysql -e "ALTER USER 'a'@'%' IDENTIFIED BY 'newpass'" writes newpass into the tracking DB permanently.

One consequence to be explicit about: without redaction, rtk mysql -psecret persists the password in the tracking DB and prints it under -v. That is what rtk psql does today, so it is consistent — flagging it so it is a decision rather than a side effect.

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.

5 participants