160 160
161It does not record session tokens or the signing key. Read `README.md` and `openapi.json` for the sample's setup and public contract.161It does not record session tokens or the signing key. Read `README.md` and `openapi.json` for the sample's setup and public contract.
162 162
163
164
165
166For Ruby, use the complete [Ruby sample project](https://github.com/openai/developers-website/tree/main/src/content/platform/ruby-examples) with its `Gemfile`, lockfile, and `codex-cloud` directory intact. Install its dependencies using Ruby 3.3. From the Ruby project directory, run `bundle exec ruby codex-cloud/api/main.rb`, `bundle exec ruby codex-cloud/test.rb --seeded`, `bundle exec ruby codex-cloud/test.rb`, and `bundle exec ruby codex-cloud/reproduce/main.rb ./evidence`. The seeded test deliberately fails; the corrected test passes. These Ruby commands replace the TypeScript commands above.
167
168
169
170
163### Inspect the runnable sample171### Inspect the runnable sample
164 172
165These excerpts come from the files in the download. Run the complete files after extracting the ZIP.173
174
175
176The TypeScript excerpts come from the ZIP.
177
178
179
180
181
182
183
184The Ruby examples come from the linked Ruby sample project.
185
186
187
188
189Run the complete files for the selected language with the supplied database fixture.
166 190
167<details>191<details>
168 <summary>Cursor and ordering implementation</summary>192 <summary>Cursor and ordering implementation</summary>
193 Create the example API
194
169```typescript195```typescript
170import { createFixtures } from "./fixtures.ts";196import { createFixtures } from "./fixtures.ts";
171type Fixtures = ReturnType<typeof createFixtures>;197type Fixtures = ReturnType<typeof createFixtures>;
297}323}
298```324```
299 325
326```ruby
327require "base64"
328require "json"
329require "net/http"
330require "openssl"
331require "time"
332require "timeout"
333require "uri"
334require "webrick"
335require_relative "../fixtures/main"
336
337module PaginationAPI
338 ERRORS = {
339 "invalid_cursor" => [400, "Invalid cursor."],
340 "invalid_limit" => [400, "Limit must be an integer from 1 through 100."],
341 "unauthenticated" => [401, "Authentication required."],
342 "not_found" => [404, "Project not found."]
343 }.freeze
344
345 def self.timestamp(value)
346 match = value.is_a?(String) && value.match(/\A(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?Z\z/)
347 raise ArgumentError, "Invalid timestamp" unless match
348
349 parsed = Time.iso8601(value)
350 raise ArgumentError, "Invalid timestamp" unless parsed.utc.strftime("%Y-%m-%dT%H:%M:%S") == match[1]
351
352 (parsed.to_r * 1_000_000_000).to_i
353 end
354
355 def self.compare(left, right)
356 [timestamp(right.fetch("created_at")), right.fetch("id")] <=> [timestamp(left.fetch("created_at")), left.fetch("id")]
357 end
358
359 def self.encode_cursor(event, tenant, project, key)
360 payload = Base64.urlsafe_encode64(
361 JSON.generate(
362 version: 1, tenant_id: tenant, project_id: project,
363 created_at: event.fetch("created_at"), id: event.fetch("id")
364 ), padding: false
365 )
366 signature = Base64.urlsafe_encode64(OpenSSL::HMAC.digest("SHA256", key, payload), padding: false)
367 "#{payload}.#{signature}"
368 end
369
370 def self.decode_cursor(token, tenant, project, key)
371 raise ArgumentError, "Invalid cursor" unless token.is_a?(String) && token.bytesize <= 2048
372
373 parts = token.split(".", -1)
374 raise ArgumentError, "Invalid cursor" unless parts.length == 2 && parts.all? { |part| part.match?(/\A[A-Za-z0-9_-]+\z/) }
375
376 payload, signature = parts
377 decoded, actual = Base64.urlsafe_decode64(payload), Base64.urlsafe_decode64(signature)
378 expected = OpenSSL::HMAC.digest("SHA256", key, payload)
379 unless Base64.urlsafe_encode64(decoded, padding: false) == payload && Base64.urlsafe_encode64(actual, padding: false) == signature &&
380 actual.bytesize == expected.bytesize && OpenSSL.fixed_length_secure_compare(actual, expected)
381 raise ArgumentError, "Invalid cursor"
382 end
383
384 cursor = JSON.parse(decoded, allow_duplicate_key: false)
385 fields = %w[version tenant_id project_id created_at id]
386 unless cursor.is_a?(Hash) && cursor.keys.sort == fields.sort && cursor["version"].is_a?(Integer) && cursor["version"] == 1 &&
387 cursor["tenant_id"] == tenant && cursor["project_id"] == project && cursor["id"].is_a?(String) && !cursor["id"].empty?
388 raise ArgumentError, "Invalid cursor"
389 end
390
391 timestamp(cursor["created_at"])
392 cursor
393 end
394
395 def self.failure(code)
396 status, message = ERRORS.fetch(code)
397 [
398 status, {
399 error: {
400 code: code,
401 message: message
402 }
403 }
404 ]
405 end
406
407 def self.handle(request, fixtures, seeded_bug)
408 bearer = request["authorization"].to_s.match(/\ABearer ([A-Za-z0-9_-]+)\z/)
409 tenant = bearer && fixtures[:sessions][bearer[1]]
410 return failure("unauthenticated") unless tenant
411
412 begin
413 url = URI.parse(request.unparsed_uri)
414 route = url.path.to_s.match(%r{\A/v1/projects/([^/]+)(/events)?\z})
415 project_id = route && URI.decode_www_form_component(route[1])
416 rescue ArgumentError, URI::InvalidURIError
417 return failure("not_found")
418 end
419 project = project_id && fixtures[:projects][project_id]
420 return failure("not_found") unless request.request_method == "GET" && route && project && project["tenant_id"] == tenant
421 unless route[2]
422 return [
423 200, {
424 id: project_id,
425 name: project["name"]
426 }
427 ]
428 end
429
430 begin
431 parameters = URI.decode_www_form(url.query.to_s)
432 rescue ArgumentError
433 return failure("invalid_cursor")
434 end
435 limits = parameters.filter_map { |key, value| value if key == "limit" }
436 return failure("invalid_limit") if limits.length > 1 || (!limits.empty? && !limits.fetch(0).match?(/\A\d+\z/))
437
438 limit = limits.empty? ? 25 : limits.fetch(0).to_i
439 return failure("invalid_limit") unless (1..100).cover?(limit)
440
441 cursors = parameters.filter_map { |key, value| value if key == "cursor" }
442 cursor = nil
443 unless cursors.empty?
444 begin
445 raise ArgumentError, "Repeated cursor" unless cursors.length == 1
446
447 cursor = decode_cursor(cursors.first, tenant, project_id, fixtures[:signing_key])
448 rescue ArgumentError, JSON::ParserError
449 return failure("invalid_cursor")
450 end
451 end
452 matching = fixtures[:events].select { |event| event["tenant_id"] == tenant && event["project_id"] == project_id }
453 .sort { |left, right| compare(left, right) }.select do |event|
454 !cursor || (seeded_bug ? timestamp(event["created_at"]) < timestamp(cursor["created_at"]) : compare(event, cursor).positive?)
455 end
456 selected = matching.take(limit)
457 items = selected.map { |event| event.slice("id", "created_at", "type", "summary") }
458 next_cursor = (matching.length > limit) ? encode_cursor(selected.last, tenant, project_id, fixtures[:signing_key]) : nil
459 [
460 200, {
461 items: items,
462 next_cursor: next_cursor
463 }
464 ]
465 end
466
467 def self.start(fixtures, seeded_bug: false)
468 ready = Queue.new
469 server = WEBrick::HTTPServer.new(
470 Port: 0, BindAddress: "127.0.0.1", AccessLog: [],
471 Logger: WEBrick::Log.new(File::NULL), StartCallback: -> { ready << true }
472 )
473 server.mount_proc("/") do |request, response|
474 status, body = handle(request, fixtures, seeded_bug)
475 response.status = status
476 response["content-type"] = "application/json"
477 response.body = JSON.generate(body)
478 end
479 worker = Thread.new { server.start }
480 Timeout.timeout(5) { ready.pop }
481 {
482 url: "http://127.0.0.1:#{server.config[:Port]}",
483
484 close: -> {
485 server.shutdown
486 worker.join
487 }
488 }
489 # Always close the owned listener if startup is interrupted.
490 rescue Exception # standard:disable Lint/RescueException
491 server&.shutdown
492 worker&.join
493 raise
494 end
495
496 def self.fetch(base, path, token)
497 request = Net::HTTP::Get.new(URI("#{base}#{path}"))
498 request["Authorization"] = "Bearer #{token}" if token
499 response = Net::HTTP.start(request.uri.host, request.uri.port, open_timeout: 5, read_timeout: 5) { |http| http.request(request) }
500 [response.code.to_i, JSON.parse(response.body)]
501 end
502end
503
504if $PROGRAM_NAME == __FILE__
505 fixtures = PaginationFixtures.create
506 api = PaginationAPI.start(fixtures)
507 begin
508 status, body = PaginationAPI.fetch(api[:url], "/v1/projects/feed/events?limit=2", fixtures[:token_a])
509 puts JSON.generate(status: status, ids: body.fetch("items").map { |item| item.fetch("id") }, has_next_page: !body["next_cursor"].nil?)
510 ensure
511 api[:close].call
512 end
513end
514```
515
300</details>516</details>
301 517
302<details>518<details>
303 <summary>Seeded records and project access fixtures</summary>519 <summary>Seeded records and project access fixtures</summary>
520 Create test fixtures
521
304```typescript522```typescript
305export function createFixtures() {523export function createFixtures() {
306 const tokenA = randomBytes(24).toString("base64url");524 const tokenA = randomBytes(24).toString("base64url");
371}589}
372```590```
373 591
592```ruby
593require "json"
594require "securerandom"
595require "time"
596
597module PaginationFixtures
598 def self.event(id, created_at, project_id, tenant_id = "tenant_a")
599 {
600 "id" => id,
601
602 "created_at" => created_at,
603
604 "project_id" => project_id,
605 "tenant_id" => tenant_id,
606
607 "type" => "deployment",
608
609 "summary" => "Synthetic event #{id}",
610 "internal_note" => "This field must never enter the HTTP response.",
611
612 "raw_payload" => { "synthetic" => true }
613 }
614 end
615
616 def self.create
617 token_a, token_b = SecureRandom.urlsafe_base64(24), SecureRandom.urlsafe_base64(24)
618 projects = {
619 "feed" => "Activity feed",
620
621 "empty" => "Empty feed",
622
623 "exact" => "Four events",
624 "large" => "Large feed",
625
626 "precision" => "Precise timestamps",
627
628 "other" => "Another project",
629 "private" => "Private project"
630 }.to_h do |id, name|
631 [
632 id, {
633 "tenant_id" => (id == "private") ? "tenant_b" : "tenant_a",
634 "name" => name
635 }
636 ]
637 end
638 feed = [["evt_105", "03"], ["evt_104", "02"], ["evt_103", "02"], ["evt_102", "02"], ["evt_101", "01"]].map do |id, second|
639 event(id, "2026-01-15T12:00:#{second}.123456Z", "feed")
640 end
641 events = feed + feed.take(4).map { |item| item.merge("project_id" => "exact") }
642 105.times do |index|
643 events << event(format("large_%03d", index), (Time.utc(2026, 1, 15, 12) + index).strftime("%Y-%m-%dT%H:%M:%S.123456Z"), "large")
644 end
645 events.concat(
646 [
647 event("precise_a", "2026-01-15T12:00:00.123999Z", "precision"),
648 event("precise_z", "2026-01-15T12:00:00.123001Z", "precision"),
649 event("other_1", "2026-01-15T12:00:00.123456Z", "other"),
650 event("other_2", "2026-01-15T11:59:59.123456Z", "other"),
651 event("private_1", "2026-01-15T12:00:00.123456Z", "private", "tenant_b"),
652 event("private_2", "2026-01-15T11:59:59.123456Z", "private", "tenant_b")
653 ]
654 )
655 {
656 sessions: {
657 token_a => "tenant_a",
658 token_b => "tenant_b"
659 },
660
661 projects: projects,
662 events: events,
663
664 signing_key: SecureRandom.random_bytes(32),
665
666 token_a: token_a,
667
668 token_b: token_b
669 }
670 end
671end
672
673if $PROGRAM_NAME == __FILE__
674 fixtures = PaginationFixtures.create
675 puts JSON.generate(projects: fixtures[:projects].length, events: fixtures[:events].length)
676end
677```
678
374</details>679</details>
375 680
376<details>681<details>
377 <summary>HTTP contract and regression tests</summary>682 <summary>HTTP contract and regression tests</summary>
683 Test the example API
684
378```typescript685```typescript
379test("five-event traversal crosses a timestamp tie and replays the same continuation", async () => {686test("five-event traversal crosses a timestamp tie and replays the same continuation", async () => {
380 const expected = ["evt_105", "evt_104", "evt_103", "evt_102", "evt_101"];687 const expected = ["evt_105", "evt_104", "evt_103", "evt_102", "evt_101"];
728});1035});
729```1036```
730 1037
1038```ruby
1039require "minitest/autorun"
1040require_relative "api/main"
1041
1042SEEDED_PAGINATION_BUG = !!ARGV.delete("--seeded")
1043ARGV << "--verbose"
1044
1045class PaginationTest < Minitest::Test
1046 def setup
1047 @fixtures = PaginationFixtures.create
1048 @spec = JSON.parse(File.read(File.expand_path("support/openapi.json", __dir__)))
1049 @api = PaginationAPI.start(@fixtures, seeded_bug: SEEDED_PAGINATION_BUG)
1050 end
1051
1052 def teardown
1053 @api&.fetch(:close)&.call
1054 end
1055
1056 # This oracle implements only the keywords in this fixture's closed schemas.
1057 def conforms?(value, schema)
1058 if schema["$ref"]
1059 resolved = schema["$ref"].delete_prefix("#/").split("/").reduce(@spec) { |item, key| item.fetch(key) }
1060 return conforms?(value, resolved)
1061 end
1062 return schema["oneOf"].count { |choice| conforms?(value, choice) } == 1 if schema["oneOf"]
1063
1064 case schema["type"]
1065 when "null"
1066 return value.nil?
1067 when "array"
1068 return value.is_a?(Array) && value.all? { |item| conforms?(item, schema.fetch("items", {})) }
1069 when "object"
1070 return false unless value.is_a?(Hash)
1071
1072 properties = schema.fetch("properties", {})
1073 return false unless schema.fetch("required", []).all? { |key| value.key?(key) }
1074 return false if schema["additionalProperties"] == false && (value.keys - properties.keys).any?
1075
1076 return properties.all? { |key, child| !value.key?(key) || conforms?(value[key], child) }
1077 when "string"
1078 return false unless value.is_a?(String)
1079 return false if value.length < schema.fetch("minLength", 0)
1080 return false if schema["pattern"] && !Regexp.new(schema["pattern"]).match?(value)
1081
1082 if schema["format"] == "date-time"
1083 begin
1084 Time.iso8601(value)
1085 rescue ArgumentError
1086 return false
1087 end
1088 end
1089 end
1090 !schema["enum"] || schema["enum"].include?(value)
1091 end
1092
1093 def request(project = "feed", parameters = {}, token: @fixtures[:token_a], detail: false)
1094 path = "/v1/projects/#{project}#{"/events" unless detail}?#{URI.encode_www_form(parameters)}"
1095 status, body = PaginationAPI.fetch(@api[:url], path, token)
1096 route = detail ? "/v1/projects/{project_id}" : "/v1/projects/{project_id}/events"
1097 schema = @spec.fetch("paths").fetch(route).fetch("get").fetch("responses").fetch(status.to_s).fetch("content").fetch("application/json").fetch("schema")
1098 assert conforms?(body, schema), "HTTP #{status} must match its closed public schema"
1099 [status, body]
1100 end
1101
1102 def ids(body)
1103 body.fetch("items").map { |item| item.fetch("id") }
1104 end
1105
1106 def page(project = "feed", parameters = {})
1107 status, body = request(project, parameters)
1108 assert_equal 200, status
1109 body
1110 end
1111
1112 def error(code, project = "feed", parameters = {}, token: @fixtures[:token_a], detail: false, **query)
1113 parameters = parameters.merge(query) unless query.empty?
1114 status, body = request(project, parameters, token: token, detail: detail)
1115 expected_status, expected_body = PaginationAPI.failure(code)
1116 assert_equal expected_status, status
1117 assert_equal JSON.parse(JSON.generate(expected_body)), body
1118 body
1119 end
1120
1121 def test_tuple_pagination_and_replay
1122 first = page("feed", limit: 2)
1123 assert_equal %w[evt_105 evt_104], ids(first)
1124 second = page("feed", limit: 2, cursor: first.fetch("next_cursor"))
1125 assert_equal %w[evt_103 evt_102], ids(second)
1126 assert_equal second, page("feed", limit: 2, cursor: first.fetch("next_cursor"))
1127 third = page("feed", limit: 2, cursor: second.fetch("next_cursor"))
1128 assert_equal ["evt_101"], ids(third)
1129 assert_nil third["next_cursor"]
1130 end
1131
1132 def test_ties_with_limit_three
1133 first = page("feed", limit: 3)
1134 assert_equal %w[evt_105 evt_104 evt_103], ids(first)
1135 last = page("feed", limit: 3, cursor: first.fetch("next_cursor"))
1136 assert_equal %w[evt_102 evt_101], ids(last)
1137 assert_nil last["next_cursor"]
1138 end
1139
1140 def test_submillisecond_precision
1141 first = page("precision", limit: 1)
1142 assert_equal ["precise_a"], ids(first)
1143 assert_equal ["precise_z"], ids(page("precision", limit: 1, cursor: first.fetch("next_cursor")))
1144 end
1145
1146 def test_limit_boundaries
1147 assert_equal 25, ids(page("large")).length
1148 assert_equal 1, ids(page("large", limit: 1)).length
1149 assert_equal 100, ids(page("large", limit: 100)).length
1150 end
1151
1152 def test_invalid_limits
1153 ["", "0", "101", "-1", "1.5", "1e2", " 2", "NaN", "Infinity"].each do |limit|
1154 error("invalid_limit", "feed", limit: limit)
1155 end
1156 error("invalid_limit", "feed", [["limit", "2"], ["limit", "3"]])
1157 end
1158
1159 def test_final_pages
1160 assert_empty ids(page("empty"))
1161 assert_nil page("empty")["next_cursor"]
1162 assert_nil page("feed", limit: 100)["next_cursor"]
1163 first = page("exact", limit: 2)
1164 last = page("exact", limit: 2, cursor: first.fetch("next_cursor"))
1165 assert_equal 2, ids(last).length
1166 assert_nil last["next_cursor"]
1167 end
1168
1169 def test_authentication_precedence
1170 [nil, "wrong", "invalid token"].each do |token|
1171 error(
1172 "unauthenticated", "feed", {
1173 cursor: "broken",
1174 limit: "0"
1175 }, token: token
1176 )
1177 end
1178 end
1179
1180 def test_authorization_precedence
1181 private_error = error("not_found", "private", cursor: "broken", limit: "0")
1182 assert_equal private_error, error("not_found", "missing", cursor: "broken", limit: "0")
1183 end
1184
1185 def test_project_cursor_scope
1186 cursor = page("other", limit: 1).fetch("next_cursor")
1187 error("invalid_cursor", "feed", cursor: cursor)
1188 end
1189
1190 def test_tenant_cursor_scope
1191 _, body = request("private", { limit: 1 }, token: @fixtures[:token_b])
1192 error("invalid_cursor", "feed", cursor: body.fetch("next_cursor"))
1193 end
1194
1195 def test_malformed_cursors
1196 cursor = page("feed", limit: 2).fetch("next_cursor")
1197 ["", "broken", "a.b.c", cursor + "=", "!" + cursor, cursor.sub(/.$/, cursor.end_with?("A") ? "B" : "A")].each do |token|
1198 error("invalid_cursor", "feed", cursor: token)
1199 end
1200 error("invalid_cursor", "feed", [["cursor", cursor], ["cursor", cursor]])
1201 end
1202
1203 def test_signed_invalid_cursors
1204 valid = {
1205 "version" => 1,
1206 "tenant_id" => "tenant_a",
1207 "project_id" => "feed",
1208 "created_at" => "2026-01-15T12:00:02.123456Z",
1209 "id" => "evt_104"
1210 }
1211 [
1212 valid.merge("version" => 2), valid.merge("version" => 1.0), valid.merge("extra" => true), valid.except("id"),
1213 valid.merge("id" => ""), valid.merge("id" => 5), valid.merge("created_at" => "2026-02-30T00:00:00Z"), nil, []
1214 ].each do |value|
1215 payload = Base64.urlsafe_encode64(JSON.generate(value), padding: false)
1216 signature = Base64.urlsafe_encode64(OpenSSL::HMAC.digest("SHA256", @fixtures[:signing_key], payload), padding: false)
1217 error("invalid_cursor", "feed", cursor: "#{payload}.#{signature}")
1218 end
1219 end
1220
1221 def test_public_event_fields
1222 page("large", limit: 100).fetch("items").each do |event|
1223 assert_equal %w[created_at id summary type], event.keys.sort
1224 end
1225 end
1226
1227 def test_schema_oracle
1228 schema = @spec.fetch("components").fetch("schemas").fetch("Event")
1229 valid = page.fetch("items").first
1230 assert conforms?(valid, schema)
1231 [valid.merge("tenant_id" => "secret"), valid.except("id"), valid.merge("id" => 1), valid.merge("created_at" => "bad-date")].each do |event|
1232 refute conforms?(event, schema)
1233 end
1234 end
1235
1236 def test_project_detail
1237 status, body = request(
1238 "feed", {
1239 cursor: "broken",
1240 limit: "0"
1241 }, detail: true
1242 )
1243 assert_equal 200, status
1244 assert_equal(
1245 {
1246 "id" => "feed",
1247 "name" => "Activity feed"
1248 }, body
1249 )
1250 error("not_found", "private", {}, detail: true)
1251 error("unauthenticated", "feed", {}, token: nil, detail: true)
1252 end
1253
1254 def test_openapi_contract
1255 assert_equal "3.1.0", @spec["openapi"]
1256 operation = @spec.fetch("paths").fetch("/v1/projects/{project_id}/events").fetch("get")
1257 assert_equal "listProjectEvents", operation["operationId"]
1258 limit = operation.fetch("parameters").find { |parameter| parameter["name"] == "limit" }.fetch("schema")
1259 assert_equal(
1260 {
1261 "type" => "integer",
1262 "minimum" => 1,
1263 "maximum" => 100,
1264 "default" => 25
1265 }, limit
1266 )
1267 assert_equal %w[200 400 401 404], operation.fetch("responses").keys.sort
1268 assert_equal "bearer", @spec.dig("components", "securitySchemes", "session", "scheme")
1269 end
1270end
1271```
1272
731</details>1273</details>
732 1274
733<details>1275<details>
734 <summary>Evidence capture</summary>1276 <summary>Evidence capture</summary>
1277 Reproduce the issue
1278
735```typescript1279```typescript
736mkdirSync(output, { recursive: true });1280mkdirSync(output, { recursive: true });
737const states = [];1281const states = [];
815);1359);
816```1360```
817 1361
1362```ruby
1363require "digest"
1364require "fileutils"
1365require "rbconfig"
1366require "timeout"
1367require_relative "../api/main"
1368
1369output = File.expand_path(ARGV.fetch(0, "evidence"))
1370FileUtils.mkdir_p(output)
1371test_path = File.expand_path("../test.rb", __dir__)
1372states = [["red", ["--seeded"]], ["green", []]].map do |name, arguments|
1373 log_path = File.join(output, "#{name}.log")
1374 pid = if arguments.empty?
1375 Process.spawn(RbConfig.ruby, test_path, out: log_path, err: [:child, :out])
1376 else
1377 Process.spawn(RbConfig.ruby, test_path, "--seeded", out: log_path, err: [:child, :out])
1378 end
1379 begin
1380 status = Timeout.timeout(30) { (Process.wait2(pid) or raise "Child process was not reaped").last }
1381 rescue Timeout::Error
1382 Process.kill("KILL", pid)
1383 Process.wait(pid)
1384 raise
1385 end
1386 {
1387 name: name,
1388 command: [RbConfig.ruby, test_path, *arguments],
1389 exit_code: status.exitstatus,
1390 signal: status.termsig
1391 }
1392end
1393
1394observed = [true, false].to_h do |seeded|
1395 fixtures = PaginationFixtures.create
1396 api = PaginationAPI.start(fixtures, seeded_bug: seeded)
1397 begin
1398 pages = []
1399 state = { cursor: nil }
1400 loop do
1401 raise "Traversal exceeded fixture bound" if pages.length >= 3
1402
1403 parameters = { limit: 2 }
1404 parameters[:cursor] = state[:cursor] if state[:cursor]
1405 status, body = PaginationAPI.fetch(api[:url], "/v1/projects/feed/events?#{URI.encode_www_form(parameters)}", fixtures[:token_a])
1406 pages << {
1407 status: status,
1408 body: body
1409 }
1410 state[:cursor] = body.fetch("next_cursor")
1411 break unless state[:cursor]
1412 end
1413 errors = [["feed", fixtures[:token_a]], ["feed", nil], ["private", fixtures[:token_a]]].map do |project, token|
1414 status, body = PaginationAPI.fetch(api[:url], "/v1/projects/#{project}/events?cursor=broken", token)
1415 {
1416 status: status,
1417 body: body
1418 }
1419 end
1420 [
1421 seeded ? :red : :green, {
1422 pages: pages,
1423 errors: errors
1424 }
1425 ]
1426 ensure
1427 api[:close].call
1428 end
1429end
1430sources = %w[api/main.rb fixtures/main.rb test.rb reproduce/main.rb support/openapi.json].to_h do |name|
1431 [name, Digest::SHA256.file(File.expand_path("../#{name}", __dir__)).hexdigest]
1432end
1433File.write(File.join(output, "observed-http.json"), JSON.pretty_generate(observed))
1434File.write(
1435 File.join(output, "run-manifest.json"),
1436 JSON.pretty_generate(
1437 execution: "Synthetic loopback HTTP fixture; no external service", recorded_at: Time.now.utc.iso8601,
1438 ruby: RUBY_VERSION, source_sha256: sources, states: states,
1439 baseline: "Deliberately seeded timestamp-only continuation; not a historical customer defect",
1440 correction: "Descending timestamp-and-ID continuation retaining fractional precision"
1441 )
1442)
1443unless states.fetch(0)[:exit_code] == 1 && states.fetch(1)[:exit_code] == 0
1444 raise "Expected seeded failure and corrected success; inspect red.log and green.log"
1445end
1446
1447puts JSON.generate(
1448 execution: "synthetic-loopback-http", red_exit: states.fetch(0)[:exit_code], green_exit: states.fetch(1)[:exit_code],
1449 green_pages: observed.fetch(:green)[:pages].map { |page| page[:body].fetch("items").map { |item| item.fetch("id") } }, evidence_directory: output
1450)
1451```
1452
818</details>1453</details>
819 1454
820## Prepare the input packet1455## Prepare the input packet