# 整合測試時過時不過，先查是不是和 worker 共用資料庫

> 錢路徑整合測試會受共用資料庫與時間條件干擾，重送也可能先被重放保護擋下。用 PostgreSQL 16.15 與 Go 1.27.4 重現三個案例，說明如何隔離與驗證。

原文：https://sheng.page/posts/integration-tests-shared-db-and-clock/ · 發布：2026-11-29 · 更新：2026-11-30 · 作者：Sheng

2026-09 替一個交易平台專案補錢路徑的整合測試，連真的 PostgreSQL，合作方用 httptest 模擬。測試時好時壞，查到共用資料庫的 compose worker 會先領走 outbox 的列，所以改讓測試用自己的資料庫。

stuck 掃描要找 30 分鐘沒動的列，測試不必真的等 30 分鐘，當時把資料時間往回改，這是權宜做法。e2e 同秒重送時沿用同一個簽章，被重放保護擋下，改用不同 timestamp 重簽後才進得了 idempotency 層。以下用簡化範例在 Mac 的 OrbStack 重現，PostgreSQL 16.15，Go 1.27.4。

Google Testing Blog 在 2016 年記錄過類似問題：當時 Google 內部約 1.5% 的測試執行結果是 flaky，將近 16% 的測試有某種程度的 flakiness。

## 測試和 worker 共用資料庫

範例 worker 每輪嘗試從 outbox 領一筆 pending，間隔 100 ms 再試，用的是 queue 常見的寫法：

```sql
-- worker.sql
UPDATE outbox SET status = 'sent', updated_at = now()
WHERE id = (SELECT id FROM outbox WHERE status = 'pending'
            ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1);
```

測試寫一筆 pending，等 0.3 秒，再用同一段 SQL 自己領，預期領到這筆：

```sql
-- test.sql
INSERT INTO outbox (order_id) VALUES ('o1');
\o /dev/null
SELECT pg_sleep(0.3);
\o
UPDATE outbox SET status = 'sent', updated_at = now()
WHERE id = (SELECT id FROM outbox WHERE status = 'pending'
            ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1)
RETURNING 'test claimed ' || order_id AS result;
SELECT order_id, status FROM outbox;
```

同一份測試，一次對 worker 正在讀的 app，一次對只給測試用的 app_test：

```text
== test against the shared database (app)
 result 
--------
(0 rows)

 order_id | status 
----------+--------
 o1       | sent
(1 row)

== test against its own database (app_test)
     result      
-----------------
 test claimed o1
(1 row)

 order_id | status 
----------+--------
 o1       | sent
(1 row)
```

共用的那一邊，測試什麼都沒領到，斷言失敗時看起來像程式沒把資料寫進去。範例的 worker 只改狀態，實際專案的 worker 還會呼叫合作方的 callback，測試看到的帳因此混了兩個行程的結果，更難查出原因。

`SKIP LOCKED` 讓 consumer 跳過別人鎖住的列，無法替測試保留資料。PostgreSQL 文件說它會得到不一致的資料視圖，不適合一般查詢，適合多個 consumer 取用同一張 queue-like table。這裡測試與 worker 都在領 pending 的列，結果就看誰先領到。

專案裡整合測試改用自建的 `rgs_test` 資料庫，由 `PG_TEST_DSN` 指定，compose 的 worker 不連這個資料庫，測試也就不用跟它搶資料。Martin Fowler 談測試的非決定性時，強調已知的初始狀態與測試隔離；隔開 worker 之後，仍要避免測試彼此干擾。

## stuck 掃描的 30 分鐘門檻

worker 另有一個掃描，找停在 in_flight 超過 30 分鐘的列。測試要驗它，直覺是等，或者靠測試主機的時間算出 30 分鐘前，再寫進資料庫。第二種在專案裡不可靠，測試主機和資料庫容器的時鐘不一定一致，條件又用資料庫的 `now()` 算。

在同一筆交易裡等待，`now()` 仍是交易開始的時間，不會跟著前進：

```sql
-- clock.sql
TRUNCATE outbox;
INSERT INTO outbox (order_id, status) VALUES ('o2', 'in_flight');

-- (a) waiting inside one transaction: now() does not move.
BEGIN;
\o /dev/null
SELECT pg_sleep(2);
\o
SELECT now() - updated_at < interval '1 second' AS now_age_under_1s,
       clock_timestamp() - updated_at >= interval '2 seconds' AS clock_age_2s
FROM outbox;
COMMIT;

-- (b) moving the data back instead of waiting.
UPDATE outbox SET updated_at = updated_at - interval '31 minutes';
SELECT order_id AS stuck FROM outbox
WHERE status = 'in_flight' AND updated_at < now() - interval '30 minutes';
```

```text
 now_age_under_1s | clock_age_2s 
------------------+--------------
 t                | t
(1 row)

 stuck 
-------
 o2
(1 row)
```

這次睡了 2 秒，用 `now()` 算出的時間差仍不到 1 秒，`clock_timestamp()` 則取呼叫當下的時間。測試若包在同一筆交易裡、最後 rollback，得預先寫入夠舊的時間才會符合條件，等待不會讓 `now()` 前進。

專案照（b）做，用 UPDATE 把資料時間往回調，範例調了 31 分鐘，越過掃描門檻，掃描條件仍用資料庫的 `now()`。這是權宜做法，繞過了正常寫入路徑，即使那條路徑改壞，測試也可能照過。

Go 1.25 起 `testing/synctest` 正式可用，bubble 裡的 `time` 套件改用假時鐘，所有 goroutine 都處於 durably blocked 時，假時間才可能前進，等待網路 I/O 不算。它只能控制 Go 這一側的時間；掃描條件若用資料庫的 `now()`，測試仍要透過資料或參數設定時間。

## 同一秒重送，重放保護先擋下

e2e 有一步重送同一筆 credit，預期由 idempotency 層回傳第一次的結果，卻有時拿到 DUPLICATE_REQUEST。

合作方 API 用 HMAC 簽章，timestamp 精度到秒，nonce 的 key 是 `nonce:<api_key>:<path>:<signature>`。同一憑證的請求若落在同一秒，method、path 與 body 也相同，signature 就相同，第二次會算成重放：

```go
key := "nonce:" + apiKey + ":" + path + ":" + sig
v.mu.Lock()
defer v.mu.Unlock()
if v.seen[key] {
	return "DUPLICATE_REQUEST"
}
v.seen[key] = true
return "OK (passed to idempotency layer)"
```

```text
first request            ts=1793980800 path=/wallet/credit -> OK (passed to idempotency layer)
retry, same second       ts=1793980800 path=/wallet/credit -> DUPLICATE_REQUEST
retry, next second       ts=1793980801 path=/wallet/credit -> OK (passed to idempotency layer)
same second, other path  ts=1793980800 path=/wallet/refund -> OK (passed to idempotency layer)
```

最後一行換了 path，key 與簽章都跟著不同，因此通過。沿用同一個簽章會先被重放保護擋下，進不了 idempotency 層，所以 e2e 要驗 idempotency，就得隔一秒再重簽，或用有效期內的另一個 timestamp 重簽，業務上的 idempotency key 保持不變。範例只做重放檢查，沒有 idempotency 層，也沒檢查 timestamp 有效期。簽哪些欄位寫在〈[HMAC 請求簽章該簽哪些東西：method、path、query 與 body 的原始 bytes](/posts/what-to-sign-in-hmac-requests/)〉。

## 補充筆記

- 測試和背景 worker 對同一個 outbox 使用 `FOR UPDATE SKIP LOCKED`，會競爭 pending 的列；專案改用 `PG_TEST_DSN` 指向的獨立資料庫。
- `now()` 是交易開始的時間，交易裡等多久都不會變；stuck 掃描範例把資料時間往回調 31 分鐘，這是繞過正常寫入路徑的權宜做法。
- `testing/synctest` 只改 Go 側的時鐘，管不到資料庫的 `now()`。
- 同一憑證與簽章的重送，nonce 檢查會擋下；e2e 要用有效期內的不同 timestamp 重簽，並保留業務上的 idempotency key，才測得到 idempotency 層。

## 延伸閱讀

- PostgreSQL〈[SELECT: The Locking Clause](https://www.postgresql.org/docs/16/sql-select.html#SQL-FOR-UPDATE-SHARE)〉：官方文件，`SKIP LOCKED` 會得到不一致的資料視圖，適合 queue-like table。
- PostgreSQL〈[Date/Time Functions: Current Date/Time](https://www.postgresql.org/docs/16/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT)〉：官方文件，`now()`、`statement_timestamp()` 與 `clock_timestamp()` 的差別。
- Go Blog〈[Testing Time (and other asynchronicities)](https://go.dev/blog/testing-time)〉：官方部落格，`testing/synctest` 在 Go 1.25 正式提供與假時鐘的行為。
- Martin Fowler〈[Eradicating Non-Determinism in Tests](https://martinfowler.com/articles/nonDeterminism.html)〉：2011 年的業界文章，隔離、非同步與時間造成的不穩定測試。
- Google Testing Blog〈[Flaky Tests at Google and How We Mitigate Them](https://testing.googleblog.com/2016/05/flaky-tests-at-google-and-how-we.html)〉：2016 年 Google 內部 flaky test 的比例與原因。
- Wikipedia〈[Test fixture](https://en.wikipedia.org/wiki/Test_fixture)〉：百科條目，讓測試從已知狀態開始。
- Wikipedia〈[Replay attack](https://en.wikipedia.org/wiki/Replay_attack)〉：百科條目，nonce 與 timestamp 防重放的做法與取捨。

> 想法與技術判斷出自 Sheng，和 Claude 一起起草 · 範例在 Mac 上 OrbStack 容器實測（PostgreSQL 16.15、Go 1.27.4）。