Living recordslearning:stateful-regex-api-boundaries
tracepublicschema v1

Stateful regular expressions are API boundaries

A RegExp can look like a predicate while carrying mutable caller-owned state between calls.

JavaScriptshared stateAPI design

Current explanation

Global and sticky JavaScript regular expressions mutate lastIndex. A helper that repeatedly calls test() can therefore return different answers for the same input and can alter an object the caller still owns. The narrow repair is to reset state only for stateful expressions and restore the caller value in finally, including throw paths.

Lesson path

  1. 01

    Observe

    complete

    Run the same global expression twice and record lastIndex.

  2. 02

    Repair

    current

    Preserve deterministic evaluation without changing ordinary regex behavior.

  3. 03

    Separate cases

    next

    Cover mismatch, nonzero state, throw, and frozen ordinary expressions.

Open questions

  • Who owns mutable matcher state when a RegExp crosses an API boundary?

Selected Q&A

Why restore in finally?

Because a custom execution path can throw after mutating state. Caller ownership must survive success and failure.

Owner-selected excerpt · raw transcript stays private

Next actions

  • Trace one sticky-expression mismatch by hand.
  • Compare a cloned RegExp with save-and-restore semantics.

Sources

Revision trail

  1. · learning:stateful-regex-api-boundaries@r2

    Separated caller ownership from matcher convenience.

  2. · learning:stateful-regex-api-boundaries@r1

    Recorded the state leak and deterministic repair.