Skip to content

feat(jobstore): Postgres doc store reaches Store-protocol parity with Firestore lock semantics (A3 step 1) - #24221

Merged
Git-on-my-level merged 3 commits into
mainfrom
lane/archmission
Nov 1, 2026
Merged

Git-on-my-level merged 3 commits into
mainfrom
lane/archmission

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Nov 1, 2026 •

Copy link
Copy Markdown
Member

Summary

Plan A3 step 1 (backend target architecture, Postgres job store). The doc-mode PostgresStore now serves the whole batch Store/Transaction surface the scheduler, merge and capacity code call, with Firestore's server-side transaction semantics instead of SERIALIZABLE.

Why. Two gaps made Postgres unusable as a batch job-state authority, independent of any rewrite:

  1. Protocol drift. Merge and capacity grew reads that only Firestore serves: first_ready_pending, fresh_pending, held_merge_owners, longest_ready_pending, projection_successor, ready_for_capacity, and projection_page(states=…). A Postgres primary would have failed on first use. The A2 shadow never noticed, because its reads go to Firestore.
  2. Contention collapse. Under SERIALIZABLE, page-granular predicate locks produced false conflicts between unrelated owners. Exhausted retries raised an untyped RuntimeError, so the scheduler did not back off, and each failure stranded the shard's pull claim for its 30 s TTL.

Measured with the real Scheduler on local Postgres 16 and synthetic owners (2,000 jobs, 200 owners). The bench is now backend/testing/jobstore_contention.py:

Load main (SERIALIZABLE) this PR
4 replicas × 2 threads, shard spread on (prod default) 3.6–6.5 jobs/s; 93% of pulls empty with 1,567 jobs still ready; 49 exhausted transactions 123.7 jobs/s; all 2,000 leased; 0 errors
4×2, spread off 33.9 jobs/s; 821 exhausted 180.2 jobs/s; 0 errors
4×2 + 4 concurrent admitters not run 104–117 jobs/s; 0 errors
12×2 + 4 admitters, 4,000 jobs (prod worker count) not run 70 jobs/s (laptop CPU-bound); 0 errors

Every run had zero double leases. For comparison, prod batch at 5% leases about 1.4 jobs/s on average, so 100% would be about 28/s.

What changed

  • Locking. PostgresTransaction runs at READ COMMITTED with per-document locks held to commit:

    • get takes FOR UPDATE on an existing row, which also returns the newest committed version;
    • a document read as missing takes its key's advisory lock, the same name DualStore's mirror already locks;
    • blind writes take the lock before writing;
    • transactional queries lock the rows they return and restart the body if a row changed in between.

    Per-owner queries stay phantom-safe through the owner-document fence that admission and merge already take (scheduler.py enqueue, merge.py commit).

  • Retry. Deadlocks, a 2 s lock timeout and restarts retry with jitter. Exhaustion raises JobStoreContentionExhausted, a subclass of FirestoreContentionExhausted, so Scheduler.pull backs off exactly as it does on Firestore.

  • Missing reads. Implemented on Postgres and the simulator, and PgSimStore delegates them. Migration 0004 adds expand-only indexes for the successor hint and for every drain state.

  • Byte-order tie-breaks (Luna r1 P1). Every key ORDER BY and keyset cursor comparison uses COLLATE "C", so ties order like Firestore's bytewise names on a locale-collated Cloud SQL database. Migration 0005 adds C-collated twins of the ordering indexes (0004 is unchanged since first push); the default-collation originals drop one train later as a contract.

  • Guard. tests/unit/test_jobstore_protocol_parity.py fails, in the unit shards with no database, when any backend lacks a FirestoreStore/FirestoreTransaction method or its parameter list.

This overlaps #23841, an external PR adding ready_for_capacity and the oldest hold-skip to the Postgres store and the simulator. This PR covers that scope, with the same semantics, and qualifies it on a real Postgres. If #23841 merges first, this rebases trivially.

Lane / contract

archmission (Plan A owner, card postgres-job-store-a3-onward-has-no). Store/Transaction protocol unchanged; Firestore code path untouched. Owner sign-offs: none needed (job-store and simulator files only).

Product invariants affected

none

Verification

  • Unit shard. backend/test.sh with BACKEND_UNIT_TEST_FILE_LIST covering parity guard, locking, backfill, codec, dual store, migrations, projection mirror, shadow seams, lock pin and metrics: 175 passed. Layer: code.

  • Store conformance. test_store_conformance.py with OMI_REQUIRE_STORE_BACKENDS=all on sim, a loopback Firestore emulator and local Postgres 16 (glibc, en_US.utf8): 120 passed, 3 skipped (plus migration unit tests: 127 with them). The skips are the simulator's single-thread design skips. There are 12 new cases: every new read, byte-order tie-breaks, a create-if-absent race and four concurrent schedulers. Negative control: the byte-order case fails against unchanged main's Postgres leg ('a' instead of 'B'). Layer: code against real Firestore emulator semantics and real Postgres.

  • Pre-existing reds on unchanged origin/main 814dd41. These are identical with and without this PR, and none are caused by it:

    • test_dual_store_postgres.py: 3 goldens (deleted_merged_targets, privacy_fence_midflight, role_policy), owners projection_watermark read mismatch;
    • test_outbox_conformance.py: 3 emulator cases, task create failed.

    CI runs neither Postgres leg; both are tracked separately.

  • Not run: gauntlet --store postgres, staging. No deploy or flag change.

Rollback

Revert the PR. Nothing serves from Postgres: BATCH_JOBSTORE_MODE keeps prod on Firestore (the prod namespace is refused in code), and the staging shadow mirror is unaffected. Migration 0004 only adds indexes.

Failure-Class: none

🤖 Generated with Claude Code

… Firestore lock semantics

Plan A3 step 1. The doc-mode PostgresStore had drifted behind FirestoreStore: merge and capacity
now call first_ready_pending, fresh_pending, held_merge_owners, longest_ready_pending,
projection_successor, ready_for_capacity and projection_page(states=...), none of which Postgres
served, so a Postgres primary would have failed on first use. It also ran every transaction
SERIALIZABLE. Under concurrent pullers, page-granular predicate locks produced false conflicts
between unrelated owners, exhausted retries with an untyped RuntimeError (no scheduler backoff) and
stranded the shard pull claim for its 30 s TTL. With the production default shard spread,
4 replicas x 2 threads leased 3.6-6.5 jobs/s and 93% of pulls came back empty while 1,567 of
2,000 jobs were still ready.

- Transactions now take Firestore's server-side semantics: READ COMMITTED with per-document locks
  held to commit (row FOR UPDATE, which returns the newest version; a missing key's advisory lock,
  the same name DualStore's mirror locks; blind writes lock first). Transactional queries lock the
  rows they return and restart if one changed. Per-owner queries stay phantom-safe through the
  owner-document fence that admission and merge already take.
- Deadlocks, lock timeouts (2 s) and restarts retry with jitter; exhaustion raises
  JobStoreContentionExhausted, a FirestoreContentionExhausted, so the scheduler backs off.
- The missing reads are implemented on Postgres and the simulator (ready_for_capacity,
  projection_successor, the allowance-hold walk in oldest, projection_page states), with migration
  0004 (expand-only indexes for the successor hint and every drain state).
- A unit guard fails when any backend lacks a FirestoreStore/FirestoreTransaction method or its
  parameters; conformance cases cover every new read on sim, emulator and Postgres, plus a
  create-if-absent race and four concurrent schedulers leasing every job exactly once.
- backend/testing/jobstore_contention.py reproduces the A3 contention gate.

Same bench after the change (local Postgres 16, synthetic owners): 4x2 with spread 123.7 jobs/s,
4x2 plus 4 admitters 104-117 jobs/s, 12x2 plus 4 admitters 70 jobs/s (laptop-bound), all with
zero errors, zero retries exhausted and zero double leases.

Postgres is still not authoritative anywhere: BATCH_JOBSTORE_MODE keeps prod on Firestore and the
staging shadow mirror is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

14 issues found across 8 files

Confidence score: 3/5

  • jobstore_contention.py can lose pull workers when completion fails without recording the error, and main() still exits successfully when the correctness checks fail. Count completion exceptions and return a nonzero status for failed checks.
  • The results_obligation index in 0004_merge_and_projection_hints.sql does not support projection_page ordering by committed_at, key, so each page may sort the full obligation backlog. Add an index that matches the query order.
  • test_jobstore_protocol_parity.py does not exercise the simulator’s _Recording adapter, which lacks first_ready_pending; simulator callers can still hit an AttributeError while this parity test passes. Include that adapter in the parity coverage.
  • postgres_store.py includes drain-state results with NULL committed_at in projection_page, unlike Firestore and the simulator. Filter out those rows to keep malformed or legacy results out of the ordered page.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/tests/unit/test_jobstore_protocol_parity.py">

<violation number="1" location="backend/tests/unit/test_jobstore_protocol_parity.py:35">
P2: This parity guard compares only parameter names, so a backend can pass while changing `ready_only` from keyword-only or making an optional argument required. Compare each parameter's kind and requiredness so signature drift fails this test.</violation>

<violation number="2" location="backend/tests/unit/test_jobstore_protocol_parity.py:47">
P2: The simulator's actual `_Recording` transaction adapter is not covered here and lacks `first_ready_pending`, so simulator callers can still fail with `AttributeError` despite this parity test passing. Include `_Recording` (or exercise the transaction object passed by `PgSimStore.run`) in the transaction-surface check.</violation>
</file>

<file name="backend/testing/jobstore_contention.py">

<violation number="1" location="backend/testing/jobstore_contention.py:66">
P3: Emulator runs leave seeded customer documents and pull-claim documents behind, so repeated benchmarks accumulate state outside the cleaned batch tables. Extend teardown to remove every resource this run creates.</violation>

<violation number="2" location="backend/testing/jobstore_contention.py:112">
P2: All pull threads in a replica share one `worker_id`, forcing them through the same shard-affinity order and distorting the R×T contention measurement. Give each pull thread a unique worker ID.</violation>

<violation number="3" location="backend/testing/jobstore_contention.py:119">
P2: A persistent `pull` exception makes this loop spin with no backoff, hammering the store and inflating the error count. Add a short `time.sleep` before the `continue` in the except branch.</violation>

<violation number="4" location="backend/testing/jobstore_contention.py:133">
P3: Overwriting `live[segment]` on a detected double lease drops the first holder's entry. Its `live.pop` then clears tracking while the second lease is still live, so later overlaps on that segment can go undetected. Keep a per-segment holder count or a set of tokens instead of a single value.</violation>

<violation number="5" location="backend/testing/jobstore_contention.py:135">
P2: Completion failures terminate the pull thread without being counted, so the benchmark can report a clean error set while silently losing workers and leases. Catch completion exceptions and record them before clearing the live lease.</violation>

<violation number="6" location="backend/testing/jobstore_contention.py:147">
P3: Wall-clock adjustments can change the benchmark duration and throughput. Use `time.monotonic()` for the deadline and elapsed measurement while keeping epoch time for scheduler timestamps.</violation>

<violation number="7" location="backend/testing/jobstore_contention.py:157">
P2: The benchmark tears down stores even when a daemon worker is still alive after the 30-second join timeout. Detect timed-out workers and prevent teardown from racing with them.</violation>

<violation number="8" location="backend/testing/jobstore_contention.py:193">
P2: The documented correctness gate is informational only because `main()` always exits zero. Return a nonzero status when jobs are missing, overlaps are detected, or errors were recorded.</violation>
</file>

<file name="backend/database/jobstore/migrations/0004_merge_and_projection_hints.sql">

<violation number="1" location="backend/database/jobstore/migrations/0004_merge_and_projection_hints.sql:3">
P2: Plain `CREATE INDEX` on the existing `results` table blocks all writes to it until the build finishes, and `migrate()` runs each file in one transaction, so `CONCURRENTLY` is not an option here. Build these two indexes outside the migration transaction with `CONCURRENTLY`, or document a write-blocking window before applying the migration to any non-empty database.</violation>

<violation number="2" location="backend/database/jobstore/migrations/0004_merge_and_projection_hints.sql:3">
P2: The `previous=None` successor query does not match this index expression, so root-link lookups scan every result for the owner instead of using the new successor hint. Add a partial index for the explicit JSON-null predicate or make both query branches use the indexed expression.</violation>

<violation number="3" location="backend/database/jobstore/migrations/0004_merge_and_projection_hints.sql:4">
P2: `results_obligation` puts `projection_state` before `committed_at`, so the multi-state `projection_page` query cannot read rows in `committed_at, key` order. Each page will sort the whole obligation backlog. Make it a partial index on `(namespace, committed_at, key)` over the four obligation states; that keeps the ordered scan and skips terminal rows.</violation>
</file>

<file name="backend/database/jobstore/postgres_store.py">

<violation number="1" location="backend/database/jobstore/postgres_store.py:421">
P2: `projection_page` includes drain-state results without `committed_at`, unlike Firestore and the simulator. Filter out NULL `committed_at` rows so malformed or legacy documents cannot enter the ordered page or produce an invalid cursor.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic



def _parameters(function) -> list[str]:
return [name for name in inspect.signature(function).parameters if name != 'self']

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This parity guard compares only parameter names, so a backend can pass while changing ready_only from keyword-only or making an optional argument required. Compare each parameter's kind and requiredness so signature drift fails this test.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_jobstore_protocol_parity.py, line 35:

<comment>This parity guard compares only parameter names, so a backend can pass while changing `ready_only` from keyword-only or making an optional argument required. Compare each parameter's kind and requiredness so signature drift fails this test.</comment>

<file context>
@@ -0,0 +1,51 @@
+
+
+def _parameters(function) -> list[str]:
+    return [name for name in inspect.signature(function).parameters if name != 'self']
+
+
</file context>
Suggested change
return [name for name in inspect.signature(function).parameters if name != 'self']
return [
(parameter.name, parameter.kind, parameter.default is inspect.Parameter.empty)
for parameter in inspect.signature(function).parameters.values()
if parameter.name != 'self'
]

assert _parameters(getattr(backend, method)) == _parameters(reference), method


@pytest.mark.parametrize('backend', [PostgresTransaction, SimTransaction], ids=lambda cls: cls.__name__)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The simulator's actual _Recording transaction adapter is not covered here and lacks first_ready_pending, so simulator callers can still fail with AttributeError despite this parity test passing. Include _Recording (or exercise the transaction object passed by PgSimStore.run) in the transaction-surface check.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_jobstore_protocol_parity.py, line 47:

<comment>The simulator's actual `_Recording` transaction adapter is not covered here and lacks `first_ready_pending`, so simulator callers can still fail with `AttributeError` despite this parity test passing. Include `_Recording` (or exercise the transaction object passed by `PgSimStore.run`) in the transaction-surface check.</comment>

<file context>
@@ -0,0 +1,51 @@
+        assert _parameters(getattr(backend, method)) == _parameters(reference), method
+
+
[email protected]('backend', [PostgresTransaction, SimTransaction], ids=lambda cls: cls.__name__)
[email protected]('method', [name for name in TRANSACTION_METHODS if name != 'flush'])
+def test_every_transaction_backend_serves_the_firestore_transaction_surface(backend, method):
</file context>

got = scheduler.pull(time.time(), 1)
except Exception as error: # noqa: BLE001
with lock:
errors[f'pull:{type(error).__name__}'] += 1

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: A persistent pull exception makes this loop spin with no backoff, hammering the store and inflating the error count. Add a short time.sleep before the continue in the except branch.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/testing/jobstore_contention.py, line 119:

<comment>A persistent `pull` exception makes this loop spin with no backoff, hammering the store and inflating the error count. Add a short `time.sleep` before the `continue` in the except branch.</comment>

<file context>
@@ -0,0 +1,197 @@
+                got = scheduler.pull(time.time(), 1)
+            except Exception as error:  # noqa: BLE001
+                with lock:
+                    errors[f'pull:{type(error).__name__}'] += 1
+                continue
+            with lock:
</file context>

-- Store-protocol parity (A3 step 1): the result-log successor hint and projection pages over any drain state,
-- including quarantine_held, which the 0001 partial index does not cover. Expand-only.
CREATE INDEX results_successor ON results (namespace, (doc->>'owner_key'), (doc->>'previous_segment_id'), key);
CREATE INDEX results_obligation ON results (namespace, projection_state, committed_at, key);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: results_obligation puts projection_state before committed_at, so the multi-state projection_page query cannot read rows in committed_at, key order. Each page will sort the whole obligation backlog. Make it a partial index on (namespace, committed_at, key) over the four obligation states; that keeps the ordered scan and skips terminal rows.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/database/jobstore/migrations/0004_merge_and_projection_hints.sql, line 4:

<comment>`results_obligation` puts `projection_state` before `committed_at`, so the multi-state `projection_page` query cannot read rows in `committed_at, key` order. Each page will sort the whole obligation backlog. Make it a partial index on `(namespace, committed_at, key)` over the four obligation states; that keeps the ordered scan and skips terminal rows.</comment>

<file context>
@@ -0,0 +1,4 @@
+-- Store-protocol parity (A3 step 1): the result-log successor hint and projection pages over any drain state,
+-- including quarantine_held, which the 0001 partial index does not cover. Expand-only.
+CREATE INDEX results_successor ON results (namespace, (doc->>'owner_key'), (doc->>'previous_segment_id'), key);
+CREATE INDEX results_obligation ON results (namespace, projection_state, committed_at, key);
</file context>
Suggested change
CREATE INDEX results_obligation ON results (namespace, projection_state, committed_at, key);
CREATE INDEX results_obligation ON results (namespace, committed_at, key)
WHERE projection_state IN ('pending', 'persisted', 'ready', 'quarantine_held');

@@ -0,0 +1,4 @@
-- Store-protocol parity (A3 step 1): the result-log successor hint and projection pages over any drain state,
-- including quarantine_held, which the 0001 partial index does not cover. Expand-only.
CREATE INDEX results_successor ON results (namespace, (doc->>'owner_key'), (doc->>'previous_segment_id'), key);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Plain CREATE INDEX on the existing results table blocks all writes to it until the build finishes, and migrate() runs each file in one transaction, so CONCURRENTLY is not an option here. Build these two indexes outside the migration transaction with CONCURRENTLY, or document a write-blocking window before applying the migration to any non-empty database.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/database/jobstore/migrations/0004_merge_and_projection_hints.sql, line 3:

<comment>Plain `CREATE INDEX` on the existing `results` table blocks all writes to it until the build finishes, and `migrate()` runs each file in one transaction, so `CONCURRENTLY` is not an option here. Build these two indexes outside the migration transaction with `CONCURRENTLY`, or document a write-blocking window before applying the migration to any non-empty database.</comment>

<file context>
@@ -0,0 +1,4 @@
+-- Store-protocol parity (A3 step 1): the result-log successor hint and projection pages over any drain state,
+-- including quarantine_held, which the 0001 partial index does not cover. Expand-only.
+CREATE INDEX results_successor ON results (namespace, (doc->>'owner_key'), (doc->>'previous_segment_id'), key);
+CREATE INDEX results_obligation ON results (namespace, projection_state, committed_at, key);
</file context>

Comment on lines +135 to +137
accepted = scheduler.complete(
WorkResult(segment, f'gs://synthetic/r/{segment}'), lease.token, time.time()
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Completion failures terminate the pull thread without being counted, so the benchmark can report a clean error set while silently losing workers and leases. Catch completion exceptions and record them before clearing the live lease.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/testing/jobstore_contention.py, line 135:

<comment>Completion failures terminate the pull thread without being counted, so the benchmark can report a clean error set while silently losing workers and leases. Catch completion exceptions and record them before clearing the live lease.</comment>

<file context>
@@ -0,0 +1,197 @@
+                        doubles.append(segment)
+                    live[segment] = lease.token
+                    leased[segment] += 1
+                accepted = scheduler.complete(
+                    WorkResult(segment, f'gs://synthetic/r/{segment}'), lease.token, time.time()
+                )
</file context>
Suggested change
accepted = scheduler.complete(
WorkResult(segment, f'gs://synthetic/r/{segment}'), lease.token, time.time()
)
try:
accepted = scheduler.complete(
WorkResult(segment, f'gs://synthetic/r/{segment}'), lease.token, time.time()
)
except Exception as error: # noqa: BLE001
with lock:
errors[f'complete:{type(error).__name__}'] += 1
accepted = False

break
stop.set()
for thread in threads:
thread.join(timeout=30)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The benchmark tears down stores even when a daemon worker is still alive after the 30-second join timeout. Detect timed-out workers and prevent teardown from racing with them.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/testing/jobstore_contention.py, line 157:

<comment>The benchmark tears down stores even when a daemon worker is still alive after the 30-second join timeout. Detect timed-out workers and prevent teardown from racing with them.</comment>

<file context>
@@ -0,0 +1,197 @@
+                break
+    stop.set()
+    for thread in threads:
+        thread.join(timeout=30)
+    elapsed = time.time() - started
+    try:
</file context>

with lock:
if segment in live:
doubles.append(segment)
live[segment] = lease.token

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: Overwriting live[segment] on a detected double lease drops the first holder's entry. Its live.pop then clears tracking while the second lease is still live, so later overlaps on that segment can go undetected. Keep a per-segment holder count or a set of tokens instead of a single value.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/testing/jobstore_contention.py, line 133:

<comment>Overwriting `live[segment]` on a detected double lease drops the first holder's entry. Its `live.pop` then clears tracking while the second lease is still live, so later overlaps on that segment can go undetected. Keep a per-segment holder count or a set of tokens instead of a single value.</comment>

<file context>
@@ -0,0 +1,197 @@
+                with lock:
+                    if segment in live:
+                        doubles.append(segment)
+                    live[segment] = lease.token
+                    leased[segment] += 1
+                accepted = scheduler.complete(
</file context>

rng = random.Random(args.seed)
items = []
for o in range(args.owners):
uid = harness.seed_user(f'u{o}')

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: Emulator runs leave seeded customer documents and pull-claim documents behind, so repeated benchmarks accumulate state outside the cleaned batch tables. Extend teardown to remove every resource this run creates.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/testing/jobstore_contention.py, line 66:

<comment>Emulator runs leave seeded customer documents and pull-claim documents behind, so repeated benchmarks accumulate state outside the cleaned batch tables. Extend teardown to remove every resource this run creates.</comment>

<file context>
@@ -0,0 +1,197 @@
+    rng = random.Random(args.seed)
+    items = []
+    for o in range(args.owners):
+        uid = harness.seed_user(f'u{o}')
+        for j in range(args.jobs):
+            segment = f's{o}-{j}'
</file context>

threading.Thread(target=pull, args=(r,), daemon=True) for r in range(args.replicas) for _ in range(args.threads)
]
threads += [threading.Thread(target=admit, args=(i,), daemon=True) for i in range(args.admitters)]
started = time.time()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: Wall-clock adjustments can change the benchmark duration and throughput. Use time.monotonic() for the deadline and elapsed measurement while keeping epoch time for scheduler timestamps.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/testing/jobstore_contention.py, line 147:

<comment>Wall-clock adjustments can change the benchmark duration and throughput. Use `time.monotonic()` for the deadline and elapsed measurement while keeping epoch time for scheduler timestamps.</comment>

<file context>
@@ -0,0 +1,197 @@
+        threading.Thread(target=pull, args=(r,), daemon=True) for r in range(args.replicas) for _ in range(args.threads)
+    ]
+    threads += [threading.Thread(target=admit, args=(i,), daemon=True) for i in range(args.admitters)]
+    started = time.time()
+    for thread in threads:
+        thread.start()
</file context>

Git-on-my-level and others added 2 commits November 1, 2026 14:08
Luna r1 P1 on #24221: every key tie-break and keyset comparison used the database's default
collation. Cloud SQL databases default to a locale collation (en_US.UTF8), which puts 'a' before 'B'
and 'ä' before 'z', while Firestore orders names bytewise. Same-capture_at jobs could then commit
out of Firestore's owner FIFO order, and projection pages could skip or repeat rows across a cursor.

All ORDER BY / cursor comparisons on key now use COLLATE "C". Migration 0004 adds C-collated twins
of the ordering indexes (expand-only; the 0001 originals drop one train later as a contract). A new
conformance case pins byte order for first_pending, due and the projection cursor; on a glibc
en_US.utf8 Postgres it fails against unchanged main ('a' instead of 'B') and passes here.

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s in 0005

Luna r2 P1 on #24221: the previous commit edited 0004 after it was pushed, and migrate() refuses a
database that applied the earlier checksum. 0004 is restored byte-for-byte to its first-pushed
content; the C-collated twins of the ordering indexes move to a new expand-only 0005. (The earlier
0004 was never applied outside a throwaway local database, but the migration contract is what holds.)

Failure-Class: none

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Git-on-my-level
Git-on-my-level merged commit 7d5b120 into main Nov 1, 2026
64 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/archmission branch November 1, 2026 10:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant