diff --git a/en/use-cases/issue-to-tested-pr.md b/en/use-cases/issue-to-tested-pr.md index dc9fe727ec9807092e260b7f29029677632f19a2..8f600fd34b16250692e4beebdef4fb5c90f5acd4 100644 --- a/en/use-cases/issue-to-tested-pr.md +++ b/en/use-cases/issue-to-tested-pr.md @@ -163,11 +163,113 @@ It does not record session tokens or the signing key. Read `README.md` and `open +Use Python 3.11 or later and uv with a complete [Python sample project](https://github.com/openai/developers-website/tree/main/src/content/platform/python-examples) from a `developers-website` checkout. Keep `codex-cloud/api.py`, `fixtures.py`, `test.py`, and [the complete reproduction program](https://github.com/openai/developers-website/blob/main/src/content/platform/python-examples/codex-cloud/reproduce.py) together with the project's `pyproject.toml` and `uv.lock`. The ZIP above contains only TypeScript. + +Start at the repository checkout root in a POSIX shell. Install the locked dependencies, including `jsonschema`, then run the Python commands below instead of the Node commands above: + +```bash +cd src/content/platform/python-examples +uv sync --locked +.venv/bin/python codex-cloud/api.py +.venv/bin/python codex-cloud/fixtures.py +.venv/bin/python codex-cloud/test.py --seeded +.venv/bin/python codex-cloud/test.py +.venv/bin/python codex-cloud/reproduce.py ./evidence +``` + +The programs read the canonical `../typescript-examples/codex-cloud/issue-to-tested-pr/openapi.json`, relative to the Python project directory, from the same checkout. Keep that sibling fixture intact. The API, test, and reproduction commands manage their own synthetic in-memory records and loopback HTTP servers; no database or API key is required. The fixtures command prints record counts. The API command prints one page summary and stops, so do not leave a separate server running. + +Expect these results: + +- The seeded test exits with `1` to expose the deliberate pagination defect; continue to the corrected test. +- All 16 corrected tests pass and the corrected test exits with `0`. +- The reproduction command runs both suites and writes `red.log`, `green.log`, `observed-http.json`, and `run-manifest.json` to a new `./evidence` directory. Use a new directory on each run; the program refuses to overwrite existing evidence. + + + + + + + +**Java setup** + +Use Java 17 or later and Maven with a complete `developers-website` checkout, including the [Java sample project](https://github.com/openai/developers-website/tree/main/src/content/platform/java-examples), its `pom.xml`, and `src/main/java/codex-cloud` files intact. + +Start at the repository checkout root in a POSIX shell. The tests require the sibling `../typescript-examples/codex-cloud/issue-to-tested-pr/openapi.json` contract, relative to the Java project directory, from the same checkout. + +```bash +cd src/content/platform/java-examples +mvn -q -DskipTests compile dependency:build-classpath -Dmdep.outputFile=target/live-classpath +java -cp "target/classes:$(cat target/live-classpath)" com.openai.docs.codexcloud.CodexCloudApi +java -cp "target/classes:$(cat target/live-classpath)" com.openai.docs.codexcloud.CodexCloudTest --seeded +java -cp "target/classes:$(cat target/live-classpath)" com.openai.docs.codexcloud.CodexCloudTest +java -cp "target/classes:$(cat target/live-classpath)" com.openai.docs.codexcloud.CodexCloudReproduce ./evidence +``` + +**Expected results** + +- The seeded test fails on the deliberate timestamp-only defect. +- The corrected test passes. +- `CodexCloudReproduce` saves logs for the failing seeded run and passing corrected run in `./evidence`. + +Use these commands in place of the Node commands for the Java tab. + + + + + + + For 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. + + + +Use Go 1.26 or later with a full [repository checkout](https://github.com/openai/developers-website). Keep the `src/content/platform/go-examples/` module (`go.mod` and `go.sum`) and the sibling `typescript-examples/codex-cloud` files intact. Start the commands below at the repository root. + +```bash +cd src/content/platform/go-examples/codex-cloud/issue-to-tested-pr +go run . api +go run . fixtures +go run . --seeded -test.v test +go run . -test.v test +go run . reproduce ./evidence +``` + +The Go tests read the canonical `../../../typescript-examples/codex-cloud/issue-to-tested-pr/openapi.json` from this example directory. The ZIP and Node commands above target TypeScript. + +Expected results + +- The seeded test exits with a nonzero status. +- The corrected test exits successfully. +- The reproduction writes red and green logs to a new `./evidence` directory. + + + + + + + +The C# excerpts come from the complete [.NET sample project](https://github.com/openai/developers-website/tree/main/src/content/platform/dotnet-examples). The project targets .NET 10, with SDK 10.0.100 and `latestFeature` roll-forward recorded in `global.json`. + +Run these commands from the repository root. + +```sh +cd src/content/platform/dotnet-examples +dotnet restore OpenAI.Docs.Examples.slnx --locked-mode +dotnet run --project OpenAI.Docs.Examples.csproj --no-restore -- codex-cloud-pagination +``` + +The complete checkout supplies `src/content/platform/typescript-examples/codex-cloud/issue-to-tested-pr/openapi.json`, the shared OpenAPI 3.1.0 contract with API version 1.0.0. The C# program locates that file relative to its source file. + +The launcher covers the API, fixtures, test, and reproduction sections in one process. It starts owned loopback servers and runs both the deliberately seeded and corrected suites, with generated session tokens and signing keys. Its success requires the seeded suite to fail and all 16 corrected checks to pass. It writes `red.log`, `green.log`, `observed-http.json`, and `run-manifest.json` into `evidence/` under the .NET project directory. + + + + ### Inspect the runnable sample @@ -186,7 +288,9 @@ The Ruby examples come from the linked Ruby sample project. -Run the complete files for the selected language with the supplied database fixture. +**Full programs** + +Use the selected language's project, supporting files, and launch commands above. The excerpts below highlight the implementation.
Cursor and ordering implementation @@ -323,446 +427,3276 @@ export async function startApi( } ``` -```ruby -require "base64" -require "json" -require "net/http" -require "openssl" -require "time" -require "timeout" -require "uri" -require "webrick" -require_relative "../fixtures/main" +```python +import base64 +import binascii +import hmac +import http.client +import json +import re +import threading +from contextlib import contextmanager +from datetime import datetime +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import parse_qs, unquote, urlsplit + +from fixtures import Fixtures, create_fixtures + +ERRORS = { + "invalid_cursor": (400, "Invalid cursor."), + "invalid_limit": (400, "Limit must be an integer from 1 through 100."), + "unauthenticated": (401, "Authentication required."), + "not_found": (404, "Project not found."), +} +PUBLIC_FIELDS = ("id", "created_at", "type", "summary") -module PaginationAPI - ERRORS = { - "invalid_cursor" => [400, "Invalid cursor."], - "invalid_limit" => [400, "Limit must be an integer from 1 through 100."], - "unauthenticated" => [401, "Authentication required."], - "not_found" => [404, "Project not found."] - }.freeze - def self.timestamp(value) - 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/) - raise ArgumentError, "Invalid timestamp" unless match +def timestamp_value(value: str) -> int: + """Preserve all nine fractional digits without float or datetime rounding.""" + if not isinstance(value, str): + raise ValueError("Invalid timestamp") + match = re.fullmatch( + r"(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?Z", value + ) + if not match: + raise ValueError("Invalid timestamp") + instant = datetime.strptime(match[1], "%Y-%m-%dT%H:%M:%S") + delta = instant - datetime(1970, 1, 1) + return (delta.days * 86400 + delta.seconds) * 10**9 + int( + (match[2] or "").ljust(9, "0") + ) - parsed = Time.iso8601(value) - raise ArgumentError, "Invalid timestamp" unless parsed.utc.strftime("%Y-%m-%dT%H:%M:%S") == match[1] - (parsed.to_r * 1_000_000_000).to_i - end +def event_key(event: dict) -> tuple[int, str]: + return timestamp_value(event["created_at"]), event["id"] - def self.compare(left, right) - [timestamp(right.fetch("created_at")), right.fetch("id")] <=> [timestamp(left.fetch("created_at")), left.fetch("id")] - end - def self.encode_cursor(event, tenant, project, key) - payload = Base64.urlsafe_encode64( - JSON.generate( - version: 1, tenant_id: tenant, project_id: project, - created_at: event.fetch("created_at"), id: event.fetch("id") - ), padding: false +def base64url(data: bytes) -> str: + return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=") + + +def unbase64url(value: str) -> bytes: + if not re.fullmatch(r"[A-Za-z0-9_-]+", value): + raise ValueError("Invalid cursor") + decoded = base64.b64decode( + value + "=" * (-len(value) % 4), altchars=b"-_", validate=True ) - signature = Base64.urlsafe_encode64(OpenSSL::HMAC.digest("SHA256", key, payload), padding: false) - "#{payload}.#{signature}" - end + if base64url(decoded) != value: + raise ValueError("Invalid cursor") + return decoded - def self.decode_cursor(token, tenant, project, key) - raise ArgumentError, "Invalid cursor" unless token.is_a?(String) && token.bytesize <= 2048 - parts = token.split(".", -1) - raise ArgumentError, "Invalid cursor" unless parts.length == 2 && parts.all? { |part| part.match?(/\A[A-Za-z0-9_-]+\z/) } +def encode_cursor(event, tenant_id, project_id, signing_key): + payload = base64url( + json.dumps( + { + "version": 1, + "tenant_id": tenant_id, + "project_id": project_id, + "created_at": event["created_at"], + "id": event["id"], + }, + separators=(",", ":"), + ).encode() + ) + signature = hmac.digest(signing_key, payload.encode("ascii"), "sha256") + return f"{payload}.{base64url(signature)}" - payload, signature = parts - decoded, actual = Base64.urlsafe_decode64(payload), Base64.urlsafe_decode64(signature) - expected = OpenSSL::HMAC.digest("SHA256", key, payload) - unless Base64.urlsafe_encode64(decoded, padding: false) == payload && Base64.urlsafe_encode64(actual, padding: false) == signature && - actual.bytesize == expected.bytesize && OpenSSL.fixed_length_secure_compare(actual, expected) - raise ArgumentError, "Invalid cursor" - end - cursor = JSON.parse(decoded, allow_duplicate_key: false) - fields = %w[version tenant_id project_id created_at id] - unless cursor.is_a?(Hash) && cursor.keys.sort == fields.sort && cursor["version"].is_a?(Integer) && cursor["version"] == 1 && - cursor["tenant_id"] == tenant && cursor["project_id"] == project && cursor["id"].is_a?(String) && !cursor["id"].empty? - raise ArgumentError, "Invalid cursor" - end +def unique_object(pairs): + result = {} + for name, value in pairs: + if name in result: + raise ValueError("Duplicate cursor field") + result[name] = value + return result - timestamp(cursor["created_at"]) - cursor - end - def self.failure(code) - status, message = ERRORS.fetch(code) - [ - status, { - error: { - code: code, - message: message - } - } - ] - end +def decode_cursor(token, tenant_id, project_id, signing_key): + if not isinstance(token, str) or len(token) > 2048: + raise ValueError("Invalid cursor") + parts = token.split(".") + if len(parts) != 2: + raise ValueError("Invalid cursor") + payload, signature = parts + decoded, actual = unbase64url(payload), unbase64url(signature) + expected = hmac.digest(signing_key, payload.encode("ascii"), "sha256") + if not hmac.compare_digest(actual, expected): + raise ValueError("Invalid cursor") + cursor = json.loads(decoded.decode("utf-8"), object_pairs_hook=unique_object) + fields = {"version", "tenant_id", "project_id", "created_at", "id"} + if ( + not isinstance(cursor, dict) + or set(cursor) != fields + or type(cursor["version"]) is not int + or cursor["version"] != 1 + or cursor["tenant_id"] != tenant_id + or cursor["project_id"] != project_id + or not isinstance(cursor["id"], str) + or not cursor["id"] + ): + raise ValueError("Invalid cursor") + timestamp_value(cursor["created_at"]) + return cursor + + +# Keep the language variants on the same authored OpenAPI contract. +SPECIFICATION_PATH = ( + Path(__file__).resolve().parents[2] + / "typescript-examples/codex-cloud/issue-to-tested-pr/openapi.json" +) +if not SPECIFICATION_PATH.is_file(): + # The shared runner copies the canonical fixture beside the authored program. + SPECIFICATION_PATH = Path(__file__).parent / "issue-to-tested-pr/openapi.json" +SPECIFICATION = json.loads(SPECIFICATION_PATH.read_text(encoding="utf-8")) +SCHEMAS = SPECIFICATION["components"]["schemas"] +EVENT_SCHEMA = SCHEMAS["Event"] +PAGE_SCHEMA = SCHEMAS["EventPage"] +DETAIL_SCHEMA = SCHEMAS["Project"] +ERROR_SCHEMAS = { + code: SCHEMAS[name] + for code, name in { + "invalid_cursor": "InvalidCursor", + "invalid_limit": "InvalidLimit", + "unauthenticated": "Unauthenticated", + "not_found": "NotFound", + }.items() +} - def self.handle(request, fixtures, seeded_bug) - bearer = request["authorization"].to_s.match(/\ABearer ([A-Za-z0-9_-]+)\z/) - tenant = bearer && fixtures[:sessions][bearer[1]] - return failure("unauthenticated") unless tenant - begin - url = URI.parse(request.unparsed_uri) - route = url.path.to_s.match(%r{\A/v1/projects/([^/]+)(/events)?\z}) - project_id = route && URI.decode_www_form_component(route[1]) - rescue ArgumentError, URI::InvalidURIError - return failure("not_found") - end - project = project_id && fixtures[:projects][project_id] - return failure("not_found") unless request.request_method == "GET" && route && project && project["tenant_id"] == tenant - unless route[2] - return [ - 200, { - id: project_id, - name: project["name"] - } +def dispatch(fixtures: Fixtures, method, target, authorization, *, seeded_bug=False): + """Pure request boundary, shared by the HTTP server and isolated unit checks.""" + + def fail(code): + status, message = ERRORS[code] + return status, {"error": {"code": code, "message": message}} + + bearer = re.fullmatch(r"Bearer ([A-Za-z0-9_-]+)", authorization) + tenant = fixtures.sessions.get(bearer[1]) if bearer else None + if not tenant: + return fail("unauthenticated") + try: + url = urlsplit(target) + route = re.fullmatch(r"/v1/projects/([^/]+)(/events)?", url.path) + project_id = unquote(route[1], errors="strict") if route else None + except (ValueError, UnicodeError): + return fail("not_found") + project = fixtures.projects.get(project_id) + if method != "GET" or not route or not project or project["tenant_id"] != tenant: + return fail("not_found") + if not route[2]: + return 200, {"id": project_id, "name": project["name"]} + try: + parameters = parse_qs(url.query, keep_blank_values=True, max_num_fields=100) + except ValueError: + return fail("invalid_limit") + limits = parameters.get("limit", ["25"]) + if ( + len(limits) != 1 + or not re.fullmatch(r"[0-9]+", limits[0]) + or len(limits[0]) > 100 + ): + return fail("invalid_limit") + limit = int(limits[0]) + if not 1 <= limit <= 100: + return fail("invalid_limit") + cursor = None + if "cursor" in parameters: + try: + if len(parameters["cursor"]) != 1: + raise ValueError("Repeated cursor") + cursor = decode_cursor( + parameters["cursor"][0], tenant, project_id, fixtures.signing_key + ) + except (ValueError, UnicodeError, binascii.Error, RecursionError): + return fail("invalid_cursor") + matching = sorted( + ( + event + for event in fixtures.events + if event["tenant_id"] == tenant and event["project_id"] == project_id + ), + key=event_key, + reverse=True, + ) + if cursor: + # Deliberately seeded baseline loses rows tied on the timestamp. + matching = [ + event + for event in matching + if ( + timestamp_value(event["created_at"]) + < timestamp_value(cursor["created_at"]) + if seeded_bug + else event_key(event) < event_key(cursor) + ) ] - end - - begin - parameters = URI.decode_www_form(url.query.to_s) - rescue ArgumentError - return failure("invalid_cursor") - end - limits = parameters.filter_map { |key, value| value if key == "limit" } - return failure("invalid_limit") if limits.length > 1 || (!limits.empty? && !limits.fetch(0).match?(/\A\d+\z/)) + selected = matching[:limit] + next_cursor = ( + encode_cursor(selected[-1], tenant, project_id, fixtures.signing_key) + if len(matching) > limit + else None + ) + return 200, { + "items": [{name: event[name] for name in PUBLIC_FIELDS} for event in selected], + "next_cursor": next_cursor, + } - limit = limits.empty? ? 25 : limits.fetch(0).to_i - return failure("invalid_limit") unless (1..100).cover?(limit) - cursors = parameters.filter_map { |key, value| value if key == "cursor" } - cursor = nil - unless cursors.empty? - begin - raise ArgumentError, "Repeated cursor" unless cursors.length == 1 +@contextmanager +def start_api(fixtures: Fixtures, *, seeded_bug=False): + class Handler(BaseHTTPRequestHandler): + timeout = 5 - cursor = decode_cursor(cursors.first, tenant, project_id, fixtures[:signing_key]) - rescue ArgumentError, JSON::ParserError - return failure("invalid_cursor") - end - end - matching = fixtures[:events].select { |event| event["tenant_id"] == tenant && event["project_id"] == project_id } - .sort { |left, right| compare(left, right) }.select do |event| - !cursor || (seeded_bug ? timestamp(event["created_at"]) < timestamp(cursor["created_at"]) : compare(event, cursor).positive?) - end - selected = matching.take(limit) - items = selected.map { |event| event.slice("id", "created_at", "type", "summary") } - next_cursor = (matching.length > limit) ? encode_cursor(selected.last, tenant, project_id, fixtures[:signing_key]) : nil - [ - 200, { - items: items, - next_cursor: next_cursor - } - ] - end + def respond(self): + authorizations = self.headers.get_all("Authorization", []) + status, body = dispatch( + fixtures, + self.command, + self.path, + authorizations[0] if len(authorizations) == 1 else "", + seeded_bug=seeded_bug, + ) + encoded = json.dumps(body, separators=(",", ":")).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(encoded))) + self.end_headers() + self.wfile.write(encoded) + + do_GET = do_POST = do_PUT = do_DELETE = do_PATCH = do_HEAD = do_OPTIONS = ( + respond + ) - def self.start(fixtures, seeded_bug: false) - ready = Queue.new - server = WEBrick::HTTPServer.new( - Port: 0, BindAddress: "127.0.0.1", AccessLog: [], - Logger: WEBrick::Log.new(File::NULL), StartCallback: -> { ready << true } + def log_message(self, format, *args): + # Requests contain bearer-bound cursors; keep them out of access logs. + return + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + server.daemon_threads = False + thread = threading.Thread(target=server.serve_forever, name="pagination-fixture") + thread.start() + try: + yield f"http://127.0.0.1:{server.server_port}" + finally: + server.shutdown() + server.server_close() + thread.join(timeout=5) + if thread.is_alive(): + raise RuntimeError("Owned HTTP server failed to stop") + + +if __name__ == "__main__": + fixtures = create_fixtures() + with start_api(fixtures) as base_url: + address = urlsplit(base_url) + connection = http.client.HTTPConnection( + address.hostname, address.port, timeout=5 ) - server.mount_proc("/") do |request, response| - status, body = handle(request, fixtures, seeded_bug) - response.status = status - response["content-type"] = "application/json" - response.body = JSON.generate(body) - end - worker = Thread.new { server.start } - Timeout.timeout(5) { ready.pop } + try: + connection.request( + "GET", + "/v1/projects/feed/events?limit=2", + headers={"Authorization": f"Bearer {fixtures.token_a}"}, + ) + response = connection.getresponse() + body = json.load(response) + if response.status != 200: + raise RuntimeError(f"Unexpected HTTP status {response.status}") + print( + json.dumps( { - url: "http://127.0.0.1:#{server.config[:Port]}", - - close: -> { - server.shutdown - worker.join - } + "status": response.status, + "ids": [item["id"] for item in body["items"]], + "has_next_page": body["next_cursor"] is not None, } - # Always close the owned listener if startup is interrupted. - rescue Exception # standard:disable Lint/RescueException - server&.shutdown - worker&.join - raise - end - - def self.fetch(base, path, token) - request = Net::HTTP::Get.new(URI("#{base}#{path}")) - request["Authorization"] = "Bearer #{token}" if token - response = Net::HTTP.start(request.uri.host, request.uri.port, open_timeout: 5, read_timeout: 5) { |http| http.request(request) } - [response.code.to_i, JSON.parse(response.body)] - end -end - -if $PROGRAM_NAME == __FILE__ - fixtures = PaginationFixtures.create - api = PaginationAPI.start(fixtures) - begin - status, body = PaginationAPI.fetch(api[:url], "/v1/projects/feed/events?limit=2", fixtures[:token_a]) - puts JSON.generate(status: status, ids: body.fetch("items").map { |item| item.fetch("id") }, has_next_page: !body["next_cursor"].nil?) - ensure - api[:close].call - end -end + ) + ) + finally: + connection.close() ``` -
+```go +type page struct { + Items []event `json:"items"` + NextCursor *string `json:"next_cursor"` +} +type cursor struct { + Version int `json:"version"` + Tenant string `json:"tenant_id"` + Project string `json:"project_id"` + CreatedAt string `json:"created_at"` + ID string `json:"id"` +} -
- Seeded records and project access fixtures - Create test fixtures +var timestampPattern = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$`) -```typescript -export function createFixtures() { - const tokenA = randomBytes(24).toString("base64url"); - const tokenB = randomBytes(24).toString("base64url"); - const sessions = new Map([ +func timestamp(value string) (time.Time, error) { + if !timestampPattern.MatchString(value) { + return time.Time{}, errors.New("invalid timestamp") + } + return time.Parse(time.RFC3339Nano, value) +} + +// Compare parsed instants, without truncating submillisecond fractions. +func compare(left, right event) int { + a, err := timestamp(left.CreatedAt) + if err != nil { + panic(err) + } + b, err := timestamp(right.CreatedAt) + if err != nil { + panic(err) + } + if a.After(b) { + return -1 + } + if a.Before(b) { + return 1 + } + return -strings.Compare(left.ID, right.ID) +} +func sign(payload string, key []byte) string { + mac := hmac.New(sha256.New, key) + _, _ = mac.Write([]byte(payload)) + return payload + "." + base64.RawURLEncoding.EncodeToString(mac.Sum(nil)) +} +func encodeCursor(e event, tenant, project string, key []byte) string { + data, err := json.Marshal(cursor{1, tenant, project, e.CreatedAt, e.ID}) + if err != nil { + panic(err) + } + return sign(base64.RawURLEncoding.EncodeToString(data), key) +} +func decodeCursor(token, tenant, project string, key []byte) (event, error) { + bad := errors.New("invalid cursor") + parts := strings.Split(token, ".") + if len(token) > 2048 || len(parts) != 2 { + return event{}, bad + } + decode := func(s string) ([]byte, error) { + b, err := base64.RawURLEncoding.Strict().DecodeString(s) + if err != nil || len(s) == 0 || base64.RawURLEncoding.EncodeToString(b) != s { + return nil, bad + } + return b, nil + } + data, err := decode(parts[0]) + if err != nil { + return event{}, bad + } + signature, err := decode(parts[1]) + if err != nil { + return event{}, bad + } + mac := hmac.New(sha256.New, key) + _, _ = mac.Write([]byte(parts[0])) + if !hmac.Equal(signature, mac.Sum(nil)) { + return event{}, bad + } + // Reject missing, duplicate, unknown and null fields, including signed payloads. + decoder := json.NewDecoder(bytes.NewReader(data)) + opening, err := decoder.Token() + if err != nil || opening != json.Delim('{') { + return event{}, bad + } + fields := map[string]json.RawMessage{} + for decoder.More() { + name, err := decoder.Token() + if err != nil { + return event{}, bad + } + field, ok := name.(string) + if !ok { + return event{}, bad + } + if _, exists := fields[field]; exists { + return event{}, bad + } + var value json.RawMessage + if decoder.Decode(&value) != nil { + return event{}, bad + } + fields[field] = value + } + if _, err := decoder.Token(); err != nil { + return event{}, bad + } + var trailing any + if decoder.Decode(&trailing) != io.EOF || len(fields) != 5 { + return event{}, bad + } + for _, name := range []string{"version", "tenant_id", "project_id", "created_at", "id"} { + value, ok := fields[name] + if !ok || bytes.Equal(value, []byte("null")) { + return event{}, bad + } + } + var c cursor + strict := json.NewDecoder(bytes.NewReader(data)) + strict.DisallowUnknownFields() + if strict.Decode(&c) != nil || c.Version != 1 || c.Tenant != tenant || c.Project != project || c.ID == "" { + return event{}, bad + } + if _, err := timestamp(c.CreatedAt); err != nil { + return event{}, bad + } + return event{ID: c.ID, CreatedAt: c.CreatedAt}, nil +} + +type publicError struct { + Error struct { + Code string `json:"code"` + Message string `json:"message"` + } `json:"error"` +} + +func failure(code string) (int, publicError) { + status, message := 400, "Invalid cursor." + switch code { + case "invalid_limit": + message = "Limit must be an integer from 1 through 100." + case "unauthenticated": + status, message = 401, "Authentication required." + case "not_found": + status, message = 404, "Project not found." + } + var body publicError + body.Error.Code = code + body.Error.Message = message + return status, body +} + +// Decode each query field independently, preserving invalid escapes for validation. +// Unlike url.ParseQuery, URLSearchParams does not treat a semicolon as a separator. +func parameters(raw string) url.Values { + result := url.Values{} + decode := func(value string) string { + decoded, err := url.QueryUnescape(value) + if err != nil { + return value + } + return decoded + } + for _, field := range strings.Split(raw, "&") { + if field == "" { + continue + } + name, value, _ := strings.Cut(field, "=") + result.Add(decode(name), decode(value)) + } + return result +} + +// createAPI keeps authentication and project authorization ahead of pagination. +func createAPI(f fixtures, seededBug bool) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + send := func(status int, body any) { + data, err := json.Marshal(body) + if err != nil { + http.Error(w, "encoding failure", 500) + return + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + if _, err := w.Write(data); err != nil { + fmt.Fprintln(os.Stderr, "write response:", err) + } + } + fail := func(code string) { status, body := failure(code); send(status, body) } + auth := r.Header.Get("Authorization") + token, ok := strings.CutPrefix(auth, "Bearer ") + tenant := f.Sessions[token] + if !ok || tenant == "" { + fail("unauthenticated") + return + } + path := strings.Split(strings.TrimPrefix(r.URL.EscapedPath(), "/"), "/") + if r.Method != "GET" || (len(path) != 3 && len(path) != 4) || path[0] != "v1" || path[1] != "projects" || (len(path) == 4 && path[3] != "events") { + fail("not_found") + return + } + projectID, err := url.PathUnescape(path[2]) + p, exists := f.Projects[projectID] + if err != nil || !exists || p.Tenant != tenant { + fail("not_found") + return + } + if len(path) == 3 { + send(200, map[string]string{"id": projectID, "name": p.Name}) + return + } + parameters := parameters(r.URL.RawQuery) + limit := 25 + if values, present := parameters["limit"]; present { + if len(values) != 1 || !regexp.MustCompile(`^[0-9]+$`).MatchString(values[0]) { + fail("invalid_limit") + return + } + limit, err = strconv.Atoi(values[0]) + if err != nil || limit < 1 || limit > 100 { + fail("invalid_limit") + return + } + } + var after *event + if values, present := parameters["cursor"]; present { + if len(values) != 1 { + fail("invalid_cursor") + return + } + value, err := decodeCursor(values[0], tenant, projectID, f.SigningKey) + if err != nil { + fail("invalid_cursor") + return + } + after = &value + } + matching := make([]event, 0) + for _, stored := range f.Events { + if stored.Tenant != tenant || stored.Project != projectID { + continue + } + e := stored.event + if after != nil { + if seededBug { + a, _ := timestamp(e.CreatedAt) + b, _ := timestamp(after.CreatedAt) + if !a.Before(b) { + continue + } + } else if compare(e, *after) <= 0 { + continue + } + } + matching = append(matching, e) + } + sort.Slice(matching, func(i, j int) bool { return compare(matching[i], matching[j]) < 0 }) + result := page{Items: matching} + if len(matching) > limit { + result.Items = matching[:limit] + value := encodeCursor(result.Items[limit-1], tenant, projectID, f.SigningKey) + result.NextCursor = &value + } + send(200, result) + }) +} + +type runningAPI struct { + BaseURL string + server *http.Server + done chan error +} + +func startAPI(f fixtures, seededBug bool) (*runningAPI, error) { + listener, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + return nil, err + } + server := &http.Server{ + Handler: createAPI(f, seededBug), + ReadHeaderTimeout: 5 * time.Second, + ReadTimeout: 10 * time.Second, + WriteTimeout: 10 * time.Second, + IdleTimeout: 10 * time.Second, + } + api := &runningAPI{BaseURL: "http://" + listener.Addr().String(), server: server, done: make(chan error, 1)} + go func() { api.done <- server.Serve(listener) }() + return api, nil +} +func (a *runningAPI) Close() error { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + err := a.server.Shutdown(ctx) + if err != nil { + _ = a.server.Close() + } + serveErr := <-a.done + if err != nil { + return err + } + if !errors.Is(serveErr, http.ErrServerClosed) { + return serveErr + } + return nil +} + +type observation struct { + Status int `json:"status"` + Body json.RawMessage `json:"body"` +} + +func request(api *runningAPI, projectID, query, token string, detail bool) (observation, error) { + path := "/v1/projects/" + url.PathEscape(projectID) + if !detail { + path += "/events" + } + req, err := http.NewRequest("GET", api.BaseURL+path+"?"+query, nil) + if err != nil { + return observation{}, err + } + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + // Fixture requests never follow redirects or use a process-configured proxy. + transport := &http.Transport{Proxy: nil} + defer transport.CloseIdleConnections() + client := http.Client{Timeout: 5 * time.Second, Transport: transport, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + response, err := client.Do(req) + if err != nil { + return observation{}, err + } + defer response.Body.Close() + if response.Header.Get("Content-Type") != "application/json" { + return observation{}, errors.New("non-JSON response") + } + data, err := io.ReadAll(io.LimitReader(response.Body, 1<<20)) + if err != nil { + return observation{}, err + } + if !json.Valid(data) { + return observation{}, errors.New("invalid JSON response") + } + return observation{response.StatusCode, data}, nil +} +func ids(p page) []string { + result := make([]string, 0, len(p.Items)) + for _, e := range p.Items { + result = append(result, e.ID) + } + return result +} +func showAPI() error { + f := createFixtures() + api, err := startAPI(f, false) + if err != nil { + return err + } + result, requestErr := request(api, "feed", "limit=2", f.TokenA, false) + closeErr := api.Close() + if requestErr != nil { + return requestErr + } + if closeErr != nil { + return closeErr + } + var p page + if err := json.Unmarshal(result.Body, &p); err != nil { + return err + } + return printJSON(map[string]any{"status": result.Status, "ids": ids(p), "has_next_page": p.NextCursor != nil}) +} +``` + +```java +package com.openai.docs.codexcloud; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.URLDecoder; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +/** A synthetic application HTTP API, not a Codex or OpenAI service client. */ +public final class CodexCloudApi implements AutoCloseable { + public static final ObjectMapper JSON = + new ObjectMapper() + .enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + private static final Base64.Encoder ENCODER = Base64.getUrlEncoder().withoutPadding(); + private static final Base64.Decoder DECODER = Base64.getUrlDecoder(); + private final CodexCloudFixtures.Fixtures fixtures; + private final boolean seededBug; + private final HttpServer server; + private final ExecutorService executor = Executors.newFixedThreadPool(4); + + public record Key(String createdAt, String id) {} + + public record Result(int status, Object body) {} + + public static Instant timestamp(String value) { + if (value == null + || !value.matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?Z")) { + throw new IllegalArgumentException("Invalid timestamp"); + } + Instant parsed = Instant.parse(value); + // Instant permits 24:00 and leap-second normalization; the fixture contract does not. + if (!parsed.toString().substring(0, 19).equals(value.substring(0, 19))) { + throw new IllegalArgumentException("Invalid timestamp"); + } + return parsed; + } + + public static final Comparator ORDER = + Comparator.comparing((Key key) -> timestamp(key.createdAt())) + .reversed() + .thenComparing(Key::id, Comparator.reverseOrder()); + + public static String signPayload(byte[] payload, byte[] signingKey) throws Exception { + String encoded = ENCODER.encodeToString(payload); + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(signingKey, "HmacSHA256")); + return encoded + + "." + + ENCODER.encodeToString(mac.doFinal(encoded.getBytes(StandardCharsets.US_ASCII))); + } + + public static String encodeCursor(Key key, String tenant, String project, byte[] signingKey) + throws Exception { + return signPayload( + JSON.writeValueAsBytes( + Map.of( + "version", + 1, + "tenant_id", + tenant, + "project_id", + project, + "created_at", + key.createdAt(), + "id", + key.id())), + signingKey); + } + + public static Key decodeCursor(String token, String tenant, String project, byte[] signingKey) + throws Exception { + if (token == null || token.length() > 2048) + throw new IllegalArgumentException("Invalid cursor"); + String[] parts = token.split("\\.", -1); + if (parts.length != 2 + || !parts[0].matches("[A-Za-z0-9_-]+") + || !parts[1].matches("[A-Za-z0-9_-]+")) + throw new IllegalArgumentException("Invalid cursor"); + byte[] decoded = DECODER.decode(parts[0]); + byte[] signature = DECODER.decode(parts[1]); + String expected = signPayload(decoded, signingKey).split("\\.")[1]; + if (!ENCODER.encodeToString(decoded).equals(parts[0]) + || !ENCODER.encodeToString(signature).equals(parts[1]) + || !MessageDigest.isEqual(signature, DECODER.decode(expected))) { + throw new IllegalArgumentException("Invalid cursor"); + } + JsonNode node = JSON.readTree(decoded); + Set fields = Set.of("version", "tenant_id", "project_id", "created_at", "id"); + if (node == null || !node.isObject() || node.size() != fields.size()) { + throw new IllegalArgumentException("Invalid cursor"); + } + for (String field : fields) + if (!node.has(field)) throw new IllegalArgumentException("Invalid cursor"); + if (!node.get("version").isIntegralNumber() + || !node.get("version").canConvertToInt() + || node.get("version").intValue() != 1 + || !node.get("tenant_id").isTextual() + || !node.get("tenant_id").textValue().equals(tenant) + || !node.get("project_id").isTextual() + || !node.get("project_id").textValue().equals(project) + || !node.get("id").isTextual() + || node.get("id").textValue().isEmpty() + || !node.get("created_at").isTextual()) + throw new IllegalArgumentException("Invalid cursor"); + timestamp(node.get("created_at").textValue()); + return new Key(node.get("created_at").textValue(), node.get("id").textValue()); + } + + private static Result error(String code) { + int status; + String message; + switch (code) { + case "invalid_cursor" -> { + status = 400; + message = "Invalid cursor."; + } + case "invalid_limit" -> { + status = 400; + message = "Limit must be an integer from 1 through 100."; + } + case "unauthenticated" -> { + status = 401; + message = "Authentication required."; + } + case "not_found" -> { + status = 404; + message = "Project not found."; + } + default -> throw new IllegalArgumentException("Unknown error code"); + } + return new Result(status, Map.of("error", Map.of("code", code, "message", message))); + } + + private static Map> parameters(String raw) { + Map> values = new LinkedHashMap<>(); + if (raw != null && !raw.isEmpty()) { + for (String part : raw.split("&", -1)) { + String[] pair = part.split("=", 2); + String name = URLDecoder.decode(pair[0], StandardCharsets.UTF_8); + String value = URLDecoder.decode(pair.length == 2 ? pair[1] : "", StandardCharsets.UTF_8); + values.computeIfAbsent(name, ignored -> new ArrayList<>()).add(value); + } + } + return values; + } + + /** Authenticate and authorize before interpreting pagination input. */ + public Result respond(String method, URI uri, String authorization) throws Exception { + String tenant = + authorization != null && authorization.matches("Bearer [A-Za-z0-9_-]+") + ? fixtures.sessions().get(authorization.substring(7)) + : null; + if (tenant == null) return error("unauthenticated"); + String[] route = uri.getRawPath().split("/", -1); + if (!method.equals("GET") + || (route.length != 4 && route.length != 5) + || !route[1].equals("v1") + || !route[2].equals("projects") + || (route.length == 5 && !route[4].equals("events"))) return error("not_found"); + String project; + try { + // URLDecoder treats '+' as space; a path component must preserve literal '+'. + project = URLDecoder.decode(route[3].replace("+", "%2B"), StandardCharsets.UTF_8); + } catch (IllegalArgumentException invalid) { + return error("not_found"); + } + CodexCloudFixtures.Project owner = fixtures.projects().get(project); + if (owner == null || !owner.tenantId().equals(tenant)) return error("not_found"); + if (route.length == 4) return new Result(200, Map.of("id", project, "name", owner.name())); + + Map> query; + try { + query = parameters(uri.getRawQuery()); + } catch (IllegalArgumentException invalid) { + return error("invalid_cursor"); + } + List limits = query.getOrDefault("limit", List.of("25")); + int limit; + try { + if (limits.size() != 1 || !limits.get(0).matches("[0-9]+")) return error("invalid_limit"); + limit = Integer.parseInt(limits.get(0)); + if (limit < 1 || limit > 100) return error("invalid_limit"); + } catch (NumberFormatException invalid) { + return error("invalid_limit"); + } + Key cursor = null; + if (query.containsKey("cursor")) { + try { + if (query.get("cursor").size() != 1) return error("invalid_cursor"); + cursor = decodeCursor(query.get("cursor").get(0), tenant, project, fixtures.signingKey()); + } catch (Exception invalid) { + return error("invalid_cursor"); + } + } + List matching = new ArrayList<>(); + for (CodexCloudFixtures.Event event : fixtures.events()) { + if (!event.tenantId().equals(tenant) || !event.projectId().equals(project)) continue; + Key key = new Key(event.createdAt(), event.id()); + if (cursor == null + || (seededBug + ? timestamp(key.createdAt()).isBefore(timestamp(cursor.createdAt())) + : ORDER.compare(key, cursor) > 0)) matching.add(event); + } + matching.sort( + (left, right) -> + ORDER.compare( + new Key(left.createdAt(), left.id()), new Key(right.createdAt(), right.id()))); + List selected = matching.subList(0, Math.min(limit, matching.size())); + String next = null; + if (matching.size() > limit) { + CodexCloudFixtures.Event last = selected.get(selected.size() - 1); + next = + encodeCursor( + new Key(last.createdAt(), last.id()), tenant, project, fixtures.signingKey()); + } + Map page = new LinkedHashMap<>(); + page.put("items", selected.stream().map(CodexCloudFixtures.Event::publicFields).toList()); + page.put("next_cursor", next); + return new Result(200, page); + } + + public CodexCloudApi(CodexCloudFixtures.Fixtures fixtures, boolean seededBug) throws IOException { + this.fixtures = fixtures; + this.seededBug = seededBug; + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.setExecutor(executor); + server.createContext("/", this::handle); + server.start(); + } + + public String baseUrl() { + return "http://127.0.0.1:" + server.getAddress().getPort(); + } + + @Override + public void close() { + server.stop(0); + executor.shutdownNow(); + } + + private void handle(HttpExchange exchange) throws IOException { + try { + Result result; + try { + result = + respond( + exchange.getRequestMethod(), + exchange.getRequestURI(), + exchange.getRequestHeaders().getFirst("Authorization")); + } catch (Exception failure) { + failure.printStackTrace(System.err); + result = + new Result( + 500, + Map.of( + "error", + Map.of("code", "internal_error", "message", "Internal server error."))); + } + byte[] bytes = JSON.writeValueAsBytes(result.body()); + exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8"); + exchange.sendResponseHeaders(result.status(), bytes.length); + exchange.getResponseBody().write(bytes); + } finally { + exchange.close(); + } + } + + public static void main(String[] args) throws Exception { + CodexCloudFixtures.Fixtures fixtures = CodexCloudFixtures.create(); + try (CodexCloudApi api = new CodexCloudApi(fixtures, false)) { + HttpClient client = + HttpClient.newBuilder().connectTimeout(java.time.Duration.ofSeconds(5)).build(); + HttpResponse response = + client.send( + HttpRequest.newBuilder(URI.create(api.baseUrl() + "/v1/projects/feed/events?limit=2")) + .timeout(java.time.Duration.ofSeconds(5)) + .header("Authorization", "Bearer " + fixtures.tokenA()) + .build(), + HttpResponse.BodyHandlers.ofString()); + JsonNode body = JSON.readTree(response.body()); + List ids = new ArrayList<>(); + body.path("items").forEach(item -> ids.add(item.path("id").asText())); + if (response.statusCode() != 200) throw new IllegalStateException(response.body()); + System.out.println( + JSON.writeValueAsString( + Map.of( + "status", + response.statusCode(), + "ids", + ids, + "has_next_page", + !body.path("next_cursor").isNull()))); + } + } +} +``` + +```csharp +internal static IResult Handle(HttpRequest request, Fixtures fixtures, bool seeded) +{ + Match bearer = Regex.Match(request.Headers.Authorization.ToString(), @"\ABearer ([A-Za-z0-9_-]+)\z", + RegexOptions.CultureInvariant); + if (!bearer.Success || !fixtures.Sessions.TryGetValue(bearer.Groups[1].Value, out string? tenant)) + return Fail("unauthenticated"); + Match route = Regex.Match(request.Path.Value ?? "", @"\A/v1/projects/([^/]+)(/events)?\z", + RegexOptions.CultureInvariant); + string projectId; + try { projectId = Uri.UnescapeDataString(route.Groups[1].Value); } + catch (UriFormatException) { return Fail("not_found"); } + if (request.Method != "GET" || !route.Success || + !fixtures.Projects.TryGetValue(projectId, out Project? project) || project.tenant_id != tenant) + return Fail("not_found"); + if (!route.Groups[2].Success) return Results.Json(new { id = projectId, name = project.name }); + int limit = 25; + if (request.Query.TryGetValue("limit", out var values) && + (values.Count != 1 || !Regex.IsMatch(values[0] ?? "", @"\A[0-9]+\z", RegexOptions.CultureInvariant) || + !int.TryParse(values[0], NumberStyles.None, CultureInfo.InvariantCulture, out limit) || limit is < 1 or > 100)) + return Fail("invalid_limit"); + (string Time, string Id)? cursor = null; + if (request.Query.TryGetValue("cursor", out var tokens)) + { + if (tokens.Count != 1) return Fail("invalid_cursor"); + try { cursor = DecodeCursor(tokens[0] ?? "", tenant, projectId, fixtures.SigningKey); } + catch (Exception error) when (error is FormatException or JsonException or InvalidOperationException) + { return Fail("invalid_cursor"); } + } + Event[] matching = fixtures.Events.Where(item => item.tenant_id == tenant && item.project_id == projectId) + .OrderBy( + item => item, + Comparer.Create((left, right) => + Compare(left.created_at, left.id, right.created_at, right.id))) + .Where(item => cursor is null || (seeded + ? Timestamp(item.created_at) < Timestamp(cursor.Value.Time) + : Compare(item.created_at, item.id, cursor.Value.Time, cursor.Value.Id) > 0)).Take(limit + 1).ToArray(); + Event[] selected = matching.Take(limit).ToArray(); + string? next = matching.Length > limit ? Sign(new + { + version = 1, + tenant_id = tenant, + project_id = projectId, + created_at = selected[^1].created_at, + id = selected[^1].id + }, fixtures.SigningKey) : null; + return Results.Json(new + { + items = selected.Select(item => new { item.id, item.created_at, item.type, item.summary }), + next_cursor = next + }); +} +``` + +```ruby +require "base64" +require "json" +require "net/http" +require "openssl" +require "time" +require "timeout" +require "uri" +require "webrick" +require_relative "../fixtures/main" + +module PaginationAPI + ERRORS = { + "invalid_cursor" => [400, "Invalid cursor."], + "invalid_limit" => [400, "Limit must be an integer from 1 through 100."], + "unauthenticated" => [401, "Authentication required."], + "not_found" => [404, "Project not found."] + }.freeze + + def self.timestamp(value) + 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/) + raise ArgumentError, "Invalid timestamp" unless match + + parsed = Time.iso8601(value) + raise ArgumentError, "Invalid timestamp" unless parsed.utc.strftime("%Y-%m-%dT%H:%M:%S") == match[1] + + (parsed.to_r * 1_000_000_000).to_i + end + + def self.compare(left, right) + [timestamp(right.fetch("created_at")), right.fetch("id")] <=> [timestamp(left.fetch("created_at")), left.fetch("id")] + end + + def self.encode_cursor(event, tenant, project, key) + payload = Base64.urlsafe_encode64( + JSON.generate( + version: 1, tenant_id: tenant, project_id: project, + created_at: event.fetch("created_at"), id: event.fetch("id") + ), padding: false + ) + signature = Base64.urlsafe_encode64(OpenSSL::HMAC.digest("SHA256", key, payload), padding: false) + "#{payload}.#{signature}" + end + + def self.decode_cursor(token, tenant, project, key) + raise ArgumentError, "Invalid cursor" unless token.is_a?(String) && token.bytesize <= 2048 + + parts = token.split(".", -1) + raise ArgumentError, "Invalid cursor" unless parts.length == 2 && parts.all? { |part| part.match?(/\A[A-Za-z0-9_-]+\z/) } + + payload, signature = parts + decoded, actual = Base64.urlsafe_decode64(payload), Base64.urlsafe_decode64(signature) + expected = OpenSSL::HMAC.digest("SHA256", key, payload) + unless Base64.urlsafe_encode64(decoded, padding: false) == payload && Base64.urlsafe_encode64(actual, padding: false) == signature && + actual.bytesize == expected.bytesize && OpenSSL.fixed_length_secure_compare(actual, expected) + raise ArgumentError, "Invalid cursor" + end + + cursor = JSON.parse(decoded, allow_duplicate_key: false) + fields = %w[version tenant_id project_id created_at id] + unless cursor.is_a?(Hash) && cursor.keys.sort == fields.sort && cursor["version"].is_a?(Integer) && cursor["version"] == 1 && + cursor["tenant_id"] == tenant && cursor["project_id"] == project && cursor["id"].is_a?(String) && !cursor["id"].empty? + raise ArgumentError, "Invalid cursor" + end + + timestamp(cursor["created_at"]) + cursor + end + + def self.failure(code) + status, message = ERRORS.fetch(code) + [ + status, { + error: { + code: code, + message: message + } + } + ] + end + + def self.handle(request, fixtures, seeded_bug) + bearer = request["authorization"].to_s.match(/\ABearer ([A-Za-z0-9_-]+)\z/) + tenant = bearer && fixtures[:sessions][bearer[1]] + return failure("unauthenticated") unless tenant + + begin + url = URI.parse(request.unparsed_uri) + route = url.path.to_s.match(%r{\A/v1/projects/([^/]+)(/events)?\z}) + project_id = route && URI.decode_www_form_component(route[1]) + rescue ArgumentError, URI::InvalidURIError + return failure("not_found") + end + project = project_id && fixtures[:projects][project_id] + return failure("not_found") unless request.request_method == "GET" && route && project && project["tenant_id"] == tenant + unless route[2] + return [ + 200, { + id: project_id, + name: project["name"] + } + ] + end + + begin + parameters = URI.decode_www_form(url.query.to_s) + rescue ArgumentError + return failure("invalid_cursor") + end + limits = parameters.filter_map { |key, value| value if key == "limit" } + return failure("invalid_limit") if limits.length > 1 || (!limits.empty? && !limits.fetch(0).match?(/\A\d+\z/)) + + limit = limits.empty? ? 25 : limits.fetch(0).to_i + return failure("invalid_limit") unless (1..100).cover?(limit) + + cursors = parameters.filter_map { |key, value| value if key == "cursor" } + cursor = nil + unless cursors.empty? + begin + raise ArgumentError, "Repeated cursor" unless cursors.length == 1 + + cursor = decode_cursor(cursors.first, tenant, project_id, fixtures[:signing_key]) + rescue ArgumentError, JSON::ParserError + return failure("invalid_cursor") + end + end + matching = fixtures[:events].select { |event| event["tenant_id"] == tenant && event["project_id"] == project_id } + .sort { |left, right| compare(left, right) }.select do |event| + !cursor || (seeded_bug ? timestamp(event["created_at"]) < timestamp(cursor["created_at"]) : compare(event, cursor).positive?) + end + selected = matching.take(limit) + items = selected.map { |event| event.slice("id", "created_at", "type", "summary") } + next_cursor = (matching.length > limit) ? encode_cursor(selected.last, tenant, project_id, fixtures[:signing_key]) : nil + [ + 200, { + items: items, + next_cursor: next_cursor + } + ] + end + + def self.start(fixtures, seeded_bug: false) + ready = Queue.new + server = WEBrick::HTTPServer.new( + Port: 0, BindAddress: "127.0.0.1", AccessLog: [], + Logger: WEBrick::Log.new(File::NULL), StartCallback: -> { ready << true } + ) + server.mount_proc("/") do |request, response| + status, body = handle(request, fixtures, seeded_bug) + response.status = status + response["content-type"] = "application/json" + response.body = JSON.generate(body) + end + worker = Thread.new { server.start } + Timeout.timeout(5) { ready.pop } + { + url: "http://127.0.0.1:#{server.config[:Port]}", + + close: -> { + server.shutdown + worker.join + } + } + # Always close the owned listener if startup is interrupted. + rescue Exception # standard:disable Lint/RescueException + server&.shutdown + worker&.join + raise + end + + def self.fetch(base, path, token) + request = Net::HTTP::Get.new(URI("#{base}#{path}")) + request["Authorization"] = "Bearer #{token}" if token + response = Net::HTTP.start(request.uri.host, request.uri.port, open_timeout: 5, read_timeout: 5) { |http| http.request(request) } + [response.code.to_i, JSON.parse(response.body)] + end +end + +if $PROGRAM_NAME == __FILE__ + fixtures = PaginationFixtures.create + api = PaginationAPI.start(fixtures) + begin + status, body = PaginationAPI.fetch(api[:url], "/v1/projects/feed/events?limit=2", fixtures[:token_a]) + puts JSON.generate(status: status, ids: body.fetch("items").map { |item| item.fetch("id") }, has_next_page: !body["next_cursor"].nil?) + ensure + api[:close].call + end +end +``` + +
+ +
+ Seeded records and project access fixtures + Create test fixtures + +```typescript +export function createFixtures() { + const tokenA = randomBytes(24).toString("base64url"); + const tokenB = randomBytes(24).toString("base64url"); + const sessions = new Map([ [tokenA, "tenant_a"], [tokenB, "tenant_b"], ]); - const projects = new Map([ - ["feed", { tenant_id: "tenant_a", name: "Activity feed" }], - ["empty", { tenant_id: "tenant_a", name: "Empty feed" }], - ["exact", { tenant_id: "tenant_a", name: "Four events" }], - ["large", { tenant_id: "tenant_a", name: "Large feed" }], - ["precision", { tenant_id: "tenant_a", name: "Precise timestamps" }], - ["other", { tenant_id: "tenant_a", name: "Another project" }], - ["private", { tenant_id: "tenant_b", name: "Private project" }], + const projects = new Map([ + ["feed", { tenant_id: "tenant_a", name: "Activity feed" }], + ["empty", { tenant_id: "tenant_a", name: "Empty feed" }], + ["exact", { tenant_id: "tenant_a", name: "Four events" }], + ["large", { tenant_id: "tenant_a", name: "Large feed" }], + ["precision", { tenant_id: "tenant_a", name: "Precise timestamps" }], + ["other", { tenant_id: "tenant_a", name: "Another project" }], + ["private", { tenant_id: "tenant_b", name: "Private project" }], + ]); + const event = ( + id: string, + created_at: string, + project_id: string, + tenant_id = "tenant_a" + ) => ({ + id, + created_at, + project_id, + tenant_id, + type: "deployment", + summary: `Synthetic event ${id}`, + internal_note: "This field must never enter the HTTP response.", + raw_payload: { synthetic: true }, + }); + const feed = [ + event("evt_105", "2026-01-15T12:00:03.123456Z", "feed"), + event("evt_104", "2026-01-15T12:00:02.123456Z", "feed"), + event("evt_103", "2026-01-15T12:00:02.123456Z", "feed"), + event("evt_102", "2026-01-15T12:00:02.123456Z", "feed"), + event("evt_101", "2026-01-15T12:00:01.123456Z", "feed"), + ]; + const events = [ + ...feed, + ...feed.slice(0, 4).map((item) => ({ ...item, project_id: "exact" })), + ...Array.from({ length: 105 }, (_, index) => + event( + `large_${String(index).padStart(3, "0")}`, + new Date(Date.UTC(2026, 0, 15, 12, 0, index)) + .toISOString() + .replace(".000Z", ".123456Z"), + "large" + ) + ), + // Reverse ID order makes timestamp precision observable in the tests. + event("precise_a", "2026-01-15T12:00:00.123999Z", "precision"), + event("precise_z", "2026-01-15T12:00:00.123001Z", "precision"), + event("other_1", "2026-01-15T12:00:00.123456Z", "other"), + event("other_2", "2026-01-15T11:59:59.123456Z", "other"), + event("private_1", "2026-01-15T12:00:00.123456Z", "private", "tenant_b"), + event("private_2", "2026-01-15T11:59:59.123456Z", "private", "tenant_b"), + ]; + return { + sessions, + projects, + events, + signingKey: randomBytes(32), + tokenA, + tokenB, + }; +} +``` + +```python +import json +import secrets +from dataclasses import dataclass +from datetime import datetime, timedelta, timezone + + +@dataclass +class Fixtures: + sessions: dict[str, str] + projects: dict[str, dict[str, str]] + events: list[dict] + signing_key: bytes + token_a: str + token_b: str + + +def create_fixtures() -> Fixtures: + token_a, token_b = secrets.token_urlsafe(24), secrets.token_urlsafe(24) + projects = { + name: {"tenant_id": tenant, "name": title} + for name, tenant, title in [ + ("feed", "tenant_a", "Activity feed"), + ("empty", "tenant_a", "Empty feed"), + ("exact", "tenant_a", "Four events"), + ("large", "tenant_a", "Large feed"), + ("precision", "tenant_a", "Precise timestamps"), + ("other", "tenant_a", "Another project"), + ("private", "tenant_b", "Private project"), + ] + } + + def event(identifier, created_at, project_id, tenant_id="tenant_a"): + return { + "id": identifier, + "created_at": created_at, + "project_id": project_id, + "tenant_id": tenant_id, + "type": "deployment", + "summary": f"Synthetic event {identifier}", + "internal_note": "This field must never enter the HTTP response.", + "raw_payload": {"synthetic": True}, + } + + feed = [ + event(f"evt_{identifier}", f"2026-01-15T12:00:0{second}.123456Z", "feed") + for identifier, second in [(105, 3), (104, 2), (103, 2), (102, 2), (101, 1)] + ] + start = datetime(2026, 1, 15, 12, tzinfo=timezone.utc) + events = [ + *feed, + *[{**item, "project_id": "exact"} for item in feed[:4]], + *[ + event( + f"large_{index:03d}", + (start + timedelta(seconds=index)).strftime("%Y-%m-%dT%H:%M:%S") + + ".123456Z", + "large", + ) + for index in range(105) + ], + # Reverse ID order makes submillisecond timestamp ordering observable. + event("precise_a", "2026-01-15T12:00:00.123999Z", "precision"), + event("precise_z", "2026-01-15T12:00:00.123001Z", "precision"), + event("other_1", "2026-01-15T12:00:00.123456Z", "other"), + event("other_2", "2026-01-15T11:59:59.123456Z", "other"), + event("private_1", "2026-01-15T12:00:00.123456Z", "private", "tenant_b"), + event("private_2", "2026-01-15T11:59:59.123456Z", "private", "tenant_b"), + ] + return Fixtures( + {token_a: "tenant_a", token_b: "tenant_b"}, + projects, + events, + secrets.token_bytes(32), + token_a, + token_b, + ) + + +if __name__ == "__main__": + fixtures = create_fixtures() + print( + json.dumps({"projects": len(fixtures.projects), "events": len(fixtures.events)}) + ) +``` + +```go +type event struct { + ID string `json:"id"` + CreatedAt string `json:"created_at"` + Type string `json:"type"` + Summary string `json:"summary"` +} +type storedEvent struct { + event + Tenant, Project, InternalNote string + RawPayload map[string]bool +} +type project struct{ Tenant, Name string } +type fixtures struct { + Sessions map[string]string + Projects map[string]project + Events []storedEvent + SigningKey []byte + TokenA, TokenB string +} + +func randomToken(size int) string { + data := make([]byte, size) + if _, err := rand.Read(data); err != nil { + panic(err) + } + return base64.RawURLEncoding.EncodeToString(data) +} + +func createFixtures() fixtures { + a, b := randomToken(24), randomToken(24) + f := fixtures{ + Sessions: map[string]string{a: "tenant_a", b: "tenant_b"}, + Projects: map[string]project{ + "feed": {"tenant_a", "Activity feed"}, + "empty": {"tenant_a", "Empty feed"}, + "exact": {"tenant_a", "Four events"}, + "large": {"tenant_a", "Large feed"}, + "precision": {"tenant_a", "Precise timestamps"}, + "other": {"tenant_a", "Another project"}, + "private": {"tenant_b", "Private project"}, + }, + TokenA: a, + TokenB: b, + SigningKey: []byte(randomToken(32)), + } + add := func(id, stamp, projectID, tenant string) { + f.Events = append(f.Events, storedEvent{event: event{id, stamp, "deployment", "Synthetic event " + id}, + Tenant: tenant, Project: projectID, InternalNote: "This field must never enter the HTTP response.", RawPayload: map[string]bool{"synthetic": true}}) + } + stamps := []string{"03", "02", "02", "02", "01"} + for i, seconds := range stamps { + id := fmt.Sprintf("evt_%d", 105-i) + stamp := "2026-01-15T12:00:" + seconds + ".123456Z" + add(id, stamp, "feed", "tenant_a") + if i < 4 { + add(id, stamp, "exact", "tenant_a") + } + } + start := time.Date(2026, 1, 15, 12, 0, 0, 123456000, time.UTC) + for i := 0; i < 105; i++ { + add(fmt.Sprintf("large_%03d", i), start.Add(time.Duration(i)*time.Second).Format(time.RFC3339Nano), "large", "tenant_a") + } + add("precise_a", "2026-01-15T12:00:00.123999Z", "precision", "tenant_a") + add("precise_z", "2026-01-15T12:00:00.123001Z", "precision", "tenant_a") + for _, p := range []string{"other", "private"} { + tenant := "tenant_a" + if p == "private" { + tenant = "tenant_b" + } + add(p+"_1", "2026-01-15T12:00:00.123456Z", p, tenant) + add(p+"_2", "2026-01-15T11:59:59.123456Z", p, tenant) + } + return f +} +``` + +```java +package com.openai.docs.codexcloud; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.security.SecureRandom; +import java.time.Instant; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeFormatterBuilder; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Map; + +/** Owned synthetic fixtures. Every construction generates fresh session and cursor secrets. */ +public final class CodexCloudFixtures { + public record Project(String tenantId, String name) {} + + public record Event( + String id, + String createdAt, + String projectId, + String tenantId, + String type, + String summary, + String internalNote, + Map rawPayload) { + public Map publicFields() { + return Map.of("id", id, "created_at", createdAt, "type", type, "summary", summary); + } + } + + public record Fixtures( + Map sessions, + Map projects, + List events, + byte[] signingKey, + String tokenA, + String tokenB) { + public Fixtures { + sessions = Map.copyOf(sessions); + projects = Map.copyOf(projects); + events = List.copyOf(events); + signingKey = signingKey.clone(); + } + + @Override + public byte[] signingKey() { + return signingKey.clone(); + } + } + + private static final SecureRandom RANDOM = new SecureRandom(); + + private static byte[] randomBytes(int length) { + byte[] bytes = new byte[length]; + RANDOM.nextBytes(bytes); + return bytes; + } + + private static String token() { + return Base64.getUrlEncoder().withoutPadding().encodeToString(randomBytes(24)); + } + + private static Event event(String id, String time, String project, String tenant) { + return new Event( + id, + time, + project, + tenant, + "deployment", + "Synthetic event " + id, + "This field must never enter the HTTP response.", + Map.of("synthetic", true)); + } + + public static Fixtures create() { + String tokenA = token(); + String tokenB = token(); + Map projects = + Map.of( + "feed", new Project("tenant_a", "Activity feed"), + "empty", new Project("tenant_a", "Empty feed"), + "exact", new Project("tenant_a", "Four events"), + "large", new Project("tenant_a", "Large feed"), + "precision", new Project("tenant_a", "Precise timestamps"), + "other", new Project("tenant_a", "Another project"), + "private", new Project("tenant_b", "Private project")); + List events = new ArrayList<>(); + String[] times = {"03", "02", "02", "02", "01"}; + for (int index = 0; index < times.length; index++) { + Event item = + event( + "evt_" + (105 - index), + "2026-01-15T12:00:" + times[index] + ".123456Z", + "feed", + "tenant_a"); + events.add(item); + if (index < 4) { + events.add(event(item.id(), item.createdAt(), "exact", "tenant_a")); + } + } + DateTimeFormatter microseconds = new DateTimeFormatterBuilder().appendInstant(6).toFormatter(); + for (int index = 0; index < 105; index++) { + events.add( + event( + String.format(java.util.Locale.ROOT, "large_%03d", index), + microseconds.format(Instant.parse("2026-01-15T12:00:00.123456Z").plusSeconds(index)), + "large", + "tenant_a")); + } + events.add(event("precise_a", "2026-01-15T12:00:00.123999Z", "precision", "tenant_a")); + events.add(event("precise_z", "2026-01-15T12:00:00.123001Z", "precision", "tenant_a")); + for (String project : List.of("other", "private")) { + String tenant = project.equals("private") ? "tenant_b" : "tenant_a"; + events.add(event(project + "_1", "2026-01-15T12:00:00.123456Z", project, tenant)); + events.add(event(project + "_2", "2026-01-15T11:59:59.123456Z", project, tenant)); + } + return new Fixtures( + Map.of(tokenA, "tenant_a", tokenB, "tenant_b"), + projects, + events, + randomBytes(32), + tokenA, + tokenB); + } + + public static void main(String[] args) throws Exception { + Fixtures fixtures = create(); + System.out.println( + new ObjectMapper() + .writeValueAsString( + Map.of( + "projects", fixtures.projects().size(), "events", fixtures.events().size()))); + } +} +``` + +```csharp +internal sealed record Event(string id, string created_at, string project_id, string tenant_id, + string type, string summary, string internal_note, object raw_payload); +internal sealed record Project(string tenant_id, string name); +internal sealed record Fixtures(Dictionary Sessions, Dictionary Projects, + List Events, byte[] SigningKey, string TokenA, string TokenB); + +internal static Fixtures CreateFixtures() +{ + string tokenA = Base64Url(RandomNumberGenerator.GetBytes(24)); + string tokenB = Base64Url(RandomNumberGenerator.GetBytes(24)); + Dictionary sessions = new(StringComparer.Ordinal) + { + [tokenA] = "tenant_a", + [tokenB] = "tenant_b" + }; + Dictionary projects = new(StringComparer.Ordinal) + { + ["feed"] = new("tenant_a", "Activity feed"), + ["empty"] = new("tenant_a", "Empty feed"), + ["exact"] = new("tenant_a", "Four events"), + ["large"] = new("tenant_a", "Large feed"), + ["precision"] = new("tenant_a", "Precise timestamps"), + ["other"] = new("tenant_a", "Another project"), + ["private"] = new("tenant_b", "Private project") + }; + static Event Make(string id, string time, string project, string tenant = "tenant_a") => + new(id, time, project, tenant, "deployment", $"Synthetic event {id}", + "This field must never enter the HTTP response.", new { synthetic = true }); + List feed = + [ + Make("evt_105", "2026-01-15T12:00:03.123456Z", "feed"), + Make("evt_104", "2026-01-15T12:00:02.123456Z", "feed"), + Make("evt_103", "2026-01-15T12:00:02.123456Z", "feed"), + Make("evt_102", "2026-01-15T12:00:02.123456Z", "feed"), + Make("evt_101", "2026-01-15T12:00:01.123456Z", "feed") + ]; + List events = [.. feed, .. feed.Take(4).Select(item => item with { project_id = "exact" })]; + for (int index = 0; index < 105; index++) + { + string time = new DateTimeOffset(2026, 1, 15, 12, 0, 0, TimeSpan.Zero) + .AddSeconds(index).ToString("yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture) + ".123456Z"; + events.Add(Make($"large_{index:D3}", time, "large")); + } + events.AddRange([ + Make("precise_a", "2026-01-15T12:00:00.123999Z", "precision"), + Make("precise_z", "2026-01-15T12:00:00.123001Z", "precision"), + Make("other_1", "2026-01-15T12:00:00.123456Z", "other"), + Make("other_2", "2026-01-15T11:59:59.123456Z", "other"), + Make("private_1", "2026-01-15T12:00:00.123456Z", "private", "tenant_b"), + Make("private_2", "2026-01-15T11:59:59.123456Z", "private", "tenant_b") + ]); + return new(sessions, projects, events, RandomNumberGenerator.GetBytes(32), tokenA, tokenB); +} +``` + +```ruby +require "json" +require "securerandom" +require "time" + +module PaginationFixtures + def self.event(id, created_at, project_id, tenant_id = "tenant_a") + { + "id" => id, + + "created_at" => created_at, + + "project_id" => project_id, + "tenant_id" => tenant_id, + + "type" => "deployment", + + "summary" => "Synthetic event #{id}", + "internal_note" => "This field must never enter the HTTP response.", + + "raw_payload" => { "synthetic" => true } + } + end + + def self.create + token_a, token_b = SecureRandom.urlsafe_base64(24), SecureRandom.urlsafe_base64(24) + projects = { + "feed" => "Activity feed", + + "empty" => "Empty feed", + + "exact" => "Four events", + "large" => "Large feed", + + "precision" => "Precise timestamps", + + "other" => "Another project", + "private" => "Private project" + }.to_h do |id, name| + [ + id, { + "tenant_id" => (id == "private") ? "tenant_b" : "tenant_a", + "name" => name + } + ] + end + feed = [["evt_105", "03"], ["evt_104", "02"], ["evt_103", "02"], ["evt_102", "02"], ["evt_101", "01"]].map do |id, second| + event(id, "2026-01-15T12:00:#{second}.123456Z", "feed") + end + events = feed + feed.take(4).map { |item| item.merge("project_id" => "exact") } + 105.times do |index| + events << event(format("large_%03d", index), (Time.utc(2026, 1, 15, 12) + index).strftime("%Y-%m-%dT%H:%M:%S.123456Z"), "large") + end + events.concat( + [ + event("precise_a", "2026-01-15T12:00:00.123999Z", "precision"), + event("precise_z", "2026-01-15T12:00:00.123001Z", "precision"), + event("other_1", "2026-01-15T12:00:00.123456Z", "other"), + event("other_2", "2026-01-15T11:59:59.123456Z", "other"), + event("private_1", "2026-01-15T12:00:00.123456Z", "private", "tenant_b"), + event("private_2", "2026-01-15T11:59:59.123456Z", "private", "tenant_b") + ] + ) + { + sessions: { + token_a => "tenant_a", + token_b => "tenant_b" + }, + + projects: projects, + events: events, + + signing_key: SecureRandom.random_bytes(32), + + token_a: token_a, + + token_b: token_b + } + end +end + +if $PROGRAM_NAME == __FILE__ + fixtures = PaginationFixtures.create + puts JSON.generate(projects: fixtures[:projects].length, events: fixtures[:events].length) +end +``` + +
+ +
+ HTTP contract and regression tests + Test the example API + +```typescript +test("five-event traversal crosses a timestamp tie and replays the same continuation", async () => { + const expected = ["evt_105", "evt_104", "evt_103", "evt_102", "evt_101"]; + const pages = await traverse("feed", 2, expected); + assert.deepEqual(pages.map(ids), [ + ["evt_105", "evt_104"], + ["evt_103", "evt_102"], + ["evt_101"], + ]); + assert.equal(pages.length, 3); + assert.ok(pages[0].next_cursor); + assert.ok(pages[1].next_cursor); + assert.equal(pages[2].next_cursor, null); + const replay = await request("feed", { + limit: "2", + cursor: pages[0].next_cursor, + }); + assert.deepEqual(replay.body.items, pages[1].items); + const next = await request("feed", { + limit: "2", + cursor: replay.body.next_cursor, + }); + assert.deepEqual(next.body.items, pages[2].items); + assert.equal(next.body.next_cursor, null); + console.log( + JSON.stringify({ + fixture: "five-event-tie", + pages: pages.map(ids), + requests: pages.length, + replay: ids(replay.body), + }) + ); +}); + +test("the same tie group traverses correctly with limit three", async () => { + const pages = await traverse("feed", 3, [ + "evt_105", + "evt_104", + "evt_103", + "evt_102", + "evt_101", + ]); + assert.deepEqual(pages.map(ids), [ + ["evt_105", "evt_104", "evt_103"], + ["evt_102", "evt_101"], + ]); +}); + +test("timestamp ordering and continuation preserve submillisecond precision", async () => { + const pages = await traverse("precision", 1, ["precise_a", "precise_z"]); + assert.equal(pages[0].items[0].created_at, "2026-01-15T12:00:00.123999Z"); + assert.equal(pages[1].items[0].created_at, "2026-01-15T12:00:00.123001Z"); +}); + +test("omitted, minimum, and maximum limits return 25, 1, and 100 of 105 events", async () => { + for (const [parameters, expected] of [ + [{}, 25], + [{ limit: "1" }, 1], + [{ limit: "100" }, 100], + ] as [Record, number][]) { + const result = await request("large", parameters); + assert.equal(result.status, 200); + assert.equal(result.body.items.length, expected); + assert.ok(result.body.next_cursor); + } + const pages = await traverse( + "large", + 100, + Array.from( + { length: 105 }, + (_, index) => `large_${String(104 - index).padStart(3, "0")}` + ) + ); + assert.deepEqual( + pages.map((page) => page.items.length), + [100, 5] + ); +}); + +test("invalid and repeated limits return the documented generic error", async (context) => { + for (const limit of [ + "0", + "101", + "-1", + "1.5", + "many", + "", + "1e2", + "Infinity", + ]) { + await context.test(`limit ${JSON.stringify(limit)}`, async () => { + const result = await request("feed", { limit }); + assert.equal(result.status, 400); + assert.deepEqual( + result.body, + expectedError( + "invalid_limit", + "Limit must be an integer from 1 through 100." + ) + ); + }); + } + const repeated = await request("feed", [ + ["limit", "1"], + ["limit", "2"], + ]); + assert.equal(repeated.status, 400); +}); + +test("empty, partial, and exactly full final pages have no continuation", async () => { + assert.deepEqual((await request("empty")).body, { + items: [], + next_cursor: null, + }); + const partial = await traverse("feed", 2, [ + "evt_105", + "evt_104", + "evt_103", + "evt_102", + "evt_101", + ]); + assert.equal(partial.at(-1).items.length, 1); + const exact = await traverse("exact", 2, [ + "evt_105", + "evt_104", + "evt_103", + "evt_102", + ]); + assert.deepEqual( + exact.map((page) => page.items.length), + [2, 2] + ); + assert.equal(exact[1].next_cursor, null); +}); + +test("authentication precedes malformed and wrong-scope cursor or limit validation", async () => { + const privateCursor = ( + await request("private", { limit: "1" }, fixtures.tokenB) + ).body.next_cursor; + for (const token of [null, "invalid_session"]) { + for (const parameters of [ + { cursor: "broken" }, + { cursor: privateCursor }, + { limit: "0", cursor: "broken" }, + ] as Record[]) { + const result = await request("feed", parameters, token); + assert.equal(result.status, 401); + assert.deepEqual(result.body, unauthenticated); + } + } +}); + +test("inaccessible and nonexistent projects return identical 404 before cursor validation", async () => { + const ownCursor = (await request("feed", { limit: "1" })).body.next_cursor; + for (const project of ["private", "missing"]) { + for (const parameters of [ + {}, + { cursor: "broken" }, + { cursor: ownCursor }, + { limit: "0", cursor: "broken" }, + ] as Record[]) { + const result = await request(project, parameters); + assert.equal(result.status, 404); + assert.deepEqual(result.body, notFound); + } + } +}); + +test("a valid cursor from another project in the same tenant is invalid on an authorized feed", async () => { + const cursor = (await request("other", { limit: "1" })).body.next_cursor; + assert.ok(cursor); + const result = await request("feed", { cursor }); + assert.equal(result.status, 400); + assert.deepEqual(result.body, invalidCursor); +}); + +test("a valid cursor from another tenant is invalid on an authorized feed", async () => { + const cursor = (await request("private", { limit: "1" }, fixtures.tokenB)) + .body.next_cursor; + assert.ok(cursor); + const result = await request("feed", { cursor }); + assert.equal(result.status, 400); + assert.deepEqual(result.body, invalidCursor); +}); + +test("undecodable, empty, tampered, and repeated cursor tokens return the same closed error", async () => { + const cursor = (await request("feed", { limit: "1" })).body.next_cursor; + const [payload, signature] = cursor.split("."); + const tampered = `${payload}.${signature[0] === "A" ? "B" : "A"}${signature.slice(1)}`; + for (const token of [ + "broken", + "", + "%%%.___", + "a.b.c", + "x".repeat(2049), + tampered, + ]) { + const result = await request("feed", { cursor: token }); + assert.equal(result.status, 400); + assert.deepEqual(result.body, invalidCursor); + } + const result = await request("feed", [ + ["cursor", cursor], + ["cursor", cursor], + ]); + assert.equal(result.status, 400); + assert.deepEqual(result.body, invalidCursor); +}); + +test("signed structurally invalid payloads and unsupported versions are rejected", async (context) => { + const valid = { + version: 1, + tenant_id: "tenant_a", + project_id: "feed", + created_at: "2026-01-15T12:00:02.123456Z", + id: "evt_104", + }; + const missing: Partial = { ...valid }; + delete missing.id; + const cases: [string, unknown][] = [ + ["missing ID", missing], + ["number ID", { ...valid, id: 104 }], + ["empty ID", { ...valid, id: "" }], + ["number timestamp", { ...valid, created_at: 0 }], + ["invalid date", { ...valid, created_at: "2026-02-30T12:00:00Z" }], + ["unsupported version", { ...valid, version: 2 }], + ["extra field", { ...valid, extra: true }], + ["wrong tenant type", { ...valid, tenant_id: 1 }], + ["wrong project type", { ...valid, project_id: null }], + ["null payload", null], + ["array payload", []], + ["invalid JSON", "not-json"], + ]; + for (const [name, payload] of cases) { + await context.test(name, async () => { + const result = await request("feed", { cursor: signFixture(payload) }); + assert.equal(result.status, 400); + assert.deepEqual(result.body, invalidCursor); + }); + } +}); + +test("every serialized event omits stored tenant, project, and raw payload fields", async () => { + const result = await request("feed", { limit: "100" }); + assert.equal(result.status, 200); + for (const item of result.body.items) { + assert.deepEqual(Object.keys(item).sort(), [ + "created_at", + "id", + "summary", + "type", ]); - const event = ( - id: string, - created_at: string, - project_id: string, - tenant_id = "tenant_a" - ) => ({ - id, - created_at, - project_id, - tenant_id, + } + assert.ok( + fixtures.events.some((event) => event.internal_note && event.raw_payload) + ); +}); + +test("the schema oracle rejects extra, missing, incorrectly typed, and malformed public fields", () => { + const schema = specification.components.schemas.EventPage; + const page = { + items: [ + { + id: "evt_1", + created_at: "2026-01-15T12:00:00.123456Z", type: "deployment", - summary: `Synthetic event ${id}`, - internal_note: "This field must never enter the HTTP response.", - raw_payload: { synthetic: true }, - }); - const feed = [ - event("evt_105", "2026-01-15T12:00:03.123456Z", "feed"), - event("evt_104", "2026-01-15T12:00:02.123456Z", "feed"), - event("evt_103", "2026-01-15T12:00:02.123456Z", "feed"), - event("evt_102", "2026-01-15T12:00:02.123456Z", "feed"), - event("evt_101", "2026-01-15T12:00:01.123456Z", "feed"), - ]; - const events = [ - ...feed, - ...feed.slice(0, 4).map((item) => ({ ...item, project_id: "exact" })), - ...Array.from({ length: 105 }, (_, index) => - event( - `large_${String(index).padStart(3, "0")}`, - new Date(Date.UTC(2026, 0, 15, 12, 0, index)) - .toISOString() - .replace(".000Z", ".123456Z"), - "large" - ) - ), - // Reverse ID order makes timestamp precision observable in the tests. - event("precise_a", "2026-01-15T12:00:00.123999Z", "precision"), - event("precise_z", "2026-01-15T12:00:00.123001Z", "precision"), - event("other_1", "2026-01-15T12:00:00.123456Z", "other"), - event("other_2", "2026-01-15T11:59:59.123456Z", "other"), - event("private_1", "2026-01-15T12:00:00.123456Z", "private", "tenant_b"), - event("private_2", "2026-01-15T11:59:59.123456Z", "private", "tenant_b"), - ]; - return { - sessions, - projects, - events, - signingKey: randomBytes(32), - tokenA, - tokenB, + summary: "Synthetic", + }, + ], + next_cursor: null, }; -} + assert.ok(conforms(page, schema)); + assert.equal(conforms({ ...page, tenant_id: "tenant_a" }, schema), false); + assert.equal( + conforms( + { ...page, items: [{ ...page.items[0], raw_payload: {} }] }, + schema + ), + false + ); + assert.equal(conforms({ items: page.items }, schema), false); + assert.equal(conforms({ ...page, next_cursor: "" }, schema), false); + assert.equal( + conforms({ ...page, items: [{ ...page.items[0], id: 1 }] }, schema), + false + ); + assert.equal( + conforms( + { ...page, items: [{ ...page.items[0], created_at: "yesterday" }] }, + schema + ), + false + ); + const errorSchema = specification.components.schemas.InvalidCursor; + assert.equal( + conforms( + { error: { ...invalidCursor.error, stack: "internal" } }, + errorSchema + ), + false + ); + assert.equal( + conforms( + { error: { ...invalidCursor.error, message: "tenant_a" } }, + errorSchema + ), + false + ); +}); + +test("the existing project-detail route preserves access and ignores pagination parameters", async () => { + const own = await request( + "feed", + { cursor: "broken", limit: "0" }, + fixtures.tokenA, + true + ); + assert.equal(own.status, 200); + assert.deepEqual(own.body, { id: "feed", name: "Activity feed" }); + const inaccessible = await request("private", {}, fixtures.tokenA, true); + assert.equal(inaccessible.status, 404); + assert.deepEqual(inaccessible.body, notFound); + const unauthenticatedResult = await request("feed", {}, null, true); + assert.equal(unauthenticatedResult.status, 401); + assert.deepEqual(unauthenticatedResult.body, unauthenticated); +}); + +test("OpenAPI declares operation, limit boundaries, signed cursor, and response statuses", () => { + assert.equal(specification.openapi, "3.1.0"); + const operation = specification.paths["/v1/projects/{project_id}/events"].get; + assert.equal(operation.operationId, "listProjectEvents"); + const limit = operation.parameters.find( + (parameter: { name: string }) => parameter.name === "limit" + ).schema; + assert.deepEqual(limit, { + type: "integer", + minimum: 1, + maximum: 100, + default: 25, + }); + assert.deepEqual(Object.keys(operation.responses).sort(), [ + "200", + "400", + "401", + "404", + ]); + assert.equal( + specification.components.securitySchemes.session.scheme, + "bearer" + ); +}); ``` -```ruby -require "json" -require "securerandom" -require "time" +```python +import copy +import hashlib +import hmac +import http.client +import json +import sys +import unittest +from urllib.parse import urlencode, urlsplit + +from api import ( + ERROR_SCHEMAS, + PAGE_SCHEMA, + SPECIFICATION, + base64url, + start_api, + timestamp_value, +) +from fixtures import create_fixtures +from jsonschema import Draft202012Validator, FormatChecker -module PaginationFixtures - def self.event(id, created_at, project_id, tenant_id = "tenant_a") - { - "id" => id, +EXPECTED = ["evt_105", "evt_104", "evt_103", "evt_102", "evt_101"] - "created_at" => created_at, - "project_id" => project_id, - "tenant_id" => tenant_id, +def ids(page): + return [item["id"] for item in page["items"]] - "type" => "deployment", - "summary" => "Synthetic event #{id}", - "internal_note" => "This field must never enter the HTTP response.", +FORMAT_CHECKER = FormatChecker() - "raw_payload" => { "synthetic" => true } - } - end - def self.create - token_a, token_b = SecureRandom.urlsafe_base64(24), SecureRandom.urlsafe_base64(24) - projects = { - "feed" => "Activity feed", +@FORMAT_CHECKER.checks("date-time", raises=ValueError) +def valid_timestamp(value): + # This application's timestamps use UTC and up to nine fractional digits. + # Do not rely on jsonschema's optional, undeclared date-time dependency. + if isinstance(value, str): + timestamp_value(value) + return True - "empty" => "Empty feed", - "exact" => "Four events", - "large" => "Large feed", +def conforms(value, schema): + # The response schemas use local OpenAPI component references. Preserve that + # exact root context instead of reimplementing the schema in each language. + root = {**schema, "components": SPECIFICATION["components"]} + return Draft202012Validator(root, format_checker=FORMAT_CHECKER).is_valid(value) - "precision" => "Precise timestamps", - "other" => "Another project", - "private" => "Private project" - }.to_h do |id, name| - [ - id, { - "tenant_id" => (id == "private") ? "tenant_b" : "tenant_a", - "name" => name +class PaginationTest(unittest.TestCase): + seeded_bug = False + + @classmethod + def setUpClass(cls): + cls.fixtures = create_fixtures() + cls.server = start_api(cls.fixtures, seeded_bug=cls.seeded_bug) + cls.base_url = cls.server.__enter__() + cls.addClassCleanup(cls.server.__exit__, None, None, None) + + def request(self, project="feed", parameters=(), token="own", detail=False): + if token == "own": + token = self.fixtures.token_a + address = urlsplit(self.base_url) + headers = {"Authorization": f"Bearer {token}"} if token else {} + path = f"/v1/projects/{project}{'' if detail else '/events'}?{urlencode(parameters)}" + connection = http.client.HTTPConnection( + address.hostname, address.port, timeout=5 + ) + try: + connection.request("GET", path, headers=headers) + response = connection.getresponse() + self.assertEqual(response.getheader("Content-Type"), "application/json") + body = json.load(response) + route = "/v1/projects/{project_id}" + ("" if detail else "/events") + operation = SPECIFICATION["paths"][route]["get"] + self.assertIn(str(response.status), operation["responses"]) + schema = operation["responses"][str(response.status)]["content"][ + "application/json" + ]["schema"] + self.assertTrue(conforms(body, schema), f"HTTP {response.status}: {body!r}") + return response.status, body + finally: + connection.close() + + def traverse(self, project, limit, expected): + pages, cursor = [], None + bound = max(1, (len(expected) + limit - 1) // limit) + while True: + self.assertLess( + len(pages), + bound, + "Traversal must terminate without an empty extra page", + ) + parameters = {"limit": str(limit)} + if cursor: + parameters["cursor"] = cursor + status, page = self.request(project, parameters) + self.assertEqual(status, 200) + pages.append(page) + cursor = page["next_cursor"] + if cursor is None: + break + observed = [identifier for page in pages for identifier in ids(page)] + self.assertEqual(observed, expected) + self.assertEqual(len(set(observed)), len(expected)) + return pages + + def assert_error(self, result, code, status): + actual_status, body = result + self.assertEqual(actual_status, status) + self.assertTrue(conforms(body, ERROR_SCHEMAS[code])) + + def sign_fixture(self, payload): + data = ( + payload + if isinstance(payload, str) + else json.dumps(payload, separators=(",", ":")) + ) + encoded = base64url(data.encode()) + signature = hmac.new( + self.fixtures.signing_key, encoded.encode(), hashlib.sha256 + ).digest() + return f"{encoded}.{base64url(signature)}" + + def test_tuple_pagination_and_replay(self): + pages = self.traverse("feed", 2, EXPECTED) + expected_pages = [["evt_105", "evt_104"], ["evt_103", "evt_102"], ["evt_101"]] + self.assertEqual(list(map(ids, pages)), expected_pages) + for previous, following in zip(pages, pages[1:]): + status, replay = self.request( + parameters={"limit": "2", "cursor": previous["next_cursor"]} + ) + self.assertEqual(status, 200) + self.assertEqual(replay, following) + print( + json.dumps( + { + "fixture": "five-event-tie", + "pages": list(map(ids, pages)), + "requests": len(pages), + "replay": ids(pages[1]), } + ), + flush=True, + ) + + def test_ties_with_limit_three(self): + pages = self.traverse("feed", 3, EXPECTED) + self.assertEqual(list(map(ids, pages)), [EXPECTED[:3], EXPECTED[3:]]) + + def test_submillisecond_precision(self): + pages = self.traverse("precision", 1, ["precise_a", "precise_z"]) + self.assertEqual( + pages[0]["items"][0]["created_at"], "2026-01-15T12:00:00.123999Z" + ) + self.assertEqual( + pages[1]["items"][0]["created_at"], "2026-01-15T12:00:00.123001Z" + ) + + def test_limit_boundaries(self): + for parameters, count in [ + ({}, 25), + ({"limit": "1"}, 1), + ({"limit": "100"}, 100), + ]: + with self.subTest(parameters=parameters): + status, body = self.request("large", parameters) + self.assertEqual(status, 200) + self.assertEqual(len(body["items"]), count) + self.assertTrue(body["next_cursor"]) + pages = self.traverse( + "large", 100, [f"large_{i:03d}" for i in range(104, -1, -1)] + ) + self.assertEqual([len(page["items"]) for page in pages], [100, 5]) + + def test_invalid_limits(self): + for limit in ["0", "101", "-1", "1.5", "many", "", "1e2", "Infinity"]: + with self.subTest(limit=limit): + self.assert_error( + self.request(parameters={"limit": limit}), "invalid_limit", 400 + ) + self.assert_error( + self.request(parameters=[("limit", "1"), ("limit", "2")]), + "invalid_limit", + 400, + ) + + def test_final_pages(self): + self.assertEqual( + self.request("empty"), (200, {"items": [], "next_cursor": None}) + ) + partial = self.traverse("feed", 2, EXPECTED) + self.assertEqual(len(partial[-1]["items"]), 1) + exact = self.traverse("exact", 2, EXPECTED[:4]) + self.assertEqual([len(page["items"]) for page in exact], [2, 2]) + self.assertIsNone(exact[-1]["next_cursor"]) + + def test_authentication_precedence(self): + private_cursor = self.request("private", {"limit": "1"}, self.fixtures.token_b)[ + 1 + ]["next_cursor"] + for token in [None, "invalid_session"]: + for parameters in [ + {"cursor": "broken"}, + {"cursor": private_cursor}, + {"limit": "0", "cursor": "broken"}, + ]: + with self.subTest(token=token, parameters=parameters): + self.assert_error( + self.request(parameters=parameters, token=token), + "unauthenticated", + 401, + ) + + def test_authorization_precedence(self): + cursor = self.request(parameters={"limit": "1"})[1]["next_cursor"] + for project in ["private", "missing"]: + for parameters in [ + {}, + {"cursor": "broken"}, + {"cursor": cursor}, + {"limit": "0", "cursor": "broken"}, + ]: + with self.subTest(project=project, parameters=parameters): + self.assert_error( + self.request(project, parameters), "not_found", 404 + ) + + def test_project_cursor_scope(self): + cursor = self.request("other", {"limit": "1"})[1]["next_cursor"] + self.assertTrue(cursor) + self.assert_error( + self.request(parameters={"cursor": cursor}), "invalid_cursor", 400 + ) + + def test_tenant_cursor_scope(self): + cursor = self.request("private", {"limit": "1"}, self.fixtures.token_b)[1][ + "next_cursor" ] - end - feed = [["evt_105", "03"], ["evt_104", "02"], ["evt_103", "02"], ["evt_102", "02"], ["evt_101", "01"]].map do |id, second| - event(id, "2026-01-15T12:00:#{second}.123456Z", "feed") - end - events = feed + feed.take(4).map { |item| item.merge("project_id" => "exact") } - 105.times do |index| - events << event(format("large_%03d", index), (Time.utc(2026, 1, 15, 12) + index).strftime("%Y-%m-%dT%H:%M:%S.123456Z"), "large") - end - events.concat( - [ - event("precise_a", "2026-01-15T12:00:00.123999Z", "precision"), - event("precise_z", "2026-01-15T12:00:00.123001Z", "precision"), - event("other_1", "2026-01-15T12:00:00.123456Z", "other"), - event("other_2", "2026-01-15T11:59:59.123456Z", "other"), - event("private_1", "2026-01-15T12:00:00.123456Z", "private", "tenant_b"), - event("private_2", "2026-01-15T11:59:59.123456Z", "private", "tenant_b") + self.assertTrue(cursor) + self.assert_error( + self.request(parameters={"cursor": cursor}), "invalid_cursor", 400 + ) + + def test_malformed_cursors(self): + cursor = self.request(parameters={"limit": "1"})[1]["next_cursor"] + payload, signature = cursor.split(".") + tampered = f"{payload}.{'B' if signature[0] == 'A' else 'A'}{signature[1:]}" + for token in ["broken", "", "%%%.___", "a.b.c", "x" * 2049, tampered]: + with self.subTest(token=token): + self.assert_error( + self.request(parameters={"cursor": token}), "invalid_cursor", 400 + ) + self.assert_error( + self.request(parameters=[("cursor", cursor), ("cursor", cursor)]), + "invalid_cursor", + 400, + ) + + def test_signed_invalid_cursors(self): + valid = { + "version": 1, + "tenant_id": "tenant_a", + "project_id": "feed", + "created_at": "2026-01-15T12:00:02.123456Z", + "id": "evt_104", + } + missing = {name: value for name, value in valid.items() if name != "id"} + cases = [ + missing, + {**valid, "id": 104}, + {**valid, "id": ""}, + {**valid, "created_at": 0}, + {**valid, "created_at": "2026-02-30T12:00:00Z"}, + {**valid, "version": 2}, + {**valid, "version": True}, + {**valid, "extra": True}, + {**valid, "tenant_id": 1}, + {**valid, "project_id": None}, + None, + [], + "not-json", ] + for payload in cases: + with self.subTest(payload=payload): + self.assert_error( + self.request(parameters={"cursor": self.sign_fixture(payload)}), + "invalid_cursor", + 400, + ) + + def test_public_event_fields(self): + status, body = self.request(parameters={"limit": "100"}) + self.assertEqual(status, 200) + for item in body["items"]: + self.assertEqual(set(item), {"id", "created_at", "type", "summary"}) + self.assertTrue( + any( + event.get("raw_payload") and event.get("internal_note") + for event in self.fixtures.events + ) ) + + def test_schema_oracle(self): + page = { + "items": [ { - sessions: { - token_a => "tenant_a", - token_b => "tenant_b" + "id": "evt_1", + "created_at": "2026-01-15T12:00:00.123456Z", + "type": "deployment", + "summary": "Synthetic", + } + ], + "next_cursor": None, + } + self.assertTrue(conforms(page, PAGE_SCHEMA)) + invalid = [ + {**page, "tenant_id": "tenant_a"}, + {"items": page["items"]}, + {**page, "next_cursor": ""}, + ] + for change in [ + {"raw_payload": {}}, + {"id": 1}, + {"created_at": "yesterday"}, + {"type": ""}, + ]: + invalid.append({**page, "items": [{**page["items"][0], **change}]}) + for value in invalid: + self.assertFalse(conforms(value, PAGE_SCHEMA)) + for error in [ + { + "error": { + "code": "invalid_cursor", + "message": "Invalid cursor.", + "stack": "internal", + } }, + {"error": {"code": "invalid_cursor", "message": "tenant_a"}}, + ]: + self.assertFalse(conforms(error, ERROR_SCHEMAS["invalid_cursor"])) + missing = copy.deepcopy(page) + del missing["items"][0]["summary"] + self.assertFalse(conforms(missing, PAGE_SCHEMA)) + + def test_project_detail(self): + self.assertEqual( + self.request(parameters={"cursor": "broken", "limit": "0"}, detail=True), + (200, {"id": "feed", "name": "Activity feed"}), + ) + self.assert_error(self.request("private", detail=True), "not_found", 404) + self.assert_error(self.request(token=None, detail=True), "unauthenticated", 401) + + def test_openapi_contract(self): + """OpenAPI declares operation, limit boundaries, signed cursor, and response statuses""" + self.assertEqual(SPECIFICATION["openapi"], "3.1.0") + operation = SPECIFICATION["paths"]["/v1/projects/{project_id}/events"]["get"] + self.assertEqual(operation["operationId"], "listProjectEvents") + limit = next( + p["schema"] for p in operation["parameters"] if p["name"] == "limit" + ) + self.assertEqual( + limit, {"type": "integer", "minimum": 1, "maximum": 100, "default": 25} + ) + self.assertEqual(set(operation["responses"]), {"200", "400", "401", "404"}) + self.assertEqual( + SPECIFICATION["components"]["securitySchemes"]["session"]["scheme"], + "bearer", + ) + Draft202012Validator.check_schema(PAGE_SCHEMA) - projects: projects, - events: events, - signing_key: SecureRandom.random_bytes(32), +def run_suite(suite): + # Native unittest remains responsible for assertions and nonzero failure exit. + result = unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite) + print( + f"# tests {result.testsRun}\n# fail {len(result.failures) + len(result.errors)}\n" + f"# cancelled 0\n# skipped {len(result.skipped)}\n# todo 0", + flush=True, + ) + return 0 if result.wasSuccessful() else 1 - token_a: token_a, - token_b: token_b +if __name__ == "__main__": + if any(arg != "--seeded" for arg in sys.argv[1:]): + raise SystemExit("Usage: python test.py [--seeded]") + PaginationTest.seeded_bug = "--seeded" in sys.argv + raise SystemExit( + run_suite(unittest.defaultTestLoader.loadTestsFromTestCase(PaginationTest)) + ) +``` + +```go +// validatePage is a closed response oracle for this sample's public contract. +// It rejects missing fields, extra storage fields, null items and invalid dates. +func validatePage(data []byte) error { + var object map[string]json.RawMessage + if json.Unmarshal(data, &object) != nil || len(object) != 2 || object["items"] == nil || object["next_cursor"] == nil { + return errors.New("invalid page fields") } - end -end + var items []map[string]json.RawMessage + if json.Unmarshal(object["items"], &items) != nil || items == nil { + return errors.New("invalid items") + } + for _, item := range items { + if len(item) != 4 { + return errors.New("invalid event fields") + } + for _, name := range []string{"id", "created_at", "type", "summary"} { + var value string + if item[name] == nil || bytes.Equal(item[name], []byte("null")) || json.Unmarshal(item[name], &value) != nil { + return errors.New("invalid event field") + } + if (name == "id" || name == "type") && value == "" { + return errors.New("empty ID or event type") + } + if name == "created_at" { + if _, err := timestamp(value); err != nil { + return err + } + } + } + } + if !bytes.Equal(object["next_cursor"], []byte("null")) { + var value string + if json.Unmarshal(object["next_cursor"], &value) != nil || value == "" { + return errors.New("invalid continuation") + } + } + return nil +} -if $PROGRAM_NAME == __FILE__ - fixtures = PaginationFixtures.create - puts JSON.generate(projects: fixtures[:projects].length, events: fixtures[:events].length) -end +// Canonical shared schema in the public source checkout. The harness copies +// that same file into its owned directory before compiling this program. +const openAPIFile = "../../../typescript-examples/codex-cloud/issue-to-tested-pr/openapi.json" + +func validateOpenAPI(data []byte) error { + var specification struct { + OpenAPI string `json:"openapi"` + Paths map[string]struct { + Get struct { + OperationID string `json:"operationId"` + Parameters []struct { + Name string `json:"name"` + Schema map[string]any `json:"schema"` + } `json:"parameters"` + Responses map[string]json.RawMessage `json:"responses"` + } `json:"get"` + } `json:"paths"` + Components struct { + SecuritySchemes map[string]struct { + Scheme string `json:"scheme"` + } `json:"securitySchemes"` + Schemas map[string]struct { + AdditionalProperties *bool `json:"additionalProperties"` + Required []string `json:"required"` + Properties map[string]map[string]any `json:"properties"` + } `json:"schemas"` + } `json:"components"` + } + if err := json.Unmarshal(data, &specification); err != nil { + return err + } + operation := specification.Paths["/v1/projects/{project_id}/events"].Get + if specification.OpenAPI != "3.1.0" || operation.OperationID != "listProjectEvents" || specification.Components.SecuritySchemes["session"].Scheme != "bearer" { + return errors.New("OpenAPI operation or session authentication changed") + } + var limit, continuation map[string]any + for _, parameter := range operation.Parameters { + if parameter.Name == "limit" { + limit = parameter.Schema + } + if parameter.Name == "cursor" { + continuation = parameter.Schema + } + } + if !reflect.DeepEqual(limit, map[string]any{"type": "integer", "minimum": float64(1), "maximum": float64(100), "default": float64(25)}) { + return errors.New("OpenAPI limit contract changed") + } + if !reflect.DeepEqual(continuation, map[string]any{"type": "string", "minLength": float64(1), "maxLength": float64(2048)}) { + return errors.New("OpenAPI cursor bounds changed") + } + statuses := []string{} + for status := range operation.Responses { + statuses = append(statuses, status) + } + sort.Strings(statuses) + if !reflect.DeepEqual(statuses, []string{"200", "400", "401", "404"}) { + return errors.New("OpenAPI response statuses changed") + } + event := specification.Components.Schemas["Event"] + required := append([]string(nil), event.Required...) + sort.Strings(required) + if event.AdditionalProperties == nil || + *event.AdditionalProperties || + !reflect.DeepEqual(required, []string{"created_at", "id", "summary", "type"}) || + len(event.Properties) != 4 || + event.Properties["id"]["minLength"] != float64(1) || + event.Properties["type"]["minLength"] != float64(1) { + return errors.New("OpenAPI public event projection changed") + } + return nil +} + +func equal(t *testing.T, actual, expected any) { + t.Helper() + if !reflect.DeepEqual(actual, expected) { + t.Fatalf("got %#v; want %#v", actual, expected) + } +} +func setup(t *testing.T, seeded bool) (fixtures, *runningAPI) { + t.Helper() + f := createFixtures() + api, err := startAPI(f, seeded) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := api.Close(); err != nil { + t.Error(err) + } + }) + return f, api +} +func get(t *testing.T, api *runningAPI, f fixtures, projectID, query, token string, detail bool) observation { + t.Helper() + result, err := request(api, projectID, query, token, detail) + if err != nil { + t.Fatal(err) + } + if result.Status != 200 { + var actual publicError + decoder := json.NewDecoder(bytes.NewReader(result.Body)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&actual); err != nil { + t.Fatal(err) + } + status, expected := failure(actual.Error.Code) + if actual.Error.Code != "invalid_cursor" && actual.Error.Code != "invalid_limit" && actual.Error.Code != "not_found" && actual.Error.Code != "unauthenticated" { + t.Fatal("undocumented error code") + } + equal(t, result.Status, status) + equal(t, actual, expected) + } else if !detail { + if err := validatePage(result.Body); err != nil { + t.Fatal(err) + } + } + return result +} +func getPage(t *testing.T, api *runningAPI, f fixtures, p, q string) page { + t.Helper() + result := get(t, api, f, p, q, f.TokenA, false) + equal(t, result.Status, 200) + var body page + if err := json.Unmarshal(result.Body, &body); err != nil { + t.Fatal(err) + } + return body +} +func traverse(t *testing.T, api *runningAPI, f fixtures, p string, limit int, expected []string) []page { + t.Helper() + pages := []page{} + all := []string{} + query := "limit=" + strconv.Itoa(limit) + for { + if len(pages) > len(expected)+1 { + t.Fatal("unbounded traversal") + } + body := getPage(t, api, f, p, query) + pages = append(pages, body) + all = append(all, ids(body)...) + if body.NextCursor == nil { + break + } + query = "limit=" + strconv.Itoa(limit) + "&cursor=" + url.QueryEscape(*body.NextCursor) + } + equal(t, all, expected) + seen := map[string]bool{} + for _, id := range all { + if seen[id] { + t.Fatal("duplicate event") + } + seen[id] = true + } + return pages +} +func signedFixture(payload any, f fixtures) string { + data, err := json.Marshal(payload) + if err != nil { + panic(err) + } + return sign(base64.RawURLEncoding.EncodeToString(data), f.SigningKey) +} + +func regressionTests(seeded bool) []testing.InternalTest { + return []testing.InternalTest{ + {Name: "TestTuplePaginationAndReplay", F: func(t *testing.T) { + f, api := setup(t, seeded) + equal(t, len(f.Projects), 7) + equal(t, len(f.Events), 120) + pages := traverse(t, api, f, "feed", 2, []string{"evt_105", "evt_104", "evt_103", "evt_102", "evt_101"}) + equal(t, len(pages), 3) + equal(t, ids(pages[0]), []string{"evt_105", "evt_104"}) + equal(t, ids(pages[1]), []string{"evt_103", "evt_102"}) + equal(t, ids(pages[2]), []string{"evt_101"}) + if pages[0].NextCursor == nil || pages[1].NextCursor == nil || pages[2].NextCursor != nil { + t.Fatal("incorrect continuation") + } + replay := getPage(t, api, f, "feed", "limit=2&cursor="+url.QueryEscape(*pages[0].NextCursor)) + equal(t, replay, pages[1]) + equal(t, getPage(t, api, f, "feed", "limit=2&cursor="+url.QueryEscape(*replay.NextCursor)), pages[2]) + }}, + {Name: "TestTiesWithLimitThree", F: func(t *testing.T) { + f, api := setup(t, seeded) + pages := traverse(t, api, f, "feed", 3, []string{"evt_105", "evt_104", "evt_103", "evt_102", "evt_101"}) + equal(t, len(pages), 2) + }}, + {Name: "TestSubmillisecondPrecision", F: func(t *testing.T) { + f, api := setup(t, seeded) + pages := traverse(t, api, f, "precision", 1, []string{"precise_a", "precise_z"}) + equal(t, pages[0].Items[0].CreatedAt, "2026-01-15T12:00:00.123999Z") + equal(t, pages[1].Items[0].CreatedAt, "2026-01-15T12:00:00.123001Z") + }}, + {Name: "TestLimitBoundaries", F: func(t *testing.T) { + f, api := setup(t, seeded) + for _, test := range []struct { + query string + count int + }{{"", 25}, {"limit=1", 1}, {"limit=100", 100}} { + p := getPage(t, api, f, "large", test.query) + equal(t, len(p.Items), test.count) + if p.NextCursor == nil { + t.Fatal("missing continuation") + } + } + expected := []string{} + for i := 104; i >= 0; i-- { + expected = append(expected, fmt.Sprintf("large_%03d", i)) + } + pages := traverse(t, api, f, "large", 100, expected) + equal(t, len(pages[0].Items), 100) + equal(t, len(pages[1].Items), 5) + }}, + {Name: "TestInvalidLimits", F: func(t *testing.T) { + f, api := setup(t, seeded) + for _, value := range []string{"0", "101", "-1", "1.5", "many", "", "1e2", "Infinity"} { + r := get(t, api, f, "feed", "limit="+url.QueryEscape(value), f.TokenA, false) + equal(t, r.Status, 400) + } + equal(t, get(t, api, f, "feed", "limit=1&limit=2", f.TokenA, false).Status, 400) + }}, + {Name: "TestFinalPages", F: func(t *testing.T) { + f, api := setup(t, seeded) + p := getPage(t, api, f, "empty", "") + equal(t, len(p.Items), 0) + equal(t, p.NextCursor, (*string)(nil)) + pages := traverse(t, api, f, "exact", 2, []string{"evt_105", "evt_104", "evt_103", "evt_102"}) + equal(t, len(pages), 2) + equal(t, pages[1].NextCursor, (*string)(nil)) + }}, + {Name: "TestAuthenticationPrecedence", F: func(t *testing.T) { + f, api := setup(t, seeded) + for _, token := range []string{"", "invalid_session"} { + for _, q := range []string{"cursor=broken", "limit=0&cursor=broken"} { + equal(t, get(t, api, f, "feed", q, token, false).Status, 401) + } + } + }}, + {Name: "TestAuthorizationPrecedence", F: func(t *testing.T) { + f, api := setup(t, seeded) + own := getPage(t, api, f, "feed", "limit=1") + for _, p := range []string{"private", "missing"} { + for _, q := range []string{"", "cursor=broken", "limit=0&cursor=broken", "cursor=" + url.QueryEscape(*own.NextCursor)} { + equal(t, get(t, api, f, p, q, f.TokenA, false).Status, 404) + } + } + }}, + {Name: "TestProjectCursorScope", F: func(t *testing.T) { + f, api := setup(t, seeded) + other := getPage(t, api, f, "other", "limit=1") + equal(t, get(t, api, f, "feed", "cursor="+url.QueryEscape(*other.NextCursor), f.TokenA, false).Status, 400) + }}, + {Name: "TestTenantCursorScope", F: func(t *testing.T) { + f, api := setup(t, seeded) + r := get(t, api, f, "private", "limit=1", f.TokenB, false) + equal(t, r.Status, 200) + var p page + if err := json.Unmarshal(r.Body, &p); err != nil { + t.Fatal(err) + } + equal(t, get(t, api, f, "feed", "cursor="+url.QueryEscape(*p.NextCursor), f.TokenA, false).Status, 400) + equal(t, get(t, api, f, "feed", "cursor="+url.QueryEscape(*p.NextCursor), "", false).Status, 401) + }}, + {Name: "TestMalformedCursors", F: func(t *testing.T) { + f, api := setup(t, seeded) + p := getPage(t, api, f, "feed", "limit=1") + parts := strings.Split(*p.NextCursor, ".") + first := "A" + if parts[1][0] == 'A' { + first = "B" + } + tampered := parts[0] + "." + first + parts[1][1:] + for _, token := range []string{"broken", "", "%%%.___", "a.b.c", strings.Repeat("x", 2049), tampered} { + equal(t, get(t, api, f, "feed", "cursor="+url.QueryEscape(token), f.TokenA, false).Status, 400) + } + q := "cursor=" + url.QueryEscape(*p.NextCursor) + equal(t, get(t, api, f, "feed", q+"&"+q, f.TokenA, false).Status, 400) + }}, + {Name: "TestSignedInvalidCursors", F: func(t *testing.T) { + f, api := setup(t, seeded) + valid := map[string]any{"version": 1, "tenant_id": "tenant_a", "project_id": "feed", "created_at": "2026-01-15T12:00:02.123456Z", "id": "evt_104"} + for _, change := range []struct { + name string + value any + }{{"id", nil}, {"id", 104}, {"id", ""}, {"created_at", 0}, {"created_at", "2026-02-30T12:00:00Z"}, {"version", 2}, {"extra", true}, {"tenant_id", 1}, {"project_id", nil}} { + input := map[string]any{} + for k, v := range valid { + input[k] = v + } + input[change.name] = change.value + equal(t, get(t, api, f, "feed", "cursor="+url.QueryEscape(signedFixture(input, f)), f.TokenA, false).Status, 400) + } + delete(valid, "id") + for _, input := range []any{valid, nil, []string{}, "not-json"} { + equal(t, get(t, api, f, "feed", "cursor="+url.QueryEscape(signedFixture(input, f)), f.TokenA, false).Status, 400) + } + }}, + {Name: "TestPublicEventFields", F: func(t *testing.T) { + f, api := setup(t, seeded) + r := get(t, api, f, "feed", "limit=100", f.TokenA, false) + equal(t, r.Status, 200) + for _, secret := range []string{"tenant_id", "project_id", "internal_note", "raw_payload"} { + if bytes.Contains(r.Body, []byte(secret)) { + t.Fatal("private field leaked:", secret) + } + } + if f.Events[0].InternalNote == "" || f.Events[0].RawPayload == nil { + t.Fatal("missing negative control") + } + }}, + {Name: "TestSchemaOracle", F: func(t *testing.T) { + valid := []byte(`{"items":[{"id":"evt_1","created_at":"2026-01-15T12:00:00.123456Z","type":"deployment","summary":"Synthetic"}],"next_cursor":null}`) + if err := validatePage(valid); err != nil { + t.Fatal(err) + } + for _, invalid := range []string{ + `{"items":[],"next_cursor":null,"tenant_id":"tenant_a"}`, `{"items":[]}`, `{"items":[],"next_cursor":""}`, + strings.Replace(string(valid), `"evt_1"`, `1`, 1), strings.Replace(string(valid), `2026-01-15T12:00:00.123456Z`, `yesterday`, 1), + strings.Replace(string(valid), `"summary":"Synthetic"`, `"summary":"Synthetic","raw_payload":{}`, 1), + strings.Replace(string(valid), `"type":"deployment"`, `"type":""`, 1), + } { + if validatePage([]byte(invalid)) == nil { + t.Fatal("oracle accepted invalid page", invalid) + } + } + }}, + {Name: "TestProjectDetail", F: func(t *testing.T) { + f, api := setup(t, seeded) + r := get(t, api, f, "feed", "cursor=broken&limit=0", f.TokenA, true) + equal(t, r.Status, 200) + var body map[string]string + if err := json.Unmarshal(r.Body, &body); err != nil { + t.Fatal(err) + } + equal(t, body, map[string]string{"id": "feed", "name": "Activity feed"}) + equal(t, get(t, api, f, "private", "", f.TokenA, true).Status, 404) + equal(t, get(t, api, f, "feed", "", "", true).Status, 401) + }}, + {Name: "TestOpenAPIContract", F: func(t *testing.T) { + data, err := os.ReadFile(openAPIFile) + if err != nil { + t.Fatal(err) + } + if err := validateOpenAPI(data); err != nil { + t.Fatal(err) + } + }}, + } +} + +func matchTest(pattern, name string) (bool, error) { return regexp.MatchString(pattern, name) } +func nativeSuite(seeded bool) { testing.Main(matchTest, regressionTests(seeded), nil, nil) } ``` -
+```java +package com.openai.docs.codexcloud; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.net.URI; +import java.net.URLEncoder; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +/** Native behavioral suite. Run with --seeded to expose the timestamp-only defect. */ +public final class CodexCloudTest { + @FunctionalInterface + public interface Checked { + void run() throws Exception; + } + + public record Response(int status, JsonNode body) {} + + public record SuiteResult(int tests, int failures, List> pages) {} + + private final CodexCloudFixtures.Fixtures fixtures; + private final CodexCloudApi api; + private final HttpClient client = + HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build(); + private int assertions; + private JsonNode specification; + + private CodexCloudTest(CodexCloudFixtures.Fixtures fixtures, CodexCloudApi api) { + this.fixtures = fixtures; + this.api = api; + } + + private void equal(Object actual, Object expected) { + assertions++; + if (!Objects.equals(actual, expected)) { + throw new AssertionError("Expected " + expected + ", got " + actual); + } + } + + private void require(boolean condition, String message) { + assertions++; + if (!condition) throw new AssertionError(message); + } + + public static String query(Map values) { + return values.entrySet().stream() + .map(entry -> encode(entry.getKey()) + "=" + encode(entry.getValue())) + .collect(java.util.stream.Collectors.joining("&")); + } + + private static String encode(String value) { + return URLEncoder.encode(value, StandardCharsets.UTF_8); + } + + private Response request(String project, String query, String token, boolean detail) + throws Exception { + HttpRequest.Builder request = + HttpRequest.newBuilder( + URI.create( + api.baseUrl() + + "/v1/projects/" + + project + + (detail ? "" : "/events") + + "?" + + query)) + .timeout(Duration.ofSeconds(5)); + if (token != null) request.header("Authorization", "Bearer " + token); + HttpResponse response = + client.send(request.build(), HttpResponse.BodyHandlers.ofString()); + require( + response.headers().firstValue("content-type").orElse("").startsWith("application/json"), + "JSON content type"); + JsonNode body = CodexCloudApi.JSON.readTree(response.body()); + require( + conforms(body, response.statusCode(), detail), "Closed public response schema: " + body); + JsonNode spec = specification(); + JsonNode operation = + spec.path("paths") + .path(detail ? "/v1/projects/{project_id}" : "/v1/projects/{project_id}/events") + .path("get"); + JsonNode schema = + operation + .path("responses") + .path(Integer.toString(response.statusCode())) + .path("content") + .path("application/json") + .path("schema"); + require( + !schema.isMissingNode() && schemaConforms(body, schema, spec), "OpenAPI response schema"); + return new Response(response.statusCode(), body); + } + + private Response request(String project, Map query) throws Exception { + return request(project, query(query), fixtures.tokenA(), false); + } + + static java.nio.file.Path openApiFile() throws java.nio.file.NoSuchFileException { + var canonical = + java.nio.file.Path.of("../typescript-examples/codex-cloud/issue-to-tested-pr/openapi.json"); + if (java.nio.file.Files.isRegularFile(canonical)) return canonical; + var isolated = java.nio.file.Path.of("codex-cloud/issue-to-tested-pr/openapi.json"); + if (java.nio.file.Files.isRegularFile(isolated)) return isolated; + throw new java.nio.file.NoSuchFileException( + canonical.toString(), isolated.toString(), "Missing shared OpenAPI fixture"); + } + + private JsonNode specification() throws Exception { + if (specification == null) { + specification = CodexCloudApi.JSON.readTree(java.nio.file.Files.readString(openApiFile())); + } + return specification; + } + + // Only the schema keywords used by the peer's owned OpenAPI fixture are supported. + private static boolean schemaConforms(JsonNode value, JsonNode schema, JsonNode spec) { + if (schema.has("$ref")) { + String reference = schema.path("$ref").asText(); + if (!reference.startsWith("#/")) + throw new IllegalArgumentException("Only local schema references are supported"); + JsonNode resolved = spec.at(reference.substring(1)); + if (resolved.isMissingNode()) + throw new IllegalArgumentException("Unresolved schema reference"); + return schemaConforms(value, resolved, spec); + } + if (schema.has("oneOf")) { + int matches = 0; + for (JsonNode choice : schema.path("oneOf")) + if (schemaConforms(value, choice, spec)) matches++; + return matches == 1; + } + String type = schema.path("type").asText(); + switch (type) { + case "null": + if (!value.isNull()) return false; + break; + case "array": + if (!value.isArray()) return false; + for (JsonNode item : value) + if (!schemaConforms(item, schema.path("items"), spec)) return false; + break; + case "object": + if (!value.isObject()) return false; + for (JsonNode key : schema.path("required")) if (!value.has(key.asText())) return false; + if (schema.path("additionalProperties").isBoolean() + && !schema.path("additionalProperties").asBoolean()) { + for (String key : fields(value)) if (!schema.path("properties").has(key)) return false; + } + for (String key : fields(schema.path("properties"))) { + if (value.has(key) + && !schemaConforms(value.get(key), schema.path("properties").get(key), spec)) + return false; + } + break; + case "string": + if (!value.isTextual()) return false; + String text = value.textValue(); + if (schema.has("minLength") + && text.codePointCount(0, text.length()) < schema.path("minLength").asInt()) + return false; + if (schema.has("pattern") + && !java.util.regex.Pattern.compile(schema.path("pattern").asText()) + .matcher(text) + .find()) return false; + if (schema.path("format").asText().equals("date-time")) { + try { + java.time.OffsetDateTime.parse(text); + } catch (RuntimeException invalid) { + return false; + } + } + break; + case "": + break; + default: + throw new IllegalArgumentException("Unsupported fixture schema type: " + type); + } + if (schema.has("enum")) { + for (JsonNode choice : schema.path("enum")) if (choice.equals(value)) return true; + return false; + } + return true; + } + + private static Set fields(JsonNode object) { + Set keys = new HashSet<>(); + object.fieldNames().forEachRemaining(keys::add); + return keys; + } + + /** Closed schema oracle for this application's public responses, not a general validator. */ + public static boolean conforms(JsonNode body, int status, boolean detail) { + if (body == null || !body.isObject()) return false; + if (status != 200) { + if (!fields(body).equals(Set.of("error"))) return false; + JsonNode error = body.path("error"); + if (!error.isObject() || !fields(error).equals(Set.of("code", "message"))) return false; + Map messages = + Map.of( + "invalid_cursor", + "Invalid cursor.", + "invalid_limit", + "Limit must be an integer from 1 through 100.", + "unauthenticated", + "Authentication required.", + "not_found", + "Project not found."); + Map statuses = + Map.of( + "invalid_cursor", + 400, + "invalid_limit", + 400, + "unauthenticated", + 401, + "not_found", + 404); + String code = error.path("code").asText(); + return error.path("code").isTextual() + && error.path("message").isTextual() + && Objects.equals(statuses.get(code), status) + && Objects.equals(messages.get(code), error.path("message").textValue()); + } + if (detail) + return fields(body).equals(Set.of("id", "name")) + && body.path("id").isTextual() + && !body.path("id").textValue().isEmpty() + && body.path("name").isTextual(); + if (!fields(body).equals(Set.of("items", "next_cursor")) || !body.path("items").isArray()) + return false; + JsonNode cursor = body.path("next_cursor"); + if (!cursor.isNull() + && (!cursor.isTextual() || !cursor.textValue().matches("[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+"))) + return false; + for (JsonNode item : body.path("items")) { + if (!item.isObject() || !fields(item).equals(Set.of("id", "created_at", "type", "summary"))) + return false; + for (String key : List.of("id", "created_at", "type", "summary")) { + if (!item.path(key).isTextual() || item.path(key).textValue().isEmpty()) return false; + } + try { + CodexCloudApi.timestamp(item.path("created_at").textValue()); + } catch (RuntimeException invalid) { + return false; + } + } + return true; + } -
- HTTP contract and regression tests - Test the example API + public static List ids(JsonNode page) { + List ids = new ArrayList<>(); + page.path("items").forEach(item -> ids.add(item.path("id").asText())); + return ids; + } -```typescript -test("five-event traversal crosses a timestamp tie and replays the same continuation", async () => { - const expected = ["evt_105", "evt_104", "evt_103", "evt_102", "evt_101"]; - const pages = await traverse("feed", 2, expected); - assert.deepEqual(pages.map(ids), [ - ["evt_105", "evt_104"], - ["evt_103", "evt_102"], - ["evt_101"], - ]); - assert.equal(pages.length, 3); - assert.ok(pages[0].next_cursor); - assert.ok(pages[1].next_cursor); - assert.equal(pages[2].next_cursor, null); - const replay = await request("feed", { - limit: "2", - cursor: pages[0].next_cursor, - }); - assert.deepEqual(replay.body.items, pages[1].items); - const next = await request("feed", { - limit: "2", - cursor: replay.body.next_cursor, - }); - assert.deepEqual(next.body.items, pages[2].items); - assert.equal(next.body.next_cursor, null); - console.log( - JSON.stringify({ - fixture: "five-event-tie", - pages: pages.map(ids), - requests: pages.length, - replay: ids(replay.body), - }) - ); -}); + private List traverse(String project, int limit, List expected) + throws Exception { + List pages = new ArrayList<>(); + List observed = new ArrayList<>(); + String cursor = null; + do { + require( + pages.size() < Math.max(1, (expected.size() + limit - 1) / limit), "Bounded traversal"); + Map query = new LinkedHashMap<>(); + query.put("limit", Integer.toString(limit)); + if (cursor != null) query.put("cursor", cursor); + Response result = request(project, query); + equal(result.status(), 200); + pages.add(result.body()); + observed.addAll(ids(result.body())); + cursor = + result.body().path("next_cursor").isNull() + ? null + : result.body().path("next_cursor").asText(); + } while (cursor != null); + equal(observed, expected); + equal(new HashSet<>(observed).size(), expected.size()); + return pages; + } -test("the same tie group traverses correctly with limit three", async () => { - const pages = await traverse("feed", 3, [ - "evt_105", - "evt_104", - "evt_103", - "evt_102", - "evt_101", - ]); - assert.deepEqual(pages.map(ids), [ - ["evt_105", "evt_104", "evt_103"], - ["evt_102", "evt_101"], - ]); -}); + private void error(Response response, int status, String code, String message) { + equal(response.status(), status); + equal( + response.body(), + CodexCloudApi.JSON.valueToTree(Map.of("error", Map.of("code", code, "message", message)))); + } -test("timestamp ordering and continuation preserve submillisecond precision", async () => { - const pages = await traverse("precision", 1, ["precise_a", "precise_z"]); - assert.equal(pages[0].items[0].created_at, "2026-01-15T12:00:00.123999Z"); - assert.equal(pages[1].items[0].created_at, "2026-01-15T12:00:00.123001Z"); -}); + private void invalidCursor(String cursor) throws Exception { + error(request("feed", Map.of("cursor", cursor)), 400, "invalid_cursor", "Invalid cursor."); + } -test("omitted, minimum, and maximum limits return 25, 1, and 100 of 105 events", async () => { - for (const [parameters, expected] of [ - [{}, 25], - [{ limit: "1" }, 1], - [{ limit: "100" }, 100], - ] as [Record, number][]) { - const result = await request("large", parameters); - assert.equal(result.status, 200); - assert.equal(result.body.items.length, expected); - assert.ok(result.body.next_cursor); + public static SuiteResult runSuite(boolean seeded) throws Exception { + CodexCloudFixtures.Fixtures fixtures = CodexCloudFixtures.create(); + try (CodexCloudApi api = new CodexCloudApi(fixtures, seeded)) { + CodexCloudTest suite = new CodexCloudTest(fixtures, api); + return suite.run(); + } } - const pages = await traverse( - "large", - 100, - Array.from( - { length: 105 }, - (_, index) => `large_${String(104 - index).padStart(3, "0")}` - ) - ); - assert.deepEqual( - pages.map((page) => page.items.length), - [100, 5] - ); -}); -test("invalid and repeated limits return the documented generic error", async (context) => { - for (const limit of [ + private SuiteResult run() throws Exception { + List expected = List.of("evt_105", "evt_104", "evt_103", "evt_102", "evt_101"); + Map tests = new LinkedHashMap<>(); + List> observedPages = new ArrayList<>(); + tests.put( + "five-event traversal crosses a timestamp tie and replays the same continuation", + () -> { + List pages = traverse("feed", 2, expected); + for (JsonNode page : pages) observedPages.add(ids(page)); + equal(pages.size(), 3); + Response replay = + request( + "feed", + Map.of("limit", "2", "cursor", pages.get(0).path("next_cursor").asText())); + equal(replay.body(), pages.get(1)); + Response last = + request( + "feed", + Map.of("limit", "2", "cursor", replay.body().path("next_cursor").asText())); + equal(last.body(), pages.get(2)); + System.out.println( + CodexCloudApi.JSON.writeValueAsString( + Map.of( + "fixture", + "five-event-tie", + "pages", + observedPages, + "requests", + pages.size(), + "replay", + ids(replay.body())))); + }); + tests.put( + "the same tie group traverses correctly with limit three", + () -> { + List pages = traverse("feed", 3, expected); + equal( + pages.stream().map(CodexCloudTest::ids).toList(), + List.of(expected.subList(0, 3), expected.subList(3, 5))); + }); + tests.put( + "timestamp ordering and continuation preserve submillisecond precision", + () -> { + List pages = traverse("precision", 1, List.of("precise_a", "precise_z")); + equal( + pages.get(0).path("items").get(0).path("created_at").asText(), + "2026-01-15T12:00:00.123999Z"); + equal( + pages.get(1).path("items").get(0).path("created_at").asText(), + "2026-01-15T12:00:00.123001Z"); + }); + tests.put( + "omitted, minimum, and maximum limits return 25, 1, and 100 of 105 events", + () -> { + for (int limit : List.of(25, 1, 100)) { + Response page = request("large", limit == 25 ? Map.of() : Map.of("limit", "" + limit)); + equal(page.body().path("items").size(), limit); + require(page.body().path("next_cursor").isTextual(), "Continuation"); + } + List large = new ArrayList<>(); + for (int index = 104; index >= 0; index--) + large.add(String.format(java.util.Locale.ROOT, "large_%03d", index)); + equal( + traverse("large", 100, large).stream() + .map(page -> page.path("items").size()) + .toList(), + List.of(100, 5)); + }); + tests.put( + "invalid and repeated limits return the documented generic error", + () -> { + for (String limit : + List.of( "0", "101", "-1", @@ -771,268 +3705,461 @@ test("invalid and repeated limits return the documented generic error", async (c "", "1e2", "Infinity", - ]) { - await context.test(`limit ${JSON.stringify(limit)}`, async () => { - const result = await request("feed", { limit }); - assert.equal(result.status, 400); - assert.deepEqual( - result.body, - expectedError( + "999999999999999999999")) { + error( + request("feed", Map.of("limit", limit)), + 400, "invalid_limit", - "Limit must be an integer from 1 through 100." - ) - ); - }); + "Limit must be an integer from 1 through 100."); } - const repeated = await request("feed", [ - ["limit", "1"], - ["limit", "2"], - ]); - assert.equal(repeated.status, 400); -}); - -test("empty, partial, and exactly full final pages have no continuation", async () => { - assert.deepEqual((await request("empty")).body, { - items: [], - next_cursor: null, + error( + request("feed", "limit=1&limit=2", fixtures.tokenA(), false), + 400, + "invalid_limit", + "Limit must be an integer from 1 through 100."); }); - const partial = await traverse("feed", 2, [ - "evt_105", - "evt_104", - "evt_103", - "evt_102", - "evt_101", - ]); - assert.equal(partial.at(-1).items.length, 1); - const exact = await traverse("exact", 2, [ - "evt_105", - "evt_104", - "evt_103", - "evt_102", - ]); - assert.deepEqual( - exact.map((page) => page.items.length), - [2, 2] - ); - assert.equal(exact[1].next_cursor, null); -}); - -test("authentication precedes malformed and wrong-scope cursor or limit validation", async () => { - const privateCursor = ( - await request("private", { limit: "1" }, fixtures.tokenB) - ).body.next_cursor; - for (const token of [null, "invalid_session"]) { - for (const parameters of [ - { cursor: "broken" }, - { cursor: privateCursor }, - { limit: "0", cursor: "broken" }, - ] as Record[]) { - const result = await request("feed", parameters, token); - assert.equal(result.status, 401); - assert.deepEqual(result.body, unauthenticated); + tests.put( + "empty, partial, and exactly full final pages have no continuation", + () -> { + equal(ids(request("empty", Map.of()).body()), List.of()); + require(request("empty", Map.of()).body().path("next_cursor").isNull(), "Empty terminal"); + equal(traverse("feed", 2, expected).get(2).path("items").size(), 1); + List pages = traverse("exact", 2, expected.subList(0, 4)); + equal(pages.stream().map(page -> page.path("items").size()).toList(), List.of(2, 2)); + require(pages.get(1).path("next_cursor").isNull(), "Exact terminal"); + }); + tests.put( + "authentication precedes malformed and wrong-scope cursor or limit validation", + () -> { + String privateCursor = + request("private", "limit=1", fixtures.tokenB(), false) + .body() + .path("next_cursor") + .asText(); + for (String token : new String[] {null, "invalid_session"}) { + for (String query : + List.of("cursor=broken", "limit=0&cursor=broken", "cursor=" + privateCursor)) { + error( + request("feed", query, token, false), + 401, + "unauthenticated", + "Authentication required."); } } -}); - -test("inaccessible and nonexistent projects return identical 404 before cursor validation", async () => { - const ownCursor = (await request("feed", { limit: "1" })).body.next_cursor; - for (const project of ["private", "missing"]) { - for (const parameters of [ - {}, - { cursor: "broken" }, - { cursor: ownCursor }, - { limit: "0", cursor: "broken" }, - ] as Record[]) { - const result = await request(project, parameters); - assert.equal(result.status, 404); - assert.deepEqual(result.body, notFound); + }); + tests.put( + "inaccessible and nonexistent projects return identical 404 before cursor validation", + () -> { + String cursor = request("feed", Map.of("limit", "1")).body().path("next_cursor").asText(); + for (String project : List.of("private", "missing")) { + for (String query : + List.of("", "cursor=broken", "limit=0&cursor=broken", "cursor=" + cursor)) { + error( + request(project, query, fixtures.tokenA(), false), + 404, + "not_found", + "Project not found."); } } -}); - -test("a valid cursor from another project in the same tenant is invalid on an authorized feed", async () => { - const cursor = (await request("other", { limit: "1" })).body.next_cursor; - assert.ok(cursor); - const result = await request("feed", { cursor }); - assert.equal(result.status, 400); - assert.deepEqual(result.body, invalidCursor); -}); - -test("a valid cursor from another tenant is invalid on an authorized feed", async () => { - const cursor = (await request("private", { limit: "1" }, fixtures.tokenB)) - .body.next_cursor; - assert.ok(cursor); - const result = await request("feed", { cursor }); - assert.equal(result.status, 400); - assert.deepEqual(result.body, invalidCursor); -}); - -test("undecodable, empty, tampered, and repeated cursor tokens return the same closed error", async () => { - const cursor = (await request("feed", { limit: "1" })).body.next_cursor; - const [payload, signature] = cursor.split("."); - const tampered = `${payload}.${signature[0] === "A" ? "B" : "A"}${signature.slice(1)}`; - for (const token of [ - "broken", - "", - "%%%.___", - "a.b.c", - "x".repeat(2049), - tampered, - ]) { - const result = await request("feed", { cursor: token }); - assert.equal(result.status, 400); - assert.deepEqual(result.body, invalidCursor); + }); + tests.put( + "a valid cursor from another project is invalid on an authorized feed", + () -> + invalidCursor( + request("other", Map.of("limit", "1")).body().path("next_cursor").asText())); + tests.put( + "a valid cursor from another tenant is invalid on an authorized feed", + () -> + invalidCursor( + request("private", "limit=1", fixtures.tokenB(), false) + .body() + .path("next_cursor") + .asText())); + tests.put( + "undecodable, empty, tampered, and repeated cursor tokens return the same closed error", + () -> { + String cursor = request("feed", Map.of("limit", "1")).body().path("next_cursor").asText(); + String[] parts = cursor.split("\\."); + String tampered = + parts[0] + "." + (parts[1].startsWith("A") ? "B" : "A") + parts[1].substring(1); + for (String value : + List.of("broken", "", "%%%.___", "a.b.c", "x".repeat(2049), tampered, cursor + "=")) + invalidCursor(value); + error( + request("feed", "cursor=" + cursor + "&cursor=" + cursor, fixtures.tokenA(), false), + 400, + "invalid_cursor", + "Invalid cursor."); + }); + tests.put( + "signed structurally invalid payloads and unsupported versions are rejected", + () -> { + ObjectNode valid = + CodexCloudApi.JSON.valueToTree( + Map.of( + "version", + 1, + "tenant_id", + "tenant_a", + "project_id", + "feed", + "created_at", + "2026-01-15T12:00:02.123456Z", + "id", + "evt_104")); + List bad = new ArrayList<>(); + ObjectNode missing = valid.deepCopy(); + missing.remove("id"); + bad.add(missing); + bad.add(valid.deepCopy().put("id", 104)); + bad.add(valid.deepCopy().put("id", "")); + bad.add(valid.deepCopy().put("created_at", 0)); + bad.add(valid.deepCopy().put("created_at", "2026-02-30T12:00:00Z")); + bad.add(valid.deepCopy().put("created_at", "2026-01-15T24:00:00Z")); + bad.add(valid.deepCopy().put("version", 2)); + bad.add(valid.deepCopy().put("version", 1.0)); + bad.add(valid.deepCopy().put("extra", true)); + bad.add(valid.deepCopy().put("tenant_id", 1)); + bad.add(valid.deepCopy().putNull("project_id")); + bad.add(CodexCloudApi.JSON.getNodeFactory().nullNode()); + bad.add(CodexCloudApi.JSON.createArrayNode()); + for (JsonNode value : bad) + invalidCursor( + CodexCloudApi.signPayload( + CodexCloudApi.JSON.writeValueAsBytes(value), fixtures.signingKey())); + for (String value : List.of("not-json", valid + " {}", "{\"version\":1,\"version\":1}")) { + invalidCursor( + CodexCloudApi.signPayload( + value.getBytes(StandardCharsets.UTF_8), fixtures.signingKey())); } - const result = await request("feed", [ - ["cursor", cursor], - ["cursor", cursor], - ]); - assert.equal(result.status, 400); - assert.deepEqual(result.body, invalidCursor); -}); - -test("signed structurally invalid payloads and unsupported versions are rejected", async (context) => { - const valid = { - version: 1, - tenant_id: "tenant_a", - project_id: "feed", - created_at: "2026-01-15T12:00:02.123456Z", - id: "evt_104", - }; - const missing: Partial = { ...valid }; - delete missing.id; - const cases: [string, unknown][] = [ - ["missing ID", missing], - ["number ID", { ...valid, id: 104 }], - ["empty ID", { ...valid, id: "" }], - ["number timestamp", { ...valid, created_at: 0 }], - ["invalid date", { ...valid, created_at: "2026-02-30T12:00:00Z" }], - ["unsupported version", { ...valid, version: 2 }], - ["extra field", { ...valid, extra: true }], - ["wrong tenant type", { ...valid, tenant_id: 1 }], - ["wrong project type", { ...valid, project_id: null }], - ["null payload", null], - ["array payload", []], - ["invalid JSON", "not-json"], - ]; - for (const [name, payload] of cases) { - await context.test(name, async () => { - const result = await request("feed", { cursor: signFixture(payload) }); - assert.equal(result.status, 400); - assert.deepEqual(result.body, invalidCursor); }); + tests.put( + "every serialized event omits stored tenant, project, and raw payload fields", + () -> { + for (JsonNode item : request("feed", Map.of("limit", "100")).body().path("items")) { + equal(fields(item), Set.of("id", "created_at", "type", "summary")); + } + require( + fixtures.events().stream() + .allMatch( + event -> !event.internalNote().isEmpty() && !event.rawPayload().isEmpty()), + "Sensitive fixture fields exist"); + }); + tests.put( + "the schema oracle rejects extra, missing, incorrectly typed, and malformed public fields", + () -> { + ObjectNode page = (ObjectNode) request("feed", Map.of("limit", "1")).body(); + require(!conforms(page.deepCopy().put("extra", true), 200, false), "Extra field"); + ObjectNode missing = page.deepCopy(); + missing.remove("items"); + require(!conforms(missing, 200, false), "Missing field"); + require(!conforms(page.deepCopy().put("items", "bad"), 200, false), "Wrong type"); + require( + !conforms(page.deepCopy().put("next_cursor", "broken"), 200, false), + "Invalid cursor schema"); + ObjectNode time = page.deepCopy(); + ((ObjectNode) time.path("items").get(0)).put("created_at", "bad"); + require(!conforms(time, 200, false), "Invalid timestamp schema"); + require( + !conforms( + CodexCloudApi.JSON.valueToTree( + Map.of("error", Map.of("code", "invalid_cursor", "message", "tenant_a"))), + 400, + false), + "Generic error only"); + }); + tests.put( + "the existing project-detail route preserves access and ignores pagination parameters", + () -> { + Response detail = request("feed", "limit=0&cursor=broken", fixtures.tokenA(), true); + equal(detail.status(), 200); + equal( + detail.body(), + CodexCloudApi.JSON.valueToTree(Map.of("id", "feed", "name", "Activity feed"))); + error( + request("private", "", fixtures.tokenA(), true), + 404, + "not_found", + "Project not found."); + error( + request("feed", "", null, true), 401, "unauthenticated", "Authentication required."); + }); + tests.put( + "OpenAPI declares operation, limit boundaries, signed cursor, and response statuses", + () -> { + // Authoritative shared OpenAPI fixture for this local application. + JsonNode specification = + CodexCloudApi.JSON.readTree(java.nio.file.Files.readString(openApiFile())); + equal(specification.path("openapi").asText(), "3.1.0"); + JsonNode operation = + specification.path("paths").path("/v1/projects/{project_id}/events").path("get"); + equal(operation.path("operationId").asText(), "listProjectEvents"); + JsonNode limit = null; + for (JsonNode parameter : operation.path("parameters")) + if (parameter.path("name").asText().equals("limit")) limit = parameter.path("schema"); + equal( + limit, + CodexCloudApi.JSON.valueToTree( + Map.of("type", "integer", "minimum", 1, "maximum", 100, "default", 25))); + equal(fields(operation.path("responses")), Set.of("200", "400", "401", "404")); + equal( + specification + .path("components") + .path("securitySchemes") + .path("session") + .path("scheme") + .asText(), + "bearer"); + }); + int failures = 0; + int index = 0; + for (Map.Entry test : tests.entrySet()) { + index++; + try { + test.getValue().run(); + System.out.println("ok " + index + " - " + test.getKey()); + } catch (Exception | AssertionError failure) { + failures++; + System.out.println("not ok " + index + " - " + test.getKey()); + failure.printStackTrace(System.err); + } + } + System.out.printf( + "# tests %d%n# assertions %d%n# fail %d%n# cancelled 0%n# skipped 0%n# todo 0%n", + tests.size(), assertions, failures); + return new SuiteResult(tests.size(), failures, observedPages); } -}); -test("every serialized event omits stored tenant, project, and raw payload fields", async () => { - const result = await request("feed", { limit: "100" }); - assert.equal(result.status, 200); - for (const item of result.body.items) { - assert.deepEqual(Object.keys(item).sort(), [ - "created_at", - "id", - "summary", - "type", - ]); + public static void main(String[] args) throws Exception { + boolean seeded = List.of(args).contains("--seeded"); + if (runSuite(seeded).failures() != 0) System.exit(1); } - assert.ok( - fixtures.events.some((event) => event.internal_note && event.raw_payload) - ); -}); +} +``` -test("the schema oracle rejects extra, missing, incorrectly typed, and malformed public fields", () => { - const schema = specification.components.schemas.EventPage; - const page = { - items: [ +```csharp +private static async Task RunSuiteAsync(bool seeded, TextWriter output) +{ + Fixtures fixtures = CreateFixtures(); + await using OwnedApi api = await StartApiAsync(fixtures, seeded); + using HttpClient client = NewClient(api.Address); + JsonObject document = Specification(); + int tests = 0, failures = 0; + List observedPages = []; + async Task Case(string name, Func test) { - id: "evt_1", - created_at: "2026-01-15T12:00:00.123456Z", - type: "deployment", - summary: "Synthetic", - }, - ], - next_cursor: null, + tests++; + if (!await ReportCaseAsync(tests, name, test, output)) failures++; + } + async Task Page(string project = "feed", string query = "", string? token = null) + { + var result = await RequestAsync(client, fixtures, project, query, token); + Require(result.Status == 200 && PublicPage(result.Body) && + Conforms(result.Body, document["components"]!["schemas"]!["EventPage"]!.AsObject(), document), "Expected a closed public page"); + return result.Body; + } + async Task Error(int status, string code, string project = "feed", string query = "", + string? token = null, bool authenticated = true) + { + var result = await RequestAsync(client, fixtures, project, query, token, authenticated); + Require(result.Status == status, $"Expected HTTP {status}, got {result.Status}"); + string message = code switch + { + "invalid_cursor" => "Invalid cursor.", + "invalid_limit" => "Limit must be an integer from 1 through 100.", + "unauthenticated" => "Authentication required.", + "not_found" => "Project not found.", + _ => throw new ArgumentOutOfRangeException(nameof(code)) }; - assert.ok(conforms(page, schema)); - assert.equal(conforms({ ...page, tenant_id: "tenant_a" }, schema), false); - assert.equal( - conforms( - { ...page, items: [{ ...page.items[0], raw_payload: {} }] }, - schema - ), - false - ); - assert.equal(conforms({ items: page.items }, schema), false); - assert.equal(conforms({ ...page, next_cursor: "" }, schema), false); - assert.equal( - conforms({ ...page, items: [{ ...page.items[0], id: 1 }] }, schema), - false - ); - assert.equal( - conforms( - { ...page, items: [{ ...page.items[0], created_at: "yesterday" }] }, - schema - ), - false - ); - const errorSchema = specification.components.schemas.InvalidCursor; - assert.equal( - conforms( - { error: { ...invalidCursor.error, stack: "internal" } }, - errorSchema - ), - false - ); - assert.equal( - conforms( - { error: { ...invalidCursor.error, message: "tenant_a" } }, - errorSchema - ), - false - ); -}); - -test("the existing project-detail route preserves access and ignores pagination parameters", async () => { - const own = await request( - "feed", - { cursor: "broken", limit: "0" }, - fixtures.tokenA, - true - ); - assert.equal(own.status, 200); - assert.deepEqual(own.body, { id: "feed", name: "Activity feed" }); - const inaccessible = await request("private", {}, fixtures.tokenA, true); - assert.equal(inaccessible.status, 404); - assert.deepEqual(inaccessible.body, notFound); - const unauthenticatedResult = await request("feed", {}, null, true); - assert.equal(unauthenticatedResult.status, 401); - assert.deepEqual(unauthenticatedResult.body, unauthenticated); -}); - -test("OpenAPI declares operation, limit boundaries, signed cursor, and response statuses", () => { - assert.equal(specification.openapi, "3.1.0"); - const operation = specification.paths["/v1/projects/{project_id}/events"].get; - assert.equal(operation.operationId, "listProjectEvents"); - const limit = operation.parameters.find( - (parameter: { name: string }) => parameter.name === "limit" - ).schema; - assert.deepEqual(limit, { - type: "integer", - minimum: 1, - maximum: 100, - default: 25, + Equal(result.Body, new { error = new { code, message } }, "Closed error body"); + JsonObject responseSchema = document["paths"]!["/v1/projects/{project_id}/events"]!["get"]! + ["responses"]![status.ToString(CultureInfo.InvariantCulture)]! + ["content"]!["application/json"]!["schema"]!.AsObject(); + Require(Conforms(result.Body, responseSchema, document), "Error matches declared response schema"); + } + async Task> Traverse(string project, int limit, string[] expected) + { + List pages = []; + string? cursor = null; + do + { + Require(pages.Count < Math.Max(1, (expected.Length + limit - 1) / limit), "Traversal request bound"); + JsonObject page = await Page(project, $"limit={limit}" + + (cursor is null ? "" : "&cursor=" + Uri.EscapeDataString(cursor))); + pages.Add(page); + cursor = page["next_cursor"]?.GetValue(); + } while (cursor is not null); + string[] actual = pages.SelectMany(Ids).ToArray(); + Require(actual.SequenceEqual(expected) && actual.Distinct().Count() == actual.Length, + "Complete ordered traversal without duplicate or lost events"); + return pages; + } + string[] feed = ["evt_105", "evt_104", "evt_103", "evt_102", "evt_101"]; + await Case("tuple_pagination_and_replay", async () => + { + var pages = await Traverse("feed", 2, feed); + observedPages.AddRange(pages.Select(Ids)); + var replay = await Page(query: "limit=2&cursor=" + Uri.EscapeDataString(pages[0]["next_cursor"]!.GetValue())); + Equal(replay, pages[1], "Replay returns the same owned continuation"); + var last = await Page(query: "limit=2&cursor=" + Uri.EscapeDataString(replay["next_cursor"]!.GetValue())); + Equal(last, pages[2], "Replay reaches the same final page"); + await output.WriteLineAsync(JsonSerializer.Serialize(new + { fixture = "five-event-tie", pages = pages.Select(Ids), requests = pages.Count, replay = Ids(replay) })); }); - assert.deepEqual(Object.keys(operation.responses).sort(), [ - "200", - "400", - "401", - "404", + await Case("ties_with_limit_three", async () => { await Traverse("feed", 3, feed); }); + await Case("submillisecond_precision", async () => + { + var pages = await Traverse("precision", 1, ["precise_a", "precise_z"]); + Equal(pages[0]["items"]![0]!["created_at"], "2026-01-15T12:00:00.123999Z", "Exact first timestamp"); + Equal(pages[1]["items"]![0]!["created_at"], "2026-01-15T12:00:00.123001Z", "Exact second timestamp"); + Require(Timestamp("2026-01-15T12:00:00.123456789Z") > Timestamp("2026-01-15T12:00:00.123456788Z"), "Nanosecond precision"); + fixtures.Events.AddRange([ + new("nano_a", "2026-01-15T12:00:00.123456789Z", "precision", "tenant_a", "deployment", "Nine digits", "private", new { synthetic = true }), + new("nano_z", "2026-01-15T12:00:00.123456788Z", "precision", "tenant_a", "deployment", "Nine digits", "private", new { synthetic = true }) ]); - assert.equal( - specification.components.securitySchemes.session.scheme, - "bearer" - ); -}); + await Traverse("precision", 1, ["precise_a", "nano_a", "nano_z", "precise_z"]); + }); + await Case("limit_boundaries", async () => + { + foreach (var (query, count) in new[] { ("", 25), ("limit=1", 1), ("limit=100", 100) }) + { + var page = await Page("large", query); + Require(Ids(page).Length == count && page["next_cursor"] is not null, "Limit boundary"); + } + await Traverse("large", 100, Enumerable.Range(0, 105).Reverse().Select(i => $"large_{i:D3}").ToArray()); + }); + await Case("invalid_limits", async () => + { + foreach (string limit in InvalidLimits) + await Error(400, "invalid_limit", query: "limit=" + Uri.EscapeDataString(limit)); + await Error(400, "invalid_limit", query: "limit=1&limit=2"); + }); + await Case("final_pages", async () => + { + Equal(await Page("empty"), new { items = Array.Empty(), next_cursor = (string?)null }, "Empty page"); + await Traverse("exact", 2, feed.Take(4).ToArray()); + await Traverse("feed", 2, feed); + }); + await Case("authentication_precedence", async () => + { + foreach (bool authenticated in AuthenticationStates) + foreach (string query in AuthenticationQueries) + await Error(401, "unauthenticated", query: query, token: "invalid_session", authenticated: authenticated); + }); + await Case("authorization_precedence", async () => + { + foreach (string project in InaccessibleProjects) + foreach (string query in AuthorizationQueries) + await Error(404, "not_found", project, query); + }); + await Case("project_cursor_scope", async () => + { + var page = await Page("other", "limit=1"); + await Error(400, "invalid_cursor", query: "cursor=" + Uri.EscapeDataString(page["next_cursor"]!.GetValue())); + }); + await Case("tenant_cursor_scope", async () => + { + var page = await Page("private", "limit=1", fixtures.TokenB); + string query = "cursor=" + Uri.EscapeDataString(page["next_cursor"]!.GetValue()); + await Error(400, "invalid_cursor", query: query); + await Error(401, "unauthenticated", query: query, authenticated: false); + }); + await Case("malformed_cursors", async () => + { + var page = await Page(query: "limit=1"); + string token = page["next_cursor"]!.GetValue(); + string[] parts = token.Split('.'); + string tampered = parts[0] + "." + (parts[1][0] == 'A' ? 'B' : 'A') + parts[1][1..]; + foreach (string cursor in new[] { "broken", "", "%%%.___", "a.b.c", new string('x', 2049), tampered }) + await Error(400, "invalid_cursor", query: "cursor=" + Uri.EscapeDataString(cursor)); + await Error(400, "invalid_cursor", query: $"cursor={token}&cursor={token}"); + }); + await Case("signed_invalid_cursors", async () => + { + JsonObject valid = new() + { + ["version"] = 1, + ["tenant_id"] = "tenant_a", + ["project_id"] = "feed", + ["created_at"] = "2026-01-15T12:00:02.123456Z", + ["id"] = "evt_104" + }; + foreach (var (field, value) in new (string, JsonNode?)[] + { + ("id", null), ("id", JsonValue.Create(104)), ("id", JsonValue.Create("")), + ("created_at", JsonValue.Create(0)), ("created_at", JsonValue.Create("2026-02-30T12:00:00Z")), + ("version", JsonValue.Create(2)), ("extra", JsonValue.Create(true)), + ("tenant_id", JsonValue.Create(1)), ("project_id", null) + }) + { + JsonObject payload = (JsonObject)valid.DeepClone(); + if (value is null && field == "id") payload.Remove(field); else payload[field] = value?.DeepClone(); + await Error(400, "invalid_cursor", query: "cursor=" + Sign(payload, fixtures.SigningKey)); + } + foreach (object? payload in new object?[] { null, Array.Empty(), "not-json" }) + await Error(400, "invalid_cursor", query: "cursor=" + Sign(payload!, fixtures.SigningKey)); + }); + await Case("public_event_fields", async () => + { + Require(fixtures.Events.Any(item => item.internal_note.Length > 0 && item.raw_payload is not null), "Private fixture fields exist"); + foreach (string project in fixtures.Projects.Keys.Where(id => id != "private")) + { + var page = await Page(project, "limit=100"); + Require(PublicPage(page), "Every public event has only the four documented fields"); + } + }); + await Case("schema_oracle", () => + { + JsonObject page = new() + { + ["items"] = new JsonArray(new JsonObject + { + ["id"] = "evt_1", + ["created_at"] = "2026-01-15T12:00:00.123456Z", + ["type"] = "deployment", + ["summary"] = "Synthetic" + }), + ["next_cursor"] = null + }; + Require(PublicPage(page), "Accept valid public page"); + foreach (string field in PageFields) + { var bad = (JsonObject)page.DeepClone(); bad.Remove(field); Require(!PublicPage(bad), "Reject missing page field"); } + var extra = (JsonObject)page.DeepClone(); extra["tenant_id"] = "tenant_a"; + Require(!PublicPage(extra), "Reject extra page field"); + foreach (string field in EventFields) + { + var missing = (JsonObject)page.DeepClone(); missing["items"]![0]!.AsObject().Remove(field); + Require(!PublicPage(missing), "Reject missing event field"); + var wrong = (JsonObject)page.DeepClone(); wrong["items"]![0]![field] = 1; + Require(!PublicPage(wrong), "Reject wrong event field type"); + } + return Task.CompletedTask; + }); + await Case("project_detail", async () => + { + var own = await RequestAsync(client, fixtures, query: "cursor=broken&limit=0", detail: true); + Require(own.Status == 200, "Detail ignores pagination"); + Equal(own.Body, new { id = "feed", name = "Activity feed" }, "Existing detail body"); + Require((await RequestAsync(client, fixtures, "private", detail: true)).Status == 404, "Detail authorization"); + Require((await RequestAsync(client, fixtures, authenticated: false, detail: true)).Status == 401, "Detail authentication"); + }); + await Case("OpenAPI declares operation, limit boundaries, signed cursor, and response statuses", () => + { + Equal(document["openapi"], "3.1.0", "OpenAPI version"); + var operation = document["paths"]!["/v1/projects/{project_id}/events"]!["get"]!; + Equal(operation["operationId"], "listProjectEvents", "Operation identity"); + JsonNode limit = operation["parameters"]!.AsArray().Single(item => item!["name"]!.GetValue() == "limit")!["schema"]!; + Equal(limit, new { type = "integer", minimum = 1, maximum = 100, @default = 25 }, "Declared limit contract"); + Require(operation["responses"]!.AsObject().Select(pair => pair.Key).Order().SequenceEqual(ResponseStatuses), "Response status set"); + Equal(document["components"]!["securitySchemes"]!["session"]!["scheme"], "bearer", "Session authentication"); + var bad = JsonSerializer.SerializeToNode(new { error = new { code = "invalid_cursor", message = "tenant_a", stack = "internal" } }); + Require(!Conforms(bad, document["components"]!["schemas"]!["InvalidCursor"]!.AsObject(), document), "Reject extra or sensitive error fields"); + return Task.CompletedTask; + }); + await output.WriteLineAsync($"1..{tests}"); + await output.WriteLineAsync($"# tests {tests}\n# pass {tests - failures}\n# fail {failures}\n# cancelled 0\n# skipped 0\n# todo 0"); + return new(tests, failures, observedPages); +} ``` ```ruby @@ -1359,6 +4486,592 @@ console.log( ); ``` +```python +import hashlib +import http.client +import json +import platform +import subprocess +import sys +from datetime import datetime, timezone +from pathlib import Path +from urllib.parse import urlencode, urlsplit + +from api import SPECIFICATION_PATH, start_api +from fixtures import create_fixtures + + +def observe(seeded_bug): + fixtures = create_fixtures() + with start_api(fixtures, seeded_bug=seeded_bug) as base_url: + address = urlsplit(base_url) + + def request(project, parameters, authenticated=True): + connection = http.client.HTTPConnection( + address.hostname, address.port, timeout=5 + ) + try: + connection.request( + "GET", + f"/v1/projects/{project}/events?{urlencode(parameters)}", + headers={"Authorization": f"Bearer {fixtures.token_a}"} + if authenticated + else {}, + ) + response = connection.getresponse() + if response.getheader("Content-Type") != "application/json": + raise RuntimeError("Expected JSON response") + return {"status": response.status, "body": json.load(response)} + finally: + connection.close() + + pages, cursor = [], None + while True: + if len(pages) >= 3: + raise RuntimeError("Traversal exceeded the fixed-fixture request bound") + parameters = {"limit": "2"} + if cursor: + parameters["cursor"] = cursor + response = request("feed", parameters) + if response["status"] != 200: + raise RuntimeError(f"Traversal failed: {response}") + pages.append(response) + cursor = response["body"]["next_cursor"] + if cursor is None: + break + errors = [ + request("feed", {"cursor": "broken"}), + request("feed", {"cursor": "broken"}, False), + request("private", {"cursor": "broken"}), + ] + if [error["status"] for error in errors] != [400, 401, 404]: + raise RuntimeError("Authentication or authorization precedence changed") + return {"pages": pages, "errors": errors} + + +def main(): + if len(sys.argv) > 2: + raise SystemExit("Usage: python reproduce.py [new-evidence-directory]") + directory = Path(__file__).resolve().parent + output = Path(sys.argv[1] if len(sys.argv) == 2 else "./evidence").resolve() + output.mkdir(parents=True, exist_ok=False) + + def write_json(name, value): + (output / name).write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + + states, logs = [], {} + for name, arguments in [("red", ["--seeded"]), ("green", [])]: + command = [sys.executable, str(directory / "test.py"), *arguments] + try: + result = subprocess.run( + command, + cwd=directory, + capture_output=True, + text=True, + timeout=30, + check=False, + ) + log = result.stdout + result.stderr + state = { + "name": name, + "command": command, + "exit_code": result.returncode, + "signal": -result.returncode if result.returncode < 0 else None, + "error": None, + } + except subprocess.TimeoutExpired as error: + + def decoded(value): + return ( + value.decode("utf-8", errors="replace") + if isinstance(value, bytes) + else (value or "") + ) + + log = decoded(error.stdout) + decoded(error.stderr) + state = { + "name": name, + "command": command, + "exit_code": None, + "signal": None, + "error": "Timed out after 30 seconds", + } + (output / f"{name}.log").write_text(log, encoding="utf-8") + logs[name] = log + states.append(state) + sources = { + path.name: hashlib.sha256(path.read_bytes()).hexdigest() + for path in ( + directory / name + for name in [ + "api.py", + "fixtures.py", + "test.py", + "reproduce.py", + ] + ) + } + sources[str(SPECIFICATION_PATH)] = hashlib.sha256( + SPECIFICATION_PATH.read_bytes() + ).hexdigest() + observed = {"red": observe(True), "green": observe(False)} + write_json("observed-http.json", observed) + write_json( + "run-manifest.json", + { + "execution": "Synthetic loopback HTTP fixture; no external service", + "recorded_at": datetime.now(timezone.utc).isoformat(), + "python": platform.python_version(), + "minimum_python": "3.11", + "dependencies": "Python standard library and jsonschema (regression oracle)", + "baseline": "Deliberately seeded timestamp-only continuation; not a historical customer defect", + "correction": "Descending timestamp-and-ID tuple continuation using full fractional precision", + "source_sha256": sources, + "states": states, + }, + ) + green_pages = [ + [item["id"] for item in page["body"]["items"]] + for page in observed["green"]["pages"] + ] + red_ids = [ + item["id"] + for page in observed["red"]["pages"] + for item in page["body"]["items"] + ] + if ( + states[0]["exit_code"] != 1 + or states[1]["exit_code"] != 0 + or "# tests 16\n" not in logs["red"] + or "AssertionError" not in logs["red"] + or "FAIL: test_tuple_pagination_and_replay" not in logs["red"] + or "# tests 16\n" not in logs["green"] + or "# fail 0\n" not in logs["green"] + or green_pages != [["evt_105", "evt_104"], ["evt_103", "evt_102"], ["evt_101"]] + or red_ids != ["evt_105", "evt_104", "evt_101"] + ): + raise RuntimeError( + "Expected the unchanged suite to detect the seeded defect and pass the correction; inspect evidence" + ) + print( + json.dumps( + { + "execution": "synthetic-loopback-http", + "red_exit": states[0]["exit_code"], + "green_exit": states[1]["exit_code"], + "green_pages": green_pages, + "evidence_directory": str(output), + }, + indent=2, + ) + ) + + +if __name__ == "__main__": + main() +``` + +```go +func observe(seeded bool) (map[string]any, error) { + f := createFixtures() + api, err := startAPI(f, seeded) + if err != nil { + return nil, err + } + pages := []observation{} + problems := []observation{} + query := "limit=2" + observeErr := func() error { + for { + if len(pages) >= 3 { + return errors.New("traversal exceeded fixture request bound") + } + result, err := request(api, "feed", query, f.TokenA, false) + if err != nil { + return err + } + if result.Status != 200 { + return fmt.Errorf("unexpected page status %d", result.Status) + } + pages = append(pages, result) + var p page + if err := json.Unmarshal(result.Body, &p); err != nil { + return err + } + if p.NextCursor == nil { + break + } + query = "limit=2&cursor=" + url.QueryEscape(*p.NextCursor) + } + for _, input := range []struct{ project, token string }{{"feed", f.TokenA}, {"feed", ""}, {"private", f.TokenA}} { + result, err := request(api, input.project, "cursor=broken", input.token, false) + if err != nil { + return err + } + problems = append(problems, result) + } + return nil + }() + closeErr := api.Close() + if observeErr != nil { + return nil, observeErr + } + if closeErr != nil { + return nil, closeErr + } + return map[string]any{"pages": pages, "errors": problems}, nil +} +func writeJSON(path string, value any) error { + data, err := json.MarshalIndent(value, "", " ") + if err != nil { + return err + } + return os.WriteFile(path, append(data, '\n'), 0600) +} + +func reproduce(output string) error { + if err := os.Mkdir(output, 0700); err != nil { + return fmt.Errorf("create new owned evidence directory: %w", err) + } + executable, err := os.Executable() + if err != nil { + return err + } + states := []map[string]any{} + exits := []int{} + for _, mode := range []struct { + name string + args []string + }{{"red", []string{"--seeded", "-test.v", "test"}}, {"green", []string{"-test.v", "test"}}} { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + command := exec.CommandContext(ctx, executable, mode.args...) + log, runErr := command.CombinedOutput() + cancel() + exit := 0 + if runErr != nil { + var exitErr *exec.ExitError + if !errors.As(runErr, &exitErr) { + return runErr + } + exit = exitErr.ExitCode() + if exit < 0 { + return fmt.Errorf("%s interrupted: %w", mode.name, runErr) + } + } + if err := os.WriteFile(filepath.Join(output, mode.name+".log"), log, 0600); err != nil { + return err + } + states = append(states, map[string]any{"name": mode.name, "command": append([]string{executable}, mode.args...), "exit_code": exit}) + exits = append(exits, exit) + } + red, err := observe(true) + if err != nil { + return err + } + green, err := observe(false) + if err != nil { + return err + } + if err := writeJSON(filepath.Join(output, "observed-http.json"), map[string]any{"red": red, "green": green}); err != nil { + return err + } + _, sourcePath, _, ok := runtime.Caller(0) + if !ok { + return errors.New("source location unavailable") + } + source, err := os.ReadFile(sourcePath) + if err != nil { + return err + } + digest := sha256.Sum256(source) + if err := writeJSON(filepath.Join(output, "run-manifest.json"), map[string]any{ + "execution": "Synthetic loopback HTTP fixture; no external service", "recorded_at": time.Now().UTC().Format(time.RFC3339Nano), + "go": runtime.Version(), "dependencies": "Go standard library only", "source_sha256": map[string]string{"main.go": fmt.Sprintf("%x", digest)}, + "baseline": "Deliberately seeded timestamp-only continuation; not a historical customer defect", + "correction": "Descending timestamp-and-ID tuple continuation using full fractional precision", "states": states, + }); err != nil { + return err + } + if exits[0] != 1 || exits[1] != 0 { + return fmt.Errorf("expected red exit 1 and green exit 0; got %v", exits) + } + pages := [][]string{} + for _, result := range green["pages"].([]observation) { + var p page + if err := json.Unmarshal(result.Body, &p); err != nil { + return err + } + pages = append(pages, ids(p)) + } + return printJSON(map[string]any{ + "execution": "synthetic-loopback-http", + "red_exit": exits[0], + "green_exit": exits[1], + "green_pages": pages, + "evidence_directory": output, + }) +} +``` + +```java +package com.openai.docs.codexcloud; + +import com.fasterxml.jackson.databind.JsonNode; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +/** Run from the Java example project after compilation, with dependencies on the classpath. */ +public final class CodexCloudReproduce { + private static void write(Path output, String name, Object value) throws Exception { + Files.writeString( + output.resolve(name), + CodexCloudApi.JSON.writerWithDefaultPrettyPrinter().writeValueAsString(value) + "\n"); + } + + public static Map observe(boolean seeded) throws Exception { + CodexCloudFixtures.Fixtures fixtures = CodexCloudFixtures.create(); + HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build(); + try (CodexCloudApi api = new CodexCloudApi(fixtures, seeded)) { + List> pages = new ArrayList<>(); + String cursor = null; + do { + if (pages.size() >= 3) + throw new IllegalStateException("Traversal exceeded the fixed-fixture bound"); + Map query = new LinkedHashMap<>(); + query.put("limit", "2"); + if (cursor != null) query.put("cursor", cursor); + HttpResponse response = + client.send( + HttpRequest.newBuilder( + URI.create( + api.baseUrl() + + "/v1/projects/feed/events?" + + CodexCloudTest.query(query))) + .header("Authorization", "Bearer " + fixtures.tokenA()) + .timeout(Duration.ofSeconds(5)) + .build(), + HttpResponse.BodyHandlers.ofString()); + JsonNode body = CodexCloudApi.JSON.readTree(response.body()); + if (response.statusCode() != 200 || !CodexCloudTest.conforms(body, 200, false)) { + throw new IllegalStateException("Unexpected pagination response: " + response.body()); + } + pages.add(Map.of("status", response.statusCode(), "body", body)); + cursor = body.path("next_cursor").isNull() ? null : body.path("next_cursor").asText(); + } while (cursor != null); + List> errors = new ArrayList<>(); + for (int index = 0; index < 3; index++) { + String project = index == 2 ? "private" : "feed"; + HttpRequest.Builder request = + HttpRequest.newBuilder( + URI.create(api.baseUrl() + "/v1/projects/" + project + "/events?cursor=broken")) + .timeout(Duration.ofSeconds(5)); + if (index != 1) request.header("Authorization", "Bearer " + fixtures.tokenA()); + HttpResponse response = + client.send(request.build(), HttpResponse.BodyHandlers.ofString()); + JsonNode body = CodexCloudApi.JSON.readTree(response.body()); + int expectedStatus = List.of(400, 401, 404).get(index); + if (response.statusCode() != expectedStatus + || !CodexCloudTest.conforms(body, expectedStatus, false)) { + throw new IllegalStateException("Unexpected error response: " + response.body()); + } + errors.add(Map.of("status", response.statusCode(), "body", body)); + } + return Map.of("pages", pages, "errors", errors); + } + } + + public static void main(String[] args) throws Exception { + if (args.length > 2) + throw new IllegalArgumentException("Usage: [evidence-directory] [native-source-root]"); + Path output = Path.of(args.length > 0 ? args[0] : "evidence").toAbsolutePath(); + Path sourceRoot = Path.of(args.length > 1 ? args[1] : "src/main/java/codex-cloud"); + Files.createDirectories(output); + List> states = new ArrayList<>(); + String java = Path.of(System.getProperty("java.home"), "bin", "java").toString(); + for (String name : List.of("red", "green")) { + List command = + new ArrayList<>( + List.of( + java, + "-cp", + System.getProperty("java.class.path"), + CodexCloudTest.class.getName())); + if (name.equals("red")) command.add("--seeded"); + Path log = output.resolve(name + ".log"); + Process process = + new ProcessBuilder(command) + .redirectErrorStream(true) + .redirectOutput(log.toFile()) + .start(); + boolean completed = process.waitFor(30, TimeUnit.SECONDS); + if (!completed) { + process.destroyForcibly(); + if (!process.waitFor(5, TimeUnit.SECONDS)) + throw new IllegalStateException("Native suite did not terminate"); + } + states.add( + Map.of( + "name", + name, + "command", + command, + "exit_code", + process.exitValue(), + "timed_out", + !completed)); + } + Map hashes = new LinkedHashMap<>(); + try (var paths = Files.walk(sourceRoot)) { + for (Path path : paths.filter(Files::isRegularFile).sorted().toList()) { + hashes.put( + sourceRoot.relativize(path).toString(), + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(path)))); + } + } + if (hashes.isEmpty()) throw new IllegalStateException("No authored sources found to hash"); + Path contract = CodexCloudTest.openApiFile(); + hashes.put( + "runtime/codex-cloud/issue-to-tested-pr/openapi.json", + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(contract)))); + Map observed = Map.of("red", observe(true), "green", observe(false)); + write(output, "observed-http.json", observed); + write( + output, + "run-manifest.json", + Map.of( + "execution", + "Synthetic loopback HTTP fixture; no external service", + "recorded_at", + Instant.now().toString(), + "java", + System.getProperty("java.version"), + "minimum_java", + "17", + "dependencies", + "Jackson databind 2.18.11; Java standard library", + "baseline", + "Deliberately seeded timestamp-only continuation; not a historical customer defect", + "correction", + "Descending timestamp-and-ID tuple continuation using full fractional precision", + "source_sha256", + hashes, + "states", + states)); + if (!states.get(0).get("exit_code").equals(1) + || !states.get(1).get("exit_code").equals(0) + || states.stream().anyMatch(state -> state.get("timed_out").equals(true))) { + throw new IllegalStateException( + "Expected failing baseline and passing correction; inspect red.log and green.log"); + } + JsonNode green = CodexCloudApi.JSON.valueToTree(observed.get("green")); + List> pages = new ArrayList<>(); + for (JsonNode page : green.path("pages")) pages.add(CodexCloudTest.ids(page.path("body"))); + if (!pages.equals( + List.of( + List.of("evt_105", "evt_104"), List.of("evt_103", "evt_102"), List.of("evt_101")))) { + throw new IllegalStateException("Corrected page traversal did not preserve every fixture ID"); + } + System.out.println( + CodexCloudApi.JSON.writeValueAsString( + Map.of( + "execution", + "synthetic-loopback-http", + "red_exit", + states.get(0).get("exit_code"), + "green_exit", + states.get(1).get("exit_code"), + "green_pages", + pages, + "evidence_directory", + output.toString()))); + } +} +``` + +```csharp +using System.Globalization; +using System.Net; +using System.Net.Http.Headers; +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.RegularExpressions; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Hosting.Server.Features; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +internal static async Task RunAsync() +{ + string output = Path.GetFullPath("evidence"); + Directory.CreateDirectory(output); + SuiteResult red; + SuiteResult green; + using (StringWriter log = new(CultureInfo.InvariantCulture)) + { + red = await RunSuiteAsync(seeded: true, log); + await File.WriteAllTextAsync(Path.Combine(output, "red.log"), log.ToString()); + } + using (StringWriter log = new(CultureInfo.InvariantCulture)) + { + green = await RunSuiteAsync(seeded: false, log); + await File.WriteAllTextAsync(Path.Combine(output, "green.log"), log.ToString()); + } + int redExit = red.Failures == 0 ? 0 : 1; + int greenExit = green.Failures == 0 ? 0 : 1; + var observed = new { red = await ObserveAsync(true), green = await ObserveAsync(false) }; + await File.WriteAllTextAsync(Path.Combine(output, "observed-http.json"), JsonSerializer.Serialize(observed)); + string sourcePath = SourceFile(); + Dictionary hashes = new(StringComparer.Ordinal) + { + [Path.GetFileName(sourcePath)] = Convert.ToHexStringLower(SHA256.HashData(await File.ReadAllBytesAsync(sourcePath))) + }; + await File.WriteAllTextAsync(Path.Combine(output, "run-manifest.json"), JsonSerializer.Serialize(new + { + execution = "Synthetic loopback HTTP fixture; no external service", + recorded_at = DateTimeOffset.UtcNow, + runtime = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription, + dependencies = "Microsoft.AspNetCore.App shared framework; no OpenAI API or SDK calls", + baseline = "Deliberately seeded timestamp-only continuation; not a historical customer defect", + correction = "Descending timestamp-and-ID tuple continuation using nine-digit fractional precision", + source_sha256 = hashes, + states = new[] { new { name = "red", exit_code = redExit }, new { name = "green", exit_code = greenExit } }, + execution_driver = "The same native behavioral suite runs in-process twice; exit_code is its failure status." + })); + if (redExit != 1 || greenExit != 0 || green.Tests != 16) + throw new InvalidOperationException("Expected failing seeded baseline and passing corrected suite; inspect evidence logs"); + Console.WriteLine(JsonSerializer.Serialize(new + { + execution = "synthetic-loopback-http", + red_exit = redExit, + green_exit = greenExit, + green_pages = green.Pages, + evidence_directory = output + })); +} +``` + ```ruby require "digest" require "fileutils"