Debian Codegraph @

benchmarks/payload_test.go

raw
1 package benchmark
2
3 import (
4 "bytes"
5 stdjson "encoding/json"
6 "fmt"
7 "strings"
8 "time"
9 "unicode/utf8"
10 )
11
12 // The payloads of the benchmarks of the APIs ( decode_github_test.go, llm_api_test.go ) are generated when the
13 // benchmarks start, instead of being files of the repository: their keys, the order of the keys, their types
14 // and nulls are the ones of the APIs, and their values are made by a generator of a fixed seed, so that they are
15 // the same at every run and at every commit which a benchmark compares. The texts have the lengths, the escapes
16 // and the characters which are not ASCII of the ones of the APIs: markdown, Go source code and messages.
17
18 // payloadRand is a generator of pseudo-random numbers ( SplitMix64 ), whose sequence is fixed by its seed.
19 type payloadRand struct {
20 state uint64
21 }
22
23 func newPayloadRand(seed uint64) *payloadRand {
24 return &payloadRand{state: seed}
25 }
26
27 func (r *payloadRand) next() uint64 {
28 r.state += 0x9e3779b97f4a7c15
29 z := r.state
30 z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9
31 z = (z ^ (z >> 27)) * 0x94d049bb133111eb
32 return z ^ (z >> 31)
33 }
34
35 // intn returns a number in [0, n).
36 func (r *payloadRand) intn(n int) int {
37 return int(r.next() % uint64(n))
38 }
39
40 // between returns a number in [min, max].
41 func (r *payloadRand) between(min, max int) int {
42 return min + r.intn(max-min+1)
43 }
44
45 // chance is true once in n.
46 func (r *payloadRand) chance(n int) bool {
47 return r.intn(n) == 0
48 }
49
50 func (r *payloadRand) pick(words []string) string {
51 return words[r.intn(len(words))]
52 }
53
54 // token returns n characters of the alphabet, as the identifiers, the signatures and the cursors of the APIs.
55 func (r *payloadRand) token(alphabet string, n int) string {
56 b := make([]byte, n)
57 for i := range b {
58 b[i] = alphabet[r.intn(len(alphabet))]
59 }
60 return string(b)
61 }
62
63 const (
64 alphanumeric = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
65 base64URL = alphanumeric + "-_"
66 hexDigits = "0123456789abcdef"
67 )
68
69 // object is a JSON object whose keys are in their order, as the APIs write them.
70 type object []field
71
72 type field struct {
73 key string
74 value any
75 }
76
77 func (o object) MarshalJSON() ([]byte, error) {
78 var b bytes.Buffer
79 b.WriteByte('{')
80 for i, f := range o {
81 if i > 0 {
82 b.WriteByte(',')
83 }
84 b.Write(encodePayload(f.key))
85 b.WriteByte(':')
86 b.Write(encodePayload(f.value))
87 }
88 b.WriteByte('}')
89 return b.Bytes(), nil
90 }
91
92 // encodePayload encodes the value as the APIs do: '<', '>' and '&' are not escaped.
93 func encodePayload(v any) []byte {
94 var b bytes.Buffer
95 enc := stdjson.NewEncoder(&b)
96 enc.SetEscapeHTML(false)
97 if err := enc.Encode(v); err != nil {
98 panic(err)
99 }
100 return bytes.TrimSuffix(b.Bytes(), []byte("\n"))
101 }
102
103 // jsonLines encodes the events of a stream, one JSON document each.
104 func jsonLines(events []object) [][]byte {
105 lines := make([][]byte, len(events))
106 for i, e := range events {
107 lines[i] = encodePayload(e)
108 }
109 return lines
110 }
111
112 // timestamp is the time of the APIs, in RFC 3339 and UTC.
113 func timestamp(t time.Time) string {
114 return t.UTC().Format(time.RFC3339)
115 }
116
117 // The words of the texts: the ones of the issues and the pull requests of a library, and of a coding agent.
118 var (
119 nouns = strings.Fields(`decoder encoder struct field key value string number buffer cursor byte escape table
120 hash map slice pointer type cache benchmark allocation loop word mask scan parser token stream reader
121 writer error test case path option compiler function call register branch layout runtime memory copy
122 length offset index array object literal rune quote backslash character input output result request
123 response message tool content model session event delta chunk payload schema property interface method
124 receiver generic release commit change regression fix issue report platform architecture version`)
125 verbs = strings.Fields(`decodes encodes returns reads writes skips scans copies checks compares allocates
126 reuses keeps handles escapes folds matches parses validates stores loads calls avoids measures reports
127 breaks fixes adds removes moves splits merges replaces caches`)
128 adjectives = strings.Fields(`short long plain escaped unknown nested empty large small first last next
129 previous invalid valid exact loose fast slow hot cold new old same other whole`)
130 smallWords = strings.Fields(`the a of to in is and for with by on at from as it that this when which not
131 only each every more than then so if but or`)
132 nonASCIIPunctuation = []string{"—", "→", "…", "✓", "×", "≤"}
133 )
134
135 // sentence returns a sentence of prose, which has code, numbers and references of issues now and then.
136 func sentence(r *payloadRand) string {
137 n := r.between(6, 18)
138 words := make([]string, 0, n)
139 for i := 0; i < n; i++ {
140 var w string
141 switch k := r.intn(20); {
142 case k < 7:
143 w = r.pick(smallWords)
144 case k < 12:
145 w = r.pick(nouns)
146 case k < 15:
147 w = r.pick(verbs)
148 case k < 17:
149 w = r.pick(adjectives)
150 case k == 17:
151 w = "`" + identifier(r) + "`"
152 case k == 18:
153 w = fmt.Sprintf("%d", r.between(2, 4096))
154 default:
155 w = fmt.Sprintf("(#%d)", r.between(100, 659))
156 }
157 words = append(words, w)
158 }
159 if r.chance(4) {
160 words[r.intn(n)] += ","
161 }
162 if r.chance(6) {
163 i := r.intn(n)
164 words[i] = `"` + words[i] + `"`
165 }
166 if r.chance(12) {
167 words[r.intn(n)] += " " + r.pick(nonASCIIPunctuation)
168 }
169 s := strings.Join(words, " ")
170 return strings.ToUpper(s[:1]) + s[1:] + "."
171 }
172
173 // prose returns paragraphs of about n bytes.
174 func prose(r *payloadRand, n int) string {
175 var b strings.Builder
176 for b.Len() < n {
177 if b.Len() > 0 {
178 if r.chance(3) {
179 b.WriteString("\n\n")
180 } else {
181 b.WriteByte(' ')
182 }
183 }
184 b.WriteString(sentence(r))
185 }
186 return b.String()
187 }
188
189 // markdown returns a text of about n bytes as the ones of issues, pull requests and answers of a model:
190 // headings, lists with bold text, paragraphs and blocks of code.
191 func markdown(r *payloadRand, n int) string {
192 return markdownWithCode(r, n, 10)
193 }
194
195 // markdownWithCode is markdown whose parts are blocks of code once in codeOneIn.
196 func markdownWithCode(r *payloadRand, n, codeOneIn int) string {
197 var b strings.Builder
198 for b.Len() < n {
199 if b.Len() > 0 {
200 b.WriteString("\n\n")
201 }
202 if r.chance(codeOneIn) {
203 b.WriteString("```go\n" + goSource(r, r.between(120, 600)) + "```")
204 continue
205 }
206 switch k := r.intn(9); {
207 case k < 2:
208 b.WriteString("## " + strings.ToUpper(r.pick(nouns)[:1]) + r.pick(nouns)[1:] + " " + r.pick(nouns))
209 case k < 6:
210 for i, items := 0, r.between(2, 6); i < items; i++ {
211 if i > 0 {
212 b.WriteByte('\n')
213 }
214 if i > 0 && r.chance(3) {
215 b.WriteString(" - " + sentence(r))
216 } else {
217 b.WriteString("- **" + sentence(r) + "** " + sentence(r))
218 }
219 }
220 default:
221 b.WriteString(prose(r, r.between(80, 400)))
222 }
223 }
224 return b.String()
225 }
226
227 // identifier returns a name of Go code.
228 func identifier(r *payloadRand) string {
229 s := r.pick(verbs)
230 s = strings.TrimSuffix(s, "s") + strings.ToUpper(r.pick(nouns)[:1])
231 return s + r.pick(nouns)[1:]
232 }
233
234 // goSource returns Go source code of about n bytes, whose indentation, strings and characters are the ones of
235 // the files which a coding agent reads: its escapes in JSON are its newlines, tabs, quotes and backslashes.
236 func goSource(r *payloadRand, n int) string {
237 var b strings.Builder
238 for b.Len() < n {
239 name := identifier(r)
240 fmt.Fprintf(&b, "// %s %s the %s %s of the %s.\n", name, r.pick(verbs), r.pick(adjectives), r.pick(nouns), r.pick(nouns))
241 fmt.Fprintf(&b, "func (d *%sDecoder) %s(buf []byte, cursor int64) (int64, error) {\n", r.pick(nouns), name)
242 depth := 1
243 for i, lines := 0, r.between(4, 16); i < lines; i++ {
244 indent := strings.Repeat("\t", depth)
245 switch k := r.intn(9); k {
246 case 0:
247 fmt.Fprintf(&b, "%sfor %s < len(buf) {\n", indent, r.pick(nouns))
248 depth++
249 case 1:
250 fmt.Fprintf(&b, "%sswitch buf[cursor] {\n%scase ' ', '\\n', '\\t', '\\r':\n", indent, indent)
251 depth++
252 case 2:
253 fmt.Fprintf(&b, "%sreturn 0, errors.ErrSyntax(fmt.Sprintf(\"invalid character %%q in %s\", buf[cursor]), cursor)\n", indent, r.pick(nouns))
254 case 3:
255 fmt.Fprintf(&b, "%s%s := %s(buf[cursor:], %q)\n", indent, r.pick(nouns), identifier(r), r.pick(nouns))
256 case 4:
257 fmt.Fprintf(&b, "%sif %s == nil {\n", indent, r.pick(nouns))
258 depth++
259 default:
260 fmt.Fprintf(&b, "%s%s = %s(%s, %d)\n", indent, r.pick(nouns), identifier(r), r.pick(nouns), r.between(0, 64))
261 }
262 if depth > 1 && r.chance(3) {
263 depth--
264 fmt.Fprintf(&b, "%s}\n", strings.Repeat("\t", depth))
265 }
266 }
267 for depth > 1 {
268 depth--
269 fmt.Fprintf(&b, "%s}\n", strings.Repeat("\t", depth))
270 }
271 b.WriteString("\treturn cursor, nil\n}\n\n")
272 }
273 return b.String()
274 }
275
276 // chunks splits the text into the pieces of 1 to 7 bytes which a stream delivers, on the boundaries of runes.
277 func chunks(r *payloadRand, text string) []string {
278 var pieces []string
279 for len(text) > 0 {
280 n := min(r.between(1, 7), len(text))
281 for n < len(text) && !utf8.RuneStart(text[n]) {
282 n++
283 }
284 pieces = append(pieces, text[:n])
285 text = text[n:]
286 }
287 return pieces
288 }