Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions API.md
Original file line number Diff line number Diff line change
Expand Up @@ -1137,18 +1137,22 @@ actual start and finish instants, status, sanitized error category and its
ordered jobs. Timestamps are Unix milliseconds. Repeated or concurrent
invocations of the same scheduled instant retain separate identities.

A job is `not_started` until the dispatcher reaches it, `running` during its
call, then `completed` or `failed`. A thrown failure stops the same downstream
work as before; those job rows retain null start and finish times. A returned
Every invocation is recorded; its jobs are recorded when they matter. A job
appears when it changed something (it wrote a business audit event), failed, or
ran longer than two seconds, so a quiet minute is one invocation with no jobs.
A recorded job is `running` during its call, then `completed` or `failed`. A
thrown failure stops the same downstream work as before; the jobs after it are
recorded as `not_started` with null start and finish times. A returned
`status: failed` is recorded without changing the job's existing continuation
behavior. Completion means that invocation returned normally: handled
per-item payment, delivery or synchronization failures remain in their
existing source records and are not a claim of settlement or delivery.
Invocations older than seven days are removed, a hundred at most each hour.

The dispatcher renews a heartbeat each minute and between jobs. On a later
The dispatcher renews a heartbeat each minute. On a later
normal tick, an invocation with no heartbeat for thirty minutes becomes
`interrupted`; its running job becomes interrupted and downstream jobs stay
unstarted. This reports an expired execution lease, including a stopped Worker,
`interrupted`; its recorded running job becomes interrupted and downstream jobs
stay unstarted. This reports an expired execution lease, including a stopped Worker,
rather than claiming to distinguish every cause of a lost heartbeat. Neither
this classification nor reading history retries any work. Ordinary future
ticks retain each product job's existing eligibility, authority and once-only
Expand Down
6 changes: 6 additions & 0 deletions management/integration/deployment-spec.json
Original file line number Diff line number Diff line change
Expand Up @@ -816,6 +816,12 @@
"name": "core-0130_invoice_payment_schedules.sql",
"sha256": "2e78f8f1939cc281e41226cbb168517b9e0cdc2fc16d1f31e82b37504bdf66af",
"sql": "-- Dated instructions carry no background execution authority. The current\n-- owner must explicitly submit the accepted instruction on its exact date.\nALTER TABLE nc_invoice_partial_payments ADD COLUMN payment_kind TEXT NOT NULL DEFAULT 'card' CHECK(payment_kind IN ('card','scheduled_ach'));\nCREATE TABLE nc_invoice_schedule_authority (\n id TEXT PRIMARY KEY REFERENCES nc_invoice_partial_payments(id),\n customer_id TEXT NOT NULL REFERENCES nc_customers(id),\n portal_session_id TEXT NOT NULL REFERENCES nc_portal_sessions(id),\n basis_hash TEXT NOT NULL, accepted_at INTEGER NOT NULL\n);\nCREATE TRIGGER nc_invoice_schedule_kind_immutable BEFORE UPDATE ON nc_invoice_partial_payments\nWHEN OLD.payment_kind IS NOT NEW.payment_kind\n AND NOT EXISTS(SELECT 1 FROM nc_privacy_context)\n AND NOT EXISTS(SELECT 1 FROM rer_portability_state WHERE id=1 AND applying=1)\nBEGIN SELECT RAISE(ABORT,'nectar_immutable'); END;\n"
},
{
"binding": "DB",
"name": "core-0131_scheduled_read_budget.sql",
"sha256": "1d6f942a12908d1949d852eda556cfbe2c794de2d2b01e18df2d0cdb409d9187",
"sql": "-- Scheduled and polled reads search by invoice and subscription instead of\n-- scanning every credit note, allocation and collection ever stored, and the\n-- observers remember when they last swept so an idle minute reads a few rows.\nCREATE INDEX nc_invoices_subscription_status ON nc_invoices(subscription_id,status,issue_date);\nCREATE INDEX nc_credit_notes_invoice ON nc_credit_notes(invoice_id);\nCREATE INDEX nc_allocations_invoice ON nc_allocations(invoice_id);\nCREATE INDEX nc_usage_credit_applications_invoice ON nc_usage_credit_applications(invoice_id);\nCREATE INDEX nc_processor_reversals_invoice ON nc_processor_reversals(invoice_id);\nCREATE INDEX nc_native_collections_invoice ON nc_native_collections(invoice_id,status);\nCREATE INDEX nc_automatic_collections_invoice ON nc_automatic_collections(invoice_id,status);\nCREATE INDEX nc_subscriptions_customer ON nc_subscriptions(customer_id,created_at);\nCREATE INDEX nc_subscription_lifecycle_subscription ON nc_subscription_lifecycle(subscription_id,seq);\n-- The collection runner reads only collections that can still act.\nCREATE INDEX nc_automatic_collection_open ON nc_automatic_collections(prepared_at,id)\n WHERE status IN ('active','claimed','uncertain','pending_settlement','refused','returned');\n-- clean_at/clean_marker: the last finished sweep. sweep_at/sweep_marker: the sweep in progress.\nALTER TABLE nc_subscription_state_cursor ADD COLUMN clean_at INTEGER;\nALTER TABLE nc_subscription_state_cursor ADD COLUMN clean_marker TEXT;\nALTER TABLE nc_subscription_state_cursor ADD COLUMN sweep_at INTEGER;\nALTER TABLE nc_subscription_state_cursor ADD COLUMN sweep_marker TEXT;\n-- swept_at: the last full pass. audit_seq/usage_rowid: the change feed already examined.\nALTER TABLE nc_webhook_observation_cursor ADD COLUMN swept_at INTEGER;\nALTER TABLE nc_webhook_observation_cursor ADD COLUMN sweep_at INTEGER;\nALTER TABLE nc_webhook_observation_cursor ADD COLUMN audit_seq INTEGER;\nALTER TABLE nc_webhook_observation_cursor ADD COLUMN usage_rowid INTEGER;\n"
}
],
"compatibilityDate": "2026-09-08",
Expand Down
25 changes: 25 additions & 0 deletions migrations/core/0131_scheduled_read_budget.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
-- Scheduled and polled reads search by invoice and subscription instead of
-- scanning every credit note, allocation and collection ever stored, and the
-- observers remember when they last swept so an idle minute reads a few rows.
CREATE INDEX nc_invoices_subscription_status ON nc_invoices(subscription_id,status,issue_date);
CREATE INDEX nc_credit_notes_invoice ON nc_credit_notes(invoice_id);
CREATE INDEX nc_allocations_invoice ON nc_allocations(invoice_id);
CREATE INDEX nc_usage_credit_applications_invoice ON nc_usage_credit_applications(invoice_id);
CREATE INDEX nc_processor_reversals_invoice ON nc_processor_reversals(invoice_id);
CREATE INDEX nc_native_collections_invoice ON nc_native_collections(invoice_id,status);
CREATE INDEX nc_automatic_collections_invoice ON nc_automatic_collections(invoice_id,status);
CREATE INDEX nc_subscriptions_customer ON nc_subscriptions(customer_id,created_at);
CREATE INDEX nc_subscription_lifecycle_subscription ON nc_subscription_lifecycle(subscription_id,seq);
-- The collection runner reads only collections that can still act.
CREATE INDEX nc_automatic_collection_open ON nc_automatic_collections(prepared_at,id)
WHERE status IN ('active','claimed','uncertain','pending_settlement','refused','returned');
-- clean_at/clean_marker: the last finished sweep. sweep_at/sweep_marker: the sweep in progress.
ALTER TABLE nc_subscription_state_cursor ADD COLUMN clean_at INTEGER;
ALTER TABLE nc_subscription_state_cursor ADD COLUMN clean_marker TEXT;
ALTER TABLE nc_subscription_state_cursor ADD COLUMN sweep_at INTEGER;
ALTER TABLE nc_subscription_state_cursor ADD COLUMN sweep_marker TEXT;
-- swept_at: the last full pass. audit_seq/usage_rowid: the change feed already examined.
ALTER TABLE nc_webhook_observation_cursor ADD COLUMN swept_at INTEGER;
ALTER TABLE nc_webhook_observation_cursor ADD COLUMN sweep_at INTEGER;
ALTER TABLE nc_webhook_observation_cursor ADD COLUMN audit_seq INTEGER;
ALTER TABLE nc_webhook_observation_cursor ADD COLUMN usage_rowid INTEGER;
18 changes: 9 additions & 9 deletions sources.lock.json
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@
"executable": false
},
"API.md": {
"sha256": "f51773668ed0b707053ac10f6961f7fcf21f7518756e4e702037adc1c6cc85e3",
"sha256": "0e2de208114f8f84a69433708d4b655e87aeb2098d1a4eae84f077e2ad5d1bfa",
"executable": false
},
"base-copies.json": {
Expand Down Expand Up @@ -382,7 +382,7 @@
"executable": false
},
"management/integration/deployment-spec.json": {
"sha256": "c6ea17c8aac9b20426715360c0a256c107d15242bc5faea95eba6a7a59953ca0",
"sha256": "e24c3a68b02bc37d42f9ed3d68bdaebb77247b49f47b044c27736e81e1f21da1",
"executable": false
},
"migrations/core/0001_owner.sql": {
Expand Down Expand Up @@ -3946,7 +3946,7 @@
"executable": false
},
"src/nectar/automatic-collection-jobs.ts": {
"sha256": "cfe5f29e14e3b18e27b61dd855e493bcc3d71e27d12de94ffb8c2504e0ef2a24",
"sha256": "6a9a98bf81e469c4dd6b1343b84038974ab301b5a71f2d28105949d3d53fbe44",
"executable": false
},
"src/nectar/automatic-collection-records.ts": {
Expand Down Expand Up @@ -4402,7 +4402,7 @@
"executable": false
},
"src/nectar/job-runs.ts": {
"sha256": "a733a583562770852917ec95a47fd9c340e0e0dcf55dcca34e2a54ca421801fd",
"sha256": "342695ec1dcf7ae926aabc1ee516f82852db5463cc8c71ec68cd76f1b9645573",
"executable": false
},
"src/nectar/ledger-postings.ts": {
Expand Down Expand Up @@ -5270,7 +5270,7 @@
"executable": false
},
"src/nectar/subscription-states.ts": {
"sha256": "1f5b9992cf3f5da7a84f1e357eb136ee937bd5362aa3cc08ab5d332efdd9cfc1",
"sha256": "e5f398c955c4890ee89f854112ba243f82b9bdff81339e2e3d108785a53e9540",
"executable": false
},
"src/nectar/subscriptions.ts": {
Expand Down Expand Up @@ -5698,7 +5698,7 @@
"executable": false
},
"src/nectar/webhook-entitlements.ts": {
"sha256": "a3dd49bab3bbf8a635eed68f3f061b365a51ed5508033959624818991166e556",
"sha256": "b491c5b5a60407561a03ca33a10fc8c669101a15a5a3466cd0027de6bb03541b",
"executable": false
},
"src/nectar/webhook-stripe.ts": {
Expand Down Expand Up @@ -6166,7 +6166,7 @@
"executable": false
},
"tests/nectar/harness.mjs": {
"sha256": "6865663a89d3fb24c6f36f9e9701e1e40035d3b93358bb7b2a5996edfd241e3f",
"sha256": "b46c260b0bf0ae892068f8e744c31e5f00f1637b030289002e7c4f7867ac7fb9",
"executable": false
},
"tests/nectar/hierarchies.mjs": {
Expand Down Expand Up @@ -6238,15 +6238,15 @@
"executable": false
},
"tests/nectar/isolated-cases.mjs": {
"sha256": "f8162a33d6c2b607e10ad53230c935d1f1d8d2a8a981e0f53680c2c9fa6d6dd6",
"sha256": "10146fa7a0498e0d83785229dd5dc00cd44ed505a40ebb7a1d47beec6401ba2a",
"executable": false
},
"tests/nectar/isolated.mjs": {
"sha256": "7ec51d3f8185c6e8d10eeeed5e3b22811ab1eafa2914bda1a6aa7c2c08cb7cfe",
"executable": false
},
"tests/nectar/job-runs.mjs": {
"sha256": "881c38ab6cb2926f68f9e509a75dad6915f493f80cb77316be66c5e2e8f70862",
"sha256": "575c6cc42aa936839504da5cab49210a20c3d30af26bbee26008ae2a6d630bd1",
"executable": false
},
"tests/nectar/journey.mjs": {
Expand Down
2 changes: 1 addition & 1 deletion src/nectar/automatic-collection-jobs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ export async function collectAutomaticInvoice(env:Bindings,invoice:string){
}
}
export async function runAutomaticCollections(env:Bindings){
for(const row of await all(env,"SELECT a.id,a.invoice_id,a.status FROM nc_automatic_collections a JOIN nc_invoices i ON i.id=a.invoice_id JOIN nc_customers c ON c.id=a.customer_id WHERE c.erased_at IS NULL AND i.status='issued' AND (a.status IN ('active','claimed','uncertain','pending_settlement') OR (a.status IN ('refused','returned') AND NOT EXISTS(SELECT 1 FROM nc_retry_series r WHERE r.collection_id=a.id))) ORDER BY a.prepared_at,a.id")){
for(const row of await all(env,"SELECT a.id,a.invoice_id,a.status FROM nc_automatic_collections a JOIN nc_invoices i ON i.id=a.invoice_id JOIN nc_customers c ON c.id=a.customer_id WHERE c.erased_at IS NULL AND i.status='issued' AND a.status IN ('active','claimed','uncertain','pending_settlement','refused','returned') AND (a.status IN ('active','claimed','uncertain','pending_settlement') OR NOT EXISTS(SELECT 1 FROM nc_retry_series r WHERE r.collection_id=a.id)) ORDER BY a.prepared_at,a.id")){
if(row.status==='active')await collectAutomaticInvoice(env,row.invoice_id)
else await reconcileAutomaticCollection(env,row.id)
}
Expand Down
57 changes: 44 additions & 13 deletions src/nectar/job-runs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,17 @@
import type { Bindings } from '../auth.server'
import { requireOwner, type Actor } from './actor'
import { clockInstant } from './clock'
import { newId, stmt, type Row } from './core'
import { newId, one, stmt, type Row } from './core'

type Job = { name: string; run: () => Promise<unknown> }
type Execution = { ordinal: number; job: string; status: string; startedAt: number | null; finishedAt: number | null; errorCode: string | null }
const LEASE_MS = 30 * 60_000
// A job still running after this long is recorded as running, so a hung job is
// visible; faster jobs are recorded only if they changed something or failed.
const SLOW_MS = 2_000
// Dispatches kept, in minutes of the per-minute schedule (seven days).
const KEEP_DISPATCHES = 7 * 24 * 60
const PRUNE_PER_RUN = 100

// Error text, provider results and even arbitrary typed error codes may contain
// customer data. The operational door publishes only these fixed categories.
Expand All @@ -16,6 +23,12 @@ function failureCode(error: unknown) {
? 'storage_failure' : 'job_failure'
}

const auditMark = async (env: Bindings) => (await one(env, 'SELECT COALESCE(MAX(seq),0) seq FROM nc_audit'))!.seq as number
const record = (env: Bindings, id: string, rows: Execution[]) => rows.map(row => stmt(env,
`INSERT INTO nc_job_executions(dispatch_id,ordinal,job,status,started_at,finished_at,error_code) VALUES(?,?,?,?,?,?,?)
ON CONFLICT(dispatch_id,ordinal) DO UPDATE SET status=excluded.status,started_at=excluded.started_at,finished_at=excluded.finished_at,error_code=excluded.error_code`,
id, row.ordinal, row.job, row.status, row.startedAt, row.finishedAt, row.errorCode))

export async function runScheduledJobs(env: Bindings, schedule: { cron: string; scheduledTime: number }, jobs: Job[]) {
const id = newId(), at = clockInstant(env)
// Observation writes deliberately do not create business audit events. A
Expand All @@ -24,40 +37,58 @@ export async function runScheduledJobs(env: Bindings, schedule: { cron: string;
stmt(env, "UPDATE nc_job_executions SET status='interrupted',finished_at=?,error_code='execution_lease_expired' WHERE status='running' AND dispatch_id IN (SELECT id FROM nc_job_dispatches WHERE status='running' AND heartbeat_at<=?)", at, at - LEASE_MS),
stmt(env, "UPDATE nc_job_dispatches SET status='interrupted',finished_at=?,error_code='execution_lease_expired' WHERE status='running' AND heartbeat_at<=?", at, at - LEASE_MS),
stmt(env, "INSERT INTO nc_job_dispatches(id,cron,scheduled_at,status,started_at,heartbeat_at) VALUES(?,?,?,'running',?,?)", id, schedule.cron, schedule.scheduledTime, at, at),
...jobs.map((job, index) => stmt(env, "INSERT INTO nc_job_executions(dispatch_id,ordinal,job,status) VALUES(?,?,?,'not_started')", id, index, job.name)),
])
// Every job's row is kept in memory and written when it matters: the job
// changed something, failed, or has been running long enough to need watching.
const rows: Execution[] = jobs.map((job, ordinal) => ({ ordinal, job: job.name, status: 'not_started', startedAt: null, finishedAt: null, errorCode: null }))
const written = new Set<number>()
const persist = async (only: Execution[], extra: D1PreparedStatement[] = []) => {
only.forEach(row => written.add(row.ordinal))
await env.DB.batch([...record(env, id, only), ...extra])
}
let heartbeat = Promise.resolve()
const timer = setInterval(() => {
heartbeat = heartbeat.then(async () => {
await stmt(env, "UPDATE nc_job_dispatches SET heartbeat_at=? WHERE id=? AND status='running'", clockInstant(env), id).run()
}).catch(() => { /* A missing heartbeat is recovered as an expired lease. */ })
}, 60_000)
let failed = false
let failed = false, mark = await auditMark(env)
try {
for (const [index, job] of jobs.entries()) {
await env.DB.batch([
stmt(env, "UPDATE nc_job_executions SET status='running',started_at=? WHERE dispatch_id=? AND ordinal=? AND status='not_started'", clockInstant(env), id, index),
stmt(env, "UPDATE nc_job_dispatches SET heartbeat_at=? WHERE id=? AND status='running'", clockInstant(env), id),
])
const row = rows[index]
row.status = 'running'; row.startedAt = clockInstant(env)
let watch: ReturnType<typeof setTimeout> | undefined, slow = Promise.resolve()
watch = setTimeout(() => { slow = persist(rows.slice(index)).catch(() => { /* Unwritten rows are recorded when the job ends. */ }) }, SLOW_MS)
try {
const result = await job.run()
clearTimeout(watch); await slow
// Some existing jobs report a handled failure without throwing. Keep
// their established continuation behavior and report that failure too.
const reportedFailure = result !== null && typeof result === 'object' && 'status' in result && result.status === 'failed'
failed ||= reportedFailure
await stmt(env, "UPDATE nc_job_executions SET status=?,finished_at=?,error_code=? WHERE dispatch_id=? AND ordinal=? AND status='running'",
reportedFailure ? 'failed' : 'completed', clockInstant(env), reportedFailure ? 'job_reported_failure' : null, id, index).run()
Object.assign(row, { status: reportedFailure ? 'failed' : 'completed', finishedAt: clockInstant(env), errorCode: reportedFailure ? 'job_reported_failure' : null })
const next = await auditMark(env), worked = next !== mark
mark = next
if (worked || reportedFailure || written.has(index)) await persist([row])
} catch (error) {
clearTimeout(watch); await slow
const code = failureCode(error)
await env.DB.batch([
stmt(env, "UPDATE nc_job_executions SET status='failed',finished_at=?,error_code=? WHERE dispatch_id=? AND ordinal=? AND status='running'", clockInstant(env), code, id, index),
stmt(env, "UPDATE nc_job_dispatches SET status='failed',finished_at=?,error_code=? WHERE id=? AND status='running'", clockInstant(env), code, id),
])
Object.assign(row, { status: 'failed', finishedAt: clockInstant(env), errorCode: code })
await persist(rows.slice(index), [stmt(env, "UPDATE nc_job_dispatches SET status='failed',finished_at=?,error_code=? WHERE id=? AND status='running'", clockInstant(env), code, id)])
throw error
}
}
await stmt(env, "UPDATE nc_job_dispatches SET status=?,finished_at=?,error_code=? WHERE id=? AND status='running'",
failed ? 'failed' : 'completed', clockInstant(env), failed ? 'job_reported_failure' : null, id).run()
// History beyond a week is dropped from the oldest end, a few rows an hour,
// so clearing an old backlog never spends the day's write allowance.
if (new Date(schedule.scheduledTime).getUTCMinutes() === 0) {
const old = "SELECT seq FROM nc_job_dispatches WHERE seq<=(SELECT COALESCE(MAX(seq),0) FROM nc_job_dispatches)-? AND status<>'running' ORDER BY seq LIMIT ?"
await env.DB.batch([
stmt(env, `DELETE FROM nc_job_executions WHERE dispatch_id IN (SELECT id FROM nc_job_dispatches WHERE seq IN (${old}))`, KEEP_DISPATCHES, PRUNE_PER_RUN),
stmt(env, `DELETE FROM nc_job_dispatches WHERE seq IN (${old})`, KEEP_DISPATCHES, PRUNE_PER_RUN),
])
}
} finally {
clearInterval(timer)
await heartbeat
Expand Down
21 changes: 21 additions & 0 deletions src/nectar/observation-gate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Scheduled observers watch dated facts, so most minutes they have nothing to
// learn. These gates keep an idle minute at a handful of rows: a full sweep runs
// only when the business's local day changed, an hour passed, or recorded
// activity suggests a source the commit-time capture does not cover.
import type { Bindings } from '../auth.server'
import { one } from './core'
import { localDate } from './dates'

export const HOUR_MS = 3_600_000
export const ACTIVITY_SWEEP_MS = 5 * 60_000

/** What the audit trail and usage ledger hold now; unchanged means no recorded change. */
export async function changeMarker(env: Bindings) {
const row = (await one(env, 'SELECT (SELECT COALESCE(MAX(seq),0) FROM nc_audit) a,(SELECT COALESCE(MAX(rowid),0) FROM nc_usage_events) u'))!
return `${row.a}:${row.u}`
}

/** True when a sweep that finished at `cleanAt` no longer covers `at`. */
export function sweepDue(at: number, cleanAt: number | null | undefined, timezone: string) {
return cleanAt == null || at < cleanAt || at - cleanAt >= HOUR_MS || localDate(at, timezone) !== localDate(cleanAt, timezone)
}
Loading
Loading