Skip to content

Order pending work by commit and snapshot timestamps - #220

Merged
ianmacartney merged 19 commits into
mainfrom
ian/use-commit-ts
Nov 18, 2026
Merged

ianmacartney merged 19 commits into
mainfrom
ian/use-commit-ts

Conversation

@ianmacartney

@ianmacartney ianmacartney commented Aug 4, 2026 •

Copy link
Copy Markdown
Member

Order ready work, completions, and cancellations by commit timestamp. A sweep finds scheduled enqueues that commit behind the incoming cursor, which stays bounded by the transaction snapshot.

Upgrade legacy keys and pointers before scanning, preserving their original time ordering. Requires Convex 1.43.

Validation: 162 tests pass; build, typecheck, lint, and changed-file formatting pass.

@ianmacartney
ianmacartney requested a review from reeceyang August 4, 2026 00:43

ianmacartney commented Aug 4, 2026 •

Copy link
Copy Markdown
Member Author

This stack of pull requests is managed by Graphite. Learn more about stacking.

@pkg-pr-new

pkg-pr-new Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/@convex-dev/workpool@220

commit: 3123bed

Copy link
Copy Markdown
Member Author

One thing to note here is that reverting to an older version would require a migration to convert segments into their old format, - which could be hard to get right, but could make some assumptions about the maximum segment a user would have previously used, or migrate based on creation time of the documents or something..?

@ianmacartney ianmacartney changed the title update convex use commitTS for workpool Aug 4, 2026

@reeceyang reeceyang left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

When users migrate to this version, would work that was originally scheduled to run in the future get executed immediately?

Comment thread src/component/loop.test.ts Resolved
Comment thread src/component/loop.test.ts Resolved
Comment thread src/component/loop.ts Resolved
@ianmacartney

Copy link
Copy Markdown
Member Author

@cubic review

@cubic-dev-ai

cubic-dev-ai Bot commented Sep 9, 2026

Copy link
Copy Markdown

@cubic review

@ianmacartney I have started the AI code review. It will take a few minutes to complete.

@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.

All reported issues were addressed across 26 files

Not reviewed (too large): example/benchmarks/2026-09-08.json (~5,865 lines) - if these are generated or fixture files, add them to ignored paths to exclude them from future reviews.

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

Re-trigger cubic

Comment thread src/component/loop.ts Resolved
Comment thread src/component/loop.test.ts Resolved
Comment thread src/component/stats.ts Resolved
Comment thread src/component/schema.ts Resolved
Comment thread src/component/danger.ts Resolved
Comment thread src/component/danger.ts Resolved
Comment thread example/convex/test/scheduling.ts Resolved
Comment thread src/component/loop.test.ts Resolved
Comment thread example/convex/test/cleanup.ts Resolved
Comment thread CHANGELOG.md Resolved

@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.

All reported issues were addressed across 17 files (changes from recent commits).

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

Re-trigger cubic

Comment thread src/component/README.md Resolved

Copy link
Copy Markdown
Member Author

I split out the pendingStart batching into a stacked PR

@ianmacartney ianmacartney changed the title use commitTS for workpool Order pending work by commit and snapshot timestamps Sep 9, 2026

@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.

All reported issues were addressed across 20 files

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

Re-trigger cubic

Comment thread src/component/stateMachine.test.ts Resolved
@ianmacartney
ianmacartney force-pushed the ian/use-commit-ts branch 2 times, most recently from 2ccceca to ba7eb18 Compare September 12, 2026 00:02
Comment thread src/component/lib.ts Resolved
Comment thread src/component/loop.ts Resolved
Comment thread src/component/loop.ts Outdated
Comment on lines +405 to +406
// (1) Out-of-order entries left at the boundary stamp. Nothing at or above
// the cursor is read, so a bulk enqueue sharing this stamp costs nothing.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

which cursor is meant in

Nothing at or above the cursor is read, so a bulk enqueue sharing this stamp costs nothing.

It looks like we do read at least one doc at or above the sweep cursor?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

We start at the sweepCursor for the scanTs field, but we only read up to incomingCursor for the segment, since anything greater than that will get picked up by the normal incomingCursor query.
So if sweep is at 3, incomingCursor is at 10, the queries are:

1. scanTs == sweepCursor && segment < incomingCursor
2. scanTs ≥ sweepCursor
3. segment ≥ incomingCursor

(1) is an optimization for the case where a huge transaction lands in a single scanTs. Instead of scanning over the whole transaction, once we land in the middle of it, the next iteration will only consider the section of it that is actually actionable, before moving on to the next scanTs.

Comment thread src/component/loop.ts Resolved
Comment thread src/component/loop.test.ts Outdated
// ────────────────────────────────────────────────────────────────────

describe("getBatch", () => {
it("waits for wall time when the snapshot clock is ahead", async () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

this scenario is not possible in practice, right?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

it was possible before, but I believe the Date.now() change should be out soon/already. And it can happen in convex-test pretty often, since Date.now() is fixed for tests, but each transaction bumps the db clock

expect(o.running.map((r) => r.workId)).toEqual([scheduledId]);
});

it("starts scheduled work once it's due, without ever rewriting it", async () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

we don't ever rewrite scheduled work now, right? (unless it's being upgraded from a legacy entry?)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

correct

@ianmacartney
ianmacartney changed the base branch from ian/pending-start-pointer to graphite-base/220 October 28, 2026 22:25
@cursor
cursor Bot changed the base branch from graphite-base/220 to main October 28, 2026 22:25
@ianmacartney
ianmacartney force-pushed the ian/use-commit-ts branch 2 times, most recently from fb5a6d9 to 68a0983 Compare October 28, 2026 22:29

@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.

3 issues found across 20 files

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="src/component/loop.ts">

<violation number="1" location="src/component/loop.ts:551">
P2: `handleCancelation` deletes a selected cancellation without rechecking that it still exists. Cleanup can remove it between `getBatch` and `run`, causing the mutation to throw and delaying the whole batch; restore the point-read guard.</violation>
</file>

<file name="src/component/lib.ts">

<violation number="1" location="src/component/lib.ts:225">
P3: This reports legacy jobs that were already running at deployment as `pending` for their entire remaining execution. Preserve the `internalState.running` check when `pendingStartId` is absent, returning `running` for active legacy work.</violation>
</file>

<file name="src/component/danger.ts">

<violation number="1" location="src/component/danger.ts:54">
P2: `clearOldWork` pings the batch worker once for every legacy work row, even though subsequent pings are no-ops while the loop runs. Kick once per cleanup batch to avoid redundant component calls and slow large legacy cleanups.</violation>
</file>

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

Re-trigger cubic

Comment thread src/component/loop.ts
const jobs: CompleteJob[] = [...toCancel];
await Promise.all(
canceled.map(async ({ pendingId, workId }) => {
await ctx.db.delete("pendingCancelation", pendingId);

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: handleCancelation deletes a selected cancellation without rechecking that it still exists. Cleanup can remove it between getBatch and run, causing the mutation to throw and delaying the whole batch; restore the point-read guard.

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 src/component/loop.ts, line 551:

<comment>`handleCancelation` deletes a selected cancellation without rechecking that it still exists. Cleanup can remove it between `getBatch` and `run`, causing the mutation to throw and delaying the whole batch; restore the point-read guard.</comment>

<file context>
@@ -453,43 +544,35 @@ async function handleCancelation(
+  const jobs: CompleteJob[] = [...toCancel];
+  await Promise.all(
+    canceled.map(async ({ pendingId, workId }) => {
+      await ctx.db.delete("pendingCancelation", pendingId);
+      if (canceledWork.has(workId)) {
+        console.error(`[main] ${workId} already canceled`);
</file context>
Suggested change
await ctx.db.delete("pendingCancelation", pendingId);
const pending = await ctx.db.get("pendingCancelation", pendingId);
if (!pending) return;
await ctx.db.delete("pendingCancelation", pendingId);

Comment thread src/component/danger.ts
.unique();
if (entry.pendingStartId === undefined) {
// The upgrade pass removes orphaned legacy queue entries.
await kickMainLoop(ctx, "kick");

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: clearOldWork pings the batch worker once for every legacy work row, even though subsequent pings are no-ops while the loop runs. Kick once per cleanup batch to avoid redundant component calls and slow large legacy cleanups.

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 src/component/danger.ts, line 54:

<comment>`clearOldWork` pings the batch worker once for every legacy work row, even though subsequent pings are no-ops while the loop runs. Kick once per cleanup batch to avoid redundant component calls and slow large legacy cleanups.</comment>

<file context>
@@ -60,20 +44,16 @@ export const clearOldWork = internalMutation({
-        .unique();
+      if (entry.pendingStartId === undefined) {
+        // The upgrade pass removes orphaned legacy queue entries.
+        await kickMainLoop(ctx, "kick");
+      }
+      const pendingStart = await findPendingStart(ctx, entry);
</file context>

Comment thread src/component/lib.ts
.withIndex("workId", (q) => q.eq("workId", id))
.unique();
if (pendingStart) {
if (work.pendingStartId === undefined) {

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: This reports legacy jobs that were already running at deployment as pending for their entire remaining execution. Preserve the internalState.running check when pendingStartId is absent, returning running for active legacy work.

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 src/component/lib.ts, line 225:

<comment>This reports legacy jobs that were already running at deployment as `pending` for their entire remaining execution. Preserve the `internalState.running` check when `pendingStartId` is absent, returning `running` for active legacy work.</comment>

<file context>
@@ -208,11 +222,13 @@ async function statusHandler(ctx: QueryCtx, { id }: { id: Id<"work"> }) {
-    .withIndex("workId", (q) => q.eq("workId", id))
-    .unique();
-  if (pendingStart) {
+  if (work.pendingStartId === undefined) {
+    // During migration, legacy work without a queue pointer reports pending,
+    // even if already running. This temporary approximation lasts until the
</file context>

@ianmacartney
ianmacartney merged commit a14eb53 into main Nov 18, 2026
4 checks passed
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.

2 participants