FFFF Strip ANSI with Nix's own filter, not a third-party regex · Issue #74 · nixidae/nixidae · GitHub
[go: up one dir, main page]

Skip to content

Strip ANSI with Nix's own filter, not a third-party regex #74

Closed

Description

@Lillecarl

TL;DR

nanopynix strips ANSI escape codes out of Nix messages with strip-ansi, a
third-party module of six lines whose regex is narrower than its own docstring
claims. Nix ships the correct function for this job, nix::filterANSIEscapes,
in a library nanopynix already links. Binding it removes a Python dependency
and replaces a regex with the parser that matches the producer by construction.

The regex is sufficient today, so this is not a defect report. It is a
dependency that has a better replacement inside the door nanopynix already
opens.

Where the stripping happens

Eight call sites, all on the path a caller reads an error message on:

  • nanopynix/exceptions.py -- _trace_lines, NixError.msg, NixError.raw,
    the ListIndexError index parser, and the classifier at line 733
  • nanopynix/models.py -- LogEvent.message and LogEvent.args
  • nanopynix/stores.py -- the store-URI ValueError

Why a setting cannot remove the need

NO_COLOR, --no-color and nix::shouldANSI() do not reach these strings.
Nix colours the interpolated arguments of a HintFmt when it builds the
message, not when it prints one. From src/libutil/include/nix/util/fmt.hh:

template<class T>
std::ostream & operator<<(std::ostream & out, const Magenta<T> & y)
{
    return out << ANSI_WARNING << y.value << ANSI_NORMAL;
}

No shouldANSI() guard, and the class comment says so outright: "By default,
arguments to HintFmt are printed in magenta." The escapes are inside
ErrorInfo::msg before any logger sees it. So nanopynix receives them whatever
the terminal settings are, and stripping is the only option. This forecloses
the "turn colour off at the source" answer, which is the one this repository
would normally reach for first.

What the current dependency is

strip_ansi is one function and one pattern:

pattern = re.compile(r'\x1B\[\d+(;\d+){0,2}m')

SGR only, at most three parameters. Its docstring says it removes sequences
"as defined by ECMA-048", and it does not -- the commented-out line above the
pattern is the general one, and it is not the one that runs.

That is sufficient for Nix today. src/libutil/include/nix/util/ansicolor.hh
defines the complete set Nix can emit, and every one is SGR with at most two
parameters:

ANSI_NORMAL "\e[0m"     ANSI_RED     "\e[31;1m"   ANSI_MAGENTA "\e[35;1m"
ANSI_BOLD   "\e[1m"     ANSI_GREEN   "\e[32;1m"   ANSI_CYAN    "\e[36;1m"
ANSI_FAINT  "\e[2m"     ANSI_WARNING "\e[35;1m"
ANSI_ITALIC "\e[3m"     ANSI_BLUE    "\e[34;1m"

The exposure is that nothing pins this. A future macro with a 24-bit colour
(\e[38;2;R;G;Bm, five parameters) passes straight through the regex and lands
in an error message, and no test fails.

Nix already ships the right function

src/libutil/include/nix/util/terminal.hh:

std::string filterANSIEscapes(
    std::string_view s, bool filterAll = false,
    unsigned int width = std::numeric_limits<unsigned int>::max());

Present at the same path in 2.31, 2.34 and 2.35, so it needs no version gate.
The implementation is a real parser, not a pattern: it walks CSI parameter,
intermediate and final bytes, handles OSC with both the ESC \ and the BEL
terminator, and handles the other Fe sequences. filterAll=true removes all of
them.

It is the correct choice for one reason above the others: it is the same code
that Nix's own nix CLI uses on the same strings. It cannot drift from the
producer, because it ships with the producer.

Measured, against the alternatives

The candidates were rich and prompt-toolkit, which are already dependencies
of pynix, and pyte. Run on Nix-shaped input:

input strip_ansi rich prompt_toolkit
\e[31;1mfoo\e[0m 'foo' 'foo' 'foo'
\e[38;2;255;0;0mfoo\e[0m '\x1b[38;2;255;0;0mfoo' 'foo' 'foo'
\e]8;;https://x\afoo\e]8;;\a unchanged '8;;https://xfoo8;;' '8;;https://x\x07foo8;;\x07'
a\tb\rc 'a\tb\rc' 'c' 'a\tb\rc'

Three findings:

  • None of the three handles OSC. rich and prompt_toolkit strip the
    ESC ] and leave the payload as text. filterANSIEscapes has an explicit
    OSC branch.
  • rich destroys carriage returns. Text.from_ansi treats \r as a real
    carriage return and overwrites the line, so 'a\tb\rc' becomes 'c'. On a
    multi-line Nix trace that silently deletes text. rich is disqualified.
  • pyte was not measured, because it is the wrong tool. It is a terminal
    emulator that renders into a fixed screen buffer, 80x24 by default, so a long
    error message comes back wrapped and truncated.

rich and prompt-toolkit are also the wrong direction on dependencies. Both
belong to pynix, the CLI. strip-ansi belongs to nanopynix, the library.
Moving the library onto either one would grow the runtime dependency set of the
thing consumers embed, to replace a module with no transitive dependencies.

What is not yet known

  • filterANSIEscapes is not a pure strip. It also expands each tab to the
    next multiple of eight spaces, and drops \r and \a. Every assertion on
    exact message text has to be checked against that, and any that changes is a
    behaviour change to state, not to absorb quietly.
  • The cost per call is not measured. These eight call sites run on every
    error a caller reads, and two of them are properties. Whether a nanobind
    round trip beats a compiled re.sub on a short string is an open question,
    and the answer decides whether the binding is worth taking.
  • Whether the binding belongs on nanopynix_bindings.util beside
    install_logger, or somewhere narrower.

Acceptance criteria

  1. nanopynix no longer depends on strip-ansi, or a test pins the exact set
    of sequences ansicolor.hh defines against whatever does the stripping, so
    a sequence Nix adds later fails a test rather than reaching a caller.
  2. If the binding lands: it is exercised on all three supported Nix versions,
    and the tab, \r and \a behaviour is stated where a reader of the
    stripped text will meet it.
  3. The measurement above is either confirmed or corrected in a comment, so the
    next person does not repeat it.

Activity

  1. Lillecarl commented on Aug 3, 2026

    @Lillecarl
    ContributorAuthor

    The measurement, confirmed and extended

    Criterion 3 asks for this. Re-run in the dev shell on 2026-08-03, with the
    binding as a fourth column. old is the strip-ansi pattern,
    \x1B\[\d+(;\d+){0,2}m.

    input old rich prompt_toolkit Nix
    ESC[31;1mfoo ESC[0m foo foo foo foo
    ESC[38;2;255;0;0mfoo ESC[0m \x1b[38;2;255;0;0mfoo foo foo foo
    ESC]8;;https://x BEL foo ESC]8;; BEL unchanged 8;;https://xfoo8;; 8;;https://x\x07foo8;;\x07 foo
    a\tb\rc a\tb\rc c a\tb\rc a bc
    ESC[2Kgone \x1b[2Kgone gone gone gone

    Every row of the original table reproduces. Two additions:

    • The fifth row was not in the original table. A sequence that does not end in
      m is the third shape the package missed, and rich and
      prompt_toolkit both handle it. The package was alone in keeping it.
    • filterANSIEscapes is the only one of the four that removes an OSC 8
      hyperlink. The finding "none of the three handles OSC" stands, and Nix
      makes four.

    The cost per call: the open question is answered, and the answer is the

    opposite of the concern

    "Whether a nanobind round trip beats a compiled re.sub on a short string"
    — it does, on every input that carries an escape sequence. 20000 iterations
    each, microseconds per call:

    input re.sub Nix boundary floor ratio
    one coloured error line (97 bytes) 1.56 1.01 0.11 0.65x
    a 40-frame trace (3919 bytes) 50.86 31.13 0.11 0.61x
    plain text, no escape (24 bytes) 0.19 0.47 0.12 2.51x

    The regex wins only when there is nothing to remove, where re.sub returns
    the input without building a new string. That costs 0.28 us on a path that
    runs once per message a caller reads. The nanobind boundary itself is 0.11 us,
    so the C++ filter does the same work in a third of the time of the compiled
    pattern.

    Status

    All three criteria are met, so this closes.

    1. nanopynix no longer depends on strip-ansi (a167255a).
    2. The binding is exercised on 2.31, 2.34, 2.35 and git — TestFilterAnsiEscapes
      in tests/nanopynix/bindings/test_util_bindings.py, green on all four in CI.
      The tab, \r and \a behaviour is stated on nanopynix.strip_ansi,
      which autodoc renders, and each of the four *_without_ansi accessors
      points at it (8f9e82cd).
    3. This comment.

    The three follow-ups this work exposed are on #77: one filter everywhere with
    a machine check (landed, 643d70e3), PyLogger::logEI dropping the position
    and the trace, and the 27% of the error trailer budget that escape bytes take.

  2. added
    source: nanopynix
    on Oct 19, 2026
  3. added theissue type on Oct 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    source: nanopynix

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      0