165 165
166 166
167 167
168Use the [complete Python incident program](https://github.com/openai/developers-website/blob/main/src/content/platform/python-examples/codex-cloud/incident-to-tested-fix.py) from a complete [Python sample project](https://github.com/openai/developers-website/tree/main/src/content/platform/python-examples) checkout. The excerpt below shows `fixed()`; use the linked full program for its supporting helpers and test runner. Keep `codex-cloud/incidents/`, `pyproject.toml`, and `uv.lock` intact. The ZIP above contains only TypeScript.
169
170Install Python 3.11 or later, uv, and Docker Compose. The locked Python dependencies include `psycopg[binary]==3.3.9`; `uv sync --locked` installs Psycopg and its binary package. Start at the repository checkout root in a POSIX shell. Keep the sibling `typescript-examples/codex-cloud/incident-to-tested-fix/compose.yaml` and `init.sql` together; the commands below start the shared PostgreSQL 17.6 fixture on `127.0.0.1:55432`.
171
172Reserve this fixture for the rehearsal and keep application data out of it. Run the following Python commands instead of the Node runner commands above. Expect the deliberately failing baseline to exit with `1`, then continue with regression and fixed:
173
174```bash
175incident_fixture_dir="$PWD/src/content/platform/typescript-examples/codex-cloud/incident-to-tested-fix"
176docker compose -f "$incident_fixture_dir/compose.yaml" -p codex-incident-rehearsal up -d --wait postgres
177cd src/content/platform/python-examples
178uv sync --locked
179CODEX_INCIDENT_TEST_PASSWORD=synthetic-incident-fixture-only .venv/bin/python codex-cloud/incident-to-tested-fix.py baseline
180CODEX_INCIDENT_TEST_PASSWORD=synthetic-incident-fixture-only .venv/bin/python codex-cloud/incident-to-tested-fix.py regression
181CODEX_INCIDENT_TEST_PASSWORD=synthetic-incident-fixture-only .venv/bin/python codex-cloud/incident-to-tested-fix.py fixed
182docker compose -f "$incident_fixture_dir/compose.yaml" -p codex-incident-rehearsal down --volumes
183```
184
185Use only the public synthetic fixture password shown above. Each Python command supplies it through `CODEX_INCIDENT_TEST_PASSWORD` for that child process; no production credential is needed. The runner connects to the fixture's `codex_incident_test` database and user. Expect regression and fixed to exit with `0`.
186
187Run the final Compose command after the checks, including after a failure, to remove the disposable fixture. The absolute Compose path keeps cleanup valid after changing to the Python directory. Do not run this fixture alongside another rehearsal using the same project or port.
188
189
190
191
192
193
194
195**Java setup**
196
197Use 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).
198
199Start at the checkout root in a POSIX shell. The fixture loader requires the sibling `../typescript-examples/codex-cloud/incident-to-tested-fix/incidents/INC-DEMO-014/order-created.sanitized.json` file, relative to the Java project directory, from the same checkout.
200
201The commands use the same Compose project, PostgreSQL service, and cleanup as above. The explicit Compose file path keeps startup and cleanup independent of the Java working directory.
202
203```bash
204incident_fixture_dir="$PWD/src/content/platform/typescript-examples/codex-cloud/incident-to-tested-fix"
205docker compose -f "$incident_fixture_dir/compose.yaml" -p codex-incident-rehearsal up -d --wait postgres
206cd src/content/platform/java-examples
207mvn -q -DskipTests compile dependency:build-classpath -Dmdep.outputFile=target/live-classpath
208PGPASSWORD=synthetic-incident-fixture-only java -cp "target/classes:$(cat target/live-classpath)" com.openai.docs.codexcloud.CodexCloudIncidentToTestedFix baseline
209PGPASSWORD=synthetic-incident-fixture-only java -cp "target/classes:$(cat target/live-classpath)" com.openai.docs.codexcloud.CodexCloudIncidentToTestedFix regression
210PGPASSWORD=synthetic-incident-fixture-only java -cp "target/classes:$(cat target/live-classpath)" com.openai.docs.codexcloud.CodexCloudIncidentToTestedFix fixed
211docker compose -f "$incident_fixture_dir/compose.yaml" -p codex-incident-rehearsal down --volumes
212```
213
214**Expected results**
215
216Each Java command supplies the existing public Compose fixture password through `PGPASSWORD` only for that child process. Expect the baseline failure, regression success, and complete fixed suite described above.
217
218
219
220
221
222
223
168For Ruby, use the complete [Ruby sample project](https://github.com/openai/developers-website/tree/main/src/content/platform/ruby-examples) and install its dependencies using Ruby 3.3. Start PostgreSQL with the Compose setup in the ZIP archive. From the Ruby project directory, run `bundle exec ruby codex-cloud/incident-to-tested-fix/main.rb baseline`, then repeat with `regression` and `fixed`. These commands use the same disposable database and produce the expected failing and passing results; use them in place of the Node runner commands.224For Ruby, use the complete [Ruby sample project](https://github.com/openai/developers-website/tree/main/src/content/platform/ruby-examples) and install its dependencies using Ruby 3.3. Start PostgreSQL with the Compose setup in the ZIP archive. From the Ruby project directory, run `bundle exec ruby codex-cloud/incident-to-tested-fix/main.rb baseline`, then repeat with `regression` and `fixed`. These commands use the same disposable database and produce the expected failing and passing results; use them in place of the Node runner commands.
169 225
170 226
171 227
172 228
229
230
231
232Use 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 incident fixture intact. Start the commands below at the repository root.
233
234The Go runner uses the same marked PostgreSQL 17.6 fixture on `127.0.0.1:55432`. Use a temporary password file containing only the fixture's public synthetic password, with mode `0600`. Set `PGPASSFILE` for each command and exclude any inherited `PGPASSWORD`.
235
236```bash
237incident_fixture_dir="$PWD/src/content/platform/typescript-examples/codex-cloud/incident-to-tested-fix"
238docker compose -p codex-incident-rehearsal -f "$incident_fixture_dir/compose.yaml" up -d --wait postgres
239codex_pgpass_file=$(mktemp)
240chmod 600 "$codex_pgpass_file"
241printf '%s\n' '127.0.0.1:55432:codex_incident_test:codex_incident_test:synthetic-incident-fixture-only' > "$codex_pgpass_file"
242cd src/content/platform/go-examples/codex-cloud/incident-to-tested-fix
243env -u PGPASSWORD PGPASSFILE="$codex_pgpass_file" go run . -test.v baseline
244env -u PGPASSWORD PGPASSFILE="$codex_pgpass_file" go run . -test.v regression
245env -u PGPASSWORD PGPASSFILE="$codex_pgpass_file" go run . -test.v fixed
246rm -f "$codex_pgpass_file"
247docker compose -p codex-incident-rehearsal -f "$incident_fixture_dir/compose.yaml" down --volumes
248```
249
250The Go runner reads the sibling `typescript-examples/codex-cloud/incident-to-tested-fix/incidents/INC-DEMO-014/order-created.sanitized.json`. Expect exit status `1` from the deliberately failing baseline and `0` from regression and fixed. Use these Go commands in place of the Node runner commands above.
251
252
253
254
173### Inspect the transaction handler255### Inspect the transaction handler
174 256
175 257
249}331}
250```332```
251 333
334```python
335# Requires an autocommit Psycopg connection dedicated to this delivery, with the
336# fixture's immediate UNIQUE(provider,account_id,event_id) receipt constraint.
337# Existing legacy orphans must be held before consumers resume ingestion.
338def fixed(client, input_event, hook=no_failure):
339 assert_not_held(client, input_event)
340 hook("beforeClaim")
341 client.execute("BEGIN ISOLATION LEVEL READ COMMITTED")
342 committed = False
343 try:
344 claim = client.execute(
345 """INSERT INTO event_receipts(provider,account_id,event_id,payload_fingerprint)
346 VALUES (%s,%s,%s,%s)
347 ON CONFLICT (provider,account_id,event_id) DO NOTHING RETURNING event_id""",
348 [*key(input_event), fingerprint(input_event)],
349 ).fetchone()
350 trace("receipt-claim-result", client, input_event, inserted=claim is not None)
351 if claim is not None:
352 hook("afterClaim")
353 write_order(client, input_event)
354 hook("afterOrder")
355 else:
356 # A new READ COMMITTED statement sees the winner after its commit.
357 check_receipt(client, input_event)
358 client.execute("COMMIT")
359 committed = True
360 trace("transaction-committed", client, input_event)
361 hook("afterCommit")
362 trace("acknowledged", client, input_event, **ACKNOWLEDGMENT)
363 return copy.deepcopy(ACKNOWLEDGMENT)
364 except BaseException:
365 if not committed:
366 client.execute("ROLLBACK")
367 trace("transaction-rolled-back-no-ack", client, input_event)
368 else:
369 trace("committed-response-lost-no-ack", client, input_event)
370 raise
371```
372
373```go
374// A nondeferrable database identity constraint serializes competing deliveries.
375// Acknowledgment follows commit; losing the response remains safe to retry.
376func fixed(c *client, input incidentEvent, h hook) (result acknowledgment, err error) {
377 if err = assertNotHeld(c, input); err != nil {
378 return result, err
379 }
380 if err = call(h, "beforeClaim"); err != nil {
381 return result, err
382 }
383 tx, err := c.conn.BeginTx(c.ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
384 if err != nil {
385 return result, err
386 }
387 committed, commitAttempted := false, false
388 defer func() {
389 if !committed && !commitAttempted {
390 if rollback(tx, &err) {
391 trace("transaction-rolled-back-no-ack", c, input, nil)
392 } else {
393 trace("rollback-unconfirmed-no-ack", c, input, nil)
394 }
395 }
396 }()
397 var claimedID string
398 err = tx.QueryRowContext(
399 c.ctx,
400 `INSERT INTO event_receipts(provider,account_id,event_id,payload_fingerprint)
401 VALUES ($1,$2,$3,$4)
402 ON CONFLICT (provider,account_id,event_id) DO NOTHING
403 RETURNING event_id`,
404 values(input)...,
405 ).Scan(&claimedID)
406 claimed := err == nil
407 if err != nil && !errors.Is(err, sql.ErrNoRows) {
408 return result, err
409 }
410 err = nil
411 trace("receipt-claim-result", c, input, map[string]any{"inserted": claimed})
412 if claimed {
413 if err = call(h, "afterClaim"); err != nil {
414 return result, err
415 }
416 if err = writeOrder(c, tx, input); err != nil {
417 return result, err
418 }
419 if err = call(h, "afterOrder"); err != nil {
420 return result, err
421 }
422 } else {
423 // READ COMMITTED gives this statement a fresh snapshot after the winner commits.
424 if err = checkReceipt(c, tx, input); err != nil {
425 return result, err
426 }
427 }
428 commitAttempted = true
429 if err = tx.Commit(); err != nil {
430 return result, fmt.Errorf("commit outcome unknown; no acknowledgment; reconcile durable state: %w", err)
431 }
432 committed = true
433 trace("transaction-committed", c, input, nil)
434 if err = call(h, "afterCommit"); err != nil {
435 trace("committed-response-lost-no-ack", c, input, nil)
436 return result, err
437 }
438 trace("acknowledged", c, input, map[string]any{"status": ack.Status, "body": ack.Body})
439 return ack, nil
440}
441```
442
443```java
444package com.openai.docs.codexcloud;
445
446import com.fasterxml.jackson.databind.ObjectMapper;
447import java.security.MessageDigest;
448import java.sql.Connection;
449import java.sql.DriverManager;
450import java.sql.PreparedStatement;
451import java.sql.ResultSet;
452import java.sql.SQLException;
453import java.sql.Statement;
454import java.time.Duration;
455import java.util.ArrayList;
456import java.util.HexFormat;
457import java.util.LinkedHashMap;
458import java.util.List;
459import java.util.Map;
460import java.util.Objects;
461import java.util.Properties;
462import java.util.concurrent.CompletableFuture;
463import java.util.concurrent.CountDownLatch;
464import java.util.concurrent.ExecutorService;
465import java.util.concurrent.Executors;
466import java.util.concurrent.TimeUnit;
467
468/**
469 * Synthetic PostgreSQL transaction rehearsal. Requires the owned, marked PostgreSQL 17.6 fixture,
470 * exclusive fixture use, org.postgresql:postgresql, and secret PGPASSWORD. Run baseline (expected
471 * exit 1), regression, then fixed. No provider delivery or unknown-COMMIT transport failure is
472 * being simulated. Never point this program at an application database.
473 */
474public final class CodexCloudIncidentToTestedFix {
475 private static final ObjectMapper JSON = new ObjectMapper();
476 private static final String URL = "jdbc:postgresql://127.0.0.1:55432/codex_incident_test";
477 private static final Map<String, Object> ACK =
478 Map.of("status", 200, "body", Map.of("received", true));
479
480 // Canonical sanitized input from the peer's fictional incident packet.
481 private static final String INCIDENT_EVENT_FILE =
482 "../typescript-examples/codex-cloud/incident-to-tested-fix/incidents/INC-DEMO-014/order-created.sanitized.json";
483 private static IncidentEvent EVENT;
484
485 static IncidentEvent parseIncidentEvent(String data) throws Exception {
486 IncidentEvent input = JSON.readValue(data, IncidentEvent.class);
487 if (input == null
488 || input.provider() == null
489 || input.provider().isBlank()
490 || input.accountId() == null
491 || input.accountId().isBlank()
492 || input.eventId() == null
493 || input.eventId().isBlank()
494 || input.payload() == null
495 || input.payload().type() == null
496 || input.payload().type().isBlank()
497 || input.payload().orderId() == null
498 || input.payload().orderId().isBlank()
499 || input.payload().amountCents() <= 0) {
500 throw new IllegalArgumentException("Incomplete sanitized incident fixture");
501 }
502 return input;
503 }
504
505 public record Payload(String type, String orderId, long amountCents) {}
506
507 public record IncidentEvent(String provider, String accountId, String eventId, Payload payload) {}
508
509 private record Counts(long orders, long receipts) {}
510
511 private record Outcome(Map<String, Object> acknowledgment, Exception failure) {}
512
513 @FunctionalInterface
514 private interface Hook {
515 void at(String boundary) throws Exception;
516 }
517
518 @FunctionalInterface
519 private interface Checked {
520 void run() throws Exception;
521 }
522
523 private static final Hook NO_FAILURE = boundary -> {};
524 private final Connection observer;
525 private final String mode;
526 private int assertions;
527
528 private CodexCloudIncidentToTestedFix(Connection observer, String mode) {
529 this.observer = observer;
530 this.mode = mode;
531 }
532
533 private static Connection connect(String name) throws SQLException {
534 String password = System.getenv("PGPASSWORD");
535 if (password == null || password.isBlank())
536 throw new IllegalArgumentException("Set the disposable fixture's PGPASSWORD secret");
537 Properties properties = new Properties();
538 properties.setProperty("user", "codex_incident_test");
539 properties.setProperty("password", password);
540 properties.setProperty("ApplicationName", "fixture-" + name);
541 properties.setProperty("connectTimeout", "5");
542 properties.setProperty("socketTimeout", "12");
543 Connection connection = DriverManager.getConnection(URL, properties);
544 try {
545 connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
546 execute(connection, "SET search_path TO incident_rehearsal, public");
547 execute(connection, "SET statement_timeout = '8s'");
548 return connection;
549 } catch (SQLException failure) {
550 try {
551 connection.close();
552 } catch (SQLException cleanup) {
553 failure.addSuppressed(cleanup);
554 }
555 throw failure;
556 }
557 }
558
559 private static void execute(Connection client, String sql) throws SQLException {
560 try (Statement statement = client.createStatement()) {
561 statement.execute(sql);
562 }
563 }
564
565 private static PreparedStatement keyed(
566 Connection client, String sql, IncidentEvent input, boolean fingerprint) throws Exception {
567 PreparedStatement statement = client.prepareStatement(sql);
568 try {
569 statement.setString(1, input.provider());
570 statement.setString(2, input.accountId());
571 statement.setString(3, input.eventId());
572 if (fingerprint) statement.setString(4, fingerprint(input));
573 return statement;
574 } catch (Exception failure) {
575 try {
576 statement.close();
577 } catch (SQLException cleanup) {
578 failure.addSuppressed(cleanup);
579 }
580 throw failure;
581 }
582 }
583
584 private static String fingerprint(IncidentEvent input) throws Exception {
585 // Explicit canonical field order, exclusively for this trusted fixture.
586 return HexFormat.of()
587 .formatHex(
588 MessageDigest.getInstance("SHA-256")
589 .digest(
590 JSON.writeValueAsBytes(
591 List.of(
592 input.payload().type(),
593 input.payload().orderId(),
594 input.payload().amountCents()))));
595 }
596
597 private static int pid(Connection client) throws SQLException {
598 try (Statement statement = client.createStatement();
599 ResultSet result = statement.executeQuery("SELECT pg_backend_pid()")) {
600 if (!result.next()) throw new SQLException("Missing backend PID");
601 return result.getInt(1);
602 }
603 }
604
605 // The shared evidence reader recognizes JSON trace records with action first.
606 private static void emit(String action, Map<String, Object> detail) throws Exception {
607 Map<String, Object> record = new LinkedHashMap<>();
608 record.put("action", action);
609 record.putAll(detail);
610 System.out.println(JSON.writeValueAsString(record));
611 }
612
613 private static void trace(
614 String action, Connection client, IncidentEvent input, Map<String, Object> detail)
615 throws Exception {
616 Map<String, Object> record = new LinkedHashMap<>();
617 record.put("action", action);
618 record.put("pid", pid(client));
619 record.put("key", List.of(input.provider(), input.accountId(), input.eventId()));
620 record.putAll(detail);
621 System.out.println(JSON.writeValueAsString(record));
622 }
623
624 private void equal(Object actual, Object expected) {
625 assertions++;
626 if (!Objects.equals(actual, expected))
627 throw new AssertionError("Expected " + expected + ", got " + actual);
628 }
629
630 private void require(boolean condition, String message) {
631 assertions++;
632 if (!condition) throw new AssertionError(message);
633 }
634
635 private static Hook failAt(String point) {
636 return boundary -> {
637 if (boundary.equals(point)) throw new IllegalStateException("injected:" + point);
638 };
639 }
640
641 private void rejects(Checked action, String message) throws Exception {
642 try {
643 action.run();
644 } catch (Exception failure) {
645 require(
646 failure.getMessage() != null && failure.getMessage().contains(message),
647 "Expected " + message + ", got " + failure);
648 return;
649 }
650 throw new AssertionError("Expected failure " + message);
651 }
652
653 private Counts counts(IncidentEvent input) throws Exception {
654 try (PreparedStatement statement =
655 keyed(
656 observer,
657 "SELECT (SELECT count(*) FROM orders WHERE provider=? AND account_id=? AND event_id=?)"
658 + " AS orders, (SELECT count(*) FROM event_receipts WHERE provider=? AND"
659 + " account_id=? AND event_id=?) AS receipts",
660 input,
661 false)) {
662 statement.setString(4, input.provider());
663 statement.setString(5, input.accountId());
664 statement.setString(6, input.eventId());
665 try (ResultSet result = statement.executeQuery()) {
666 if (!result.next()) throw new SQLException("Missing counts");
667 Counts counts = new Counts(result.getLong("orders"), result.getLong("receipts"));
668 trace(
669 "committed-state",
670 observer,
671 input,
672 Map.of("orders", counts.orders(), "receipts", counts.receipts()));
673 return counts;
674 }
675 }
676 }
677
678 private void assertCounts(long orders, long receipts, IncidentEvent input) throws Exception {
679 equal(counts(input), new Counts(orders, receipts));
680 }
681
682 private static void writeOrder(Connection client, IncidentEvent input) throws Exception {
683 try (PreparedStatement statement =
684 keyed(
685 client,
686 "INSERT INTO orders(provider,account_id,event_id,payload_fingerprint) VALUES (?,?,?,?)",
687 input,
688 true)) {
689 statement.executeUpdate();
690 }
691 trace("order-written", client, input, Map.of());
692 }
693
694 private static void checkReceipt(Connection client, IncidentEvent input) throws Exception {
695 try (PreparedStatement statement =
696 keyed(
697 client,
698 "SELECT payload_fingerprint FROM event_receipts WHERE provider=? AND account_id=?"
699 + " AND event_id=?",
700 input,
701 false);
702 ResultSet result = statement.executeQuery()) {
703 if (!result.next()) throw new IllegalStateException("missing-receipt-after-skipped-claim");
704 String stored = result.getString(1);
705 if (!fingerprint(input).equals(stored)) throw new IllegalStateException("payload-conflict");
706 if (result.next()) throw new IllegalStateException("multiple-receipts");
707 }
708 }
709
710 private static void assertNotHeld(Connection client, IncidentEvent input) throws Exception {
711 try (PreparedStatement statement =
712 keyed(
713 client,
714 "SELECT 1 FROM delivery_holds WHERE provider=? AND account_id=? AND event_id=?",
715 input,
716 false);
717 ResultSet result = statement.executeQuery()) {
718 if (result.next()) {
719 trace("legacy-retry-held-no-ack", client, input, Map.of());
720 throw new IllegalStateException("legacy-retry-held");
721 }
722 }
723 }
724
725 /** Legacy defect: the order survives failure before receipt creation. */
726 private static Map<String, Object> baseline(Connection client, IncidentEvent input, Hook hook)
727 throws Exception {
728 try (PreparedStatement statement =
729 keyed(
730 client,
731 "SELECT 1 FROM event_receipts WHERE provider=? AND account_id=? AND event_id=?",
732 input,
733 false);
734 ResultSet result = statement.executeQuery()) {
735 if (result.next()) {
736 checkReceipt(client, input);
737 return ACK;
738 }
739 }
740 client.setAutoCommit(false);
741 boolean restore = true;
742 try {
743 writeOrder(client, input);
744 client.commit();
745 } catch (Exception failure) {
746 restore = rollback(client, failure);
747 throw failure;
748 } finally {
749 if (restore) client.setAutoCommit(true);
750 }
751 trace("legacy-order-committed-without-receipt", client, input, Map.of());
752 hook.at("afterOrder");
753 try (PreparedStatement statement =
754 keyed(
755 client,
756 "INSERT INTO event_receipts(provider,account_id,event_id,payload_fingerprint) VALUES"
757 + " (?,?,?,?)",
758 input,
759 true)) {
760 statement.executeUpdate();
761 }
762 trace("legacy-receipt-committed", client, input, Map.of());
763 return ACK;
764 }
765
766 private static boolean rollback(Connection client, Exception failure) {
767 try {
768 client.rollback();
769 return true;
770 } catch (SQLException cleanup) {
771 failure.addSuppressed(cleanup);
772 try {
773 client.close();
774 } catch (SQLException closing) {
775 failure.addSuppressed(closing);
776 }
777 return false; // Never restore autocommit after an unsuccessful rollback.
778 }
779 }
780
781 /** Claim and business write commit together, with READ COMMITTED duplicate visibility. */
782 private static Map<String, Object> fixed(Connection client, IncidentEvent input, Hook hook)
783 throws Exception {
784 assertNotHeld(client, input);
785 hook.at("beforeClaim");
786 client.setAutoCommit(false);
787 boolean committed = false;
788 boolean commitAttempted = false;
789 boolean restore = true;
790 try {
791 boolean inserted;
792 try (PreparedStatement statement =
793 keyed(
794 client,
795 "INSERT INTO event_receipts(provider,account_id,event_id,payload_fingerprint)"
796 + " VALUES (?,?,?,?) ON CONFLICT (provider,account_id,event_id) DO NOTHING"
797 + " RETURNING event_id",
798 input,
799 true);
800 ResultSet result = statement.executeQuery()) {
801 inserted = result.next();
802 }
803 trace("receipt-claim-result", client, input, Map.of("inserted", inserted));
804 if (inserted) {
805 hook.at("afterClaim");
806 writeOrder(client, input);
807 hook.at("afterOrder");
808 } else {
809 // A new statement sees the winner's commit after a blocked claim returns.
810 checkReceipt(client, input);
811 }
812 commitAttempted = true;
813 client.commit();
814 committed = true;
815 trace("transaction-committed", client, input, Map.of());
816 hook.at("afterCommit");
817 trace("acknowledged", client, input, ACK);
818 return ACK;
819 } catch (Exception failure) {
820 if (!committed && commitAttempted) {
821 // A transport error during COMMIT does not establish whether the commit happened.
822 // This branch is not exercised by the post-commit response-loss rehearsal.
823 restore = false;
824 try {
825 client.close();
826 } catch (SQLException closing) {
827 failure.addSuppressed(closing);
828 }
829 throw new IllegalStateException(
830 "commit-outcome-unknown; discard connection and inspect durable state", failure);
831 } else if (!committed) {
832 restore = rollback(client, failure);
833 if (restore) trace("transaction-rolled-back-no-ack", client, input, Map.of());
834 } else {
835 trace("committed-response-lost-no-ack", client, input, Map.of());
836 }
837 throw failure;
838 } finally {
839 if (restore) client.setAutoCommit(true);
840 }
841 }
842
843 /** Only after ingestion is paused and all legacy consumers have drained. */
844 private static int identifyAndHoldLegacyOrphans(Connection client) throws Exception {
845 int count;
846 try (Statement statement = client.createStatement()) {
847 count =
848 statement.executeUpdate(
849 "INSERT INTO delivery_holds(provider,account_id,event_id) SELECT DISTINCT"
850 + " o.provider,o.account_id,o.event_id FROM orders o WHERE NOT EXISTS (SELECT 1"
851 + " FROM event_receipts r WHERE r.provider=o.provider AND"
852 + " r.account_id=o.account_id AND r.event_id=o.event_id) ON CONFLICT DO NOTHING");
853 }
854 emit("pre-resume-orphans-held", Map.of("keys", count));
855 return count;
856 }
857
858 private void reconcileHeldOrphan(Connection client, IncidentEvent input) throws Exception {
859 client.setAutoCommit(false);
860 boolean restore = true;
861 try {
862 try (PreparedStatement statement =
863 keyed(
864 client,
865 "SELECT 1 FROM delivery_holds WHERE provider=? AND account_id=? AND event_id=?"
866 + " FOR UPDATE",
867 input,
868 false);
869 ResultSet result = statement.executeQuery()) {
870 require(result.next(), "Reconciliation requires a durable hold");
871 }
872 try (PreparedStatement statement =
873 keyed(
874 client,
875 "SELECT payload_fingerprint FROM orders WHERE provider=? AND account_id=? AND"
876 + " event_id=? FOR UPDATE",
877 input,
878 false);
879 ResultSet result = statement.executeQuery()) {
880 if (!result.next() || !fingerprint(input).equals(result.getString(1)) || result.next()) {
881 throw new IllegalStateException("legacy-evidence-insufficient-keep-held");
882 }
883 }
884 try (PreparedStatement statement =
885 keyed(
886 client,
887 "INSERT INTO event_receipts(provider,account_id,event_id,payload_fingerprint) VALUES"
888 + " (?,?,?,?) ON CONFLICT DO NOTHING",
889 input,
890 true)) {
891 statement.executeUpdate();
892 }
893 checkReceipt(client, input);
894 try (PreparedStatement statement =
895 keyed(
896 client,
897 "DELETE FROM delivery_holds WHERE provider=? AND account_id=? AND event_id=?",
898 input,
899 false)) {
900 equal(statement.executeUpdate(), 1);
901 }
902 client.commit();
903 trace("trusted-orphan-reconciled-hold-released", client, input, Map.of());
904 } catch (Exception failure) {
905 restore = rollback(client, failure);
906 throw failure;
907 } finally {
908 if (restore) client.setAutoCommit(true);
909 }
910 }
911
912 private void waitForContention(int waiter, int winner) throws Exception {
913 long deadline = System.nanoTime() + Duration.ofSeconds(5).toNanos();
914 while (System.nanoTime() < deadline) {
915 try (PreparedStatement statement =
916 observer.prepareStatement(
917 "SELECT wait_event_type, wait_event, pg_blocking_pids(pid) AS blockers FROM"
918 + " pg_stat_activity WHERE pid=?")) {
919 statement.setInt(1, waiter);
920 try (ResultSet result = statement.executeQuery()) {
921 if (result.next()) {
922 java.sql.Array array = result.getArray("blockers");
923 List<Integer> blockers = new ArrayList<>();
924 try {
925 Object values = array.getArray();
926 for (int index = 0; index < java.lang.reflect.Array.getLength(values); index++) {
927 blockers.add(((Number) java.lang.reflect.Array.get(values, index)).intValue());
928 }
929 } finally {
930 array.free();
931 }
932 if ("Lock".equals(result.getString("wait_event_type")) && blockers.contains(winner)) {
933 Map<String, Object> record = new LinkedHashMap<>();
934 record.put("action", "real-database-contention");
935 record.put("pid", waiter);
936 record.put("winner", winner);
937 record.put("wait_event_type", "Lock");
938 record.put("wait_event", result.getString("wait_event"));
939 record.put("blockers", blockers);
940 System.out.println(JSON.writeValueAsString(record));
941 return;
942 }
943 }
944 }
945 }
946 Thread.sleep(10);
947 }
948 throw new IllegalStateException("competitor-never-observed-blocking-on-winner");
949 }
950
951 private static void await(CountDownLatch latch) throws Exception {
952 if (!latch.await(7, TimeUnit.SECONDS))
953 throw new IllegalStateException("Timed out awaiting transaction boundary");
954 }
955
956 private static Outcome outcome(Connection client, Hook hook) {
957 try {
958 return new Outcome(fixed(client, EVENT, hook), null);
959 } catch (Exception failure) {
960 return new Outcome(null, failure);
961 }
962 }
963
964 private void overlap(boolean winnerRollsBack) throws Exception {
965 ExecutorService workers = Executors.newFixedThreadPool(2);
966 CountDownLatch claimed = new CountDownLatch(1);
967 CountDownLatch release = new CountDownLatch(1);
968 try (Connection winner = connect("winner");
969 Connection waiter = connect("waiter")) {
970 int winnerPid = pid(winner), waiterPid = pid(waiter);
971 require(winnerPid != waiterPid, "Independent database backends");
972 CompletableFuture<Outcome> first =
973 CompletableFuture.supplyAsync(
974 () ->
975 outcome(
976 winner,
977 boundary -> {
978 if (!boundary.equals("afterClaim")) return;
979 claimed.countDown();
980 await(release);
981 if (winnerRollsBack)
982 throw new IllegalStateException("injected:winner-rollback");
983 }),
984 workers);
985 CompletableFuture<Outcome> second = null;
986 try {
987 await(claimed);
988 assertCounts(0, 0, EVENT);
989 second = CompletableFuture.supplyAsync(() -> outcome(waiter, NO_FAILURE), workers);
990 waitForContention(waiterPid, winnerPid);
991 } finally {
992 release.countDown();
993 // Join while connections remain open, including failure paths.
994 Outcome a = first.get(12, TimeUnit.SECONDS);
995 Outcome b = second == null ? null : second.get(12, TimeUnit.SECONDS);
996 if (winnerRollsBack)
997 require(
998 a.failure() != null && a.failure().getMessage().contains("winner-rollback"),
999 "Winner rollback");
1000 else {
1001 equal(a.failure(), null);
1002 equal(a.acknowledgment(), ACK);
1003 }
1004 require(b != null, "Waiter started");
1005 equal(b.failure(), null);
1006 equal(b.acknowledgment(), ACK);
1007 }
1008 assertCounts(1, 1, EVENT);
1009 } finally {
1010 release.countDown();
1011 workers.shutdownNow();
1012 if (!workers.awaitTermination(15, TimeUnit.SECONDS))
1013 throw new IllegalStateException("Transaction workers did not stop");
1014 }
1015 }
1016
1017 private void verifyFixture() throws Exception {
1018 try (Statement statement = observer.createStatement();
1019 ResultSet result =
1020 statement.executeQuery(
1021 "SELECT current_database(), current_user, shobj_description(oid,'pg_database') FROM"
1022 + " pg_database WHERE datname=current_database()")) {
1023 require(result.next(), "Database identity");
1024 equal(result.getString(1), "codex_incident_test");
1025 equal(result.getString(2), "codex_incident_test");
1026 equal(result.getString(3), "codex-synthetic-incident-fixture-v1");
1027 }
1028 String version;
1029 try (Statement statement = observer.createStatement();
1030 ResultSet result = statement.executeQuery("SHOW server_version")) {
1031 require(result.next(), "Database version");
1032 version = result.getString(1);
1033 equal(version, "17.6 (Debian 17.6-2.pgdg12+1)");
1034 }
1035 try (Statement statement = observer.createStatement();
1036 ResultSet result = statement.executeQuery("SELECT pg_try_advisory_lock(14014)")) {
1037 require(result.next() && result.getBoolean(1), "Exclusive synthetic fixture lease");
1038 }
1039 emit(
1040 "fixture-environment",
1041 Map.of(
1042 "java",
1043 System.getProperty("java.version"),
1044 "pg",
1045 version,
1046 "mode",
1047 mode,
1048 "event_source",
1049 "canonical-sanitized-incident-record"));
1050 }
1051
1052 private void createSchema() throws Exception {
1053 execute(observer, "DROP SCHEMA IF EXISTS incident_rehearsal CASCADE");
1054 execute(observer, "CREATE SCHEMA incident_rehearsal");
1055 execute(observer, "SET search_path TO incident_rehearsal, public");
1056 execute(
1057 observer,
1058 "CREATE TABLE event_receipts(provider text NOT NULL,account_id text NOT NULL,event_id text"
1059 + " NOT NULL,payload_fingerprint text NOT NULL,CONSTRAINT event_receipts_identity"
1060 + " UNIQUE(provider,account_id,event_id) NOT DEFERRABLE)");
1061 execute(
1062 observer,
1063 "CREATE TABLE orders(id bigserial PRIMARY KEY,provider text NOT NULL,account_id text NOT"
1064 + " NULL,event_id text NOT NULL,payload_fingerprint text)");
1065 execute(
1066 observer,
1067 "CREATE TABLE delivery_holds(provider text NOT NULL,account_id text NOT NULL,event_id text"
1068 + " NOT NULL,PRIMARY KEY(provider,account_id,event_id))");
1069 try (Statement statement = observer.createStatement();
1070 ResultSet result =
1071 statement.executeQuery(
1072 "SELECT condeferrable,pg_get_constraintdef(oid) FROM pg_constraint WHERE"
1073 + " conrelid='incident_rehearsal.event_receipts'::regclass AND"
1074 + " conname='event_receipts_identity'")) {
1075 require(result.next(), "Receipt uniqueness");
1076 equal(result.getBoolean(1), false);
1077 emit(
1078 "receipt-schema",
1079 Map.of(
1080 "conname",
1081 "event_receipts_identity",
1082 "condeferrable",
1083 result.getBoolean(1),
1084 "definition",
1085 result.getString(2)));
1086 }
1087 }
1088
1089 private int run() throws Exception {
1090 Map<String, Checked> tests = new LinkedHashMap<>();
1091 tests.put(
1092 "retry after the order boundary leaves exactly one order and one receipt",
1093 () -> {
1094 try (Connection client = connect("regression")) {
1095 rejects(
1096 () -> {
1097 if (mode.equals("baseline")) baseline(client, EVENT, failAt("afterOrder"));
1098 else fixed(client, EVENT, failAt("afterOrder"));
1099 },
1100 "injected:afterOrder");
1101 assertCounts(mode.equals("baseline") ? 1 : 0, 0, EVENT);
1102 equal(
1103 mode.equals("baseline")
1104 ? baseline(client, EVENT, NO_FAILURE)
1105 : fixed(client, EVENT, NO_FAILURE),
1106 ACK);
1107 assertCounts(
1108 1, 1, EVENT); // Baseline deliberately fails here, after exposing two orders.
1109 }
1110 });
1111 if (mode.equals("fixed")) {
1112 tests.put(
1113 "first delivery and committed duplicate return the exact acknowledgment",
1114 () -> {
1115 try (Connection client = connect("duplicate")) {
1116 equal(fixed(client, EVENT, NO_FAILURE), ACK);
1117 equal(fixed(client, EVENT, NO_FAILURE), ACK);
1118 assertCounts(1, 1, EVENT);
1119 }
1120 });
1121 for (String boundary : List.of("beforeClaim", "afterClaim", "afterOrder")) {
1122 tests.put(
1123 "failure " + boundary + " rolls back and remains retryable",
1124 () -> {
1125 try (Connection client = connect("failure-" + boundary)) {
1126 rejects(() -> fixed(client, EVENT, failAt(boundary)), "injected:" + boundary);
1127 assertCounts(0, 0, EVENT);
1128 equal(fixed(client, EVENT, NO_FAILURE), ACK);
1129 assertCounts(1, 1, EVENT);
1130 }
1131 });
1132 }
1133 tests.put(
1134 "lost acknowledgment after commit does not duplicate the order",
1135 () -> {
1136 try (Connection client = connect("lost-ack")) {
1137 rejects(() -> fixed(client, EVENT, failAt("afterCommit")), "injected:afterCommit");
1138 assertCounts(1, 1, EVENT);
1139 equal(fixed(client, EVENT, NO_FAILURE), ACK);
1140 assertCounts(1, 1, EVENT);
1141 }
1142 });
1143 tests.put("real overlapping duplicate contention: winner commit", () -> overlap(false));
1144 tests.put("real overlapping duplicate contention: winner rollback", () -> overlap(true));
1145 tests.put(
1146 "event, account, and provider scope remain independent; conflicting payload is rejected",
1147 () -> {
1148 try (Connection client = connect("identity")) {
1149 for (IncidentEvent input :
1150 List.of(
1151 EVENT,
1152 new IncidentEvent(
1153 EVENT.provider(), EVENT.accountId(), "evt_demo_043", EVENT.payload()),
1154 new IncidentEvent(
1155 EVENT.provider(), "acct_demo_02", EVENT.eventId(), EVENT.payload()),
1156 new IncidentEvent(
1157 "synthetic-other",
1158 EVENT.accountId(),
1159 EVENT.eventId(),
1160 EVENT.payload()))) {
1161 equal(fixed(client, input, NO_FAILURE), ACK);
1162 assertCounts(1, 1, input);
1163 }
1164 rejects(() -> fixed(client, changedPayload(), NO_FAILURE), "payload-conflict");
1165 assertCounts(1, 1, EVENT);
1166 }
1167 });
1168 tests.put(
1169 "legacy orphan is held before retry and reconciled only from trusted evidence",
1170 () -> {
1171 try (Connection client = connect("legacy-orphan")) {
1172 writeOrder(client, EVENT);
1173 assertCounts(1, 0, EVENT);
1174 equal(identifyAndHoldLegacyOrphans(client), 1);
1175 rejects(() -> fixed(client, EVENT, NO_FAILURE), "legacy-retry-held");
1176 assertCounts(1, 0, EVENT);
1177 rejects(() -> reconcileHeldOrphan(client, changedPayload()), "evidence-insufficient");
1178 rejects(() -> fixed(client, EVENT, NO_FAILURE), "legacy-retry-held");
1179 reconcileHeldOrphan(client, EVENT);
1180 equal(fixed(client, EVENT, NO_FAILURE), ACK);
1181 assertCounts(1, 1, EVENT);
1182 }
1183 });
1184 tests.put(
1185 "missing legacy payload evidence stays quarantined without a fabricated receipt",
1186 () -> {
1187 try (Connection client = connect("legacy-missing-evidence")) {
1188 try (PreparedStatement statement =
1189 keyed(
1190 client,
1191 "INSERT INTO orders(provider,account_id,event_id) VALUES (?,?,?)",
1192 EVENT,
1193 false)) {
1194 statement.executeUpdate();
1195 }
1196 equal(identifyAndHoldLegacyOrphans(client), 1);
1197 rejects(() -> reconcileHeldOrphan(client, EVENT), "evidence-insufficient");
1198 rejects(() -> fixed(client, EVENT, NO_FAILURE), "legacy-retry-held");
1199 assertCounts(1, 0, EVENT);
1200 }
1201 });
1202 }
1203 int failures = 0, index = 0;
1204 for (Map.Entry<String, Checked> test : tests.entrySet()) {
1205 index++;
1206 try {
1207 execute(observer, "TRUNCATE orders,event_receipts,delivery_holds RESTART IDENTITY");
1208 test.getValue().run();
1209 System.out.println("ok " + index + " - " + test.getKey());
1210 } catch (Exception | AssertionError failure) {
1211 failures++;
1212 System.out.println("not ok " + index + " - " + test.getKey());
1213 failure.printStackTrace(System.err);
1214 }
1215 }
1216 System.out.printf(
1217 "# tests %d%n# assertions %d%n# fail %d%n# cancelled 0%n# skipped 0%n# todo 0%n",
1218 tests.size(), assertions, failures);
1219 return failures;
1220 }
1221
1222 private static IncidentEvent changedPayload() {
1223 return new IncidentEvent(
1224 EVENT.provider(),
1225 EVENT.accountId(),
1226 EVENT.eventId(),
1227 new Payload(EVENT.payload().type(), EVENT.payload().orderId(), 9999));
1228 }
1229
1230 public static void main(String[] args) throws Exception {
1231 if (args.length > 1) throw new IllegalArgumentException("Usage: baseline|regression|fixed");
1232 String mode = args.length == 0 ? "fixed" : args[0];
1233 if (!List.of("baseline", "regression", "fixed").contains(mode))
1234 throw new IllegalArgumentException("Unknown incident mode");
1235 EVENT =
1236 parseIncidentEvent(
1237 java.nio.file.Files.readString(java.nio.file.Path.of(INCIDENT_EVENT_FILE)));
1238 int failures;
1239 try (Connection observer = connect("observer")) {
1240 CodexCloudIncidentToTestedFix suite = new CodexCloudIncidentToTestedFix(observer, mode);
1241 suite.verifyFixture(); // No schema mutation before all identity and lease checks pass.
1242 try {
1243 suite.createSchema();
1244 failures = suite.run();
1245 } finally {
1246 execute(observer, "DROP SCHEMA IF EXISTS incident_rehearsal CASCADE");
1247 execute(observer, "SELECT pg_advisory_unlock(14014)");
1248 }
1249 }
1250 if (failures != 0) System.exit(1);
1251 }
1252}
1253```
1254
252```csharp1255```csharp
253using System.Data;1256using System.Data;
254using System.Diagnostics;1257using System.Diagnostics;