diff --git a/internal/gateway/embeddings_guard_test.go b/internal/gateway/embeddings_guard_test.go new file mode 100644 index 000000000..04ecf12a5 --- /dev/null +++ b/internal/gateway/embeddings_guard_test.go @@ -0,0 +1,76 @@ +package gateway + +import ( + "io" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/appdir" + "github.com/yetone/magpie/internal/pii" + "github.com/yetone/magpie/internal/settings" +) + +// #4553 (SunnyRx, Windows): with AstrLink Guard masking requests, an +// embeddings input with a stray byte (the reporter's body, a lone 0xff) +// panicked in the model's tokenizer, on the model's own goroutine, and +// magpie exited with code 2. The real model reads it now, the vendor gets +// the request, and the next request is served. It needs the model's +// files, in MAGPIE_GUARD_DIR, as internal/pii/guard's tests do. +func TestEmbeddingsWithAStrayByteUnderAstrLinkGuard(t *testing.T) { + src := os.Getenv("MAGPIE_GUARD_DIR") + if src == "" { + t.Skip("MAGPIE_GUARD_DIR is not set") + } + s, l := shelved(t) + // where pii looks for the pinned revision's files + dst := filepath.Join(appdir.Cache(), "astrlink-guard", "7216b6a3b897") + if err := os.MkdirAll(dst, 0o755); err != nil { + t.Fatal(err) + } + for _, f := range []string{"model_int8.onnx", "model_int8.onnx_data", "tokenizer.json"} { + copyFile(t, filepath.Join(src, f), filepath.Join(dst, f)) + } + g := pii.Of(pii.AstrLinkGuard) + if !g.Installed() { + t.Fatalf("the model isn't installed from %s: the pinned revision moved, and this test's folder with it", dst) + } + t.Cleanup(g.Stop) + if err := settings.Save(settings.Settings{Redact: true, RedactPersonal: true, RedactModel: true, RedactModelName: pii.AstrLinkGuard}); err != nil { + t.Fatal(err) + } + body := `{"model":"lib/embed-1","input":["hello ` + string([]byte{0xff}) + `","world"]}` + if code, raw := postRetrieval(t, s, "/v1/embeddings", body); code != 200 { + t.Fatalf("%d %s", code, raw) + } + if code, raw := postRetrieval(t, s, "/v1/embeddings", `{"model":"lib/embed-1","input":["call 13800138000","world"]}`); code != 200 { + t.Fatalf("the next request: %d %s", code, raw) + } + sent := l.got("/v1/embeddings") + if len(sent) != 2 || !strings.Contains(sent[0], "hello") || strings.Contains(sent[1], "13800138000") { + t.Fatalf("vendor was sent %q", sent) + } + if st := g.Now(); !st.Running { + t.Fatalf("the model didn't read the requests: %+v", st) + } +} + +func copyFile(t *testing.T, from, to string) { + t.Helper() + in, err := os.Open(from) + if err != nil { + t.Fatal(err) + } + defer in.Close() + out, err := os.Create(to) + if err != nil { + t.Fatal(err) + } + if _, err := io.Copy(out, in); err != nil { + t.Fatal(err) + } + if err := out.Close(); err != nil { + t.Fatal(err) + } +} diff --git a/internal/pii/guard/guard_test.go b/internal/pii/guard/guard_test.go index e08270434..d063488df 100644 --- a/internal/pii/guard/guard_test.go +++ b/internal/pii/guard/guard_test.go @@ -114,6 +114,39 @@ func TestModelFinds(t *testing.T) { } } +// The model reads text that isn't valid UTF-8, as an embeddings input +// with a stray byte came to it (#4553: "hello \xff" panicked in the +// tokenizer and ended magpie), and finds in the valid text around it +// what it finds without the byte, with every span inside the text. +func TestModelFindsAroundMalformedBytes(t *testing.T) { + m, err := Load(dir(t)) + if err != nil { + t.Fatal(err) + } + m.ml = nil + for _, text := range []string{ + "hello \xff", "\xff", "\xc3", "\xed\xa0\x80", "\xf0\x9f", + "联系人:张三\xff,电话 13800138000\xc3。", + } { + have := map[string]string{} + phone := false + for _, s := range m.Find(text) { + if s.Start < 0 || s.End > len(text) || s.Start >= s.End { + t.Fatalf("Find(%q): span %+v is out of the text", text, s) + } + if s.Score >= MinScore { + have[text[s.Start:s.End]] = s.Label + // a stray byte against the number is a character of its + // word, so the span may take it too + phone = phone || s.Label == "phone" && strings.Contains(text[s.Start:s.End], "13800138000") + } + } + if strings.Contains(text, "13800138000") && !phone { + t.Errorf("Find(%q) = %v, want the phone number", text, have) + } + } +} + // TestWindowsAtOnceReadAsOneByOne: a text of many windows, read with its // windows at once, finds what it does read a window at a time. func TestWindowsAtOnceReadAsOneByOne(t *testing.T) { diff --git a/internal/pii/guard/tokenizer.go b/internal/pii/guard/tokenizer.go index 3465d4e1e..1f83ebaa4 100644 --- a/internal/pii/guard/tokenizer.go +++ b/internal/pii/guard/tokenizer.go @@ -241,10 +241,14 @@ func (t *tokenizer) normalize(text string, base int) []nchar { out := make([]nchar, 0, len(text)) add := func(part string, at int, to string) { // the first characters of to are the first of part's, in turn; - // any more are put after the last + // any more are put after the last. Step by the decoded width: a + // malformed byte comes out as RuneError but takes up one byte, + // not utf8.RuneLen(RuneError)'s three. var orig [][2]int - for i, r := range part { - orig = append(orig, [2]int{base + at + i, base + at + i + utf8.RuneLen(r)}) + for i := 0; i < len(part); { + _, size := utf8.DecodeRuneInString(part[i:]) + orig = append(orig, [2]int{base + at + i, base + at + i + size}) + i += size } k := 0 for _, r := range to { @@ -262,13 +266,15 @@ func (t *tokenizer) normalize(text string, base int) []nchar { continue } } - for i, r := range gr { - part := gr[i : i+utf8.RuneLen(r)] + for i := 0; i < len(gr); { + r, size := utf8.DecodeRuneInString(gr[i:]) + part := gr[i : i+size] if to, ok := t.transform(part); ok { add(part, at+i, to) } else { out = append(out, nchar{r, base + at + i, base + at + i + len(part)}) } + i += size } } return out diff --git a/internal/pii/guard/tokenizer_test.go b/internal/pii/guard/tokenizer_test.go new file mode 100644 index 000000000..afe2b7b05 --- /dev/null +++ b/internal/pii/guard/tokenizer_test.go @@ -0,0 +1,80 @@ +package guard + +import ( + "reflect" + "testing" + "unicode/utf8" +) + +// A malformed byte decodes to RuneError but consumes one byte, not +// utf8.RuneLen(RuneError)'s three: normalize must step by the decoded +// width, or it both misreports what the text came from and slices past +// the end of a short grapheme (a panic, through Find, in the model's +// worker goroutine). +func TestNormalizeMalformedBytes(t *testing.T) { + tk := &tokenizer{} + for _, c := range []struct { + text string + want []nchar + }{ + {"\xff", []nchar{{utf8.RuneError, 0, 1}}}, + {"\xc3", []nchar{{utf8.RuneError, 0, 1}}}, + {"\xed\xa0\x80", []nchar{ + {utf8.RuneError, 0, 1}, {utf8.RuneError, 1, 2}, {utf8.RuneError, 2, 3}, + }}, + {"hi\xffthere", []nchar{ + {'h', 0, 1}, {'i', 1, 2}, {utf8.RuneError, 2, 3}, + {'t', 3, 4}, {'h', 4, 5}, {'e', 5, 6}, {'r', 6, 7}, {'e', 7, 8}, + }}, + {"\xf0\x9f", []nchar{{utf8.RuneError, 0, 1}, {utf8.RuneError, 1, 2}}}, + // #4553's embeddings input, a lone 0xff after a word and a space + {"hello \xff", []nchar{ + {'h', 0, 1}, {'e', 1, 2}, {'l', 2, 3}, {'l', 3, 4}, {'o', 4, 5}, + {' ', 5, 6}, {utf8.RuneError, 6, 7}, + }}, + // a properly encoded U+FFFD keeps its three bytes + {"\uFFFD", []nchar{{utf8.RuneError, 0, 3}}}, + // valid text is unchanged + {"aéb", []nchar{{'a', 0, 1}, {'é', 1, 3}, {'b', 3, 4}}}, + } { + got := tk.normalize(c.text, 0) + if !reflect.DeepEqual(got, c.want) { + t.Errorf("normalize(%q) = %v, want %v", c.text, got, c.want) + } + for _, nc := range got { + if nc.s < 0 || nc.e > len(c.text) || nc.s >= nc.e { + t.Errorf("normalize(%q): offset [%d, %d) is out of the text", c.text, nc.s, nc.e) + } + } + } + // encode, the path Find runs, for one malformed byte gives one token + // over that byte + if got := tk.encode("\xff"); !reflect.DeepEqual(got, []token{{0, 0, 1}}) { + t.Errorf("encode(\"\\xff\") = %v, want [{0 0 1}]", got) + } + for _, tok := range tk.encode("hello \xff") { + if tok.start < 0 || tok.end > len("hello \xff") { + t.Errorf("encode(\"hello \\xff\"): token [%d, %d) is out of the text", tok.start, tok.end) + } + } +} + +// A charsmap can map the malformed byte itself: add must then give its +// output the byte's one-byte span as where it came from. +func TestNormalizeMappedMalformedByte(t *testing.T) { + tk := &tokenizer{trie: make([]uint32, 0x100), norm: []byte{'X', 0}} + // the double-array cell for the byte 0xff: its check byte, a value, + // and the offset landing the walk on the value at norm[0] + tk.trie[0xff] = 0x3F800 | 0x100 | 0xFF + for _, c := range []struct { + text string + want []nchar + }{ + {"\xff", []nchar{{'X', 0, 1}}}, + {"\xff\xff a", []nchar{{'X', 0, 1}, {'X', 1, 2}, {' ', 2, 3}, {'a', 3, 4}}}, + } { + if got := tk.normalize(c.text, 0); !reflect.DeepEqual(got, c.want) { + t.Errorf("normalize(%q) = %v, want %v", c.text, got, c.want) + } + } +}