SpyBara
Go Premium

Documentation 2026-11-24 23:01 UTC to 2026-11-25 23:02 UTC

4 files changed +490 −4. View all changes and history on the product overview
2026
Thu 26 23:00 Wed 25 23:02 Tue 24 23:01 Mon 23 23:58 Fri 20 23:59 Thu 19 23:02 Wed 18 22:59 Tue 17 22:59 Mon 16 23:00 Sun 15 23:01 Sat 14 23:01 Fri 13 23:58 Thu 12 22:58 Wed 11 23:00 Tue 10 23:57 Mon 9 23:02 Fri 6 23:02 Thu 5 23:03 Wed 4 23:02 Tue 3 23:57 Mon 2 23:02

dots.md +1 −1

Details

54 54 

55Tell your dot where to send different kinds of updates. For example, ask it to keep routine progress in ChatGPT and bring decisions to you in Slack. Explain which changes need your attention, such as a deadline at risk.55Tell your dot where to send different kinds of updates. For example, ask it to keep routine progress in ChatGPT and bring decisions to you in Slack. Explain which changes need your attention, such as a deadline at risk.

56 56 

57Open your dot's profile and select **Add** to connect an available contact method. Texting is rolling out in beta to ChatGPT Pro users in the U.S. See how to [set up texting](https://learn.chatgpt.com/docs/dots/channels#texting) with iMessage or RCS on Android. See [Message your dot](https://learn.chatgpt.com/docs/dots/channels) for other ways to reach it.57Open your dot's profile and select **Add** to connect an available contact method. Texting is rolling out in beta to ChatGPT Pro users in the U.S., Canada, and Mexico. See how to [set up texting](https://learn.chatgpt.com/docs/dots/channels#texting) with iMessage or RCS on Android. See [Message your dot](https://learn.chatgpt.com/docs/dots/channels) for other ways to reach it.

58 58 

59In Slack, you can DM your dot or mention it in a channel you’ve added it to. By default, it responds to you; you can instruct it to engage with others. Existing permissions and safeguards still apply to what it shares and does. Tell it which channels and events to watch for. Adding it to a channel alone doesn’t start monitoring. See [Message your dot in Slack](https://learn.chatgpt.com/docs/dots/channels#slack) for setup instructions.59In Slack, you can DM your dot or mention it in a channel you’ve added it to. By default, it responds to you; you can instruct it to engage with others. Existing permissions and safeguards still apply to what it shares and does. Tell it which channels and events to watch for. Adding it to a channel alone doesn’t start monitoring. See [Message your dot in Slack](https://learn.chatgpt.com/docs/dots/channels#slack) for setup instructions.

60 60 

Details

98 98 

99## Texting99## Texting

100 100 

101Reach your dot through iMessage or RCS on Android. Texting supports one-to-one conversations. It’s rolling out in beta to ChatGPT Pro users in the U.S.101Reach your dot through iMessage or RCS on Android. Texting supports one-to-one conversations. It’s rolling out in beta to ChatGPT Pro users in the U.S., Canada, and Mexico.

102 102 

103Your dot can use relevant context from your conversations in ChatGPT and other connected channels, along with the plugins you’ve connected.103Your dot can use relevant context from your conversations in ChatGPT and other connected channels, along with the plugins you’ve connected.

104 104 

Details

2 2 

3> For the complete documentation index, see [llms.txt](https://learn.chatgpt.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.3> For the complete documentation index, see [llms.txt](https://learn.chatgpt.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.

4 4 

5Hosting is free through **December 31, 2026**. Starting **January 1, 2027**, Plus, Pro, and Business customers pay for hosting usage above their monthly allowance. Enterprise billing follows your organization’s agreement.5We plan to show your Sites hosting usage in the app starting **January 1, 2027**. Hosting is free through **January 31, 2027**. We plan to start charging Plus, Pro, and Business customers for hosting usage above their monthly allowance on **February 1, 2027**. Enterprise billing follows your organization’s agreement.

6 6 

7You can create as many sites as you want. Building and editing them count toward your plan’s [Codex usage](https://learn.chatgpt.com/docs/pricing). Hosting covers the traffic your sites receive and the storage they use.7You can create as many sites as you want. Building and editing them count toward your plan’s [Codex usage](https://learn.chatgpt.com/docs/pricing). Hosting covers the traffic your sites receive and the storage they use.

8 8 


21 21 

22## Hosting usage rates22## Hosting usage rates

23 23 

24Use these approximate credit rates to estimate hosting costs starting January 1, 2027.24Use these approximate credit rates to estimate hosting costs.

25 25 

26| What you use | Billing unit | Approx. credits |26| What you use | Billing unit | Approx. credits |

27| ------------------------------------------------------------------ | ------------------------ | --------------- |27| ------------------------------------------------------------------ | ------------------------ | --------------- |

Details

249}249}

250```250```

251 251 

252```csharp

253using System.Data;

254using System.Diagnostics;

255using System.Security.Cryptography;

256using System.Text.Json;

257using System.Text.Json.Serialization;

258using Npgsql;

259 

260namespace OpenAI.Docs.Examples.CodexCloud.IncidentToTestedFix;

261 

262internal static class IncidentToTestedFixSample

263{

264 // The entry point targets only a marked disposable PostgreSQL fixture.

265 // A native scenario adapter can call RunModeAsync("baseline"|"regression"|"fixed").

266 internal static Task RunAsync() => RunModeAsync("fixed");

267 

268 internal static string ParseMode(string[] arguments) => arguments.Length == 1 &&

269 arguments[0] is "baseline" or "regression" or "fixed"

270 ? arguments[0]

271 : throw new ArgumentException("Expected exactly one mode: baseline, regression, or fixed.", nameof(arguments));

272 

273 internal sealed record Payload(string type, string orderId, [property: JsonRequired] int amountCents);

274 internal sealed record Incident(string provider, string accountId, string eventId, Payload payload);

275 private sealed record Acknowledgment(int status, object body);

276 private const string FixtureRelativePath = "../../typescript-examples/codex-cloud/incident-to-tested-fix/incidents/INC-DEMO-014/order-created.sanitized.json";

277 

278 internal static string ResolveInputPath(string sourceFile, string relativePath) =>

279 Path.GetFullPath(Path.Combine(Path.GetDirectoryName(sourceFile)!, relativePath));

280 

281 internal static Incident LoadInput([System.Runtime.CompilerServices.CallerFilePath] string sourceFile = "")

282 {

283 string owned = Path.Combine("codex-cloud", "incident-to-tested-fix", "incidents", "INC-DEMO-014", "order-created.sanitized.json");

284 return ParseInput(File.ReadAllText(File.Exists(owned) ? owned : ResolveInputPath(sourceFile, FixtureRelativePath)));

285 }

286 

287 private static readonly JsonSerializerOptions InputJsonOptions = new()

288 { UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow };

289 

290 internal static Incident ParseInput(string json)

291 {

292 Incident? input = JsonSerializer.Deserialize<Incident>(json, InputJsonOptions);

293 if (input is null || string.IsNullOrWhiteSpace(input.provider) ||

294 string.IsNullOrWhiteSpace(input.accountId) || string.IsNullOrWhiteSpace(input.eventId) ||

295 input.payload is null || string.IsNullOrWhiteSpace(input.payload.type) ||

296 string.IsNullOrWhiteSpace(input.payload.orderId) || input.payload.amountCents < 0)

297 throw new FormatException("Invalid sanitized incident fixture.");

298 return input;

299 }

300 private static readonly Acknowledgment Ack = new(200, new { received = true });

301 internal static string Fingerprint(Incident input) => Convert.ToHexStringLower(SHA256.HashData(

302 JsonSerializer.SerializeToUtf8Bytes(new object[] { input.payload.type, input.payload.orderId, input.payload.amountCents })));

303 internal static object[] Key(Incident input) => [input.provider, input.accountId, input.eventId];

304 internal static object[] Values(Incident input) => [.. Key(input), Fingerprint(input)];

305 

306 private static void Trace(string action, NpgsqlConnection client, Incident input, object? details = null)

307 {

308 Dictionary<string, object?> value = new(StringComparer.Ordinal)

309 { ["action"] = action, ["pid"] = client.ProcessID, ["key"] = Key(input) };

310 if (details is not null)

311 foreach (var property in JsonSerializer.SerializeToElement(details).EnumerateObject())

312 value.Add(property.Name, property.Value.Clone());

313 Console.WriteLine(JsonSerializer.Serialize(value));

314 }

315 

316 private static NpgsqlCommand Command(NpgsqlConnection client, string sql, object[]? values = null,

317 NpgsqlTransaction? transaction = null)

318 {

319 NpgsqlCommand command = new(sql, client, transaction) { CommandTimeout = 8 };

320 // Empty parameter names select Npgsql's positional $1, $2, ... binding.

321 foreach (object value in values ?? []) command.Parameters.Add(new NpgsqlParameter { Value = value });

322 return command;

323 }

324 private static async Task<int> Execute(NpgsqlConnection client, string sql, object[]? values = null,

325 NpgsqlTransaction? transaction = null)

326 {

327 await using NpgsqlCommand command = Command(client, sql, values, transaction);

328 return await command.ExecuteNonQueryAsync();

329 }

330 private static async Task<object?> Scalar(NpgsqlConnection client, string sql, object[]? values = null,

331 NpgsqlTransaction? transaction = null)

332 {

333 await using NpgsqlCommand command = Command(client, sql, values, transaction);

334 return await command.ExecuteScalarAsync();

335 }

336 private static void Require(bool condition, string message)

337 {

338 if (!condition) throw new InvalidOperationException(message);

339 }

340 private static async Task Reject(Func<Task> action, string message)

341 {

342 try { await action(); }

343 catch (InvalidOperationException error) when (error.Message == message) { return; }

344 throw new InvalidOperationException("Expected failure: " + message);

345 }

346 private static Func<string, Task> FailAt(string point) => boundary =>

347 boundary == point ? Task.FromException(new InvalidOperationException("injected:" + point)) : Task.CompletedTask;

348 

349 private static async Task WriteOrder(NpgsqlConnection client, Incident input, NpgsqlTransaction? transaction = null)

350 {

351 await Execute(client,

352 "INSERT INTO orders(provider,account_id,event_id,payload_fingerprint) VALUES ($1,$2,$3,$4)", Values(input), transaction);

353 Trace("order-written", client, input);

354 }

355 private static async Task CheckReceipt(NpgsqlConnection client, Incident input, NpgsqlTransaction? transaction = null)

356 {

357 object? value = await Scalar(client,

358 "SELECT payload_fingerprint FROM event_receipts WHERE provider=$1 AND account_id=$2 AND event_id=$3", Key(input), transaction);

359 Require(value is string, "missing-receipt-after-skipped-claim");

360 Require((string)value! == Fingerprint(input), "payload-conflict");

361 }

362 

363 // Deliberate legacy defect: its first commit survives the injected failure.

364 private static async Task<Acknowledgment> Baseline(NpgsqlConnection client, Incident input, Func<string, Task>? hook = null)

365 {

366 hook ??= _ => Task.CompletedTask;

367 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)

368 {

369 await CheckReceipt(client, input);

370 return Ack;

371 }

372 await using (NpgsqlTransaction transaction = await client.BeginTransactionAsync(IsolationLevel.ReadCommitted))

373 {

374 await WriteOrder(client, input, transaction);

375 await transaction.CommitAsync();

376 }

377 Trace("legacy-order-committed-without-receipt", client, input);

378 await hook("afterOrder");

379 await Execute(client, "INSERT INTO event_receipts(provider,account_id,event_id,payload_fingerprint) VALUES ($1,$2,$3,$4)", Values(input));

380 Trace("legacy-receipt-committed", client, input);

381 return Ack;

382 }

383 

384 private static async Task<Acknowledgment> Fixed(NpgsqlConnection client, Incident input, Func<string, Task>? hook = null)

385 {

386 hook ??= _ => Task.CompletedTask;

387 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)

388 {

389 Trace("legacy-retry-held-no-ack", client, input);

390 throw new InvalidOperationException("legacy-retry-held");

391 }

392 await hook("beforeClaim");

393 await using NpgsqlTransaction transaction = await client.BeginTransactionAsync(IsolationLevel.ReadCommitted);

394 bool committed = false;

395 try

396 {

397 object? claimed = await Scalar(client, """

398 INSERT INTO event_receipts(provider,account_id,event_id,payload_fingerprint)

399 VALUES ($1,$2,$3,$4) ON CONFLICT (provider,account_id,event_id)

400 DO NOTHING RETURNING event_id

401 """, Values(input), transaction);

402 Trace("receipt-claim-result", client, input, new { inserted = claimed is not null });

403 if (claimed is not null)

404 {

405 await hook("afterClaim");

406 await WriteOrder(client, input, transaction);

407 await hook("afterOrder");

408 }

409 else

410 {

411 // A new READ COMMITTED statement sees the committed winner.

412 await CheckReceipt(client, input, transaction);

413 }

414 await transaction.CommitAsync();

415 committed = true;

416 Trace("transaction-committed", client, input);

417 await hook("afterCommit");

418 Trace("acknowledged", client, input, Ack);

419 return Ack;

420 }

421 catch (Exception failure)

422 {

423 if (!committed)

424 {

425 try { await transaction.RollbackAsync(); }

426 catch (Exception rollbackFailure)

427 { throw new AggregateException("Transaction failed and rollback could not be confirmed", failure, rollbackFailure); }

428 Trace("transaction-rolled-back-no-ack", client, input);

429 }

430 else Trace("committed-response-lost-no-ack", client, input);

431 throw;

432 }

433 }

434 

435 // Run with ingestion paused and legacy consumers drained. This durable hold

436 // models an operator-controlled quarantine, not a production migration.

437 private static async Task<int> HoldOrphans(NpgsqlConnection client)

438 {

439 int held = await Execute(client, """

440 INSERT INTO delivery_holds(provider,account_id,event_id)

441 SELECT DISTINCT o.provider,o.account_id,o.event_id FROM orders o

442 WHERE NOT EXISTS (SELECT 1 FROM event_receipts r

443 WHERE r.provider=o.provider AND r.account_id=o.account_id AND r.event_id=o.event_id)

444 ON CONFLICT DO NOTHING

445 """);

446 Console.WriteLine(JsonSerializer.Serialize(new { action = "pre-resume-orphans-held", keys = held }));

447 return held;

448 }

449 private static async Task Reconcile(NpgsqlConnection client, Incident input)

450 {

451 await using NpgsqlTransaction transaction = await client.BeginTransactionAsync(IsolationLevel.ReadCommitted);

452 try

453 {

454 Require(await Scalar(client, "SELECT 1 FROM delivery_holds WHERE provider=$1 AND account_id=$2 AND event_id=$3 FOR UPDATE",

455 Key(input), transaction) is not null, "reconciliation-requires-hold");

456 List<string?> fingerprints = [];

457 await using (NpgsqlCommand command = Command(client,

458 "SELECT payload_fingerprint FROM orders WHERE provider=$1 AND account_id=$2 AND event_id=$3 FOR UPDATE", Key(input), transaction))

459 await using (NpgsqlDataReader reader = await command.ExecuteReaderAsync())

460 while (await reader.ReadAsync()) fingerprints.Add(reader.IsDBNull(0) ? null : reader.GetString(0));

461 Require(fingerprints.Count == 1 && fingerprints[0] == Fingerprint(input), "legacy-evidence-insufficient-keep-held");

462 await Execute(client, """

463 INSERT INTO event_receipts(provider,account_id,event_id,payload_fingerprint) VALUES ($1,$2,$3,$4)

464 ON CONFLICT DO NOTHING

465 """, Values(input), transaction);

466 await CheckReceipt(client, input, transaction);

467 await Execute(client, "DELETE FROM delivery_holds WHERE provider=$1 AND account_id=$2 AND event_id=$3", Key(input), transaction);

468 await transaction.CommitAsync();

469 Trace("trusted-orphan-reconciled-hold-released", client, input);

470 }

471 catch (Exception failure)

472 {

473 try { await transaction.RollbackAsync(); }

474 catch (Exception rollbackFailure)

475 { throw new AggregateException("Reconciliation failed and rollback could not be confirmed", failure, rollbackFailure); }

476 throw;

477 }

478 }

479 private static async Task Counts(NpgsqlConnection observer, int orders, int receipts, Incident input)

480 {

481 await using NpgsqlCommand command = Command(observer, """

482 SELECT (SELECT count(*)::integer FROM orders WHERE provider=$1 AND account_id=$2 AND event_id=$3),

483 (SELECT count(*)::integer FROM event_receipts WHERE provider=$1 AND account_id=$2 AND event_id=$3)

484 """, Key(input));

485 await using NpgsqlDataReader reader = await command.ExecuteReaderAsync();

486 Require(await reader.ReadAsync(), "Missing committed-state counts");

487 int actualOrders = reader.GetInt32(0), actualReceipts = reader.GetInt32(1);

488 Trace("committed-state", observer, input, new { orders = actualOrders, receipts = actualReceipts });

489 Require(actualOrders == orders && actualReceipts == receipts,

490 $"Expected {orders} order(s)/{receipts} receipt(s); got {actualOrders}/{actualReceipts}");

491 }

492 private static void Acknowledged(Acknowledgment value) => Require(

493 JsonSerializer.Serialize(value) == "{\"status\":200,\"body\":{\"received\":true}}", "Exact delivery acknowledgment");

494 

495 internal static async Task RunModeAsync(string mode)

496 {

497 if (mode is not ("baseline" or "regression" or "fixed")) throw new ArgumentException("Expected baseline, regression, or fixed", nameof(mode));

498 Incident original = LoadInput();

499 string password = Environment.GetEnvironmentVariable("CODEX_INCIDENT_DB_PASSWORD")

500 ?? throw new InvalidOperationException("Set CODEX_INCIDENT_DB_PASSWORD to the disposable fixture password");

501 NpgsqlConnectionStringBuilder configuration = new()

502 {

503 Host = "127.0.0.1",

504 Port = 55432,

505 Username = "codex_incident_test",

506 Database = "codex_incident_test",

507 Password = password,

508 Timeout = 5,

509 CommandTimeout = 8,

510 Pooling = false,

511 ApplicationName = "csharp-incident-rehearsal"

512 };

513 await using NpgsqlConnection observer = new(configuration.ConnectionString);

514 await observer.OpenAsync();

515 // Verify all fixture identity evidence before creating or changing any DB object.

516 await using (NpgsqlCommand identity = Command(observer, """

517 SELECT current_database(),current_user,shobj_description(oid,'pg_database'),current_setting('server_version')

518 FROM pg_database WHERE datname=current_database()

519 """))

520 await using (NpgsqlDataReader reader = await identity.ExecuteReaderAsync())

521 {

522 Require(await reader.ReadAsync() && reader.GetString(0) == "codex_incident_test" &&

523 reader.GetString(1) == "codex_incident_test" && !reader.IsDBNull(2) &&

524 reader.GetString(2) == "codex-synthetic-incident-fixture-v1" &&

525 reader.GetString(3) == "17.6 (Debian 17.6-2.pgdg12+1)", "Refusing an unmarked or unexpected database fixture");

526 Console.WriteLine(JsonSerializer.Serialize(new

527 {

528 action = "fixture-environment",

529 mode,

530 runtime = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription,

531 pg = reader.GetString(3)

532 }));

533 }

534 string schema = "incident_rehearsal_" + Guid.NewGuid().ToString("N");

535 // The generated identifier is hex only; external input never enters this SQL.

536 await Execute(observer, $"CREATE SCHEMA {schema}");

537 List<NpgsqlConnection> clients = [];

538 int tests = 0, failures = 0;

539 try

540 {

541 await Execute(observer, $"SET search_path TO {schema},public");

542 await Execute(observer, """

543 CREATE TABLE event_receipts (

544 provider text NOT NULL, account_id text NOT NULL, event_id text NOT NULL,

545 payload_fingerprint text NOT NULL,

546 CONSTRAINT event_receipts_identity UNIQUE(provider,account_id,event_id) NOT DEFERRABLE);

547 CREATE TABLE orders (id bigserial PRIMARY KEY, provider text NOT NULL,

548 account_id text NOT NULL, event_id text NOT NULL, payload_fingerprint text);

549 CREATE TABLE delivery_holds (provider text NOT NULL, account_id text NOT NULL,

550 event_id text NOT NULL, PRIMARY KEY(provider,account_id,event_id));

551 """);

552 Require(await Scalar(observer, """

553 SELECT NOT condeferrable FROM pg_constraint

554 WHERE conname='event_receipts_identity' AND conrelid='event_receipts'::regclass

555 """) is true, "Receipt uniqueness must be nondeferrable");

556 async Task<NpgsqlConnection> Connect()

557 {

558 NpgsqlConnection client = new(configuration.ConnectionString);

559 clients.Add(client);

560 await client.OpenAsync();

561 await Execute(client, $"SET search_path TO {schema},public");

562 await Execute(client, "SET statement_timeout = '8s'");

563 return client;

564 }

565 async Task Case(string name, Func<NpgsqlConnection, Task> test)

566 {

567 tests++;

568 try

569 {

570 await Execute(observer, "TRUNCATE orders,event_receipts,delivery_holds RESTART IDENTITY");

571 NpgsqlConnection client = await Connect();

572 try { await test(client); }

573 finally { await client.DisposeAsync(); clients.Remove(client); }

574 Console.WriteLine($"ok {tests} - {name}");

575 }

576 catch (Exception error)

577 {

578 failures++;

579 Console.WriteLine($"not ok {tests} - {name}");

580 Console.WriteLine("# " + error.ToString().Replace("\r", "").Replace("\n", "\n# "));

581 }

582 }

583 await Case("retry after the order boundary leaves exactly one order and one receipt", async client =>

584 {

585 async Task<Acknowledgment> Handle(Func<string, Task>? hook = null) => mode == "baseline"

586 ? await Baseline(client, original, hook) : await Fixed(client, original, hook);

587 await Reject(async () => { await Handle(FailAt("afterOrder")); }, "injected:afterOrder");

588 await Counts(observer, mode == "baseline" ? 1 : 0, 0, original);

589 Acknowledged(await Handle());

590 await Counts(observer, 1, 1, original);

591 });

592 if (mode == "fixed")

593 {

594 await Case("first delivery and committed duplicate return the exact acknowledgment", async client =>

595 {

596 Acknowledged(await Fixed(client, original));

597 Acknowledged(await Fixed(client, original));

598 await Counts(observer, 1, 1, original);

599 });

600 foreach (string boundary in new[] { "beforeClaim", "afterClaim", "afterOrder" })

601 await Case("failure " + boundary + " rolls back and remains retryable", async client =>

602 {

603 await Reject(async () => { await Fixed(client, original, FailAt(boundary)); }, "injected:" + boundary);

604 await Counts(observer, 0, 0, original);

605 Acknowledged(await Fixed(client, original));

606 await Counts(observer, 1, 1, original);

607 });

608 await Case("lost acknowledgment after commit does not duplicate the order", async client =>

609 {

610 await Reject(async () => { await Fixed(client, original, FailAt("afterCommit")); }, "injected:afterCommit");

611 await Counts(observer, 1, 1, original);

612 Acknowledged(await Fixed(client, original));

613 await Counts(observer, 1, 1, original);

614 });

615 foreach (bool rollback in new[] { false, true })

616 await Case("real overlapping duplicate contention: winner " + (rollback ? "rollback" : "commit"), async winner =>

617 {

618 NpgsqlConnection waiter = await Connect();

619 try

620 {

621 Require(winner.ProcessID != waiter.ProcessID, "Contention requires independent backends");

622 TaskCompletionSource claimed = new(TaskCreationOptions.RunContinuationsAsynchronously);

623 TaskCompletionSource release = new(TaskCreationOptions.RunContinuationsAsynchronously);

624 Task<Acknowledgment> winnerTask = Fixed(winner, original, async boundary =>

625 {

626 if (boundary != "afterClaim") return;

627 claimed.TrySetResult();

628 await release.Task.WaitAsync(TimeSpan.FromSeconds(7));

629 if (rollback) throw new InvalidOperationException("injected:winner-rollback");

630 });

631 Task<Acknowledgment>? waiterTask = null;

632 try

633 {

634 await Task.WhenAny(claimed.Task, winnerTask).WaitAsync(TimeSpan.FromSeconds(5));

635 if (!claimed.Task.IsCompleted) { await winnerTask; throw new InvalidOperationException("Winner did not claim receipt"); }

636 await Counts(observer, 0, 0, original);

637 waiterTask = Fixed(waiter, original);

638 await WaitForContention(observer, waiter, winner, original);

639 }

640 finally

641 {

642 release.TrySetResult();

643 // Observe both outcomes even when the first assertion fails.

644 await Task.WhenAll(

645 ObserveWinner(winnerTask, rollback),

646 waiterTask is null ? Task.CompletedTask : ObserveWaiter(waiterTask));

647 }

648 await Counts(observer, 1, 1, original);

649 }

650 finally { await waiter.DisposeAsync(); clients.Remove(waiter); }

651 });

652 await Case("event, account, and provider identity; conflicting payload rejected", async client =>

653 {

654 foreach (Incident input in new[] { original, original with { eventId = "evt_demo_043" },

655 original with { accountId = "acct_demo_02" }, original with { provider = "synthetic-other" } })

656 {

657 Acknowledged(await Fixed(client, input));

658 await Counts(observer, 1, 1, input);

659 }

660 await Reject(async () => { await Fixed(client, original with { payload = original.payload with { amountCents = 9999 } }); }, "payload-conflict");

661 await Counts(observer, 1, 1, original);

662 });

663 await Case("legacy orphan held before retry and reconciled only from trusted evidence", async client =>

664 {

665 await WriteOrder(client, original);

666 await Counts(observer, 1, 0, original);

667 Require(await HoldOrphans(client) == 1, "Hold the orphan before resuming ingestion");

668 await Reject(async () => { await Fixed(client, original); }, "legacy-retry-held");

669 await Reject(

670 () => Reconcile(client, original with

671 {

672 payload = original.payload with { amountCents = 9999 },

673 }),

674 "legacy-evidence-insufficient-keep-held");

675 await Reject(async () => { await Fixed(client, original); }, "legacy-retry-held");

676 await Reconcile(client, original);

677 Acknowledged(await Fixed(client, original));

678 await Counts(observer, 1, 1, original);

679 });

680 await Case("missing legacy payload evidence stays quarantined", async client =>

681 {

682 await Execute(client, "INSERT INTO orders(provider,account_id,event_id) VALUES ($1,$2,$3)", Key(original));

683 Require(await HoldOrphans(client) == 1, "Hold missing-evidence orphan");

684 await Reject(() => Reconcile(client, original), "legacy-evidence-insufficient-keep-held");

685 await Reject(async () => { await Fixed(client, original); }, "legacy-retry-held");

686 await Counts(observer, 1, 0, original);

687 });

688 }

689 Require(tests == (mode == "fixed" ? 11 : 1), "All native incident scenarios must execute");

690 Console.WriteLine($"1..{tests}\n# tests {tests}\n# pass {tests - failures}\n# fail {failures}\n# cancelled 0\n# skipped 0\n# todo 0");

691 }

692 finally

693 {

694 try

695 {

696 foreach (NpgsqlConnection client in clients) await client.DisposeAsync();

697 }

698 finally { await Execute(observer, $"DROP SCHEMA {schema} CASCADE"); }

699 }

700 if (failures != 0) throw new InvalidOperationException($"{failures} native incident regression(s) failed");

701 }

702 

703 private static async Task ObserveWinner(Task<Acknowledgment> task, bool rollback)

704 {

705 if (rollback) await Reject(async () => { await task; }, "injected:winner-rollback");

706 else Acknowledged(await task);

707 }

708 private static async Task ObserveWaiter(Task<Acknowledgment> task) => Acknowledged(await task);

709 private static async Task WaitForContention(NpgsqlConnection observer, NpgsqlConnection waiter, NpgsqlConnection winner, Incident input)

710 {

711 Stopwatch elapsed = Stopwatch.StartNew();

712 while (elapsed.Elapsed < TimeSpan.FromSeconds(5))

713 {

714 await using (NpgsqlCommand command = Command(observer, """

715 SELECT wait_event_type,wait_event,pg_blocking_pids(pid)

716 FROM pg_stat_activity WHERE pid=$1

717 """, [waiter.ProcessID]))

718 await using (NpgsqlDataReader reader = await command.ExecuteReaderAsync())

719 {

720 if (await reader.ReadAsync() && !reader.IsDBNull(0) && reader.GetString(0) == "Lock")

721 {

722 int[] blockers = reader.GetFieldValue<int[]>(2);

723 if (blockers.Contains(winner.ProcessID))

724 {

725 Trace("real-database-contention", waiter, input, new

726 { winner = winner.ProcessID, wait_event_type = reader.GetString(0), wait_event = reader.GetString(1), blockers });

727 return;

728 }

729 }

730 }

731 await Task.Delay(10);

732 }

733 throw new InvalidOperationException("competitor-never-observed-blocking-on-winner");

734 }

735}

736```

737 

252```ruby738```ruby

253def self.fixed(client, input, hook = ->(_boundary) {})739def self.fixed(client, input, hook = ->(_boundary) {})

254 assert_not_held(client, input)740 assert_not_held(client, input)