1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52import type { Client } from "pg";
type IncidentEvent = {
provider: string;
accountId: string;
eventId: string;
payload: { type: string; orderId: string; amountCents: number };
};
async function fixed(
client: Client,
input: IncidentEvent,
hook = async (_boundary: string) => {}
) {
await assertNotHeld(client, input);
await hook("beforeClaim");
await client.query("BEGIN ISOLATION LEVEL READ COMMITTED");
let committed = false;
try {
const claimed = await client.query(
`INSERT INTO event_receipts(provider, account_id, event_id, payload_fingerprint)
VALUES ($1,$2,$3,$4)
ON CONFLICT (provider, account_id, event_id) DO NOTHING RETURNING event_id`,
[...key(input), fingerprint(input)]
);
trace("receipt-claim-result", client, input, {
inserted: claimed.rowCount === 1,
});
if (claimed.rowCount === 1) {
await hook("afterClaim");
await writeOrder(client, input);
await hook("afterOrder");
} else {
// A new READ COMMITTED statement sees the winner after its commit.
await checkReceipt(client, input);
}
await client.query("COMMIT");
committed = true;
trace("transaction-committed", client, input);
await hook("afterCommit");
trace("acknowledged", client, input, acknowledgment);
return acknowledgment;
} catch (error) {
if (!committed) {
await client.query("ROLLBACK");
trace("transaction-rolled-back-no-ack", client, input);
} else {
trace("committed-response-lost-no-ack", client, input);
}
throw error;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67// A nondeferrable database identity constraint serializes competing deliveries.
// Acknowledgment follows commit; losing the response remains safe to retry.
func fixed(c *client, input incidentEvent, h hook) (result acknowledgment, err error) {
if err = assertNotHeld(c, input); err != nil {
return result, err
}
if err = call(h, "beforeClaim"); err != nil {
return result, err
}
tx, err := c.conn.BeginTx(c.ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
if err != nil {
return result, err
}
committed, commitAttempted := false, false
defer func() {
if !committed && !commitAttempted {
if rollback(tx, &err) {
trace("transaction-rolled-back-no-ack", c, input, nil)
} else {
trace("rollback-unconfirmed-no-ack", c, input, nil)
}
}
}()
var claimedID string
err = tx.QueryRowContext(
c.ctx,
`INSERT INTO event_receipts(provider,account_id,event_id,payload_fingerprint)
VALUES ($1,$2,$3,$4)
ON CONFLICT (provider,account_id,event_id) DO NOTHING
RETURNING event_id`,
values(input)...,
).Scan(&claimedID)
claimed := err == nil
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return result, err
}
err = nil
trace("receipt-claim-result", c, input, map[string]any{"inserted": claimed})
if claimed {
if err = call(h, "afterClaim"); err != nil {
return result, err
}
if err = writeOrder(c, tx, input); err != nil {
return result, err
}
if err = call(h, "afterOrder"); err != nil {
return result, err
}
} else {
// READ COMMITTED gives this statement a fresh snapshot after the winner commits.
if err = checkReceipt(c, tx, input); err != nil {
return result, err
}
}
commitAttempted = true
if err = tx.Commit(); err != nil {
return result, fmt.Errorf("commit outcome unknown; no acknowledgment; reconcile durable state: %w", err)
}
committed = true
trace("transaction-committed", c, input, nil)
if err = call(h, "afterCommit"); err != nil {
trace("committed-response-lost-no-ack", c, input, nil)
return result, err
}
trace("acknowledged", c, input, map[string]any{"status": ack.Status, "body": ack.Body})
return ack, nil
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809package com.openai.docs.codexcloud;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Synthetic PostgreSQL transaction rehearsal. Requires the owned, marked PostgreSQL 17.6 fixture,
* exclusive fixture use, org.postgresql:postgresql, and secret PGPASSWORD. Run baseline (expected
* exit 1), regression, then fixed. No provider delivery or unknown-COMMIT transport failure is
* being simulated. Never point this program at an application database.
*/
public final class CodexCloudIncidentToTestedFix {
private static final ObjectMapper JSON = new ObjectMapper();
private static final String URL = "jdbc:postgresql://127.0.0.1:55432/codex_incident_test";
private static final Map<String, Object> ACK =
Map.of("status", 200, "body", Map.of("received", true));
// Canonical sanitized input from the peer's fictional incident packet.
private static final String INCIDENT_EVENT_FILE =
"../typescript-examples/codex-cloud/incident-to-tested-fix/incidents/INC-DEMO-014/order-created.sanitized.json";
private static IncidentEvent EVENT;
static IncidentEvent parseIncidentEvent(String data) throws Exception {
IncidentEvent input = JSON.readValue(data, IncidentEvent.class);
if (input == null
|| input.provider() == null
|| input.provider().isBlank()
|| input.accountId() == null
|| input.accountId().isBlank()
|| input.eventId() == null
|| input.eventId().isBlank()
|| input.payload() == null
|| input.payload().type() == null
|| input.payload().type().isBlank()
|| input.payload().orderId() == null
|| input.payload().orderId().isBlank()
|| input.payload().amountCents() <= 0) {
throw new IllegalArgumentException("Incomplete sanitized incident fixture");
}
return input;
}
public record Payload(String type, String orderId, long amountCents) {}
public record IncidentEvent(String provider, String accountId, String eventId, Payload payload) {}
private record Counts(long orders, long receipts) {}
private record Outcome(Map<String, Object> acknowledgment, Exception failure) {}
@FunctionalInterface
private interface Hook {
void at(String boundary) throws Exception;
}
@FunctionalInterface
private interface Checked {
void run() throws Exception;
}
private static final Hook NO_FAILURE = boundary -> {};
private final Connection observer;
private final String mode;
private int assertions;
private CodexCloudIncidentToTestedFix(Connection observer, String mode) {
this.observer = observer;
this.mode = mode;
}
private static Connection connect(String name) throws SQLException {
String password = System.getenv("PGPASSWORD");
if (password == null || password.isBlank())
throw new IllegalArgumentException("Set the disposable fixture's PGPASSWORD secret");
Properties properties = new Properties();
properties.setProperty("user", "codex_incident_test");
properties.setProperty("password", password);
properties.setProperty("ApplicationName", "fixture-" + name);
properties.setProperty("connectTimeout", "5");
properties.setProperty("socketTimeout", "12");
Connection connection = DriverManager.getConnection(URL, properties);
try {
connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
execute(connection, "SET search_path TO incident_rehearsal, public");
execute(connection, "SET statement_timeout = '8s'");
return connection;
} catch (SQLException failure) {
try {
connection.close();
} catch (SQLException cleanup) {
failure.addSuppressed(cleanup);
}
throw failure;
}
}
private static void execute(Connection client, String sql) throws SQLException {
try (Statement statement = client.createStatement()) {
statement.execute(sql);
}
}
private static PreparedStatement keyed(
Connection client, String sql, IncidentEvent input, boolean fingerprint) throws Exception {
PreparedStatement statement = client.prepareStatement(sql);
try {
statement.setString(1, input.provider());
statement.setString(2, input.accountId());
statement.setString(3, input.eventId());
if (fingerprint) statement.setString(4, fingerprint(input));
return statement;
} catch (Exception failure) {
try {
statement.close();
} catch (SQLException cleanup) {
failure.addSuppressed(cleanup);
}
throw failure;
}
}
private static String fingerprint(IncidentEvent input) throws Exception {
// Explicit canonical field order, exclusively for this trusted fixture.
return HexFormat.of()
.formatHex(
MessageDigest.getInstance("SHA-256")
.digest(
JSON.writeValueAsBytes(
List.of(
input.payload().type(),
input.payload().orderId(),
input.payload().amountCents()))));
}
private static int pid(Connection client) throws SQLException {
try (Statement statement = client.createStatement();
ResultSet result = statement.executeQuery("SELECT pg_backend_pid()")) {
if (!result.next()) throw new SQLException("Missing backend PID");
return result.getInt(1);
}
}
// The shared evidence reader recognizes JSON trace records with action first.
private static void emit(String action, Map<String, Object> detail) throws Exception {
Map<String, Object> record = new LinkedHashMap<>();
record.put("action", action);
record.putAll(detail);
System.out.println(JSON.writeValueAsString(record));
}
private static void trace(
String action, Connection client, IncidentEvent input, Map<String, Object> detail)
throws Exception {
Map<String, Object> record = new LinkedHashMap<>();
record.put("action", action);
record.put("pid", pid(client));
record.put("key", List.of(input.provider(), input.accountId(), input.eventId()));
record.putAll(detail);
System.out.println(JSON.writeValueAsString(record));
}
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);
}
private static Hook failAt(String point) {
return boundary -> {
if (boundary.equals(point)) throw new IllegalStateException("injected:" + point);
};
}
private void rejects(Checked action, String message) throws Exception {
try {
action.run();
} catch (Exception failure) {
require(
failure.getMessage() != null && failure.getMessage().contains(message),
"Expected " + message + ", got " + failure);
return;
}
throw new AssertionError("Expected failure " + message);
}
private Counts counts(IncidentEvent input) throws Exception {
try (PreparedStatement statement =
keyed(
observer,
"SELECT (SELECT count(*) FROM orders WHERE provider=? AND account_id=? AND event_id=?)"
+ " AS orders, (SELECT count(*) FROM event_receipts WHERE provider=? AND"
+ " account_id=? AND event_id=?) AS receipts",
input,
false)) {
statement.setString(4, input.provider());
statement.setString(5, input.accountId());
statement.setString(6, input.eventId());
try (ResultSet result = statement.executeQuery()) {
if (!result.next()) throw new SQLException("Missing counts");
Counts counts = new Counts(result.getLong("orders"), result.getLong("receipts"));
trace(
"committed-state",
observer,
input,
Map.of("orders", counts.orders(), "receipts", counts.receipts()));
return counts;
}
}
}
private void assertCounts(long orders, long receipts, IncidentEvent input) throws Exception {
equal(counts(input), new Counts(orders, receipts));
}
private static void writeOrder(Connection client, IncidentEvent input) throws Exception {
try (PreparedStatement statement =
keyed(
client,
"INSERT INTO orders(provider,account_id,event_id,payload_fingerprint) VALUES (?,?,?,?)",
input,
true)) {
statement.executeUpdate();
}
trace("order-written", client, input, Map.of());
}
private static void checkReceipt(Connection client, IncidentEvent input) throws Exception {
try (PreparedStatement statement =
keyed(
client,
"SELECT payload_fingerprint FROM event_receipts WHERE provider=? AND account_id=?"
+ " AND event_id=?",
input,
false);
ResultSet result = statement.executeQuery()) {
if (!result.next()) throw new IllegalStateException("missing-receipt-after-skipped-claim");
String stored = result.getString(1);
if (!fingerprint(input).equals(stored)) throw new IllegalStateException("payload-conflict");
if (result.next()) throw new IllegalStateException("multiple-receipts");
}
}
private static void assertNotHeld(Connection client, IncidentEvent input) throws Exception {
try (PreparedStatement statement =
keyed(
client,
"SELECT 1 FROM delivery_holds WHERE provider=? AND account_id=? AND event_id=?",
input,
false);
ResultSet result = statement.executeQuery()) {
if (result.next()) {
trace("legacy-retry-held-no-ack", client, input, Map.of());
throw new IllegalStateException("legacy-retry-held");
}
}
}
/** Legacy defect: the order survives failure before receipt creation. */
private static Map<String, Object> baseline(Connection client, IncidentEvent input, Hook hook)
throws Exception {
try (PreparedStatement statement =
keyed(
client,
"SELECT 1 FROM event_receipts WHERE provider=? AND account_id=? AND event_id=?",
input,
false);
ResultSet result = statement.executeQuery()) {
if (result.next()) {
checkReceipt(client, input);
return ACK;
}
}
client.setAutoCommit(false);
boolean restore = true;
try {
writeOrder(client, input);
client.commit();
} catch (Exception failure) {
restore = rollback(client, failure);
throw failure;
} finally {
if (restore) client.setAutoCommit(true);
}
trace("legacy-order-committed-without-receipt", client, input, Map.of());
hook.at("afterOrder");
try (PreparedStatement statement =
keyed(
client,
"INSERT INTO event_receipts(provider,account_id,event_id,payload_fingerprint) VALUES"
+ " (?,?,?,?)",
input,
true)) {
statement.executeUpdate();
}
trace("legacy-receipt-committed", client, input, Map.of());
return ACK;
}
private static boolean rollback(Connection client, Exception failure) {
try {
client.rollback();
return true;
} catch (SQLException cleanup) {
failure.addSuppressed(cleanup);
try {
client.close();
} catch (SQLException closing) {
failure.addSuppressed(closing);
}
return false; // Never restore autocommit after an unsuccessful rollback.
}
}
/** Claim and business write commit together, with READ COMMITTED duplicate visibility. */
private static Map<String, Object> fixed(Connection client, IncidentEvent input, Hook hook)
throws Exception {
assertNotHeld(client, input);
hook.at("beforeClaim");
client.setAutoCommit(false);
boolean committed = false;
boolean commitAttempted = false;
boolean restore = true;
try {
boolean inserted;
try (PreparedStatement statement =
keyed(
client,
"INSERT INTO event_receipts(provider,account_id,event_id,payload_fingerprint)"
+ " VALUES (?,?,?,?) ON CONFLICT (provider,account_id,event_id) DO NOTHING"
+ " RETURNING event_id",
input,
true);
ResultSet result = statement.executeQuery()) {
inserted = result.next();
}
trace("receipt-claim-result", client, input, Map.of("inserted", inserted));
if (inserted) {
hook.at("afterClaim");
writeOrder(client, input);
hook.at("afterOrder");
} else {
// A new statement sees the winner's commit after a blocked claim returns.
checkReceipt(client, input);
}
commitAttempted = true;
client.commit();
committed = true;
trace("transaction-committed", client, input, Map.of());
hook.at("afterCommit");
trace("acknowledged", client, input, ACK);
return ACK;
} catch (Exception failure) {
if (!committed && commitAttempted) {
// A transport error during COMMIT does not establish whether the commit happened.
// This branch is not exercised by the post-commit response-loss rehearsal.
restore = false;
try {
client.close();
} catch (SQLException closing) {
failure.addSuppressed(closing);
}
throw new IllegalStateException(
"commit-outcome-unknown; discard connection and inspect durable state", failure);
} else if (!committed) {
restore = rollback(client, failure);
if (restore) trace("transaction-rolled-back-no-ack", client, input, Map.of());
} else {
trace("committed-response-lost-no-ack", client, input, Map.of());
}
throw failure;
} finally {
if (restore) client.setAutoCommit(true);
}
}
/** Only after ingestion is paused and all legacy consumers have drained. */
private static int identifyAndHoldLegacyOrphans(Connection client) throws Exception {
int count;
try (Statement statement = client.createStatement()) {
count =
statement.executeUpdate(
"INSERT INTO delivery_holds(provider,account_id,event_id) SELECT DISTINCT"
+ " o.provider,o.account_id,o.event_id FROM orders o WHERE NOT EXISTS (SELECT 1"
+ " FROM event_receipts r WHERE r.provider=o.provider AND"
+ " r.account_id=o.account_id AND r.event_id=o.event_id) ON CONFLICT DO NOTHING");
}
emit("pre-resume-orphans-held", Map.of("keys", count));
return count;
}
private void reconcileHeldOrphan(Connection client, IncidentEvent input) throws Exception {
client.setAutoCommit(false);
boolean restore = true;
try {
try (PreparedStatement statement =
keyed(
client,
"SELECT 1 FROM delivery_holds WHERE provider=? AND account_id=? AND event_id=?"
+ " FOR UPDATE",
input,
false);
ResultSet result = statement.executeQuery()) {
require(result.next(), "Reconciliation requires a durable hold");
}
try (PreparedStatement statement =
keyed(
client,
"SELECT payload_fingerprint FROM orders WHERE provider=? AND account_id=? AND"
+ " event_id=? FOR UPDATE",
input,
false);
ResultSet result = statement.executeQuery()) {
if (!result.next() || !fingerprint(input).equals(result.getString(1)) || result.next()) {
throw new IllegalStateException("legacy-evidence-insufficient-keep-held");
}
}
try (PreparedStatement statement =
keyed(
client,
"INSERT INTO event_receipts(provider,account_id,event_id,payload_fingerprint) VALUES"
+ " (?,?,?,?) ON CONFLICT DO NOTHING",
input,
true)) {
statement.executeUpdate();
}
checkReceipt(client, input);
try (PreparedStatement statement =
keyed(
client,
"DELETE FROM delivery_holds WHERE provider=? AND account_id=? AND event_id=?",
input,
false)) {
equal(statement.executeUpdate(), 1);
}
client.commit();
trace("trusted-orphan-reconciled-hold-released", client, input, Map.of());
} catch (Exception failure) {
restore = rollback(client, failure);
throw failure;
} finally {
if (restore) client.setAutoCommit(true);
}
}
private void waitForContention(int waiter, int winner) throws Exception {
long deadline = System.nanoTime() + Duration.ofSeconds(5).toNanos();
while (System.nanoTime() < deadline) {
try (PreparedStatement statement =
observer.prepareStatement(
"SELECT wait_event_type, wait_event, pg_blocking_pids(pid) AS blockers FROM"
+ " pg_stat_activity WHERE pid=?")) {
statement.setInt(1, waiter);
try (ResultSet result = statement.executeQuery()) {
if (result.next()) {
java.sql.Array array = result.getArray("blockers");
List<Integer> blockers = new ArrayList<>();
try {
Object values = array.getArray();
for (int index = 0; index < java.lang.reflect.Array.getLength(values); index++) {
blockers.add(((Number) java.lang.reflect.Array.get(values, index)).intValue());
}
} finally {
array.free();
}
if ("Lock".equals(result.getString("wait_event_type")) && blockers.contains(winner)) {
Map<String, Object> record = new LinkedHashMap<>();
record.put("action", "real-database-contention");
record.put("pid", waiter);
record.put("winner", winner);
record.put("wait_event_type", "Lock");
record.put("wait_event", result.getString("wait_event"));
record.put("blockers", blockers);
System.out.println(JSON.writeValueAsString(record));
return;
}
}
}
}
Thread.sleep(10);
}
throw new IllegalStateException("competitor-never-observed-blocking-on-winner");
}
private static void await(CountDownLatch latch) throws Exception {
if (!latch.await(7, TimeUnit.SECONDS))
throw new IllegalStateException("Timed out awaiting transaction boundary");
}
private static Outcome outcome(Connection client, Hook hook) {
try {
return new Outcome(fixed(client, EVENT, hook), null);
} catch (Exception failure) {
return new Outcome(null, failure);
}
}
private void overlap(boolean winnerRollsBack) throws Exception {
ExecutorService workers = Executors.newFixedThreadPool(2);
CountDownLatch claimed = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
try (Connection winner = connect("winner");
Connection waiter = connect("waiter")) {
int winnerPid = pid(winner), waiterPid = pid(waiter);
require(winnerPid != waiterPid, "Independent database backends");
CompletableFuture<Outcome> first =
CompletableFuture.supplyAsync(
() ->
outcome(
winner,
boundary -> {
if (!boundary.equals("afterClaim")) return;
claimed.countDown();
await(release);
if (winnerRollsBack)
throw new IllegalStateException("injected:winner-rollback");
}),
workers);
CompletableFuture<Outcome> second = null;
try {
await(claimed);
assertCounts(0, 0, EVENT);
second = CompletableFuture.supplyAsync(() -> outcome(waiter, NO_FAILURE), workers);
waitForContention(waiterPid, winnerPid);
} finally {
release.countDown();
// Join while connections remain open, including failure paths.
Outcome a = first.get(12, TimeUnit.SECONDS);
Outcome b = second == null ? null : second.get(12, TimeUnit.SECONDS);
if (winnerRollsBack)
require(
a.failure() != null && a.failure().getMessage().contains("winner-rollback"),
"Winner rollback");
else {
equal(a.failure(), null);
equal(a.acknowledgment(), ACK);
}
require(b != null, "Waiter started");
equal(b.failure(), null);
equal(b.acknowledgment(), ACK);
}
assertCounts(1, 1, EVENT);
} finally {
release.countDown();
workers.shutdownNow();
if (!workers.awaitTermination(15, TimeUnit.SECONDS))
throw new IllegalStateException("Transaction workers did not stop");
}
}
private void verifyFixture() throws Exception {
try (Statement statement = observer.createStatement();
ResultSet result =
statement.executeQuery(
"SELECT current_database(), current_user, shobj_description(oid,'pg_database') FROM"
+ " pg_database WHERE datname=current_database()")) {
require(result.next(), "Database identity");
equal(result.getString(1), "codex_incident_test");
equal(result.getString(2), "codex_incident_test");
equal(result.getString(3), "codex-synthetic-incident-fixture-v1");
}
String version;
try (Statement statement = observer.createStatement();
ResultSet result = statement.executeQuery("SHOW server_version")) {
require(result.next(), "Database version");
version = result.getString(1);
equal(version, "17.6 (Debian 17.6-2.pgdg12+1)");
}
try (Statement statement = observer.createStatement();
ResultSet result = statement.executeQuery("SELECT pg_try_advisory_lock(14014)")) {
require(result.next() && result.getBoolean(1), "Exclusive synthetic fixture lease");
}
emit(
"fixture-environment",
Map.of(
"java",
System.getProperty("java.version"),
"pg",
version,
"mode",
mode,
"event_source",
"canonical-sanitized-incident-record"));
}
private void createSchema() throws Exception {
execute(observer, "DROP SCHEMA IF EXISTS incident_rehearsal CASCADE");
execute(observer, "CREATE SCHEMA incident_rehearsal");
execute(observer, "SET search_path TO incident_rehearsal, public");
execute(
observer,
"CREATE TABLE event_receipts(provider text NOT NULL,account_id text NOT NULL,event_id text"
+ " NOT NULL,payload_fingerprint text NOT NULL,CONSTRAINT event_receipts_identity"
+ " UNIQUE(provider,account_id,event_id) NOT DEFERRABLE)");
execute(
observer,
"CREATE TABLE orders(id bigserial PRIMARY KEY,provider text NOT NULL,account_id text NOT"
+ " NULL,event_id text NOT NULL,payload_fingerprint text)");
execute(
observer,
"CREATE TABLE delivery_holds(provider text NOT NULL,account_id text NOT NULL,event_id text"
+ " NOT NULL,PRIMARY KEY(provider,account_id,event_id))");
try (Statement statement = observer.createStatement();
ResultSet result =
statement.executeQuery(
"SELECT condeferrable,pg_get_constraintdef(oid) FROM pg_constraint WHERE"
+ " conrelid='incident_rehearsal.event_receipts'::regclass AND"
+ " conname='event_receipts_identity'")) {
require(result.next(), "Receipt uniqueness");
equal(result.getBoolean(1), false);
emit(
"receipt-schema",
Map.of(
"conname",
"event_receipts_identity",
"condeferrable",
result.getBoolean(1),
"definition",
result.getString(2)));
}
}
private int run() throws Exception {
Map<String, Checked> tests = new LinkedHashMap<>();
tests.put(
"retry after the order boundary leaves exactly one order and one receipt",
() -> {
try (Connection client = connect("regression")) {
rejects(
() -> {
if (mode.equals("baseline")) baseline(client, EVENT, failAt("afterOrder"));
else fixed(client, EVENT, failAt("afterOrder"));
},
"injected:afterOrder");
assertCounts(mode.equals("baseline") ? 1 : 0, 0, EVENT);
equal(
mode.equals("baseline")
? baseline(client, EVENT, NO_FAILURE)
: fixed(client, EVENT, NO_FAILURE),
ACK);
assertCounts(
1, 1, EVENT); // Baseline deliberately fails here, after exposing two orders.
}
});
if (mode.equals("fixed")) {
tests.put(
"first delivery and committed duplicate return the exact acknowledgment",
() -> {
try (Connection client = connect("duplicate")) {
equal(fixed(client, EVENT, NO_FAILURE), ACK);
equal(fixed(client, EVENT, NO_FAILURE), ACK);
assertCounts(1, 1, EVENT);
}
});
for (String boundary : List.of("beforeClaim", "afterClaim", "afterOrder")) {
tests.put(
"failure " + boundary + " rolls back and remains retryable",
() -> {
try (Connection client = connect("failure-" + boundary)) {
rejects(() -> fixed(client, EVENT, failAt(boundary)), "injected:" + boundary);
assertCounts(0, 0, EVENT);
equal(fixed(client, EVENT, NO_FAILURE), ACK);
assertCounts(1, 1, EVENT);
}
});
}
tests.put(
"lost acknowledgment after commit does not duplicate the order",
() -> {
try (Connection client = connect("lost-ack")) {
rejects(() -> fixed(client, EVENT, failAt("afterCommit")), "injected:afterCommit");
assertCounts(1, 1, EVENT);
equal(fixed(client, EVENT, NO_FAILURE), ACK);
assertCounts(1, 1, EVENT);
}
});
tests.put("real overlapping duplicate contention: winner commit", () -> overlap(false));
tests.put("real overlapping duplicate contention: winner rollback", () -> overlap(true));
tests.put(
"event, account, and provider scope remain independent; conflicting payload is rejected",
() -> {
try (Connection client = connect("identity")) {
for (IncidentEvent input :
List.of(
EVENT,
new IncidentEvent(
EVENT.provider(), EVENT.accountId(), "evt_demo_043", EVENT.payload()),
new IncidentEvent(
EVENT.provider(), "acct_demo_02", EVENT.eventId(), EVENT.payload()),
new IncidentEvent(
"synthetic-other",
EVENT.accountId(),
EVENT.eventId(),
EVENT.payload()))) {
equal(fixed(client, input, NO_FAILURE), ACK);
assertCounts(1, 1, input);
}
rejects(() -> fixed(client, changedPayload(), NO_FAILURE), "payload-conflict");
assertCounts(1, 1, EVENT);
}
});
tests.put(
"legacy orphan is held before retry and reconciled only from trusted evidence",
() -> {
try (Connection client = connect("legacy-orphan")) {
writeOrder(client, EVENT);
assertCounts(1, 0, EVENT);
equal(identifyAndHoldLegacyOrphans(client), 1);
rejects(() -> fixed(client, EVENT, NO_FAILURE), "legacy-retry-held");
assertCounts(1, 0, EVENT);
rejects(() -> reconcileHeldOrphan(client, changedPayload()), "evidence-insufficient");
rejects(() -> fixed(client, EVENT, NO_FAILURE), "legacy-retry-held");
reconcileHeldOrphan(client, EVENT);
equal(fixed(client, EVENT, NO_FAILURE), ACK);
assertCounts(1, 1, EVENT);
}
});
tests.put(
"missing legacy payload evidence stays quarantined without a fabricated receipt",
() -> {
try (Connection client = connect("legacy-missing-evidence")) {
try (PreparedStatement statement =
keyed(
client,
"INSERT INTO orders(provider,account_id,event_id) VALUES (?,?,?)",
EVENT,
false)) {
statement.executeUpdate();
}
equal(identifyAndHoldLegacyOrphans(client), 1);
rejects(() -> reconcileHeldOrphan(client, EVENT), "evidence-insufficient");
rejects(() -> fixed(client, EVENT, NO_FAILURE), "legacy-retry-held");
assertCounts(1, 0, EVENT);
}
});
}
int failures = 0, index = 0;
for (Map.Entry<String, Checked> test : tests.entrySet()) {
index++;
try {
execute(observer, "TRUNCATE orders,event_receipts,delivery_holds RESTART IDENTITY");
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 failures;
}
private static IncidentEvent changedPayload() {
return new IncidentEvent(
EVENT.provider(),
EVENT.accountId(),
EVENT.eventId(),
new Payload(EVENT.payload().type(), EVENT.payload().orderId(), 9999));
}
public static void main(String[] args) throws Exception {
if (args.length > 1) throw new IllegalArgumentException("Usage: baseline|regression|fixed");
String mode = args.length == 0 ? "fixed" : args[0];
if (!List.of("baseline", "regression", "fixed").contains(mode))
throw new IllegalArgumentException("Unknown incident mode");
EVENT =
parseIncidentEvent(
java.nio.file.Files.readString(java.nio.file.Path.of(INCIDENT_EVENT_FILE)));
int failures;
try (Connection observer = connect("observer")) {
CodexCloudIncidentToTestedFix suite = new CodexCloudIncidentToTestedFix(observer, mode);
suite.verifyFixture(); // No schema mutation before all identity and lease checks pass.
try {
suite.createSchema();
failures = suite.run();
} finally {
execute(observer, "DROP SCHEMA IF EXISTS incident_rehearsal CASCADE");
execute(observer, "SELECT pg_advisory_unlock(14014)");
}
}
if (failures != 0) System.exit(1);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483using System.Data;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text.Json;
using System.Text.Json.Serialization;
using Npgsql;
namespace OpenAI.Docs.Examples.CodexCloud.IncidentToTestedFix;
internal static class IncidentToTestedFixSample
{
// The entry point targets only a marked disposable PostgreSQL fixture.
// A native scenario adapter can call RunModeAsync("baseline"|"regression"|"fixed").
internal static Task RunAsync() => RunModeAsync("fixed");
internal static string ParseMode(string[] arguments) => arguments.Length == 1 &&
arguments[0] is "baseline" or "regression" or "fixed"
? arguments[0]
: throw new ArgumentException("Expected exactly one mode: baseline, regression, or fixed.", nameof(arguments));
internal sealed record Payload(string type, string orderId, [property: JsonRequired] int amountCents);
internal sealed record Incident(string provider, string accountId, string eventId, Payload payload);
private sealed record Acknowledgment(int status, object body);
private const string FixtureRelativePath = "../../typescript-examples/codex-cloud/incident-to-tested-fix/incidents/INC-DEMO-014/order-created.sanitized.json";
internal static string ResolveInputPath(string sourceFile, string relativePath) =>
Path.GetFullPath(Path.Combine(Path.GetDirectoryName(sourceFile)!, relativePath));
internal static Incident LoadInput([System.Runtime.CompilerServices.CallerFilePath] string sourceFile = "")
{
string owned = Path.Combine("codex-cloud", "incident-to-tested-fix", "incidents", "INC-DEMO-014", "order-created.sanitized.json");
return ParseInput(File.ReadAllText(File.Exists(owned) ? owned : ResolveInputPath(sourceFile, FixtureRelativePath)));
}
private static readonly JsonSerializerOptions InputJsonOptions = new()
{ UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow };
internal static Incident ParseInput(string json)
{
Incident? input = JsonSerializer.Deserialize<Incident>(json, InputJsonOptions);
if (input is null || string.IsNullOrWhiteSpace(input.provider) ||
string.IsNullOrWhiteSpace(input.accountId) || string.IsNullOrWhiteSpace(input.eventId) ||
input.payload is null || string.IsNullOrWhiteSpace(input.payload.type) ||
string.IsNullOrWhiteSpace(input.payload.orderId) || input.payload.amountCents < 0)
throw new FormatException("Invalid sanitized incident fixture.");
return input;
}
private static readonly Acknowledgment Ack = new(200, new { received = true });
internal static string Fingerprint(Incident input) => Convert.ToHexStringLower(SHA256.HashData(
JsonSerializer.SerializeToUtf8Bytes(new object[] { input.payload.type, input.payload.orderId, input.payload.amountCents })));
internal static object[] Key(Incident input) => [input.provider, input.accountId, input.eventId];
internal static object[] Values(Incident input) => [.. Key(input), Fingerprint(input)];
private static void Trace(string action, NpgsqlConnection client, Incident input, object? details = null)
{
Dictionary<string, object?> value = new(StringComparer.Ordinal)
{ ["action"] = action, ["pid"] = client.ProcessID, ["key"] = Key(input) };
if (details is not null)
foreach (var property in JsonSerializer.SerializeToElement(details).EnumerateObject())
value.Add(property.Name, property.Value.Clone());
Console.WriteLine(JsonSerializer.Serialize(value));
}
private static NpgsqlCommand Command(NpgsqlConnection client, string sql, object[]? values = null,
NpgsqlTransaction? transaction = null)
{
NpgsqlCommand command = new(sql, client, transaction) { CommandTimeout = 8 };
// Empty parameter names select Npgsql's positional $1, $2, ... binding.
foreach (object value in values ?? []) command.Parameters.Add(new NpgsqlParameter { Value = value });
return command;
}
private static async Task<int> Execute(NpgsqlConnection client, string sql, object[]? values = null,
NpgsqlTransaction? transaction = null)
{
await using NpgsqlCommand command = Command(client, sql, values, transaction);
return await command.ExecuteNonQueryAsync();
}
private static async Task<object?> Scalar(NpgsqlConnection client, string sql, object[]? values = null,
NpgsqlTransaction? transaction = null)
{
await using NpgsqlCommand command = Command(client, sql, values, transaction);
return await command.ExecuteScalarAsync();
}
private static void Require(bool condition, string message)
{
if (!condition) throw new InvalidOperationException(message);
}
private static async Task Reject(Func<Task> action, string message)
{
try { await action(); }
catch (InvalidOperationException error) when (error.Message == message) { return; }
throw new InvalidOperationException("Expected failure: " + message);
}
private static Func<string, Task> FailAt(string point) => boundary =>
boundary == point ? Task.FromException(new InvalidOperationException("injected:" + point)) : Task.CompletedTask;
private static async Task WriteOrder(NpgsqlConnection client, Incident input, NpgsqlTransaction? transaction = null)
{
await Execute(client,
"INSERT INTO orders(provider,account_id,event_id,payload_fingerprint) VALUES ($1,$2,$3,$4)", Values(input), transaction);
Trace("order-written", client, input);
}
private static async Task CheckReceipt(NpgsqlConnection client, Incident input, NpgsqlTransaction? transaction = null)
{
object? value = await Scalar(client,
"SELECT payload_fingerprint FROM event_receipts WHERE provider=$1 AND account_id=$2 AND event_id=$3", Key(input), transaction);
Require(value is string, "missing-receipt-after-skipped-claim");
Require((string)value! == Fingerprint(input), "payload-conflict");
}
// Deliberate legacy defect: its first commit survives the injected failure.
private static async Task<Acknowledgment> Baseline(NpgsqlConnection client, Incident input, Func<string, Task>? hook = null)
{
hook ??= _ => Task.CompletedTask;
if (await Scalar(client, "SELECT 1 FROM event_receipts WHERE provider=$1 AND account_id=$2 AND event_id=$3", Key(input)) is not null)
{
await CheckReceipt(client, input);
return Ack;
}
await using (NpgsqlTransaction transaction = await client.BeginTransactionAsync(IsolationLevel.ReadCommitted))
{
await WriteOrder(client, input, transaction);
await transaction.CommitAsync();
}
Trace("legacy-order-committed-without-receipt", client, input);
await hook("afterOrder");
await Execute(client, "INSERT INTO event_receipts(provider,account_id,event_id,payload_fingerprint) VALUES ($1,$2,$3,$4)", Values(input));
Trace("legacy-receipt-committed", client, input);
return Ack;
}
private static async Task<Acknowledgment> Fixed(NpgsqlConnection client, Incident input, Func<string, Task>? hook = null)
{
hook ??= _ => Task.CompletedTask;
if (await Scalar(client, "SELECT 1 FROM delivery_holds WHERE provider=$1 AND account_id=$2 AND event_id=$3", Key(input)) is not null)
{
Trace("legacy-retry-held-no-ack", client, input);
throw new InvalidOperationException("legacy-retry-held");
}
await hook("beforeClaim");
await using NpgsqlTransaction transaction = await client.BeginTransactionAsync(IsolationLevel.ReadCommitted);
bool committed = false;
try
{
object? claimed = await Scalar(client, """
INSERT INTO event_receipts(provider,account_id,event_id,payload_fingerprint)
VALUES ($1,$2,$3,$4) ON CONFLICT (provider,account_id,event_id)
DO NOTHING RETURNING event_id
""", Values(input), transaction);
Trace("receipt-claim-result", client, input, new { inserted = claimed is not null });
if (claimed is not null)
{
await hook("afterClaim");
await WriteOrder(client, input, transaction);
await hook("afterOrder");
}
else
{
// A new READ COMMITTED statement sees the committed winner.
await CheckReceipt(client, input, transaction);
}
await transaction.CommitAsync();
committed = true;
Trace("transaction-committed", client, input);
await hook("afterCommit");
Trace("acknowledged", client, input, Ack);
return Ack;
}
catch (Exception failure)
{
if (!committed)
{
try { await transaction.RollbackAsync(); }
catch (Exception rollbackFailure)
{ throw new AggregateException("Transaction failed and rollback could not be confirmed", failure, rollbackFailure); }
Trace("transaction-rolled-back-no-ack", client, input);
}
else Trace("committed-response-lost-no-ack", client, input);
throw;
}
}
// Run with ingestion paused and legacy consumers drained. This durable hold
// models an operator-controlled quarantine, not a production migration.
private static async Task<int> HoldOrphans(NpgsqlConnection client)
{
int held = await Execute(client, """
INSERT INTO delivery_holds(provider,account_id,event_id)
SELECT DISTINCT o.provider,o.account_id,o.event_id FROM orders o
WHERE NOT EXISTS (SELECT 1 FROM event_receipts r
WHERE r.provider=o.provider AND r.account_id=o.account_id AND r.event_id=o.event_id)
ON CONFLICT DO NOTHING
""");
Console.WriteLine(JsonSerializer.Serialize(new { action = "pre-resume-orphans-held", keys = held }));
return held;
}
private static async Task Reconcile(NpgsqlConnection client, Incident input)
{
await using NpgsqlTransaction transaction = await client.BeginTransactionAsync(IsolationLevel.ReadCommitted);
try
{
Require(await Scalar(client, "SELECT 1 FROM delivery_holds WHERE provider=$1 AND account_id=$2 AND event_id=$3 FOR UPDATE",
Key(input), transaction) is not null, "reconciliation-requires-hold");
List<string?> fingerprints = [];
await using (NpgsqlCommand command = Command(client,
"SELECT payload_fingerprint FROM orders WHERE provider=$1 AND account_id=$2 AND event_id=$3 FOR UPDATE", Key(input), transaction))
await using (NpgsqlDataReader reader = await command.ExecuteReaderAsync())
while (await reader.ReadAsync()) fingerprints.Add(reader.IsDBNull(0) ? null : reader.GetString(0));
Require(fingerprints.Count == 1 && fingerprints[0] == Fingerprint(input), "legacy-evidence-insufficient-keep-held");
await Execute(client, """
INSERT INTO event_receipts(provider,account_id,event_id,payload_fingerprint) VALUES ($1,$2,$3,$4)
ON CONFLICT DO NOTHING
""", Values(input), transaction);
await CheckReceipt(client, input, transaction);
await Execute(client, "DELETE FROM delivery_holds WHERE provider=$1 AND account_id=$2 AND event_id=$3", Key(input), transaction);
await transaction.CommitAsync();
Trace("trusted-orphan-reconciled-hold-released", client, input);
}
catch (Exception failure)
{
try { await transaction.RollbackAsync(); }
catch (Exception rollbackFailure)
{ throw new AggregateException("Reconciliation failed and rollback could not be confirmed", failure, rollbackFailure); }
throw;
}
}
private static async Task Counts(NpgsqlConnection observer, int orders, int receipts, Incident input)
{
await using NpgsqlCommand command = Command(observer, """
SELECT (SELECT count(*)::integer FROM orders WHERE provider=$1 AND account_id=$2 AND event_id=$3),
(SELECT count(*)::integer FROM event_receipts WHERE provider=$1 AND account_id=$2 AND event_id=$3)
""", Key(input));
await using NpgsqlDataReader reader = await command.ExecuteReaderAsync();
Require(await reader.ReadAsync(), "Missing committed-state counts");
int actualOrders = reader.GetInt32(0), actualReceipts = reader.GetInt32(1);
Trace("committed-state", observer, input, new { orders = actualOrders, receipts = actualReceipts });
Require(actualOrders == orders && actualReceipts == receipts,
$"Expected {orders} order(s)/{receipts} receipt(s); got {actualOrders}/{actualReceipts}");
}
private static void Acknowledged(Acknowledgment value) => Require(
JsonSerializer.Serialize(value) == "{\"status\":200,\"body\":{\"received\":true}}", "Exact delivery acknowledgment");
internal static async Task RunModeAsync(string mode)
{
if (mode is not ("baseline" or "regression" or "fixed")) throw new ArgumentException("Expected baseline, regression, or fixed", nameof(mode));
Incident original = LoadInput();
string password = Environment.GetEnvironmentVariable("CODEX_INCIDENT_DB_PASSWORD")
?? throw new InvalidOperationException("Set CODEX_INCIDENT_DB_PASSWORD to the disposable fixture password");
NpgsqlConnectionStringBuilder configuration = new()
{
Host = "127.0.0.1",
Port = 55432,
Username = "codex_incident_test",
Database = "codex_incident_test",
Password = password,
Timeout = 5,
CommandTimeout = 8,
Pooling = false,
ApplicationName = "csharp-incident-rehearsal"
};
await using NpgsqlConnection observer = new(configuration.ConnectionString);
await observer.OpenAsync();
// Verify all fixture identity evidence before creating or changing any DB object.
await using (NpgsqlCommand identity = Command(observer, """
SELECT current_database(),current_user,shobj_description(oid,'pg_database'),current_setting('server_version')
FROM pg_database WHERE datname=current_database()
"""))
await using (NpgsqlDataReader reader = await identity.ExecuteReaderAsync())
{
Require(await reader.ReadAsync() && reader.GetString(0) == "codex_incident_test" &&
reader.GetString(1) == "codex_incident_test" && !reader.IsDBNull(2) &&
reader.GetString(2) == "codex-synthetic-incident-fixture-v1" &&
reader.GetString(3) == "17.6 (Debian 17.6-2.pgdg12+1)", "Refusing an unmarked or unexpected database fixture");
Console.WriteLine(JsonSerializer.Serialize(new
{
action = "fixture-environment",
mode,
runtime = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription,
pg = reader.GetString(3)
}));
}
string schema = "incident_rehearsal_" + Guid.NewGuid().ToString("N");
// The generated identifier is hex only; external input never enters this SQL.
await Execute(observer, $"CREATE SCHEMA {schema}");
List<NpgsqlConnection> clients = [];
int tests = 0, failures = 0;
try
{
await Execute(observer, $"SET search_path TO {schema},public");
await Execute(observer, """
CREATE TABLE event_receipts (
provider text NOT NULL, account_id text NOT NULL, event_id text NOT NULL,
payload_fingerprint text NOT NULL,
CONSTRAINT event_receipts_identity UNIQUE(provider,account_id,event_id) NOT DEFERRABLE);
CREATE TABLE orders (id bigserial PRIMARY KEY, provider text NOT NULL,
account_id text NOT NULL, event_id text NOT NULL, payload_fingerprint text);
CREATE TABLE delivery_holds (provider text NOT NULL, account_id text NOT NULL,
event_id text NOT NULL, PRIMARY KEY(provider,account_id,event_id));
""");
Require(await Scalar(observer, """
SELECT NOT condeferrable FROM pg_constraint
WHERE conname='event_receipts_identity' AND conrelid='event_receipts'::regclass
""") is true, "Receipt uniqueness must be nondeferrable");
async Task<NpgsqlConnection> Connect()
{
NpgsqlConnection client = new(configuration.ConnectionString);
clients.Add(client);
await client.OpenAsync();
await Execute(client, $"SET search_path TO {schema},public");
await Execute(client, "SET statement_timeout = '8s'");
return client;
}
async Task Case(string name, Func<NpgsqlConnection, Task> test)
{
tests++;
try
{
await Execute(observer, "TRUNCATE orders,event_receipts,delivery_holds RESTART IDENTITY");
NpgsqlConnection client = await Connect();
try { await test(client); }
finally { await client.DisposeAsync(); clients.Remove(client); }
Console.WriteLine($"ok {tests} - {name}");
}
catch (Exception error)
{
failures++;
Console.WriteLine($"not ok {tests} - {name}");
Console.WriteLine("# " + error.ToString().Replace("\r", "").Replace("\n", "\n# "));
}
}
await Case("retry after the order boundary leaves exactly one order and one receipt", async client =>
{
async Task<Acknowledgment> Handle(Func<string, Task>? hook = null) => mode == "baseline"
? await Baseline(client, original, hook) : await Fixed(client, original, hook);
await Reject(async () => { await Handle(FailAt("afterOrder")); }, "injected:afterOrder");
await Counts(observer, mode == "baseline" ? 1 : 0, 0, original);
Acknowledged(await Handle());
await Counts(observer, 1, 1, original);
});
if (mode == "fixed")
{
await Case("first delivery and committed duplicate return the exact acknowledgment", async client =>
{
Acknowledged(await Fixed(client, original));
Acknowledged(await Fixed(client, original));
await Counts(observer, 1, 1, original);
});
foreach (string boundary in new[] { "beforeClaim", "afterClaim", "afterOrder" })
await Case("failure " + boundary + " rolls back and remains retryable", async client =>
{
await Reject(async () => { await Fixed(client, original, FailAt(boundary)); }, "injected:" + boundary);
await Counts(observer, 0, 0, original);
Acknowledged(await Fixed(client, original));
await Counts(observer, 1, 1, original);
});
await Case("lost acknowledgment after commit does not duplicate the order", async client =>
{
await Reject(async () => { await Fixed(client, original, FailAt("afterCommit")); }, "injected:afterCommit");
await Counts(observer, 1, 1, original);
Acknowledged(await Fixed(client, original));
await Counts(observer, 1, 1, original);
});
foreach (bool rollback in new[] { false, true })
await Case("real overlapping duplicate contention: winner " + (rollback ? "rollback" : "commit"), async winner =>
{
NpgsqlConnection waiter = await Connect();
try
{
Require(winner.ProcessID != waiter.ProcessID, "Contention requires independent backends");
TaskCompletionSource claimed = new(TaskCreationOptions.RunContinuationsAsynchronously);
TaskCompletionSource release = new(TaskCreationOptions.RunContinuationsAsynchronously);
Task<Acknowledgment> winnerTask = Fixed(winner, original, async boundary =>
{
if (boundary != "afterClaim") return;
claimed.TrySetResult();
await release.Task.WaitAsync(TimeSpan.FromSeconds(7));
if (rollback) throw new InvalidOperationException("injected:winner-rollback");
});
Task<Acknowledgment>? waiterTask = null;
try
{
await Task.WhenAny(claimed.Task, winnerTask).WaitAsync(TimeSpan.FromSeconds(5));
if (!claimed.Task.IsCompleted) { await winnerTask; throw new InvalidOperationException("Winner did not claim receipt"); }
await Counts(observer, 0, 0, original);
waiterTask = Fixed(waiter, original);
await WaitForContention(observer, waiter, winner, original);
}
finally
{
release.TrySetResult();
// Observe both outcomes even when the first assertion fails.
await Task.WhenAll(
ObserveWinner(winnerTask, rollback),
waiterTask is null ? Task.CompletedTask : ObserveWaiter(waiterTask));
}
await Counts(observer, 1, 1, original);
}
finally { await waiter.DisposeAsync(); clients.Remove(waiter); }
});
await Case("event, account, and provider identity; conflicting payload rejected", async client =>
{
foreach (Incident input in new[] { original, original with { eventId = "evt_demo_043" },
original with { accountId = "acct_demo_02" }, original with { provider = "synthetic-other" } })
{
Acknowledged(await Fixed(client, input));
await Counts(observer, 1, 1, input);
}
await Reject(async () => { await Fixed(client, original with { payload = original.payload with { amountCents = 9999 } }); }, "payload-conflict");
await Counts(observer, 1, 1, original);
});
await Case("legacy orphan held before retry and reconciled only from trusted evidence", async client =>
{
await WriteOrder(client, original);
await Counts(observer, 1, 0, original);
Require(await HoldOrphans(client) == 1, "Hold the orphan before resuming ingestion");
await Reject(async () => { await Fixed(client, original); }, "legacy-retry-held");
await Reject(
() => Reconcile(client, original with
{
payload = original.payload with { amountCents = 9999 },
}),
"legacy-evidence-insufficient-keep-held");
await Reject(async () => { await Fixed(client, original); }, "legacy-retry-held");
await Reconcile(client, original);
Acknowledged(await Fixed(client, original));
await Counts(observer, 1, 1, original);
});
await Case("missing legacy payload evidence stays quarantined", async client =>
{
await Execute(client, "INSERT INTO orders(provider,account_id,event_id) VALUES ($1,$2,$3)", Key(original));
Require(await HoldOrphans(client) == 1, "Hold missing-evidence orphan");
await Reject(() => Reconcile(client, original), "legacy-evidence-insufficient-keep-held");
await Reject(async () => { await Fixed(client, original); }, "legacy-retry-held");
await Counts(observer, 1, 0, original);
});
}
Require(tests == (mode == "fixed" ? 11 : 1), "All native incident scenarios must execute");
Console.WriteLine($"1..{tests}\n# tests {tests}\n# pass {tests - failures}\n# fail {failures}\n# cancelled 0\n# skipped 0\n# todo 0");
}
finally
{
try
{
foreach (NpgsqlConnection client in clients) await client.DisposeAsync();
}
finally { await Execute(observer, $"DROP SCHEMA {schema} CASCADE"); }
}
if (failures != 0) throw new InvalidOperationException($"{failures} native incident regression(s) failed");
}
private static async Task ObserveWinner(Task<Acknowledgment> task, bool rollback)
{
if (rollback) await Reject(async () => { await task; }, "injected:winner-rollback");
else Acknowledged(await task);
}
private static async Task ObserveWaiter(Task<Acknowledgment> task) => Acknowledged(await task);
private static async Task WaitForContention(NpgsqlConnection observer, NpgsqlConnection waiter, NpgsqlConnection winner, Incident input)
{
Stopwatch elapsed = Stopwatch.StartNew();
while (elapsed.Elapsed < TimeSpan.FromSeconds(5))
{
await using (NpgsqlCommand command = Command(observer, """
SELECT wait_event_type,wait_event,pg_blocking_pids(pid)
FROM pg_stat_activity WHERE pid=$1
""", [waiter.ProcessID]))
await using (NpgsqlDataReader reader = await command.ExecuteReaderAsync())
{
if (await reader.ReadAsync() && !reader.IsDBNull(0) && reader.GetString(0) == "Lock")
{
int[] blockers = reader.GetFieldValue<int[]>(2);
if (blockers.Contains(winner.ProcessID))
{
Trace("real-database-contention", waiter, input, new
{ winner = winner.ProcessID, wait_event_type = reader.GetString(0), wait_event = reader.GetString(1), blockers });
return;
}
}
}
await Task.Delay(10);
}
throw new InvalidOperationException("competitor-never-observed-blocking-on-winner");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36def self.fixed(client, input, hook = ->(_boundary) {})
assert_not_held(client, input)
hook.call("beforeClaim")
client.exec("BEGIN ISOLATION LEVEL READ COMMITTED")
committed = false
begin
claimed = client.exec_params(<<~SQL, key(input) + [fingerprint(input)])
INSERT INTO event_receipts(provider, account_id, event_id, payload_fingerprint)
VALUES ($1,$2,$3,$4)
ON CONFLICT (provider, account_id, event_id) DO NOTHING RETURNING event_id
SQL
trace("receipt-claim-result", client, input, inserted: claimed.ntuples == 1)
if claimed.ntuples == 1
hook.call("afterClaim")
write_order(client, input)
hook.call("afterOrder")
else
# A new READ COMMITTED statement sees the winner after its commit.
check_receipt(client, input)
end
client.exec("COMMIT")
committed = true
trace("transaction-committed", client, input)
hook.call("afterCommit")
trace("acknowledged", client, input, **ACK)
ACK
rescue
if committed
trace("committed-response-lost-no-ack", client, input)
else
client.exec("ROLLBACK")
trace("transaction-rolled-back-no-ack", client, input)
end
raise
end
end