capre: a length check, not an unrolled repeat, holds nine patterns

Go's regexp unrolls a bounded repeat into that many copies of its
class: [A-Za-z0-9.-]{0,254} (the session terminal's bundle id) was
89kB of program, kept from start to exit, and Codex's item-id refusal
`.{0,1000}?` 88kB. Measured one by one over magpie's 540 package-level
patterns (1.5MB in all), the nine largest bounded ones were ~440kB.

capre.MustCompile(expr, max) is the pattern with * or +, matching only
a string of max characters at most (rune count, so the (?i) Kelvin
sign and invalid bytes count as the regexp counted them). The nine:
settings' bundle id, library's name and agent id (now name@wsl:distro
cut in two), Anthropic tool names, the trace page's name and find,
access's MCP server, OpenClaw's profile and Codex's provider id. The
item-id refusal is a function: the tail within 1000 characters of a
head.

Run on mote (go1.26.8):
- go test ./internal/capre ./internal/access ./internal/settings
  ./internal/library ./internal/sessions ./internal/agent ./internal/gui
  . : ok; ./internal/gateway -run 'ItemID|Undeclared|ToolName|Refus': ok
- TestCappedMatchesBounded holds each old pattern against its new one
  over 14 units x 19 lengths (0..300, at each bound +-1); with the
  length check taken out it is red (1586 mismatches).
  TestItemIDRefusalAsTheRegexp holds the function against the old
  regexp at 998..1002 characters of x, é, 日, \xff, \n; with 1001 it is
  red. TestCappedIsSmall: 1304 bytes held, 49680 bounded.
- go vet native, GOOS=linux and GOOS=windows over the touched packages
  (gui natively: its Linux build needs cgo); gofmt -l clean.
- Real build, GODEBUG=inittrace=1: magpie's own inits allocate
  11.93MB -> 10.61MB.
- Idle on the real-account copy, 180s heap: regexp programs (sampled)
  4.54MB -> 3.01MB.

Not tried: the full ./... suite; the gateway package beyond the run
above.
This commit is contained in:
yetone
2026-11-09 21:47:24 +08:00
parent ffbc45eac5
commit dae104bfac
12 changed files with 163 additions and 19 deletions
+3 -2
View File
@@ -2,9 +2,10 @@ package access
import (
"errors"
"regexp"
"slices"
"strings"
"github.com/yetone/magpie/internal/capre"
)
// A key's MCP list (Key.MCP, wakaka on Discord) holds it to some of the
@@ -20,7 +21,7 @@ const NoMCP = "-"
// mcpServerRe is a server's name as the Library takes one (library's
// nameRe), and as magpie names its own servers.
var mcpServerRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$`)
var mcpServerRe = capre.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]*$`, 64)
// CleanMCP is a key's MCP list as it is kept: each entry trimmed and
// checked, told apart in no other way than as written, a tool dropped
+2 -2
View File
@@ -45,13 +45,13 @@ import (
"fmt"
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"github.com/tidwall/gjson"
"github.com/tidwall/jsonc"
"github.com/yetone/magpie/internal/capre"
"github.com/yetone/magpie/internal/edit"
)
@@ -72,7 +72,7 @@ const (
)
// openClawProfile is a profile name OpenClaw takes (profile-utils.ts).
var openClawProfile = regexp.MustCompile(`(?i)^[a-z0-9][a-z0-9_-]{0,63}$`)
var openClawProfile = capre.MustCompile(`(?i)^[a-z0-9][a-z0-9_-]*$`, 64)
// openClawHome is OpenClaw's ~: $OPENCLAW_HOME, a leading ~ in it the
// system's home (resolveEffectiveHomeDir).
+30
View File
@@ -0,0 +1,30 @@
// Package capre is a regular expression held to a length.
//
// Go's regexp unrolls a bounded repeat: [A-Za-z0-9.-]{0,254} is 254
// copies of the class, 89kB of program kept from start to exit for
// one settings check. The same class with * is a few states, and the
// bound is a length check. A pattern here is whole-string (^…$), every
// character of it of the repeated classes, so the length is its count
// of characters.
package capre
import (
"regexp"
"unicode/utf8"
)
type Regexp struct {
re *regexp.Regexp
max int
}
// MustCompile is expr, unbounded, matching only a string of max
// characters at most.
func MustCompile(expr string, max int) *Regexp {
return &Regexp{regexp.MustCompile(expr), max}
}
// MatchString is whether s, of max characters at most, matches.
func (r *Regexp) MatchString(s string) bool {
return (len(s) <= r.max || utf8.RuneCountInString(s) <= r.max) && r.re.MatchString(s)
}
+62
View File
@@ -0,0 +1,62 @@
package capre
import (
"regexp"
"runtime"
"strings"
"testing"
)
// The bounded patterns magpie had, each beside what replaced it.
var pairs = []struct {
bounded, open string
max int
}{
{`^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$`, `^[A-Za-z0-9][A-Za-z0-9.-]*$`, 255},
{`^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$`, `^[A-Za-z0-9][A-Za-z0-9_-]*$`, 64},
{`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`, `^[A-Za-z0-9][A-Za-z0-9._-]*$`, 64},
{`^[a-zA-Z0-9_-]{1,128}$`, `^[a-zA-Z0-9_-]+$`, 128},
{`^[A-Za-z0-9._@:/ -]{1,80}$`, `^[A-Za-z0-9._@:/ -]+$`, 80},
{`^[^\x00-\x1f\x7f]{0,100}$`, `^[^\x00-\x1f\x7f]*$`, 100},
{`(?i)^[a-z0-9][a-z0-9_-]{0,63}$`, `(?i)^[a-z0-9][a-z0-9_-]*$`, 64},
{`^[0-9A-Za-z_.-]{1,64}$`, `^[0-9A-Za-z_.-]{1,}$`, 64},
}
func TestCappedMatchesBounded(t *testing.T) {
var in []string
for _, unit := range []string{"a", "Z", "9", "-", ".", "_", " ", "é", "K", "ſ", "\x00", "\xff", "@", "日"} {
for _, n := range []int{0, 1, 2, 63, 64, 65, 79, 80, 81, 99, 100, 101, 127, 128, 129, 254, 255, 256, 300} {
in = append(in, strings.Repeat(unit, n), "a"+strings.Repeat(unit, n), strings.Repeat(unit, n)+"a")
}
}
for _, p := range pairs {
want, got := regexp.MustCompile(p.bounded), MustCompile(p.open, p.max)
for _, s := range in {
if w, g := want.MatchString(s), got.MatchString(s); w != g {
t.Errorf("%s on %d bytes of %q: %v, want %v", p.open, len(s), s[:min(len(s), 4)], g, w)
}
}
}
}
// TestCappedIsSmall: the reason for the package. A program of the
// bounded class is tens of kB; held to a length it is a fraction of one.
func TestCappedIsSmall(t *testing.T) {
heap := func(f func() any) int64 {
var a, b runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&a)
v := f()
runtime.GC()
runtime.ReadMemStats(&b)
runtime.KeepAlive(v)
return max(0, int64(b.HeapAlloc)-int64(a.HeapAlloc))
}
p := pairs[0]
bounded := heap(func() any { return regexp.MustCompile(p.bounded) })
capped := heap(func() any { return MustCompile(p.open, p.max) })
if capped*10 > bounded {
t.Fatalf("held to a length: %d bytes, bounded %d", capped, bounded)
}
t.Logf("held to a length: %d bytes, bounded %d", capped, bounded)
}
+19 -1
View File
@@ -19,6 +19,7 @@ import (
"sync"
"sync/atomic"
"time"
"unicode/utf8"
"github.com/tidwall/gjson"
@@ -3099,7 +3100,24 @@ func callItemIDs(body []byte) []byte {
// "Invalid 'input[1].id': 'rs_6aca2fc7533c979d5f0e4f7a:rs_01a125caa544754e9a3c70080100b009'.
// Expected an ID that contains letters, numbers, underscores, or dashes,
// but this value contained additional characters."
var itemIDRefusal = regexp.MustCompile(`(?s)Invalid 'input\[\d+\]\.id'.{0,1000}?Expected an ID that contains letters, numbers, underscores, or dashes`)
// It is the tail within 1000 characters of the head: the regexp
// .{0,1000}? it was unrolled to 88kB of program, held from start to exit.
func itemIDRefusal(b []byte) bool {
const tail = "Expected an ID that contains letters, numbers, underscores, or dashes"
for _, at := range itemIDRefusalHead.FindAllIndex(b, -1) {
rest, end := b[at[1]:], 0
for n := 0; n < 1000 && end < len(rest); n++ {
_, w := utf8.DecodeRune(rest[end:])
end += w
}
if bytes.Contains(rest[:min(len(rest), end+len(tail))], []byte(tail)) {
return true
}
}
return false
}
var itemIDRefusalHead = regexp.MustCompile(`Invalid 'input\[\d+\]\.id'`)
// itemIDsRefused is how unfit remembers a provider turning away, for
// model, an input item id with another character in it (plainItemIDs).
+1 -1
View File
@@ -6756,7 +6756,7 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
continue
}
}
if len(fs) == 0 && len(ms) == 0 && proto == provider.Responses && itemIDRefusal.Match(b) {
if len(fs) == 0 && len(ms) == 0 && proto == provider.Responses && itemIDRefusal(b) {
// and an input item's id with a character OpenAI's don't
// have, which a relay in front of OpenAI turns away as it
// does (echo_ts): asked once more with ids it takes, and so
+30
View File
@@ -0,0 +1,30 @@
package gateway
import (
"regexp"
"strings"
"testing"
)
// TestItemIDRefusalAsTheRegexp: the hand-made match finds what the
// regexp it replaced found, at the 1000-character edge too.
func TestItemIDRefusalAsTheRegexp(t *testing.T) {
was := regexp.MustCompile(`(?s)Invalid 'input\[\d+\]\.id'.{0,1000}?Expected an ID that contains letters, numbers, underscores, or dashes`)
const head, tail = "Invalid 'input[12].id'", "Expected an ID that contains letters, numbers, underscores, or dashes"
in := []string{
`{"error":{"message":"Invalid 'input[1].id': 'rs_6aca2fc7533c979d5f0e4f7a:rs_01a1'.\nExpected an ID that contains letters, numbers, underscores, or dashes, but this value contained additional characters."}}`,
"", head, tail, tail + head, head + tail, "Invalid 'input[].id'" + tail,
head + strings.Repeat("x", 2000) + head + "." + tail,
head + "Expected an ID" + strings.Repeat(" ", 900) + tail,
}
for _, unit := range []string{"x", "é", "日", "\xff", "\n"} {
for _, n := range []int{998, 999, 1000, 1001, 1002} {
in = append(in, head+strings.Repeat(unit, n)+tail, head+strings.Repeat(unit, n)+tail[:20])
}
}
for _, s := range in {
if w, g := was.MatchString(s), itemIDRefusal([]byte(s)); w != g {
t.Errorf("%d bytes: %v, want %v", len(s), g, w)
}
}
}
+2 -1
View File
@@ -5,6 +5,7 @@ import (
"encoding/json"
"regexp"
"github.com/yetone/magpie/internal/capre"
"github.com/yetone/magpie/internal/provider"
)
@@ -35,7 +36,7 @@ const historyToolsRefused = "tools[].history"
const stubToolDescription = "Called earlier in this conversation; not available now."
// anthropicToolName is a name Anthropic takes for a tool.
var anthropicToolName = regexp.MustCompile(`^[a-zA-Z0-9_-]{1,128}$`)
var anthropicToolName = capre.MustCompile(`^[a-zA-Z0-9_-]+$`, 128)
// toolsMissing is an upstream refusing tool calls in a request with no
// tools: Anthropic's "must define tools", Bedrock's "The toolConfig field
+3 -3
View File
@@ -4,13 +4,13 @@ import (
"encoding/json"
"net/http"
"net/url"
"regexp"
"slices"
"strconv"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/capre"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/sessions"
@@ -346,10 +346,10 @@ func mainView(q url.Values) string {
}
// mainName is the id of a provider or an agent.
var mainName = regexp.MustCompile(`^[A-Za-z0-9._@:/ -]{1,80}$`)
var mainName = capre.MustCompile(`^[A-Za-z0-9._@:/ -]+$`, 80)
// mainFind is a line of text to look for, as a search field holds one.
var mainFind = regexp.MustCompile(`^[^\x00-\x1f\x7f]{0,100}$`)
var mainFind = capre.MustCompile(`^[^\x00-\x1f\x7f]*$`, 100)
// mainURL is the window's page for a view as mainView gives it, the
// request's id kept as its own parameter (the panel's link to one request,
+7 -6
View File
@@ -9,12 +9,12 @@ import (
"encoding/json"
"fmt"
"path/filepath"
"regexp"
"slices"
"sort"
"strings"
"sync"
"github.com/yetone/magpie/internal/capre"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/settings"
)
@@ -276,7 +276,7 @@ func (l *Library) skill(name string) *Skill {
// A name is what a server or a skill is called in every agent's file, and
// a skill's folder: it has to be a bare key in TOML and a plain file name.
var nameRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$`)
var nameRe = capre.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]*$`, 64)
func checkName(kind, name string) error {
if !nameRe.MatchString(name) {
@@ -285,12 +285,13 @@ func checkName(kind, name string) error {
return nil
}
// agentRe is an agent's id: a name, or one in a WSL distro's
// (codex@wsl:Ubuntu-24.04).
var agentRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]{0,63}(@wsl:[A-Za-z0-9][A-Za-z0-9._-]{0,63})?$`)
// An agent's id is a name, or one in a WSL distro's
// (codex@wsl:Ubuntu-24.04): distroRe is the distro's name.
var distroRe = capre.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`, 64)
func checkAgent(id string) error {
if !agentRe.MatchString(id) {
name, distro, wsl := strings.Cut(id, "@wsl:")
if !nameRe.MatchString(name) || wsl && !distroRe.MatchString(distro) {
return fmt.Errorf("agent %q: not an agent's id", id)
}
return nil
+2 -2
View File
@@ -12,7 +12,6 @@ import (
"net/url"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
@@ -23,6 +22,7 @@ import (
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/capre"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/filelock"
"github.com/yetone/magpie/internal/filememo"
@@ -42,7 +42,7 @@ import (
// codexProviderRe is what a provider id may be: a key of config.toml's
// [model_providers], or a built-in one.
var codexProviderRe = regexp.MustCompile(`^[0-9A-Za-z_.-]{1,64}$`)
var codexProviderRe = capre.MustCompile(`^[0-9A-Za-z_.-]+$`, 64)
// CodexMove is one session moved to another provider.
type CodexMove struct {
+2 -1
View File
@@ -26,6 +26,7 @@ import (
"time"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/capre"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/filememo"
@@ -1308,7 +1309,7 @@ var DefaultTextSize = func() int {
return 100
}
var validTerminalBundleID = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$`)
var validTerminalBundleID = capre.MustCompile(`^[A-Za-z0-9][A-Za-z0-9.-]*$`, 255)
// providerID is how a provider's id is spelled: lower-case letters, digits
// and dashes, as provider.Slug derives it (a custom provider's id is the