@tidegap/core 0.23.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/scheduler.js CHANGED
@@ -353,8 +353,12 @@ export class Scheduler {
353
353
  * nothing, when the row exists. Planning picks the cleanest forecast hour
354
354
  * inside `[earliest, deadline]`, or leaves the row unplanned for
355
355
  * `replanSweep` when the forecast does not reach it (or fails).
356
+ *
357
+ * `runNow` (a job's extra run): the row is due now as a run-now row is
358
+ * (`scheduledFor` now, no `notBefore`, `intensitySource: "expedited"`, so
359
+ * never the Batch API), with no planning; `actor` is on its `created` event.
356
360
  */
357
- async materializeOccurrence(occ, details) {
361
+ async materializeOccurrence(occ, details, opts = {}) {
358
362
  if (!this.store)
359
363
  throw new Error("materializeOccurrence: jobs need a ledger (dbPath)");
360
364
  const earliestMs = Date.parse(occ.earliest);
@@ -366,8 +370,9 @@ export class Scheduler {
366
370
  region: this.defaultRegion(),
367
371
  bodyJson: occ.bodyJson,
368
372
  deadline: new Date(deadlineMs).toISOString(),
369
- notBefore: new Date(earliestMs).toISOString(),
370
- scheduledFor: new Date(Math.min(earliestMs + MINUTE_MS, deadlineMs)).toISOString(),
373
+ ...(opts.runNow
374
+ ? { scheduledFor: new Date().toISOString(), intensitySource: "expedited" }
375
+ : { notBefore: new Date(earliestMs).toISOString(), scheduledFor: new Date(Math.min(earliestMs + MINUTE_MS, deadlineMs)).toISOString() }),
371
376
  title: occ.title,
372
377
  originHost: occ.originHost,
373
378
  originCwd: occ.originCwd,
@@ -375,12 +380,14 @@ export class Scheduler {
375
380
  repeat: "none",
376
381
  jobId: occ.jobId,
377
382
  };
378
- const created = this.eventFor(undefined, record, { kind: "created", actor: "system", details });
383
+ const created = this.eventFor(undefined, record, { kind: "created", actor: opts.runNow?.actor ?? "system", details });
379
384
  if (!this.store.insertIfAbsent(record, created))
380
385
  return false;
381
386
  if (record.originSessionId)
382
387
  this.store.startSessionNotices(new Date(record.enqueuedAt));
383
388
  this.cacheRow(record);
389
+ if (opts.runNow)
390
+ return true;
384
391
  try {
385
392
  await this.scheduleProviderCall(record.taskId, new Date(deadlineMs));
386
393
  }
@@ -649,6 +656,9 @@ export class Scheduler {
649
656
  // poll sweep — submit and poll are distinct ticks (the provider needs
650
657
  // time to start the batch).
651
658
  const submittedThisTick = new Set();
659
+ // Job rows held back this tick: a due row the Batch API could take meets
660
+ // both sweeps, and its wait is logged once.
661
+ const waiting = new Set();
652
662
  for (const record of this.collectBatchSubmitCandidates(adapters)) {
653
663
  if (opts.signal?.aborted)
654
664
  break;
@@ -656,16 +666,7 @@ export class Scheduler {
656
666
  // the same row twice (double-billed batch). In-memory-only mode
657
667
  // has no cross-process race, so claim only when a store exists.
658
668
  if (this.store) {
659
- let claimed = false;
660
- try {
661
- claimed = this.store.claimScheduled(record.taskId);
662
- }
663
- catch (err) {
664
- // eslint-disable-next-line no-console
665
- console.warn(`[tidegap/scheduler] tick: could not claim task ${record.taskId} for batch submit: ${describeErr(err)}; skipping this round`);
666
- continue;
667
- }
668
- if (!claimed)
669
+ if (!this.claimForTick(this.store, record, waiting, " for batch submit"))
669
670
  continue;
670
671
  // The claim succeeded on the stored row; re-read it so a write from
671
672
  // another process (run now, reschedule) since our list is honoured.
@@ -738,19 +739,7 @@ export class Scheduler {
738
739
  // processes pointing at the same SQLite file (e.g. an
739
740
  // interactive `tidegap tick` racing the launchd cron).
740
741
  if (this.store) {
741
- let claimed = false;
742
- try {
743
- claimed = this.store.claimScheduled(record.taskId);
744
- }
745
- catch (err) {
746
- // A locked / throwing row (e.g. SQLITE_BUSY under heavy
747
- // multi-process contention) is skipped — it stays "scheduled"
748
- // and a later tick retries. It must never abort the whole tick.
749
- // eslint-disable-next-line no-console
750
- console.warn(`[tidegap/scheduler] tick: could not claim task ${record.taskId}: ${describeErr(err)}; skipping this round`);
751
- continue;
752
- }
753
- if (!claimed)
742
+ if (!this.claimForTick(this.store, record, waiting))
754
743
  continue;
755
744
  // Re-read after the claim (KTD1): a reschedule written between our
756
745
  // list and the claim must not be dispatched on the old time.
@@ -888,6 +877,31 @@ export class Scheduler {
888
877
  return false;
889
878
  return !(record.notBefore && Date.parse(record.notBefore) > now);
890
879
  }
880
+ /**
881
+ * The tick's row-level claim ({@link TaskStore.claimScheduled}). False
882
+ * when the row is not this tick's this round: another process claimed it
883
+ * or moved it on; another run of its job is running or submitted, so it
884
+ * stays `scheduled` for a later tick (one log line per tick, kept in
885
+ * `waiting`); or the claim threw (a locked ledger under heavy contention),
886
+ * which never aborts the tick.
887
+ */
888
+ claimForTick(store, record, waiting, purpose = "") {
889
+ try {
890
+ if (store.claimScheduled(record.taskId))
891
+ return true;
892
+ const active = record.jobId && !waiting.has(record.taskId) ? store.activeJobRun(record.taskId) : undefined;
893
+ if (active) {
894
+ waiting.add(record.taskId);
895
+ // eslint-disable-next-line no-console
896
+ console.warn(`[tidegap/scheduler] tick: job ${record.jobId}: another run is active (${active}), waiting`);
897
+ }
898
+ }
899
+ catch (err) {
900
+ // eslint-disable-next-line no-console
901
+ console.warn(`[tidegap/scheduler] tick: could not claim task ${record.taskId}${purpose}: ${describeErr(err)}; skipping this round`);
902
+ }
903
+ return false;
904
+ }
891
905
  /** Replace a just-claimed cached record with the stored row (status `running`). */
892
906
  reloadClaimed(record) {
893
907
  const fresh = this.store?.get(record.taskId);
@@ -1546,9 +1560,12 @@ export class Scheduler {
1546
1560
  // Same row-level claim `tick` uses: if a concurrent process (e.g. the
1547
1561
  // cron tick) grabbed the row between our read and here, do NOT
1548
1562
  // dispatch a second (double-billed) provider call.
1549
- if (!this.writeIf(record, next, PENDING_STATUSES, { kind: "expedited", actor: opts.actor }) ||
1550
- (this.store && !this.store.claimScheduled(taskId))) {
1551
- throw new Error(`task ${taskId} was just claimed by another process (racing tick?)`);
1563
+ const racing = `task ${taskId} was just claimed by another process (racing tick?)`;
1564
+ if (!this.writeIf(record, next, PENDING_STATUSES, { kind: "expedited", actor: opts.actor }))
1565
+ throw new Error(racing);
1566
+ if (this.store && !this.store.claimScheduled(taskId)) {
1567
+ const active = record.jobId ? this.store.activeJobRun(taskId) : undefined;
1568
+ throw new Error(active ? `expediteTask: another run of job ${record.jobId} is active (${active}); ${taskId} runs at a tick after it ends` : racing);
1552
1569
  }
1553
1570
  return this.dispatchProviderCall(record, adapters);
1554
1571
  }
@@ -325,8 +325,16 @@ export declare class TaskStore {
325
325
  * handles on the same DB file; this row-level claim is what makes a
326
326
  * dispatch exactly-once across them (e.g. an interactive `tidegap tick`
327
327
  * racing the launchd cron, or `expedite_task` racing a cron tick).
328
+ *
329
+ * A run of a job is claimed only while no other run of that job is
330
+ * running or submitted: the check is part of the one UPDATE, so two
331
+ * tickers on one ledger cannot both start a run of the same job. A row
332
+ * held back this way stays `scheduled` ({@link activeJobRun} names the
333
+ * run it waits for).
328
334
  */
329
335
  claimScheduled(taskId: string): boolean;
336
+ /** Another run of this row's job that is running or submitted and so holds its claim back: its task id, or undefined. */
337
+ activeJobRun(taskId: string): string | undefined;
330
338
  /**
331
339
  * Atomic row-level claim for the polling side of the Batch API path
332
340
  * (v0.12): flips a row from "submitted" to "running" so two racing
@@ -189,7 +189,8 @@ CREATE TABLE IF NOT EXISTS jobs (
189
189
  end_reason TEXT,
190
190
  end_notified_at TEXT,
191
191
  wake_json TEXT,
192
- origin_session_id TEXT
192
+ origin_session_id TEXT,
193
+ extra_task_id TEXT
193
194
  );
194
195
  CREATE INDEX IF NOT EXISTS jobs_status_idx ON jobs(status);
195
196
  `;
@@ -268,7 +269,7 @@ function columnAdder(db, table) {
268
269
  }
269
270
  };
270
271
  }
271
- /** The `jobs` columns added after the table first shipped: the job lifetime, then the wake binding. */
272
+ /** The `jobs` columns added after the table first shipped: the job lifetime, the wake binding, then the extra run. */
272
273
  function ensureJobColumns(db) {
273
274
  const addColumn = columnAdder(db, "jobs");
274
275
  addColumn("until", "TEXT");
@@ -278,6 +279,7 @@ function ensureJobColumns(db) {
278
279
  addColumn("end_notified_at", "TEXT");
279
280
  addColumn("wake_json", "TEXT");
280
281
  addColumn("origin_session_id", "TEXT");
282
+ addColumn("extra_task_id", "TEXT");
281
283
  }
282
284
  const REPEAT_RULES = new Set(["none", "daily", "weekly", "quota_reset"]);
283
285
  /** Every column of the tasks table, in INSERT order. */
@@ -292,6 +294,13 @@ const INSERT_SQL = `INSERT INTO tasks (${INSERT_COLUMNS.join(", ")})
292
294
  VALUES (${INSERT_COLUMNS.map((c) => `@${c}`).join(", ")})`;
293
295
  /** Timing columns `transitionIf(..., unchangedSince)` compares with an earlier read. */
294
296
  const TIMING_GUARD_COLUMNS = ["scheduled_for", "not_before", "deadline", "intensity_source"];
297
+ /**
298
+ * The other runs of the outer `tasks` row's job that are `running`, or
299
+ * `submitted` to a Batch API (the provider may be running it). None for a
300
+ * row with no `job_id`.
301
+ */
302
+ const ACTIVE_JOB_RUNS_SQL = `SELECT other.task_id FROM tasks AS other
303
+ WHERE other.job_id = tasks.job_id AND other.task_id <> tasks.task_id AND other.status IN ('running', 'submitted')`;
295
304
  /** Columns `transitionIf` binds: the mutable ones plus the key. */
296
305
  const TRANSITION_COLUMNS = [
297
306
  "task_id", "status", "scheduled_for", "completed_at", "result_json", "error",
@@ -326,7 +335,8 @@ function recordParams(record) {
326
335
  repeat: record.repeat ?? null,
327
336
  origin_session_id: record.originSessionId ?? null,
328
337
  not_before: record.notBefore ?? null,
329
- job_id: record.jobId ?? null,
338
+ // NULL, never '': the dispatch guard (`claimScheduled`) holds back rows with an equal job_id.
339
+ job_id: record.jobId || null,
330
340
  };
331
341
  }
332
342
  /**
@@ -1142,12 +1152,26 @@ export class TaskStore {
1142
1152
  * handles on the same DB file; this row-level claim is what makes a
1143
1153
  * dispatch exactly-once across them (e.g. an interactive `tidegap tick`
1144
1154
  * racing the launchd cron, or `expedite_task` racing a cron tick).
1155
+ *
1156
+ * A run of a job is claimed only while no other run of that job is
1157
+ * running or submitted: the check is part of the one UPDATE, so two
1158
+ * tickers on one ledger cannot both start a run of the same job. A row
1159
+ * held back this way stays `scheduled` ({@link activeJobRun} names the
1160
+ * run it waits for).
1145
1161
  */
1146
1162
  claimScheduled(taskId) {
1147
- const stmt = this.db.prepare(`UPDATE tasks SET status = 'running' WHERE task_id = ? AND status = 'scheduled'`);
1163
+ const stmt = this.db.prepare(`UPDATE tasks SET status = 'running'
1164
+ WHERE task_id = ? AND status = 'scheduled' AND NOT EXISTS (${ACTIVE_JOB_RUNS_SQL})`);
1148
1165
  const res = stmt.run(taskId);
1149
1166
  return Number(res.changes) === 1;
1150
1167
  }
1168
+ /** Another run of this row's job that is running or submitted and so holds its claim back: its task id, or undefined. */
1169
+ activeJobRun(taskId) {
1170
+ const row = this.db
1171
+ .prepare(`SELECT (${ACTIVE_JOB_RUNS_SQL} LIMIT 1) AS active FROM tasks WHERE task_id = ?`)
1172
+ .get(taskId);
1173
+ return row?.active ?? undefined;
1174
+ }
1151
1175
  /**
1152
1176
  * Atomic row-level claim for the polling side of the Batch API path
1153
1177
  * (v0.12): flips a row from "submitted" to "running" so two racing
@@ -1233,7 +1257,7 @@ const JOB_COLUMNS = [
1233
1257
  "time_zone", "runner", "template_json", "caps_json", "notify", "origin_host", "origin_cwd", "created_by",
1234
1258
  "created_at", "updated_at", "revision", "next_seq", "pending_task_id", "last_task_id", "last_run_started_at",
1235
1259
  "last_outcome", "consecutive_failures", "retry_used", "pause_reason", "paused_at", "pause_notified_at",
1236
- "until", "runs_left", "ended_at", "end_reason", "end_notified_at", "wake_json", "origin_session_id",
1260
+ "until", "runs_left", "ended_at", "end_reason", "end_notified_at", "wake_json", "origin_session_id", "extra_task_id",
1237
1261
  ];
1238
1262
  /** Columns `updateJobIf` writes: everything except the identity and the revision. */
1239
1263
  const JOB_MUTABLE_COLUMNS = JOB_COLUMNS.filter((c) => !["job_id", "created_at", "created_by", "origin_host", "origin_cwd", "revision"].includes(c));
@@ -1280,6 +1304,7 @@ function jobParams(job) {
1280
1304
  end_notified_at: job.endNotifiedAt ?? null,
1281
1305
  wake_json: job.wake ? JSON.stringify(job.wake) : null,
1282
1306
  origin_session_id: job.originSessionId ?? null,
1307
+ extra_task_id: job.extraTaskId ?? null,
1283
1308
  };
1284
1309
  }
1285
1310
  /** A job row's wake rule and session, both or neither: a rule that does not parse binds nothing. */
@@ -1362,6 +1387,7 @@ function rowToJob(row) {
1362
1387
  revision: Number(row.revision),
1363
1388
  nextSeq: Number(row.next_seq),
1364
1389
  pendingTaskId: str(row.pending_task_id),
1390
+ extraTaskId: str(row.extra_task_id),
1365
1391
  lastTaskId: str(row.last_task_id),
1366
1392
  lastRunStartedAt: str(row.last_run_started_at),
1367
1393
  lastOutcome: JOB_OUTCOMES.has(row.last_outcome) ? row.last_outcome : undefined,
package/dist/types.d.ts CHANGED
@@ -728,7 +728,11 @@ export interface JobWake {
728
728
  }
729
729
  /** Why a run of a bound job is a session notice. */
730
730
  export type JobNoticeReason = "failed" | "matched" | "ended";
731
- /** Outcome of a job's last finished occurrence. */
731
+ /**
732
+ * Outcome of a job's last run: `ok` (completed) or `failed`. `skipped` is
733
+ * read from rows written before a cancelled occurrence stopped counting as
734
+ * the last run; the sweep no longer writes it.
735
+ */
732
736
  export type JobOutcome = "ok" | "failed" | "skipped";
733
737
  /** One row of the `jobs` table. */
734
738
  export interface JobRecord {
@@ -755,8 +759,17 @@ export interface JobRecord {
755
759
  nextSeq: number;
756
760
  /** The one live occurrence the sweep tracks. */
757
761
  pendingTaskId?: string;
762
+ /**
763
+ * The extra run that run now added (`<job_id>~<seq>x`, its retries
764
+ * `<job_id>~<seq>xr`, `...xr2`), live or finished and not yet recorded.
765
+ * It runs beside the planned occurrence and does not move it.
766
+ */
767
+ extraTaskId?: string;
768
+ /** The last occurrence that ran (completed or failed), a regular one or an extra run; never a cancelled one. */
758
769
  lastTaskId?: string;
770
+ /** When the last regular occurrence started: the anchor of the next one. An extra run does not move it. */
759
771
  lastRunStartedAt?: string;
772
+ /** Outcome of {@link lastTaskId}. */
760
773
  lastOutcome?: JobOutcome;
761
774
  consecutiveFailures: number;
762
775
  /** The retries the current slot used, 0 to the job's retries (`retry_used`; a row from before held 0 or 1). */
@@ -19,4 +19,6 @@ export declare function localTime(ms: number, tz: string): number;
19
19
  * a local time inside a DST gap gives the first instant after the gap.
20
20
  */
21
21
  export declare function localToUtcMs(y: number, mo: number, d: number, h: number, mi: number, tz: string): number;
22
+ /** `HH:MM` in `timeZone` when `at` falls on the same day there as `now`, else `Ddd HH:MM`. */
23
+ export declare function zoneTimeLabel(at: Date, now: Date, timeZone: string): string;
22
24
  //# sourceMappingURL=zone-time.d.ts.map
package/dist/zone-time.js CHANGED
@@ -73,4 +73,15 @@ export function localToUtcMs(y, mo, d, h, mi, tz) {
73
73
  }
74
74
  return hi;
75
75
  }
76
+ /** `HH:MM` in `timeZone` when `at` falls on the same day there as `now`, else `Ddd HH:MM`. */
77
+ export function zoneTimeLabel(at, now, timeZone) {
78
+ const parts = (d) => {
79
+ // An unknown zone falls back to the system zone.
80
+ const fmt = new Intl.DateTimeFormat("en-US", { timeZone: isValidTimeZone(timeZone) ? timeZone : undefined, weekday: "short", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23" });
81
+ const p = Object.fromEntries(fmt.formatToParts(d).map((x) => [x.type, x.value]));
82
+ return { day: `${p.year}-${p.month}-${p.day}`, weekday: p.weekday, time: `${p.hour}:${p.minute}` };
83
+ };
84
+ const a = parts(at);
85
+ return a.day === parts(now).day ? a.time : `${a.weekday} ${a.time}`;
86
+ }
76
87
  //# sourceMappingURL=zone-time.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tidegap/core",
3
- "version": "0.23.0",
3
+ "version": "0.25.0",
4
4
  "description": "Carbon-aware scheduling for agentic AI workflows — core TypeScript library.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Vitalii Borovyk",