LibreChat/packages/data-schemas/misc/documentdb/compat.documentdb.spec.ts
Danny Avila 81338cef95
🍃 test: Sweep Every DB Schema Method Against a Live Engine (#15392)
* 🍃 test: Sweep Every data-schemas Method Against a Live Engine

Adds `misc/documentdb/sweep.documentdb.spec.ts`: drives all 510 exported
data-schemas methods against a real engine and records, per method, how many
driver queries it issued and whether the engine rejected any of them.

Every DocumentDB incompatibility found so far — pipeline updates, `$$REMOVE`,
`$facet`, the transaction-probe false negative, the Mongoose-compiled mixed
projection — was invisible until someone thought to look for its class. The
sweep inverts that: the engine adjudicates whatever each method emits, known
class or not. Query shapes are parsed before they are matched, so an empty
database adjudicates most entry paths.

Mechanics: arguments are synthesized from each function's parameter names,
then repaired adaptively from the validation errors they provoke (ObjectId and
number casts, required schema paths, object-parameter shapes) until the method
reaches the database; the driver prototype is instrumented to count calls and
capture server errors — including on cursor consumption, where parse errors
actually surface — and duplicate-key violations are classified as benign. A
method that never issues a query is reported un-adjudicated instead of
silently green: coverage is visible, not assumed.

Two modes with identical mechanics so matrices diff cleanly: in-memory MongoDB
(`SWEEP_BASELINE=true`, free, CI-able) and live DocumentDB (`DOCUMENTDB_URI`).
`SWEEP_REPORT_PATH` writes JSON for machine diffing;
`DOCUMENTDB_STRICT=true` turns rejections into failures.

First full run against live DocumentDB 5.0.0: 363 of 510 methods issued at
least one query, zero engine rejections, zero divergences from the MongoDB
baseline. The jest config gains the main config's transform-ignore patterns so
the full method bundle (which pulls ESM markdown tooling) loads.

* 🍃 fix: Adjudicate Index DDL, Real ACL Cascades, and a Run-Scoped Sweep Database

Review round 1, all four findings real:

- The driver instrumentation now wraps `createIndex`, `createIndexes`,
  `dropIndex`, `dropIndexes`, and `listIndexes` (cursor-wrapped), so an engine
  rejecting index DDL — which `recordAuditEntry` issues before any listed
  operation and then swallows — is adjudicated instead of surfacing as a
  false `no-queries` under STRICT.
- The `removeAllPermissions` no-op override is gone: `createMethods` supplies
  a real implementation delegating to `deleteAclEntries`, so driven deletion
  cascades exercise their ACL operations (not-driven drops 147 → 142).
- Each race timer is cleared when its attempt settles, instead of hundreds of
  referenced timers living until the shared deadline and the last one holding
  the process open after the report.
- The live run connects to a run-scoped database
  (`librechat_sweep_<runId>`), so its `dropDatabase` teardown can never erase
  fixtures out from under the sibling live suites sharing the URI, nor any
  retained state in the URI's own database.

* 🍃 fix: Attribute Straggler Queries by Async Context and Adjudicate Transaction Commits

Review round 2, all three findings real:

- Per-method attribution now rides AsyncLocalStorage instead of a module
  global: a method that outlives its timeout keeps recording queries and
  engine errors under ITS OWN row rather than corrupting whichever row the
  sweep advanced to, and a final reclassification pass upgrades any row whose
  engine error arrived after its outcome was assigned.
- The session prototype's `commitTransaction`/`abortTransaction`/
  `withTransaction` are instrumented: transaction-lifecycle rejections surface
  from the session, not a collection operation, and several methods convert
  them into domain errors — previously a real commit rejection classified as
  a mere `threw` and STRICT passed.
- The compatibility doc's published numbers now come from the
  corrected-harness baseline (368 driven / 142 un-driven) and state explicitly
  that the recorded live-run matrix predates the instrumentation widening, so
  the next live run is authoritative for the newly adjudicated surfaces.

* 🍃 fix: Settle Stragglers Before STRICT and Commit a Real Transaction on a Replica-Set Baseline

Review round 3, all four findings real:

- STRICT is now enforced against the FINALIZED rows: `afterAll` waits
  (bounded) for every timed-out invocation to settle, reclassifies rows whose
  engine errors arrived late, and asserts zero rejections — previously a
  straggler's rejection could arrive after its per-test assertion had already
  passed against the `timeout` outcome.
- The baseline runs on a single-node replica set with the live branch's exact
  connection options (`autoIndex`/`autoCreate` off, run-scoped `dbName`):
  a standalone baseline would reject driven transactions for topology reasons,
  and asymmetric model auto-creation would attribute DDL in one mode and not
  the other — both manufacturing false matrix divergences.
- `resolveMCPAuthorityProof` gets a seeded case (fixture ported from the
  compat suite, executed in tenant context via the new `within` wrapper on
  overrides): generic synthesis died on target validation before a session
  ever started, so the session instrumentation adjudicated nothing. It now
  drives 22 operations through the production path, transaction commit
  included, on both engines.

* 🍃 docs: Sync the Published Baseline Counts With the Seeded Harness

* 🍃 fix: Materialize Transaction-Read Collections and Settle Stragglers Before Teardown

Review round 4, three findings real (the fourth — stale doc totals — was
already fixed on the pushed head):

- Straggler settlement moved BEFORE engine teardown: dropping the database or
  closing the client would abort outstanding work with closed-client errors
  that are not engine verdicts, leaving a timed-out row unadjudicated while
  STRICT passes.
- The authority fixtures (sweep AND compat) materialize PluginAuth and Token
  before the transaction: `loadCurrentProof` reads both inside it, and
  DocumentDB rejects any in-transaction statement touching a non-existent
  collection — the rejection surfaces as `proof_unavailable` before the commit
  is reached. This is the mechanism behind the compat authority test failing
  on every live cluster run while passing against MongoDB; with the
  collections materialized, the next live run adjudicates the transaction
  itself instead of the missing namespace.
- Engine errors are recognized by `instanceof MongoServerError` instead of a
  `name` equality, so server-originated subclasses (MongoWriteConcernError,
  MongoBulkWriteError) can no longer slip through the session wrapper as
  domain throws.

* 🍃 fix: Materialize Group and Config for the Authority Transaction and Exclude Constructor Exports

Review round 5, both findings real. The proof transaction also reads Group and
Config; the sweep fixture materializes both (the compat fixture already
creates a Config record and now materializes Group). SessionError — an error
class exported alongside the session methods — is excluded from the method
map, correcting the totals to 509 methods / 369 driven / 140 un-driven; the
published baseline is synced in the same commit.

* 🍃 fix: Build a Fresh Method Bundle per Case and Emit a Normalized Matrix

Review round 6, both findings real:

- Every row now invokes a freshly constructed method bundle. Factory-local
  caches leaked across alphabetically ordered rows — the session methods cache
  `sessionIndexesPromise`, so `ensureSessionIndexes` returned that settled
  promise and was misreported as `no-queries`. It now issues its 3 index
  operations, making the matrix order-independent (370 driven / 139 un-driven).

- The report separates run metadata from a canonical `rows` payload with
  run-specific values normalized out (run id, generated ObjectIds and UUIDs),
  so the two engines' matrices diff cleanly instead of differing on every row
  that embeds a synthesized value in its error text.

* 🍃 fix: Materialize Authority Snapshot Namespaces Before Its Transaction

Amazon DocumentDB rejects any statement inside a transaction that touches a
collection which does not exist, and `asMCPError` converts that server
rejection into `proof_unavailable` — so on a deployment where no PluginAuth
or Token row has ever been written, every MCP authority proof fails with an
error naming nothing about the real cause. This is the mechanism behind the
live-harness authority probe failing on every real cluster run since July
while passing against MongoDB.

`loadAuthoritativeSnapshot` now materializes the nine namespaces its snapshot
reads before opening the transaction, once per process. MongoDB tolerates the
in-transaction read either way, so nothing changes there; a create failure is
logged at debug and left to surface from the transaction itself.

The regression test drops the credential namespaces to reproduce the state and
asserts the resolve recreates them and succeeds; it fails without the fix.

* 🍃 docs: Record the Authoritative Hardened Live Run

The hardened harness ran against a live DocumentDB 5.0.0 cluster: 370 of 509
methods drove at least one query, zero engine rejections, and the matrix is
byte-identical to the MongoDB baseline — every outcome and query count
matches. This run adjudicated index DDL, transaction commits and aborts, ACL
cascades, and the authority snapshot transaction, none of which the first
pre-hardening run could see.

The same run turned the compatibility suite's MCP authority probe green for
the first time on any real cluster, confirming the namespace-materialization
diagnosis for the `proof_unavailable` failures seen since July.

* 🍃 fix: Retry Snapshot Namespace Creation After a Transient Failure

The catch suppressed every `createCollection` error, so a transient failure
settled the once-per-process memo as successful: creation was skipped for the
rest of the process, the transaction kept failing on the missing collection,
and every later proof returned `proof_unavailable` even after the condition
cleared. The existing reset-on-reject path could never fire because the inner
promise never rejected.

Only `NamespaceExists` (including a concurrent creator winning the race) is
suppressed now; every other failure propagates, clears the memo, and lets the
next request retry. The regression test rejects the first creation with a
transient error, asserts the proof fails, then asserts the following request
recreates the namespace and succeeds — it fails against the swallow-all form.

* 🍃 fix: Throttle Snapshot Namespace Preflight Retries With a Bounded Cooldown

Clearing the memo on every rejection made a persistent failure — an
authorization error, say — turn each authority request into another serial
collection preflight: a DDL retry storm precisely while the database is
unhealthy, since the single-flight promise only coalesces requests while an
attempt is pending.

A failure is now recorded with its timestamp and replayed without touching the
database until a bounded cooldown elapses (30s, overridable through the
existing hooks for tests). Transient failures stay retryable, just not on
every request. Both sides of the boundary are covered: one test asserts a
persistent failure issues no further creations inside the cooldown, and the
existing retry test runs with the cooldown disabled to assert recovery still
works. The throttle test fails with the cooldown gate removed.

* 🍃 fix: Instrument Db-Level Namespace DDL in the Sweep

The authority path's namespace preflight calls `Model.createCollection()`,
which delegates to `Db.createCollection` — not to any `Collection` operation
the sweep wrapped. A DocumentDB rejection of that DDL would therefore be
laundered by `asMCPError` into `proof_unavailable`, leaving the row
classified as a mere `threw` while `DOCUMENTDB_STRICT=true` passed: the exact
false-green class this suite exists to close, reintroduced by the preflight
itself.

`Db.createCollection`/`dropCollection`/`renameCollection` are now
instrumented, and `NamespaceExists` (48) joins the benign server codes since
an idempotent preflight against an existing collection is the expected
outcome, not an incompatibility. The authority row's adjudicated query count
rises from 22 to 31, which is those nine preflight operations becoming
visible.
2026-08-31 09:54:32 -04:00

446 lines
18 KiB
TypeScript

import mongoose from 'mongoose';
import { randomUUID } from 'crypto';
import {
Permissions,
PermissionBits,
ResourceType,
PrincipalType,
PrincipalModel,
PermissionTypes,
} from 'librechat-data-provider';
import type { ConnectOptions, Model } from 'mongoose';
import type { IConversationTag } from '~/schema/conversationTag';
import type * as t from '~/types';
import {
createMCPAuthorityMethods,
createMCPAuthorityBootRevision,
createMCPAuthorityCredentialRevision,
createMCPAuthorityDatabaseSourceRevision,
} from '~/methods/mcpAuthority';
import { decrementTagCounts } from '~/methods/conversationTag';
import { tenantStorage } from '~/config/tenantContext';
import { supportsTransactions } from '~/utils/transactions';
import { createScheduleMethods } from '~/methods/schedule';
import { createUserMethods } from '~/methods/user';
import { createFileMethods } from '~/methods/file';
import { createModels } from '~/models';
/**
* Amazon DocumentDB live-compatibility suite.
*
* Exercises the operations that have historically broken on DocumentDB
* (aggregation-pipeline updates — issue #14488) against a REAL cluster, plus
* informational capability probes whose results print as a matrix at the end.
* There is no faithful local emulator of Amazon DocumentDB (the open-source
* "DocumentDB Local" image is an unrelated PostgreSQL-based engine), so this
* suite only runs when DOCUMENTDB_URI is set and skips otherwise.
*
* Run (from packages/data-schemas, against a DEDICATED database):
* DOCUMENTDB_URI="mongodb://user:pass@127.0.0.1:27017/librechat_compat\
* ?tls=true&retryWrites=false&authSource=admin&authMechanism=SCRAM-SHA-1&directConnection=true" \
* DOCUMENTDB_TLS_CA_FILE="global-bundle.pem" \
* npx jest --config misc/documentdb/jest.documentdb.config.mjs
*
* `authSource`/`authMechanism`/`directConnection` are load-bearing against a
* real cluster (see audit.documentdb.spec.ts for why each is required).
*
* Through an SSH tunnel, additionally set
* DOCUMENTDB_TLS_ALLOW_INVALID_HOSTNAMES=true
* because the tunnel endpoint will not match the cluster certificate.
*
* Set DOCUMENTDB_EXPECT_PARTIAL_INDEXES=true when targeting DocumentDB 5.0+
* instance-based clusters to turn the partial-index probe into a hard assertion.
*/
const DOCUMENTDB_URI = process.env.DOCUMENTDB_URI ?? '';
const describeLive = DOCUMENTDB_URI ? describe : describe.skip;
const HOUR = 3_600_000;
const runId = randomUUID().slice(0, 8);
const capabilities: Record<string, string> = {};
function getDb() {
const db = mongoose.connection.db;
if (!db) {
throw new Error('MongoDB database handle not available');
}
return db;
}
describeLive('Amazon DocumentDB live compatibility', () => {
let User: Model<t.IUser>;
let ConversationTag: Model<IConversationTag>;
let userMethods: ReturnType<typeof createUserMethods>;
let fileMethods: ReturnType<typeof createFileMethods>;
const testEmail = (label: string) => `${label}-${runId}@compat.test`;
beforeAll(async () => {
const options: ConnectOptions = { autoIndex: false, autoCreate: false };
if (process.env.DOCUMENTDB_TLS_CA_FILE) {
options.tlsCAFile = process.env.DOCUMENTDB_TLS_CA_FILE;
}
if (process.env.DOCUMENTDB_TLS_ALLOW_INVALID_HOSTNAMES === 'true') {
options.tlsAllowInvalidHostnames = true;
}
await mongoose.connect(DOCUMENTDB_URI, options);
const models = createModels(mongoose);
Object.assign(mongoose.models, models);
User = mongoose.models.User;
ConversationTag = mongoose.models.ConversationTag;
userMethods = createUserMethods(mongoose);
fileMethods = createFileMethods(mongoose);
});
afterAll(async () => {
if (mongoose.connection.readyState === 1) {
await User.deleteMany({ email: { $regex: runId } });
await ConversationTag.deleteMany({ tag: { $regex: runId } });
await mongoose.models.File.deleteMany({ filename: { $regex: runId } });
const rows = Object.entries(capabilities).map(
([capability, verdict]) => ` ${capability.padEnd(36)} ${verdict}`,
);
console.log(`\nDocumentDB capability matrix (run ${runId}):\n${rows.join('\n')}\n`);
await mongoose.disconnect();
}
});
describe('pipeline-form updates (bug class behind #14488)', () => {
it('records whether the engine accepts pipeline updates and $$NOW', async () => {
const probe = getDb().collection(`pipeline_probe_${runId}`);
await probe.insertOne({ probe: 1 });
capabilities['pipeline-form updateOne'] = await probe
.updateOne({ probe: 1 }, [{ $set: { probed: true } }])
.then(() => 'supported')
.catch((error: Error) => `rejected (${error.message})`);
capabilities['$$NOW system variable'] = await probe
.updateOne({ probe: 1 }, [{ $set: { probedAt: '$$NOW' } }])
.then(() => 'supported')
.catch((error: Error) => `rejected (${error.message})`);
await probe.drop().catch(() => undefined);
expect(capabilities['pipeline-form updateOne']).toBeDefined();
});
it('acceptTerms stamps once and preserves the first timestamp', async () => {
const user = await User.create({
name: 'DocDB Terms',
email: testEmail('terms'),
provider: 'local',
});
const userId = String(user._id);
const first = await userMethods.acceptTerms(userId);
expect(first?.termsAccepted).toBe(true);
expect(first?.termsAcceptedAt).toBeInstanceOf(Date);
const repeat = await userMethods.acceptTerms(userId);
expect((repeat?.termsAcceptedAt as Date).getTime()).toBe(
(first?.termsAcceptedAt as Date).getTime(),
);
});
it('acceptTerms converges under concurrent requests', async () => {
const user = await User.create({
name: 'DocDB Concurrent',
email: testEmail('concurrent'),
provider: 'local',
});
const userId = String(user._id);
const results = await Promise.all(
Array.from({ length: 5 }, () => userMethods.acceptTerms(userId)),
);
expect(results.every((result) => result?.termsAccepted === true)).toBe(true);
const stamped = new Set(results.map((result) => (result?.termsAcceptedAt as Date).getTime()));
expect(stamped.size).toBe(1);
});
it('decrementTagCounts clamps at zero', async () => {
const user = `docdb-user-${runId}`;
const tag = `tag-${runId}`;
await ConversationTag.create({ user, tag, position: 1, count: 1 });
await decrementTagCounts(mongoose, user, [tag, tag, tag]);
const stored = await ConversationTag.findOne({ user, tag }).lean();
expect(stored?.count).toBe(0);
});
it('extendFilesTTL widens toward the window and clamps to the ceiling', async () => {
const userId = new mongoose.Types.ObjectId();
const fileId = randomUUID();
await fileMethods.createFile({
file_id: fileId,
user: userId,
filename: `${fileId}-${runId}.txt`,
filepath: `/uploads/${fileId}.txt`,
type: 'text/plain',
bytes: 1,
});
await mongoose.models.File.updateOne(
{ file_id: fileId },
{ $set: { expiresAt: new Date(Date.now() + 60_000) } },
{ timestamps: false },
);
const hold = { renewMs: 24 * HOUR, maxLifetimeMs: 48 * HOUR };
const widened = await fileMethods.extendFilesTTL([fileId], hold, { user: String(userId) });
expect(widened).toBe(1);
const stored = await mongoose.models.File.findOne({ file_id: fileId }).lean<{
createdAt: Date;
expiresAt?: Date;
}>();
expect(stored?.expiresAt).toBeDefined();
expect(stored!.expiresAt!.getTime()).toBeGreaterThan(Date.now() + 23 * HOUR);
expect(stored!.expiresAt!.getTime()).toBeLessThanOrEqual(
stored!.createdAt.getTime() + hold.maxLifetimeMs,
);
});
});
describe('capability probes (informational)', () => {
it('probes multi-document transaction support', async () => {
const supported = await supportsTransactions(mongoose);
capabilities['multi-document transactions'] = supported
? 'supported'
: 'unsupported (runtime fallback engages)';
expect(typeof supported).toBe('boolean');
});
it('executes the bounded MCP authority snapshot transaction', async () => {
const tenantId = `authority-tenant-${runId}`;
const roleName = `AUTHORITY_${runId}`;
const serverName = `authority-server-${runId}`;
const models = mongoose.models;
const methods = createMCPAuthorityMethods(mongoose);
const boot = createMCPAuthorityBootRevision(`docdb-${runId}`, { mcpServers: {} });
const userId = new mongoose.Types.ObjectId();
const serverId = new mongoose.Types.ObjectId();
const agentIds = Array.from({ length: 3 }, () => new mongoose.Types.ObjectId());
try {
await tenantStorage.run({ tenantId, userId: userId.toHexString() }, async () => {
await models.User.create({
_id: userId,
name: 'DocumentDB authority probe',
email: testEmail('authority'),
provider: 'local',
role: roleName,
});
await models.Role.create({
name: roleName,
permissions: {
[PermissionTypes.MCP_SERVERS]: { [Permissions.USE]: true },
},
});
await models.Config.create({
principalType: PrincipalType.USER,
principalId: userId.toHexString(),
principalModel: PrincipalModel.USER,
priority: 30,
overrides: { mcpSettings: { allowedDomains: ['example.com'] } },
tombstones: ['mcpSettings.autoStart'],
isActive: true,
configVersion: 1,
});
await models.MCPServer.create({
_id: serverId,
serverName,
config: { type: 'sse', url: `https://${serverName}.example/mcp` },
author: userId,
});
await models.Agent.insertMany(
agentIds.map((agentId, index) => ({
_id: agentId,
id: `authority-agent-${runId}-${index}`,
name: `DocumentDB authority probe agent ${index}`,
provider: 'openAI',
model: 'probe-model',
author: userId,
mcpServerNames: [serverName, `unselected-${runId}`],
})),
);
await models.AclEntry.create({
principalType: PrincipalType.USER,
principalId: userId,
principalModel: PrincipalModel.USER,
resourceType: ResourceType.MCPSERVER,
resourceId: serverId,
permBits: PermissionBits.VIEW,
grantedBy: userId,
});
/** The proof transaction READS PluginAuth and Token. On a database
* where they do not exist yet, DocumentDB rejects the in-transaction
* read of a non-existent collection and `asMCPError` reports it as
* `proof_unavailable` — which is why this test failed on every live
* cluster run while passing against MongoDB. Materialize both
* before the transaction. */
await models.PluginAuth.createCollection();
await models.Token.createCollection();
await models.Group.createCollection();
const server = await models.MCPServer.findById(serverId).lean();
if (!server) {
throw new Error('DocumentDB authority probe server was not created');
}
const sourceRevision = createMCPAuthorityDatabaseSourceRevision({
databaseId: server._id.toHexString(),
serverName: server.serverName,
author: server.author.toString(),
config: server.config,
createdAt: server.createdAt,
updatedAt: server.updatedAt,
});
const proof = await methods.resolveMCPAuthorityProof({
userId: userId.toHexString(),
tenantId,
boot,
targets: [
{
serverName,
source: 'database',
databaseId: serverId.toHexString(),
sourceRevision,
expectedCredentialRevision: createMCPAuthorityCredentialRevision([], []),
expectedOAuthGrantGeneration: null,
resolvedConfig: server.config,
},
],
});
expect(proof.servers[0].linkedAgentIds).toHaveLength(agentIds.length);
await methods.assertMCPAuthorityProofsCurrent({ proofs: proof, boot });
});
capabilities['MCP authority snapshot'] = 'supported';
} finally {
await Promise.all([
getDb().collection('aclentries').deleteMany({ resourceId: serverId }),
getDb().collection('mcpservers').deleteMany({ _id: serverId }),
getDb().collection('configs').deleteMany({ principalId: userId.toHexString() }),
getDb()
.collection('agents')
.deleteMany({ _id: { $in: agentIds } }),
getDb().collection('roles').deleteMany({ name: roleName }),
getDb().collection('users').deleteMany({ _id: userId }),
]);
}
});
it('probes partial unique index support (OAuth id uniqueness relies on it)', async () => {
const probe = getDb().collection(`partial_index_probe_${runId}`);
await probe.insertOne({ seeded: true });
const outcome = await probe
.createIndex(
{ googleId: 1, tenantId: 1 },
{ unique: true, partialFilterExpression: { googleId: { $exists: true } } },
)
.then(() => 'supported')
.catch((error: Error) => `REJECTED (${error.message})`);
capabilities['partial unique indexes'] = outcome;
await probe.drop().catch(() => undefined);
if (process.env.DOCUMENTDB_EXPECT_PARTIAL_INDEXES === 'true') {
expect(outcome).toBe('supported');
}
});
it('verifies TTL index support (session/token expiry relies on it)', async () => {
const probe = getDb().collection(`ttl_probe_${runId}`);
await probe.insertOne({ createdAt: new Date() });
await expect(
probe.createIndex({ createdAt: 1 }, { expireAfterSeconds: 60 }),
).resolves.toBeDefined();
capabilities['TTL indexes'] = 'supported';
await probe.drop().catch(() => undefined);
});
it('flags a connection string missing retryWrites=false', () => {
const disabled = /retryWrites=false/i.test(DOCUMENTDB_URI);
capabilities['retryWrites=false in URI'] = disabled
? 'present'
: 'MISSING — DocumentDB rejects retryable writes';
expect(typeof disabled).toBe('boolean');
});
});
/**
* The scheduler's rewritten write shapes (classic operators, worker clock — the
* DocumentDB-portable replacements for its original pipeline/$$NOW CAS forms),
* exercised through the real methods against the live engine.
*/
describe('scheduler write shapes', () => {
const scheduleMethods = () => createScheduleMethods(mongoose);
const scheduleData = (overrides: Record<string, unknown> = {}) => ({
id: `sched_compat_${runId}_${randomUUID().slice(0, 8)}`,
user: new mongoose.Types.ObjectId(),
name: `compat ${runId}`,
prompt: 'compat probe',
agent_id: 'agent_compat',
cadence: { frequency: 'daily', hour: 8, minute: 0 },
timezone: 'America/New_York',
target: 'new',
enabled: true,
nextRunAt: new Date(Date.now() - 60_000),
...overrides,
});
afterAll(async () => {
await mongoose.models.Schedule.deleteMany({ name: `compat ${runId}` });
await mongoose.models.ScheduleRun.deleteMany({ scheduleId: { $regex: runId } });
});
it('claims a due schedule via the classic-operator lease CAS', async () => {
const methods = scheduleMethods();
const schedule = await methods.createSchedule(scheduleData() as never);
const claimed = await methods.claimDueSchedule({
instanceId: `compat-${runId}`,
leaseMs: 60_000,
});
expect(claimed?.leaseUntil).toBeInstanceOf(Date);
// Held lease: a second claim must not steal it.
const contender = await methods.claimDueSchedule({
instanceId: `compat2-${runId}`,
leaseMs: 60_000,
});
expect(contender?.id).not.toBe(schedule.id);
capabilities['scheduler lease CAS'] = 'supported';
});
it('stamps and resolves an abort request with guarded classic updates', async () => {
const methods = scheduleMethods();
const schedule = await methods.createSchedule(scheduleData() as never);
const scheduledFor = new Date('2026-07-20T12:00:00Z');
await mongoose.models.ScheduleRun.create({
scheduleId: schedule.id,
user: schedule.user,
scheduledFor,
status: 'started',
firedAt: new Date(),
});
expect(await methods.requestRunAbort(schedule.id, scheduledFor, 'stop')).toBe(true);
await methods.markRunAbortPersisted(schedule.id, scheduledFor);
const state = await methods.getScheduleRunAbortState(schedule.id, scheduledFor);
expect(state?.abortSource).toBe('stop');
expect(state?.abortPersistedAt).toBeInstanceOf(Date);
capabilities['scheduler abort stamps'] = 'supported';
});
it('arms only an unarmed row through the shared arming CAS', async () => {
const methods = scheduleMethods();
const schedule = await methods.createSchedule(
scheduleData({ nextRunAt: undefined }) as never,
);
const armAt = new Date(Date.now() + HOUR);
expect(await methods.armSchedule(schedule.id, armAt, 0)).toBe(true);
expect(await methods.armSchedule(schedule.id, new Date(Date.now() + 2 * HOUR), 0)).toBe(
false,
);
capabilities['scheduler arming CAS'] = 'supported';
});
});
});