@tnunamak/dalan 0.8.5 → 0.9.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/CHANGELOG.md +9 -0
- package/bin/dot-acp-agent.mjs +197 -43
- package/bin/dot-worker.mjs +75 -11
- package/docs/design/target-architecture-v2.md +1 -0
- package/docs/t3-integration.md +6 -0
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +20 -2
- package/package.json +1 -1
- package/src/acp-bridge.mjs +80 -15
- package/src/host-execution-policy.mjs +1 -1
- package/src/inbox.mjs +44 -2
- package/src/patch-apply.mjs +125 -42
- package/src/server.mjs +196 -46
- package/src/store.mjs +371 -68
- package/src/submission-policy.mjs +59 -8
- package/src/tool-registry.mjs +6 -0
- package/src/workspace.mjs +92 -5
package/src/store.mjs
CHANGED
|
@@ -69,6 +69,7 @@ function waiterOwnerGone(attemptId) {
|
|
|
69
69
|
}
|
|
70
70
|
|
|
71
71
|
const SUPPORTED_SCHEMA_VERSION = 75;
|
|
72
|
+
const ADMISSION_RESERVATION_MS = 15_000;
|
|
72
73
|
const monotonicMs=()=>Number(process.hrtime.bigint())/1e6;
|
|
73
74
|
function systemBootId() {
|
|
74
75
|
if(process.platform!=='linux') return null;
|
|
@@ -125,6 +126,11 @@ export function nonterminalOutcome(id,receipt) {
|
|
|
125
126
|
}
|
|
126
127
|
const stamp = () => new Date().toISOString();
|
|
127
128
|
const hash = value => createHash('sha256').update(value).digest('hex');
|
|
129
|
+
const FACADE_GRACE_MS = 2000;
|
|
130
|
+
const FACADE_PENDING_GRACE_TTL = 24 * 60 * 60 * 1000;
|
|
131
|
+
class FacadeFinishCutoff extends Error {
|
|
132
|
+
constructor(at) { super('facade withdrawal won'); this.at=at; }
|
|
133
|
+
}
|
|
128
134
|
function validateSubmitKey(key) {
|
|
129
135
|
if(key!==null&&(typeof key!=='string'||key.length<1||key.length>128)) throw new Error('invalid command_key: use a nonempty string of at most 128 characters');
|
|
130
136
|
}
|
|
@@ -388,6 +394,7 @@ export class Store {
|
|
|
388
394
|
this.resumeIdleOption=options.resumeIdleMs;
|
|
389
395
|
this.workers=options.workers??LEGACY_PROFILE;
|
|
390
396
|
this.destinationProfile=options.destinationProfile??null;
|
|
397
|
+
this.admissionOpen=options.admissionOpen??(()=>true);
|
|
391
398
|
// Server-side diagnostic only: receives the raw configuration error that destinationConfigurationError hides from callers.
|
|
392
399
|
this.onConfigError=options.onConfigError??null;
|
|
393
400
|
this.allowedDotSubjects=options.allowedDotSubjects??null;
|
|
@@ -1128,6 +1135,32 @@ export class Store {
|
|
|
1128
1135
|
prior_id TEXT NOT NULL REFERENCES assignments(request_id),
|
|
1129
1136
|
at TEXT NOT NULL
|
|
1130
1137
|
); PRAGMA user_version=75;`);
|
|
1138
|
+
// Older bridges read every open row of worker_breaks as a primary-worker hold.
|
|
1139
|
+
// Keep secondary-worker holds out of that table so a rollback can still read current data.
|
|
1140
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS scoped_worker_breaks(
|
|
1141
|
+
id INTEGER PRIMARY KEY, worker TEXT NOT NULL CHECK(length(worker)>0),
|
|
1142
|
+
since TEXT NOT NULL, reason TEXT NOT NULL, until TEXT, expected_end TEXT,
|
|
1143
|
+
end_source TEXT, last_probe_at TEXT
|
|
1144
|
+
); CREATE UNIQUE INDEX IF NOT EXISTS scoped_worker_breaks_one_open
|
|
1145
|
+
ON scoped_worker_breaks(worker) WHERE until IS NULL;`);
|
|
1146
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS admission_reservations(
|
|
1147
|
+
worker TEXT PRIMARY KEY, request_id TEXT NOT NULL UNIQUE REFERENCES assignments(request_id) ON DELETE CASCADE,
|
|
1148
|
+
subscription_id TEXT NOT NULL, issued_at TEXT NOT NULL, expires_at TEXT NOT NULL,
|
|
1149
|
+
boot_id TEXT, monotonic_deadline_ms REAL
|
|
1150
|
+
);`);
|
|
1151
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS facade_withdrawals(
|
|
1152
|
+
request_id TEXT PRIMARY KEY REFERENCES assignments(request_id) ON DELETE CASCADE,
|
|
1153
|
+
intent TEXT NOT NULL, due_ms INTEGER NOT NULL
|
|
1154
|
+
); CREATE INDEX IF NOT EXISTS facade_withdrawals_due ON facade_withdrawals(due_ms);
|
|
1155
|
+
CREATE TABLE IF NOT EXISTS facade_withdrawal_keeps(
|
|
1156
|
+
request_id TEXT REFERENCES assignments(request_id) ON DELETE CASCADE,
|
|
1157
|
+
intent TEXT NOT NULL, due_ms INTEGER NOT NULL, PRIMARY KEY(request_id,intent)
|
|
1158
|
+
) WITHOUT ROWID;
|
|
1159
|
+
CREATE TABLE IF NOT EXISTS facade_withdrawal_admissions(
|
|
1160
|
+
request_id TEXT NOT NULL, owner_hash TEXT NOT NULL, intent TEXT NOT NULL,
|
|
1161
|
+
due_ms INTEGER NOT NULL, expires_ms INTEGER NOT NULL, kept INTEGER NOT NULL DEFAULT 0,
|
|
1162
|
+
PRIMARY KEY(request_id,owner_hash)
|
|
1163
|
+
) WITHOUT ROWID;`);
|
|
1131
1164
|
// Worker run receipts (D9), hosted-session lifetimes (D14) and the publication grant on a relationship (D10).
|
|
1132
1165
|
// Additive and idempotent, so it needs no schema number: older code ignores these tables and column.
|
|
1133
1166
|
{
|
|
@@ -1352,7 +1385,15 @@ export class Store {
|
|
|
1352
1385
|
admissionForQueuedRequest(requestId) {
|
|
1353
1386
|
const row=this.db.prepare(`SELECT a.target_worker,a.priority,${queueKindSql} AS kind
|
|
1354
1387
|
FROM assignments a WHERE a.request_id=? AND a.status='queued'`).get(requestId);
|
|
1355
|
-
|
|
1388
|
+
if(!row) return null;
|
|
1389
|
+
const admission=this.admissionAnswer(row.target_worker,row.kind,row.priority,{excludeIds:[requestId]});
|
|
1390
|
+
const reservation=this.admissionReservation(row.target_worker);
|
|
1391
|
+
if(!this.admissionOpen()||reservation?.request_id!==requestId||admission.worker_state!=='live'||
|
|
1392
|
+
this.capacityHoldUntil(row.target_worker)||
|
|
1393
|
+
this.db.prepare('SELECT 1 FROM facade_withdrawals WHERE request_id=?').get(requestId)) return admission;
|
|
1394
|
+
const sub=this.db.prepare('SELECT * FROM subscriptions WHERE id=?').get(reservation.subscription_id);
|
|
1395
|
+
if(!sub||this.subscriptionFreeLanes(sub,undefined,undefined,requestId)<=0) return admission;
|
|
1396
|
+
return {...admission,start:'now',ahead:{count:0,oldest_age_ms:null},reserved_until:reservation.expires_at};
|
|
1356
1397
|
}
|
|
1357
1398
|
// Reuse the worker's list tuple. A prospective row is unskipped and comes last among rows at its timestamp.
|
|
1358
1399
|
admissionAnswer(worker,kind,priority,{excludeIds=[],createdBefore=null,callerWaiting=false}={}) {
|
|
@@ -1364,18 +1405,62 @@ export class Store {
|
|
|
1364
1405
|
const rankSkipped=anchor?.skipped_at!=null?1:0;
|
|
1365
1406
|
const rankCreated=anchor?.created_at??createdBefore??at;
|
|
1366
1407
|
const rankRow=anchor?.queue_rowid??'9223372036854775807';
|
|
1367
|
-
const
|
|
1408
|
+
const aheadRows=this.db.prepare(`SELECT request_id,created_at,
|
|
1409
|
+
EXISTS(SELECT 1 FROM destination_blocks b WHERE b.request_id=assignments.request_id) blocked FROM assignments
|
|
1368
1410
|
WHERE status='queued' AND target_worker=? AND request_id IS NOT ? AND request_id IS NOT ? AND ${live(now)}
|
|
1411
|
+
AND NOT EXISTS(SELECT 1 FROM facade_withdrawals f WHERE f.request_id=assignments.request_id)
|
|
1369
1412
|
AND (${LIST_ORDER}) < (?, ?, ?, CAST(? AS INTEGER))`)
|
|
1370
|
-
.
|
|
1371
|
-
const
|
|
1413
|
+
.all(worker,first,second,rankPriority,rankSkipped,rankCreated,rankRow);
|
|
1414
|
+
const blocked=this.destinationBlockRecheck();
|
|
1415
|
+
let count=0, oldest=null;
|
|
1416
|
+
for(const row of aheadRows) {
|
|
1417
|
+
if(row.blocked&&blocked(row.request_id)) continue;
|
|
1418
|
+
count++;
|
|
1419
|
+
if(oldest===null||row.created_at<oldest) oldest=row.created_at;
|
|
1420
|
+
}
|
|
1421
|
+
const workerBreak=this.holdingBreak(worker);
|
|
1372
1422
|
const worker_state=this.paused()?'paused':workerBreak?'break':
|
|
1373
1423
|
this.activeSubscriptions().some(sub=>sub.worker===worker)?'live':'no_live_subscription';
|
|
1374
1424
|
const track_record=this.trackRecord(worker,kind);
|
|
1375
|
-
//
|
|
1425
|
+
// A forecast is always advisory. Only an owned, current reservation can upgrade it.
|
|
1376
1426
|
return {start:'queued',ahead:{count,oldest_age_ms:oldest===null?null:Math.max(0,now-Date.parse(oldest))},
|
|
1377
1427
|
latency:this.admissionEvidence(worker,kind),track_record,claim_to_report:track_record.claim_to_report,session_length:track_record.session_length,worker_state,...(worker_state==='break'?this.breakForecast(workerBreak.id,now):{}),at};
|
|
1378
1428
|
}
|
|
1429
|
+
admissionSubscriptionReady(sub) {
|
|
1430
|
+
return this.subscriptionActive(sub)&&sub.auth_failures<3&&!sub.rotation_blocked;
|
|
1431
|
+
}
|
|
1432
|
+
admissionReservation(worker) {
|
|
1433
|
+
const now=this.stamp();
|
|
1434
|
+
const reservation=this.db.prepare(`SELECT r.* FROM admission_reservations r JOIN assignments a USING(request_id)
|
|
1435
|
+
WHERE r.worker=? AND a.target_worker=r.worker AND a.status='queued'
|
|
1436
|
+
AND r.issued_at<=? AND r.expires_at>? AND ${live(this.nowMs())}`).get(worker,now,now);
|
|
1437
|
+
if(!reservation||reservation.boot_id!==this.leaseBootId) return null;
|
|
1438
|
+
if(reservation.boot_id!==null&&!(reservation.monotonic_deadline_ms>this.monotonicNow())) return null;
|
|
1439
|
+
const sub=this.db.prepare('SELECT * FROM subscriptions WHERE id=?').get(reservation.subscription_id);
|
|
1440
|
+
return this.admissionSubscriptionReady(sub)?reservation:null;
|
|
1441
|
+
}
|
|
1442
|
+
reserveAdmissionLane(id,worker) {
|
|
1443
|
+
if(!this.db.isTransaction)protocolError('transaction_required');
|
|
1444
|
+
if(!this.admissionOpen()||this.workers.laneScope!=='worker'||this.paused()||this.holdingBreak(worker)||this.capacityHoldUntil(worker)||
|
|
1445
|
+
this.admissionReservation(worker)) return;
|
|
1446
|
+
const hint=this.claimHint(worker);
|
|
1447
|
+
if(hint!==null&&this.recentClaimCount(worker)>=hint) return;
|
|
1448
|
+
const sub=this.activeSubscriptions().find(candidate=>candidate.worker===worker&&this.admissionSubscriptionReady(candidate)&&
|
|
1449
|
+
this.subscriptionFreeLanes(candidate)>0);
|
|
1450
|
+
if(!sub) return;
|
|
1451
|
+
const first=this.listPending(worker).find(item=>item.kind==='assignment'&&!item.blocked&&!item.resume);
|
|
1452
|
+
if(first?.request_id!==id||this.destinationAdmissionInTransaction(id)) return;
|
|
1453
|
+
try { this.assertClaimGap(id,sub.principal,worker); }
|
|
1454
|
+
catch(error) { if(error.message.startsWith('claim_throttled:')) return; throw error; }
|
|
1455
|
+
const now=this.nowMs(), expires=Math.min(now+ADMISSION_RESERVATION_MS,Date.parse(sub.expires_at));
|
|
1456
|
+
if(expires<=now) return;
|
|
1457
|
+
this.db.prepare(`INSERT INTO admission_reservations
|
|
1458
|
+
(worker,request_id,subscription_id,issued_at,expires_at,boot_id,monotonic_deadline_ms) VALUES(?,?,?,?,?,?,?)
|
|
1459
|
+
ON CONFLICT(worker) DO UPDATE SET
|
|
1460
|
+
request_id=excluded.request_id,subscription_id=excluded.subscription_id,issued_at=excluded.issued_at,
|
|
1461
|
+
expires_at=excluded.expires_at,boot_id=excluded.boot_id,monotonic_deadline_ms=excluded.monotonic_deadline_ms`)
|
|
1462
|
+
.run(worker,id,sub.id,iso(now),iso(expires),this.leaseBootId,this.monotonicDeadlineFor(expires));
|
|
1463
|
+
}
|
|
1379
1464
|
// D14: a hosted worker's own account of one session. A later job in the same session only extends it.
|
|
1380
1465
|
recordWorkerSession(worker,subject,session) {
|
|
1381
1466
|
if(!session) return;
|
|
@@ -1566,15 +1651,22 @@ export class Store {
|
|
|
1566
1651
|
if(targetId===payload.request_id) throw new Error('supersede_cycle');
|
|
1567
1652
|
// A correction proves the prior owner's capability. Withdrawal is a separate, keyed opt-in.
|
|
1568
1653
|
if(revises!==null) {
|
|
1569
|
-
if(!revises||typeof revises!=='object'||Array.isArray(revises)||Object.keys(revises).some(k=>!['prior_id','prior_token','withdraw_prior'].includes(k))||
|
|
1570
|
-
typeof revises.prior_id!=='string'||!/^[-\w]{8,128}$/.test(revises.prior_id)||typeof revises.prior_token!=='string') throw new Error('invalid revises: use {prior_id, prior_token, withdraw_prior?}');
|
|
1654
|
+
if(!revises||typeof revises!=='object'||Array.isArray(revises)||Object.keys(revises).some(k=>!['prior_id','prior_token','withdraw_prior','require_active_prior'].includes(k))||
|
|
1655
|
+
typeof revises.prior_id!=='string'||!/^[-\w]{8,128}$/.test(revises.prior_id)||typeof revises.prior_token!=='string') throw new Error('invalid revises: use {prior_id, prior_token, withdraw_prior?, require_active_prior?}');
|
|
1571
1656
|
if(Object.hasOwn(revises,'withdraw_prior')&&revises.withdraw_prior!==true) throw new Error('withdraw_prior must be true when supplied');
|
|
1657
|
+
if(Object.hasOwn(revises,'require_active_prior')&&(revises.require_active_prior!==true||!revises.withdraw_prior)) throw new Error('require_active_prior requires withdraw_prior and must be true when supplied');
|
|
1572
1658
|
if(revises.withdraw_prior&&commandKey===null) throw new Error('withdraw_prior requires command_key');
|
|
1573
1659
|
if(supersedes) throw new Error('revises_and_supersedes: a correction does not cancel its prior job; send one of them');
|
|
1574
1660
|
if(revises.prior_id===payload.request_id) throw new Error('revises_cycle');
|
|
1575
1661
|
const prior=this.db.prepare('SELECT revision,status FROM assignments WHERE request_id=?').get(revises.prior_id);
|
|
1576
1662
|
if(!prior) throw new Error('revises_prior_not_found');
|
|
1577
1663
|
this.owner(revises.prior_id,revises.prior_token);
|
|
1664
|
+
if(!old&&revises.require_active_prior) {
|
|
1665
|
+
const active=this.db.prepare(`SELECT 1 FROM assignments WHERE request_id=? AND target_worker=? AND status IN ('queued','claimed')
|
|
1666
|
+
AND ${live(this.nowMs())} AND NOT EXISTS(SELECT 1 FROM facade_withdrawals f WHERE f.request_id=assignments.request_id)`)
|
|
1667
|
+
.get(revises.prior_id,targetWorker??'dot');
|
|
1668
|
+
if(!active) throw new Error('revises_prior_not_active: the prior job no longer waits for this worker');
|
|
1669
|
+
}
|
|
1578
1670
|
if(!old&&revises.withdraw_prior&&['queued','claimed'].includes(prior.status)&&this.isProtocolJob(revises.prior_id))
|
|
1579
1671
|
throw new Error('withdraw_prior requires the protocol cancellation path for this prior job');
|
|
1580
1672
|
// The same revision under another request_id is a duplicate in the metrics, not a correction.
|
|
@@ -1628,7 +1720,7 @@ export class Store {
|
|
|
1628
1720
|
if(!command||command.key_digest!==hash(commandKey)) throw new Error('EXISTS: assignment already submitted under another command');
|
|
1629
1721
|
const intent=submitIntentDigest(identity,deliveryValue,environmentId,review,priority,m,targetWorker??old.target_worker,execution??old.execution,requiredCapabilities,destinationRevision,this.legacyFixNames);
|
|
1630
1722
|
const receipt=JSON.parse(command.receipt);
|
|
1631
|
-
if((previous?.target_id??null)!==targetId||(previousRevision?.prior_id??null)!==priorId||(previousFollow?.prior_id??null)!==followsId||!!receipt.withdraw_prior!==!!revises?.withdraw_prior||command.owner_hash!==ownerHash||command.intent_digest!==intent) throw new Error('KEY_CONFLICT: command intent changed');
|
|
1723
|
+
if((previous?.target_id??null)!==targetId||(previousRevision?.prior_id??null)!==priorId||(previousFollow?.prior_id??null)!==followsId||!!receipt.withdraw_prior!==!!revises?.withdraw_prior||!!receipt.require_active_prior!==!!revises?.require_active_prior||command.owner_hash!==ownerHash||command.intent_digest!==intent) throw new Error('KEY_CONFLICT: command intent changed');
|
|
1632
1724
|
return {...receipt,duplicate:true,...(approval?{destination_approval:approval}:{})};
|
|
1633
1725
|
}
|
|
1634
1726
|
if(command) throw new Error('EXISTS: command_key required to retry this assignment');
|
|
@@ -1711,7 +1803,7 @@ export class Store {
|
|
|
1711
1803
|
if(relationship) this.db.prepare('UPDATE assignments SET relationship_id=? WHERE request_id=?').run(relationship.relationship_id,id);
|
|
1712
1804
|
if(disclosure)this.db.prepare('INSERT INTO destination_approvals(request_id,revision,snapshot,actor,approved_at) VALUES(?,?,?,?,?)').run(id,disclosure.revision,JSON.stringify(disclosure),JSON.stringify({kind:'owner_capability',id:ownerHash}),this.stamp());
|
|
1713
1805
|
const requestedValidUntil=validUntilOf(payload);
|
|
1714
|
-
const mayUseDefault=priority==='normal'&&!this.paused()&&!(
|
|
1806
|
+
const mayUseDefault=priority==='normal'&&!this.paused()&&!this.holdingBreak(targetWorker??'dot');
|
|
1715
1807
|
const effectiveValidUntil=requestedValidUntil??(mayUseDefault&&typeof defaultValidUntil==='string'?defaultValidUntil:null);
|
|
1716
1808
|
this.db.prepare('UPDATE assignments SET valid_until=?,valid_until_source=? WHERE request_id=?').run(effectiveValidUntil,requestedValidUntil?'requester':effectiveValidUntil?'queue_p90':null,id);
|
|
1717
1809
|
this.recordPrPreflight(id,'submit',payload,preflight);
|
|
@@ -1738,8 +1830,21 @@ export class Store {
|
|
|
1738
1830
|
}
|
|
1739
1831
|
}
|
|
1740
1832
|
if(follows) this.db.prepare('INSERT INTO job_follows(request_id,prior_id,at) VALUES(?,?,?)').run(id,follows.prior_id,this.stamp());
|
|
1741
|
-
|
|
1742
|
-
|
|
1833
|
+
const waitingWithdrawal=this.db.prepare(`DELETE FROM facade_withdrawal_admissions WHERE request_id=? AND owner_hash=?
|
|
1834
|
+
RETURNING intent,due_ms,expires_ms,kept`).get(id,ownerHash);
|
|
1835
|
+
let status='queued';
|
|
1836
|
+
if(waitingWithdrawal && waitingWithdrawal.expires_ms>this.nowMs()) {
|
|
1837
|
+
if(waitingWithdrawal.kept) this.db.prepare('INSERT INTO facade_withdrawal_keeps(request_id,intent,due_ms) VALUES(?,?,?)').run(id,waitingWithdrawal.intent,waitingWithdrawal.due_ms);
|
|
1838
|
+
else {
|
|
1839
|
+
this.db.prepare('INSERT INTO facade_withdrawals(request_id,intent,due_ms) VALUES(?,?,?)').run(id,waitingWithdrawal.intent,waitingWithdrawal.due_ms);
|
|
1840
|
+
if(this.applyFacadeWithdrawalInTransaction(id)) status='cancelled';
|
|
1841
|
+
}
|
|
1842
|
+
}
|
|
1843
|
+
if(status==='queued') {
|
|
1844
|
+
if(callerWaiting===true&&priority==='normal'&&!protocol&&!inheritedOwnerHash) this.reserveAdmissionLane(id,targetWorker??'dot');
|
|
1845
|
+
for (const sub of this.activeSubscriptions()) this.submitWake(id,sub);
|
|
1846
|
+
}
|
|
1847
|
+
const receipt={request_id:id,status,duplicate:false,...(revises?.withdraw_prior?{withdraw_prior:true}:{}),...(revises?.require_active_prior?{require_active_prior:true}:{}),...(protocol?{revision:this.protocolRevision(id)}:{}),...this.destinationFields(id)};
|
|
1743
1848
|
if(commandKey!==null) {
|
|
1744
1849
|
const intent=submitIntentDigest(identity,deliveryValue,environmentId,review,priority,m,targetWorker??'dot',execution??defaultExecution,requiredCapabilities,destinationRevision,this.legacyFixNames);
|
|
1745
1850
|
this.db.prepare('INSERT INTO owner_submit_commands(request_id,key_digest,intent_digest,receipt,owner_hash) VALUES(?,?,?,?,?)').run(id,hash(commandKey),intent,JSON.stringify(receipt),ownerHash);
|
|
@@ -1857,6 +1962,8 @@ export class Store {
|
|
|
1857
1962
|
if(!this.db.isTransaction)protocolError('transaction_required');
|
|
1858
1963
|
// HTTP authenticates the subject; native admission checks visibility before any receipt lookup.
|
|
1859
1964
|
if(!this.mayAct(worker,id)||typeof subject!=='string'||!subject)throw new Error('assignment not found');
|
|
1965
|
+
if(this.db.prepare("SELECT 1 FROM facade_withdrawals WHERE request_id=? AND EXISTS (SELECT 1 FROM assignments WHERE request_id=? AND status='queued')").get(id,id))
|
|
1966
|
+
throw new Error('assignment withdrawal pending');
|
|
1860
1967
|
this.assertProtocolAvailable(id);
|
|
1861
1968
|
if(!ctx||typeof ctx.key!=='string'||!ctx.key||ctx.key.length>512||!protocolNat(ctx.revision))protocolError('command_context_required');
|
|
1862
1969
|
const command={job:id,subject,worker,operation:'claim',key:ctx.key,expectedRevision:ctx.revision,
|
|
@@ -1904,6 +2011,7 @@ export class Store {
|
|
|
1904
2011
|
subscriptionActive(sub) { return !!sub&&sub.state==='active'&&sub.expires_at>this.stamp()&&this.subscriptionVisible(sub); }
|
|
1905
2012
|
suppressSubscriptionRows(ids,reason) {
|
|
1906
2013
|
for(const id of ids) {
|
|
2014
|
+
this.releaseSubscriptionReservation(id);
|
|
1907
2015
|
this.db.prepare("UPDATE subscriptions SET state='revoked' WHERE id=?").run(id);
|
|
1908
2016
|
this.db.prepare("UPDATE notifications SET state='suppressed',last_error=? WHERE subscription_id=? AND state IN ('pending','failed')").run(reason,id);
|
|
1909
2017
|
}
|
|
@@ -1937,8 +2045,13 @@ export class Store {
|
|
|
1937
2045
|
activeClaims(subject,worker,exceptId=null) {
|
|
1938
2046
|
return this.db.prepare("SELECT c.* FROM claims c JOIN assignments a USING(request_id) WHERE a.status='claimed' AND c.state='active' AND c.worker=? AND (c.lane_scope='worker' OR c.lane_key=?) AND c.request_id IS NOT ?").all(worker,subject,exceptId);
|
|
1939
2047
|
}
|
|
1940
|
-
subscriptionFreeLanes(sub,laneCapacity=this.limits.laneCapacity??6,claimCapacity=this.capacity) {
|
|
1941
|
-
|
|
2048
|
+
subscriptionFreeLanes(sub,laneCapacity=this.limits.laneCapacity??6,claimCapacity=this.capacity,requestId=null) {
|
|
2049
|
+
const reserved=this.admissionReservation(sub.worker);
|
|
2050
|
+
const own=reserved&&reserved.subscription_id===sub.id&&reserved.request_id===requestId?requestId:null;
|
|
2051
|
+
return this.freeLanes(sub.principal,sub.worker,laneCapacity,claimCapacity,own);
|
|
2052
|
+
}
|
|
2053
|
+
releaseSubscriptionReservation(id) {
|
|
2054
|
+
if(this.db.prepare('DELETE FROM admission_reservations WHERE subscription_id=?').run(id).changes>0) this.laneFreed();
|
|
1942
2055
|
}
|
|
1943
2056
|
activeSubscriptions() { return this.db.prepare("SELECT * FROM subscriptions WHERE state='active' AND expires_at>?").all(this.stamp()).filter(sub=>this.subscriptionActive(sub)); }
|
|
1944
2057
|
// Text of a wake that names the queue head when several items wait: the worker claims oldest first via list_pending.
|
|
@@ -1969,7 +2082,11 @@ export class Store {
|
|
|
1969
2082
|
return this.db.prepare(`SELECT a.request_id,a.payload,a.priority,a.caller_waiting,a.target_worker,${queuedAt} queued_at FROM assignments a WHERE a.status='queued' AND a.cancelled_at IS NULL AND ${live(this.nowMs())} ORDER BY ${LIST_ORDER}`).all();
|
|
1970
2083
|
}
|
|
1971
2084
|
// Break intervals [since, until or open] in ms. Owner since never reaches back before the previous break's end, so they are disjoint.
|
|
1972
|
-
breakIntervals(
|
|
2085
|
+
breakIntervals(worker='dot') {
|
|
2086
|
+
const rows=worker==='dot'?this.db.prepare('SELECT since,until FROM worker_breaks ORDER BY since').all():
|
|
2087
|
+
this.db.prepare('SELECT since,until FROM scoped_worker_breaks WHERE worker=? ORDER BY since').all(worker);
|
|
2088
|
+
return rows.map(b=>[Date.parse(b.since),b.until?Date.parse(b.until):Infinity]);
|
|
2089
|
+
}
|
|
1973
2090
|
// How long a row has been queued, minus usage-break time: the re-wake window and the unclaimed clock stand still during a break.
|
|
1974
2091
|
queuedAgeMs(queuedAtText,now=this.nowMs(),breaks=this.breakIntervals()) {
|
|
1975
2092
|
const from=Date.parse(queuedAtText);
|
|
@@ -1978,7 +2095,7 @@ export class Store {
|
|
|
1978
2095
|
// Queued assignments that waited longer than the re-wake window, so re-wake no longer names them. Items with an uncertain or
|
|
1979
2096
|
// sending owner delivery are left out: they wait for reconcile, not for the worker. Derived only: a requeue restarts the clock.
|
|
1980
2097
|
unclaimedAfterReannounce(limits=this.limits,worker='dot') {
|
|
1981
|
-
const now=this.nowMs(), windowMs=limits.rewakeWindowMs??defaultRedeliveryLimits.rewakeWindowMs, breaks=
|
|
2098
|
+
const now=this.nowMs(), windowMs=limits.rewakeWindowMs??defaultRedeliveryLimits.rewakeWindowMs, breaks=this.breakIntervals(worker);
|
|
1982
2099
|
const rows=this.db.prepare(`SELECT a.request_id,${queuedAt} queued_at FROM assignments a WHERE a.target_worker=? AND a.status='queued' AND ${live(now)} ORDER BY queued_at`).all(worker).filter(r=>this.queuedAgeMs(r.queued_at,now,breaks)>=windowMs&&!this.uncertainDeliveries(r.request_id));
|
|
1983
2100
|
return {count:rows.length,oldest_age_ms:rows.length?now-Date.parse(rows[0].queued_at):null,request_ids:rows.slice(0,10).map(r=>r.request_id)};
|
|
1984
2101
|
}
|
|
@@ -2035,7 +2152,7 @@ export class Store {
|
|
|
2035
2152
|
ON CONFLICT(worker,subject) DO UPDATE SET last_call_at=excluded.last_call_at,last_list_pending_at=COALESCE(excluded.last_list_pending_at,last_list_pending_at)`).run(worker,subject,at,tool==='list_pending'?at:null);
|
|
2036
2153
|
this.db.prepare('INSERT INTO worker_calls(worker,subject,minute,tool,count,bytes) VALUES(?,?,?,?,1,0) ON CONFLICT(worker,subject,minute,tool) DO UPDATE SET count=count+1').run(worker,subject,Math.floor(this.nowMs()/60000),tool);
|
|
2037
2154
|
// The worker's next authenticated tool call ends an active usage break.
|
|
2038
|
-
|
|
2155
|
+
const active=this.activeBreak(worker); if(active) this.endBreak(active,'tool_call');
|
|
2039
2156
|
}); }
|
|
2040
2157
|
// Bytes of the serialized MCP response to one tool call, added once the response is written (the minute it was written).
|
|
2041
2158
|
recordResponseBytes(subject,tool,bytes,worker='dot') {
|
|
@@ -2127,28 +2244,35 @@ export class Store {
|
|
|
2127
2244
|
if(updated) this.db.prepare('UPDATE worker_breaks SET usage=? WHERE id=?').run(next,id);
|
|
2128
2245
|
return {id,since:row.since,updated,usage_before:usage};
|
|
2129
2246
|
}); }
|
|
2130
|
-
|
|
2131
|
-
|
|
2247
|
+
activeBreak(worker='dot') {
|
|
2248
|
+
if(worker==='dot') return this.db.prepare('SELECT * FROM worker_breaks WHERE until IS NULL').get()??null;
|
|
2249
|
+
return this.db.prepare("SELECT -id id,worker,since,reason,last_probe_at,'owner' source FROM scoped_worker_breaks WHERE worker=? AND until IS NULL").get(worker)??null;
|
|
2250
|
+
}
|
|
2132
2251
|
// The break that holds work: only an owner-confirmed one. An inferred break (silence) is reported and alerted, not held on.
|
|
2133
|
-
holdingBreak() { const b=this.activeBreak(); return b?.source==='owner'?b:null; }
|
|
2252
|
+
holdingBreak(worker='dot') { const b=this.activeBreak(worker); return b?.source==='owner'?b:null; }
|
|
2134
2253
|
// The forecast is an operator observation tied to one break. The break row's
|
|
2135
2254
|
// until remains the time that a worker call or owner clear actually ended it.
|
|
2136
2255
|
breakForecast(id,now=this.nowMs()) {
|
|
2137
|
-
const forecast=this.db.prepare('SELECT
|
|
2256
|
+
const forecast=id<0?this.db.prepare('SELECT expected_end FROM scoped_worker_breaks WHERE id=?').get(-id)?.expected_end:
|
|
2257
|
+
this.db.prepare('SELECT value FROM bridge_state WHERE key=?').get(`break_expected_end:${id}`)?.value;
|
|
2138
2258
|
const until=Date.parse(forecast)>now?forecast:null;
|
|
2139
2259
|
return {until,until_source:until===null?null:'owner_reported'};
|
|
2140
2260
|
}
|
|
2141
|
-
breakState() {
|
|
2142
|
-
const b=this.activeBreak();
|
|
2261
|
+
breakState(worker='dot') {
|
|
2262
|
+
const b=this.activeBreak(worker);
|
|
2143
2263
|
if(!b) return {active:false,since:null,reason:null,source:null,duration_ms:null};
|
|
2144
2264
|
const now=this.nowMs(),forecast=b.source==='owner'?this.breakForecast(b.id,now):null;
|
|
2145
|
-
return {active:true,id:b.id,since:b.since,reason:b.reason,source:b.source,duration_ms:now-Date.parse(b.since),
|
|
2265
|
+
return {active:true,id:b.id,since:b.since,reason:b.reason,source:b.source,duration_ms:now-Date.parse(b.since),...(b.worker?{worker:b.worker}:{}),
|
|
2146
2266
|
last_probe_at:b.last_probe_at,...(forecast?.until?forecast:{})};
|
|
2147
2267
|
}
|
|
2148
2268
|
breaks() {
|
|
2149
2269
|
return this.db.prepare('SELECT * FROM worker_breaks ORDER BY id').all().map(b=>({id:b.id,since:b.since,until:b.until,reason:b.reason,source:b.source,end_source:b.end_source,
|
|
2150
2270
|
duration_ms:(b.until?Date.parse(b.until):this.nowMs())-Date.parse(b.since),usage_before:JSON.parse(b.usage),last_probe_at:b.last_probe_at}));
|
|
2151
2271
|
}
|
|
2272
|
+
scopedBreaks(worker) {
|
|
2273
|
+
return this.db.prepare("SELECT -id id,worker,since,until,reason,'owner' source,end_source,last_probe_at FROM scoped_worker_breaks WHERE worker=? ORDER BY scoped_worker_breaks.id")
|
|
2274
|
+
.all(worker).map(b=>({...b,duration_ms:(b.until?Date.parse(b.until):this.nowMs())-Date.parse(b.since)}));
|
|
2275
|
+
}
|
|
2152
2276
|
startBreak({since,reason,source}) {
|
|
2153
2277
|
const usage=this.usageBefore(Date.parse(since));
|
|
2154
2278
|
const {lastInsertRowid}=this.db.prepare('INSERT INTO worker_breaks(since,reason,source,usage,created_at) VALUES(?,?,?,?,?)').run(since,reason,source,JSON.stringify(usage),this.stamp());
|
|
@@ -2172,14 +2296,22 @@ export class Store {
|
|
|
2172
2296
|
...(learned[name]&&effective[name]<configured[name]?{learned:learned[name].value,break_id:learned[name].break_id}:{})}));
|
|
2173
2297
|
}
|
|
2174
2298
|
// Owner mark. Over an active break (e.g. an inferred one) it takes over: source owner, new reason, since if given, fresh snapshot.
|
|
2175
|
-
setBreak(reason,since=null,until=undefined) { return this.transaction(() => {
|
|
2299
|
+
setBreak(reason,since=null,until=undefined,worker='dot') { return this.transaction(() => {
|
|
2176
2300
|
if(typeof reason!=='string'||!reason.trim()||reason.length>512) throw new Error('invalid reason');
|
|
2177
|
-
const active=this.activeBreak(), now=this.nowMs(), at=since??active?.since??iso(now);
|
|
2301
|
+
const active=this.activeBreak(worker), now=this.nowMs(), at=since??active?.since??iso(now);
|
|
2178
2302
|
if(until!==undefined&&until!==null&&(typeof until!=='string'||!(Date.parse(until)>now)))
|
|
2179
2303
|
throw new Error('until must be in the future');
|
|
2180
2304
|
if(!Number.isFinite(Date.parse(at))||Date.parse(at)>now) throw new Error('since must not be in the future');
|
|
2181
|
-
const ended=this.db.prepare('SELECT max(until) u FROM worker_breaks WHERE until IS NOT NULL').get().u
|
|
2305
|
+
const ended=worker==='dot'?this.db.prepare('SELECT max(until) u FROM worker_breaks WHERE until IS NOT NULL').get().u:
|
|
2306
|
+
this.db.prepare('SELECT max(until) u FROM scoped_worker_breaks WHERE worker=? AND until IS NOT NULL').get(worker).u;
|
|
2182
2307
|
if(ended&&Date.parse(at)<Date.parse(ended)) throw new Error(`since must not be before the end of the previous break (${ended})`);
|
|
2308
|
+
if(worker!=='dot') {
|
|
2309
|
+
if(active) this.db.prepare('UPDATE scoped_worker_breaks SET since=?,reason=?,expected_end=CASE WHEN ? THEN ? ELSE expected_end END WHERE id=?')
|
|
2310
|
+
.run(at,reason,until!==undefined?1:0,until?iso(Date.parse(until)):null,-active.id);
|
|
2311
|
+
else this.db.prepare('INSERT INTO scoped_worker_breaks(worker,since,reason,expected_end) VALUES(?,?,?,?)')
|
|
2312
|
+
.run(worker,at,reason,until?iso(Date.parse(until)):null);
|
|
2313
|
+
return this.breakState(worker);
|
|
2314
|
+
}
|
|
2183
2315
|
const id=active?.id??this.startBreak({since:at,reason,source:'owner'}).id;
|
|
2184
2316
|
if(active) {
|
|
2185
2317
|
const usage=this.usageBefore(Date.parse(at));
|
|
@@ -2192,15 +2324,20 @@ export class Store {
|
|
|
2192
2324
|
else if(until!==undefined) this.db.prepare('INSERT INTO bridge_state(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value').run(key,iso(Date.parse(until)));
|
|
2193
2325
|
return this.breakState();
|
|
2194
2326
|
}); }
|
|
2195
|
-
clearBreak() { return this.transaction(() => {
|
|
2196
|
-
const active=this.activeBreak();
|
|
2327
|
+
clearBreak(worker='dot') { return this.transaction(() => {
|
|
2328
|
+
const active=this.activeBreak(worker);
|
|
2197
2329
|
if(active) this.endBreak(active,'owner');
|
|
2198
|
-
return {cleared:!!active,...(active?{id:active.id,since:active.since}:{}),worker_break:this.breakState()};
|
|
2330
|
+
return {cleared:!!active,...(active?{id:active.id,since:active.since}:{}),worker_break:this.breakState(worker)};
|
|
2199
2331
|
}); }
|
|
2200
2332
|
// End a usage break, by owner clear or by the worker's next tool call. A break never moves a claim's lease deadline: only the
|
|
2201
2333
|
// claimant's own progress extends a lease, so a claim with no progress for one lease period is released even across a break.
|
|
2202
2334
|
// Call inside a transaction.
|
|
2203
2335
|
endBreak(active,endSource) {
|
|
2336
|
+
if(active.id<0) {
|
|
2337
|
+
this.db.prepare('UPDATE scoped_worker_breaks SET until=?,end_source=?,expected_end=NULL WHERE id=?')
|
|
2338
|
+
.run(this.stamp(),endSource,-active.id);
|
|
2339
|
+
return;
|
|
2340
|
+
}
|
|
2204
2341
|
this.db.prepare('UPDATE worker_breaks SET until=?,end_source=? WHERE id=?').run(this.stamp(),endSource,active.id);
|
|
2205
2342
|
this.db.prepare('DELETE FROM bridge_state WHERE key=?').run(`break_expected_end:${active.id}`);
|
|
2206
2343
|
}
|
|
@@ -2431,13 +2568,19 @@ export class Store {
|
|
|
2431
2568
|
// never hold it back through pending or failed rows. The event names the first eligible item in list_pending order (the
|
|
2432
2569
|
// oldest, normal work first) and says how many lanes are free; it marks nothing else delivered and touches no other row. startAttempt checks it again before it is sent.
|
|
2433
2570
|
reannounceQueued(limits=this.limits) { return this.transaction(() => {
|
|
2571
|
+
for(const {worker} of this.db.prepare('SELECT worker FROM admission_reservations').all()) {
|
|
2572
|
+
if(!this.admissionReservation(worker)) {
|
|
2573
|
+
this.db.prepare('DELETE FROM admission_reservations WHERE worker=?').run(worker);
|
|
2574
|
+
this.laneFreed();
|
|
2575
|
+
}
|
|
2576
|
+
}
|
|
2434
2577
|
// A lane freed since the last tick (laneFreed) waives the rewakeMs cadence once; every other gate below still applies.
|
|
2435
2578
|
const dispatchNow=this.dispatchWake; this.dispatchWake=false;
|
|
2436
2579
|
if (this.paused()||!this.db.prepare("SELECT 1 FROM assignments WHERE status='queued'").get()) return {announced:0};
|
|
2437
2580
|
const now=this.nowMs(), rewakeMs=dispatchNow?0:limits.rewakeMs??defaultRedeliveryLimits.rewakeMs;
|
|
2438
2581
|
// During an owner-confirmed usage break the only re-wake is one probe every breakProbeMs (first one breakProbeMs after
|
|
2439
2582
|
// since). An inferred break is silence, not evidence, so it does not pace re-wakes.
|
|
2440
|
-
const
|
|
2583
|
+
const probed=new Set();
|
|
2441
2584
|
let probe=false,heldBreak=false,heldCapacity=false;
|
|
2442
2585
|
const outstanding=this.db.prepare("SELECT 1 FROM notifications WHERE subscription_id=? AND state IN ('pending','sending','failed') AND wake_kind IN ('submit','rewake') LIMIT 1");
|
|
2443
2586
|
const lastWake=this.db.prepare(`SELECT max(at) at FROM (SELECT max(COALESCE(attempt_started_at,created_at)) at FROM notifications WHERE subscription_id=?1 AND state='delivered' AND wake_kind IN ('submit','rewake','owner_note')
|
|
@@ -2445,15 +2588,20 @@ export class Store {
|
|
|
2445
2588
|
let announced=0;
|
|
2446
2589
|
for (const sub of this.activeSubscriptions()) {
|
|
2447
2590
|
if(this.capacityHoldUntil(sub.worker)) {heldCapacity=true;continue;}
|
|
2448
|
-
|
|
2449
|
-
if(
|
|
2591
|
+
const brk=this.holdingBreak(sub.worker);
|
|
2592
|
+
if(brk&&(probed.has(sub.worker)||now-Date.parse(brk.last_probe_at??brk.since)<(limits.breakProbeMs??defaultRedeliveryLimits.breakProbeMs))) {heldBreak=true;continue;}
|
|
2593
|
+
if(outstanding.get(sub.id)) continue;
|
|
2450
2594
|
const last=lastWake.get(sub.id).at;
|
|
2451
2595
|
if(last&&rewakeMs&&now-Date.parse(last)<rewakeMs) continue;
|
|
2452
2596
|
const eligible=this.rewakeCandidates(sub.id,limits);
|
|
2453
|
-
if(!eligible.length) continue;
|
|
2597
|
+
if(!eligible.length||this.subscriptionFreeLanes(sub,limits.laneCapacity??6,undefined,eligible[0].request_id)<=0) continue;
|
|
2454
2598
|
this.queueEvent(eligible[0].request_id,sub,true,this.queueHeadTitle(eligible,this.subscriptionFreeLanes(sub,limits.laneCapacity??6)),'rewake');
|
|
2455
2599
|
announced++;
|
|
2456
|
-
if(brk
|
|
2600
|
+
if(brk) {
|
|
2601
|
+
const table=brk.id<0?'scoped_worker_breaks':'worker_breaks';
|
|
2602
|
+
this.db.prepare(`UPDATE ${table} SET last_probe_at=? WHERE id=?`).run(this.stamp(),Math.abs(brk.id));
|
|
2603
|
+
probed.add(sub.worker); probe=true;
|
|
2604
|
+
}
|
|
2457
2605
|
}
|
|
2458
2606
|
return {announced,...(probe?{probe:true}:{}),...(!announced&&heldBreak?{worker_break:true}:{}),...(!announced&&heldCapacity?{capacity_denied:true}:{})};
|
|
2459
2607
|
}); }
|
|
@@ -2462,27 +2610,29 @@ export class Store {
|
|
|
2462
2610
|
// by the callback with HTTP 410 or 413 (terminal), and, once queued rewakeWindowMs or longer, no wake delivered or sending
|
|
2463
2611
|
// for the item in the last rewakeStaleMs (a backoff: a stale item stays eligible but is re-woken rarely).
|
|
2464
2612
|
rewakeCandidates(subscriptionId,limits=this.limits) {
|
|
2465
|
-
const now=this.nowMs(), windowMs=limits.rewakeWindowMs??defaultRedeliveryLimits.rewakeWindowMs, staleMs=limits.rewakeStaleMs??defaultRedeliveryLimits.rewakeStaleMs
|
|
2613
|
+
const now=this.nowMs(), windowMs=limits.rewakeWindowMs??defaultRedeliveryLimits.rewakeWindowMs, staleMs=limits.rewakeStaleMs??defaultRedeliveryLimits.rewakeStaleMs;
|
|
2466
2614
|
const latest=this.db.prepare("SELECT state,last_error FROM notifications WHERE request_id=? AND subscription_id=? AND wake_kind IN ('submit','rewake') ORDER BY created_at DESC, rowid DESC LIMIT 1");
|
|
2467
2615
|
const lastSent=this.db.prepare("SELECT max(COALESCE(attempt_started_at,created_at)) at FROM notifications WHERE request_id=? AND subscription_id=? AND state IN ('delivered','sending') AND wake_kind IN ('submit','rewake')");
|
|
2468
2616
|
const sub=this.db.prepare('SELECT * FROM subscriptions WHERE id=?').get(subscriptionId);
|
|
2469
2617
|
if(!sub||!this.subscriptionVisible(sub)) return [];
|
|
2618
|
+
const breaks=this.breakIntervals(sub.worker);
|
|
2470
2619
|
const denied=new Set(this.deniedQueued(sub.worker).map(d=>d.request_id));
|
|
2620
|
+
const reservedId=this.admissionReservation(sub.worker)?.request_id;
|
|
2471
2621
|
return this.queuedRows().filter(row=>{
|
|
2472
2622
|
if(!this.mayAct(sub.worker,row.request_id)||denied.has(row.request_id)||this.uncertainDeliveries(row.request_id)) return false;
|
|
2473
2623
|
const event=latest.get(row.request_id,subscriptionId);
|
|
2474
2624
|
if(event?.state==='suppressed'&&/^HTTP 41[03]$/.test(event.last_error??'')) return false;
|
|
2475
|
-
if(this.queuedAgeMs(row.queued_at,now,
|
|
2625
|
+
if(this.queuedAgeMs(row.queued_at,now,breaks)<windowMs) return true;
|
|
2476
2626
|
const sent=lastSent.get(row.request_id,subscriptionId).at;
|
|
2477
2627
|
return !sent||now-Date.parse(sent)>=staleMs;
|
|
2478
|
-
});
|
|
2628
|
+
}).sort((a,b)=>Number(b.request_id===reservedId)-Number(a.request_id===reservedId));
|
|
2479
2629
|
}
|
|
2480
2630
|
// Why a queued re-wake must not be sent now, or null. Its eligibility was decided when it was queued; drain may send it
|
|
2481
2631
|
// later, after the head was claimed, a delivery for it turned uncertain or the last free lane filled.
|
|
2482
2632
|
rewakeStale(row) {
|
|
2483
2633
|
const sub=this.db.prepare("SELECT * FROM subscriptions WHERE id=? AND state='active' AND expires_at>?").get(row.subscription_id,this.stamp());
|
|
2484
2634
|
if(!sub||!this.subscriptionVisible(sub)) return 'subscription inactive';
|
|
2485
|
-
if(this.subscriptionFreeLanes(sub)<=0) return 'no free lane';
|
|
2635
|
+
if(this.subscriptionFreeLanes(sub,undefined,undefined,row.request_id)<=0) return 'no free lane';
|
|
2486
2636
|
if(this.capacityHoldUntil(sub.worker)) return 'the worker reported a capacity denial; waiting for a slot';
|
|
2487
2637
|
if(!this.rewakeCandidates(row.subscription_id).some(x=>x.request_id===row.request_id)) return 'head no longer eligible';
|
|
2488
2638
|
return null;
|
|
@@ -2503,6 +2653,7 @@ export class Store {
|
|
|
2503
2653
|
}
|
|
2504
2654
|
}
|
|
2505
2655
|
return this.transaction(() => {
|
|
2656
|
+
if(old) this.releaseSubscriptionReservation(id);
|
|
2506
2657
|
if(replacing) {
|
|
2507
2658
|
// A verified re-subscribe creates a new row for the same worker, never updates an immutable connection.
|
|
2508
2659
|
// Retire unsent events before replaying the queue for the new connection under the stable subscription ID.
|
|
@@ -2520,6 +2671,7 @@ export class Store {
|
|
|
2520
2671
|
}
|
|
2521
2672
|
}); }
|
|
2522
2673
|
unsubscribe(id) { return this.transaction(() => {
|
|
2674
|
+
this.releaseSubscriptionReservation(id);
|
|
2523
2675
|
this.db.prepare("UPDATE subscriptions SET state='revoked' WHERE id=?").run(id);
|
|
2524
2676
|
this.db.prepare("UPDATE notifications SET state='suppressed',last_error='subscription revoked' WHERE subscription_id=? AND state IN ('pending','failed')").run(id);
|
|
2525
2677
|
}); }
|
|
@@ -2544,10 +2696,10 @@ export class Store {
|
|
|
2544
2696
|
const authorityRevoked=!!a.cancelled_at||this.isProtocolJob(id)&&a.status==='finished';
|
|
2545
2697
|
return {...this.destinationFields(id),...(this.pullQueue.row(id)?{work_order_id:this.pullQueue.row(id).work_order_id,child_request_id:id}:{}),request_id:id,supersedes,superseded_by,revises,...(follows?{follows:{...follows}}:{}),revised_by:this.newerRevision(id),apply:this.applyState(id),target_worker:a.target_worker,assignment:JSON.parse(a.payload),delivery_mode:a.delivery,t3_muted:this.deliveryMuted(id),thread_id:a.thread_id||null,environment_id:a.environment_id||null,parent_generation:a.parent_generation??null,status:a.status,execution:a.execution,required_capabilities:a.required_capabilities?JSON.parse(a.required_capabilities):[],review:!!a.review,created_at:a.created_at,valid_until:a.valid_until??null,valid_until_source:a.valid_until_source??null,expiry_requeues:a.expiry_requeues??0,...this.failureFields(id),cancelled_at:a.cancelled_at,cancelled_reason:a.cancelled_reason??null,cancellation_requested:!!a.cancelled_at,authority_revoked:authorityRevoked,...this.sandboxStop(id,authorityRevoked),claim,progress,lifecycle_events:this.db.prepare("SELECT type,at,actor,reason FROM lifecycle_events WHERE request_id=? ORDER BY id").all(id),report:report??null,late_evidence,delivery,watch,owner_notes:this.ownerNotes(id),...this.workerRunsFor(id),publication_authority:this.publicationAuthority(id),worker_break_notices:this.breakNotices(id),claim_denied:this.claimDenial(id),skipped_by_worker:a.skipped_at?{at:a.skipped_at,listed_count:a.listed_count,passed_over:a.passed_over}:null,pr_preflights:this.db.prepare("SELECT phase,evidence FROM pr_preflights WHERE request_id=? ORDER BY CASE phase WHEN 'submit' THEN 0 ELSE 1 END").all(id).map(row=>({phase:row.phase,...JSON.parse(row.evidence)}))};
|
|
2546
2698
|
}
|
|
2547
|
-
// D9: the worker's own run receipts
|
|
2699
|
+
// D9: store the worker's own run receipts in the report transaction.
|
|
2548
2700
|
recordWorkerRuns(id,claimId,{runs,run_limit}) {
|
|
2549
2701
|
if(!runs.length&&run_limit===null) return;
|
|
2550
|
-
this.
|
|
2702
|
+
this.inTransaction(()=>{
|
|
2551
2703
|
if(this.db.prepare('SELECT 1 FROM reports WHERE request_id=?').get(id)) return;
|
|
2552
2704
|
const at=this.stamp();
|
|
2553
2705
|
this.db.prepare('DELETE FROM worker_runs WHERE request_id=? AND claim_id=?').run(id,claimId);
|
|
@@ -2861,9 +3013,8 @@ export class Store {
|
|
|
2861
3013
|
.run('claim_batch_v1_'+match[1],`$.ids[${match[2]}]`,id);
|
|
2862
3014
|
}
|
|
2863
3015
|
|
|
2864
|
-
|
|
2865
|
-
// Recheck
|
|
2866
|
-
// Listing is read-only: it neither deletes audit evidence nor grants approval.
|
|
3016
|
+
destinationBlockRecheck() {
|
|
3017
|
+
// Recheck recorded blocks against one lazy profile snapshot without granting approval.
|
|
2867
3018
|
let loaded=false,failed=false,profile,loadError;
|
|
2868
3019
|
const fail=error=>{ failed=true; loadError=error??new Error('destination configuration could not be loaded'); };
|
|
2869
3020
|
const resolve=()=>{
|
|
@@ -2878,7 +3029,7 @@ export class Store {
|
|
|
2878
3029
|
if(failed)throw loadError;
|
|
2879
3030
|
return profile;
|
|
2880
3031
|
};
|
|
2881
|
-
|
|
3032
|
+
return id=>{
|
|
2882
3033
|
if(failed)return true; // a failed load is reported once per listing, whatever it threw or returned
|
|
2883
3034
|
const row=this.db.prepare('SELECT payload,target_worker,execution FROM assignments WHERE request_id=?').get(id);
|
|
2884
3035
|
const approval=this.destinationApproval(id);
|
|
@@ -2887,14 +3038,22 @@ export class Store {
|
|
|
2887
3038
|
return !(!approval&&!current||approval&¤t?.revision===approval.revision&¤t.policy.allowed);
|
|
2888
3039
|
} catch { return true; }
|
|
2889
3040
|
};
|
|
3041
|
+
}
|
|
3042
|
+
listPending(worker='dot',{batch=false,handoffExclusions=null}={}) {
|
|
3043
|
+
const blocked=this.destinationBlockRecheck();
|
|
3044
|
+
const reservedId=this.admissionReservation(worker)?.request_id;
|
|
3045
|
+
const reserveOrder=(a,b)=>Number(b.request_id===reservedId)-Number(a.request_id===reservedId);
|
|
2890
3046
|
let filler=this.activeCallerReserve(worker)>0?this.fillerRoom(worker):Infinity;
|
|
2891
|
-
const assignments=this.db.prepare(`SELECT request_id,payload,created_at,priority,review,caller_waiting,EXISTS(SELECT 1 FROM destination_blocks b WHERE b.request_id=assignments.request_id) blocked FROM assignments WHERE status='queued' AND ${live(this.nowMs())}${batch?' AND skipped_at IS NULL':''} ORDER BY ${LIST_ORDER}`).all().filter(a=>this.mayAct(worker,a.request_id)&&this.protocolListingLive(a.request_id)&&(!batch||!this.isProtocolJob(a.request_id)&&!this.pullQueue.row(a.request_id))).map(a=>({...a,blocked:!!a.blocked&&blocked(a.request_id)}))
|
|
3047
|
+
const assignments=this.db.prepare(`SELECT request_id,payload,created_at,priority,review,caller_waiting,EXISTS(SELECT 1 FROM destination_blocks b WHERE b.request_id=assignments.request_id) blocked FROM assignments WHERE status='queued' AND NOT EXISTS(SELECT 1 FROM facade_withdrawals f WHERE f.request_id=assignments.request_id) AND ${live(this.nowMs())}${batch?' AND skipped_at IS NULL':''} ORDER BY ${LIST_ORDER}`).all().filter(a=>this.mayAct(worker,a.request_id)&&this.protocolListingLive(a.request_id)&&(!batch||!this.isProtocolJob(a.request_id)&&!this.pullQueue.row(a.request_id))).map(a=>({...a,blocked:!!a.blocked&&blocked(a.request_id)}))
|
|
3048
|
+
.sort((a,b)=>Number(a.blocked)-Number(b.blocked)||reserveOrder(a,b))
|
|
3049
|
+
.filter(a=>handoffExclusions===null||!a.blocked&&a.request_id!==reservedId&&!handoffExclusions.has(a.request_id)&&!this.handoffLapsed(a.request_id,worker))
|
|
3050
|
+
.filter(a=>a.caller_waiting===1||filler-- > 0).slice(0,50).map(a=>({kind:'assignment',request_id:a.request_id,title:JSON.parse(a.payload).brief.slice(0,160),created_at:a.created_at,...(a.blocked?{blocked:true}:triageFields(JSON.parse(a.payload),a))}));
|
|
2892
3051
|
if(batch||handoffExclusions!==null) return assignments;
|
|
2893
3052
|
const messages=this.listMessages(worker).map(m=>({kind:'message',request_id:m.message_id,message_id:m.message_id,title:m.preview,created_at:m.created_at})).sort((a,b)=>a.created_at.localeCompare(b.created_at));
|
|
2894
3053
|
const resumes=this.idleClaims(worker).filter(c=>this.protocolListingLive(c.request_id)).map(c=>({kind:'assignment',request_id:c.request_id,resume:true,idle_seconds:Math.floor(this.claimIdleMs(c)/1000),previous_epoch:c.epoch,
|
|
2895
3054
|
...(this.db.prepare('SELECT 1 FROM destination_blocks WHERE request_id=?').get(c.request_id)&&blocked(c.request_id)?{blocked:true}:{}),
|
|
2896
3055
|
note:'The prior lease expired. Call claim(request_id, claimant, acquisition_id) to request a new epoch after old host work has verifiably stopped. Read progress and owner notes with get first.'}));
|
|
2897
|
-
return [...resumes,...messages,...assignments].sort((a,b)=>Number(!!a.blocked)-Number(!!b.blocked)).slice(0,50);
|
|
3056
|
+
return [...resumes,...messages,...assignments].sort((a,b)=>Number(!!a.blocked)-Number(!!b.blocked)||reserveOrder(a,b)).slice(0,50);
|
|
2898
3057
|
}
|
|
2899
3058
|
// Called for each list_pending answer to the worker: the first freeLanes assignments are the ones it could claim now. One that
|
|
2900
3059
|
// is still there SKIP_AFTER_ELIGIBLE_MS after it first was, with no claim, is marked skipped_by_worker (and goes behind its
|
|
@@ -3014,6 +3173,8 @@ export class Store {
|
|
|
3014
3173
|
leaseMs=this.cappedClaimLeaseMs(leaseMs,worker);
|
|
3015
3174
|
if(acquisitionId!==null&&(typeof acquisitionId!=='string'||!/^[A-Za-z0-9_-]{1,128}$/.test(acquisitionId))) throw new Error('invalid acquisition_id: use 1-128 letters, digits, underscores or hyphens');
|
|
3016
3175
|
if(!this.mayAct(worker,id)) throw new Error('assignment not found');
|
|
3176
|
+
if(this.db.prepare("SELECT 1 FROM facade_withdrawals WHERE request_id=? AND EXISTS (SELECT 1 FROM assignments WHERE request_id=? AND status='queued')").get(id,id))
|
|
3177
|
+
throw new Error('assignment withdrawal pending');
|
|
3017
3178
|
if (this.paused()) throw new Error(pausedClaimMessage);
|
|
3018
3179
|
const a=this.db.prepare('SELECT * FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
|
|
3019
3180
|
if(a.cancelled_at) throw new Error(a.cancelled_reason==='expired'?expiredError(a.valid_until,{cancelled:true}):'assignment cancelled'); if(a.status==='finished') throw new Error('assignment finished');
|
|
@@ -3044,7 +3205,9 @@ export class Store {
|
|
|
3044
3205
|
if(old) this.assertNoUncertainDelivery(id);
|
|
3045
3206
|
const active=this.activeClaims(subject,worker,id);
|
|
3046
3207
|
this.assertWorkerClaimSlot(worker,id);
|
|
3047
|
-
|
|
3208
|
+
const reserved=this.admissionReservation(worker);
|
|
3209
|
+
const claimLimit=reserved?Math.min(capacity,this.limits.laneCapacity??6):capacity;
|
|
3210
|
+
if(active.length+(reserved&&reserved.request_id!==id?1:0)>=claimLimit) throw new Error('capacity_full');
|
|
3048
3211
|
this.assertClaimGap(id,subject,worker,active);
|
|
3049
3212
|
this.recordPrPreflight(id,'claim',JSON.parse(a.payload),preflight,!!old);
|
|
3050
3213
|
if(takeover) { const why=Store.expirySummary(old); this.db.prepare("UPDATE claims SET state='abandoned',abandoned_at=?,abandon_reason=? WHERE request_id=?").run(this.stamp(),why,id); this.lifecycle(id,'abandoned','system',why,old); this.laneFreed(); }
|
|
@@ -3060,6 +3223,7 @@ export class Store {
|
|
|
3060
3223
|
this.db.prepare("UPDATE assignments SET eligible_since=NULL WHERE target_worker=? AND status='queued' AND request_id<>? AND eligible_since IS NOT NULL").run(worker,id);
|
|
3061
3224
|
}
|
|
3062
3225
|
this.db.prepare("UPDATE assignments SET status='claimed',listed_count=0,last_listed_at=NULL,skipped_at=NULL,eligible_since=NULL,passed_over=0 WHERE request_id=?").run(id);
|
|
3226
|
+
this.db.prepare('DELETE FROM admission_reservations WHERE request_id=?').run(id);
|
|
3063
3227
|
this.markBatchGrant(id,acquisitionId);
|
|
3064
3228
|
this.lifecycle(id,'claimed',`worker:${subject}`,takeover?'takeover':old?'reclaim':'new',{claim_id:claimId,epoch:old?old.epoch+1:1,worker});
|
|
3065
3229
|
this.db.prepare('DELETE FROM claim_denials WHERE request_id=?').run(id);
|
|
@@ -3074,6 +3238,7 @@ export class Store {
|
|
|
3074
3238
|
this.assertLiveConnection(old.request_id,worker,connectionId);
|
|
3075
3239
|
const id=old.request_id, idleS=Math.floor(this.claimIdleMs(old)/1000);
|
|
3076
3240
|
this.assertWorkerClaimSlot(worker,id);
|
|
3241
|
+
this.assertReservationLane(subject,worker,id);
|
|
3077
3242
|
const destinationRefusal=this.destinationAdmissionInTransaction(id);
|
|
3078
3243
|
if(destinationRefusal)return destinationRefusal;
|
|
3079
3244
|
this.assertNoUncertainDelivery(id);
|
|
@@ -3102,6 +3267,7 @@ export class Store {
|
|
|
3102
3267
|
this.assertLiveConnection(id,old.worker,connectionId);
|
|
3103
3268
|
this.assertRegrantReady(old);
|
|
3104
3269
|
this.assertWorkerClaimSlot(old.worker,id);
|
|
3270
|
+
this.assertReservationLane(subject,old.worker,id);
|
|
3105
3271
|
const destinationRefusal=this.destinationAdmissionInTransaction(id);
|
|
3106
3272
|
if(destinationRefusal)return destinationRefusal;
|
|
3107
3273
|
this.assertNoUncertainDelivery(id);
|
|
@@ -3144,7 +3310,22 @@ export class Store {
|
|
|
3144
3310
|
// count never invites a claim that capacity_full would refuse.
|
|
3145
3311
|
laneState(subject,worker='dot',laneCapacity=this.limits.laneCapacity??6,claimCapacity=this.capacity) {
|
|
3146
3312
|
const max=this.workerMaxClaims(worker);
|
|
3147
|
-
|
|
3313
|
+
const ready=this.listPending(worker).filter(x=>x.kind==='assignment'&&!x.resume&&!x.blocked);
|
|
3314
|
+
const free_lanes=this.freeLanes(subject,worker,laneCapacity,claimCapacity);
|
|
3315
|
+
const reserved_request_id=this.readyReservedLane(subject,worker,ready,laneCapacity,claimCapacity);
|
|
3316
|
+
return {...(max===null?{}:{worker_max_claims:max}),free_lanes,queued:ready.length,...(reserved_request_id?{reserved_request_id}:{})};
|
|
3317
|
+
}
|
|
3318
|
+
readyReservedLane(subject,worker,ready,laneCapacity,claimCapacity) {
|
|
3319
|
+
const reserved=this.admissionReservation(worker);
|
|
3320
|
+
if(reserved&&reserved.request_id===ready[0]?.request_id&&
|
|
3321
|
+
this.freeLanes(subject,worker,laneCapacity,claimCapacity,reserved.request_id)>0) return reserved.request_id;
|
|
3322
|
+
return null;
|
|
3323
|
+
}
|
|
3324
|
+
batchClaimRoom(subject,worker,laneCapacity,claimCapacity) {
|
|
3325
|
+
const ready=this.listPending(worker,{batch:true}).filter(item=>!item.blocked);
|
|
3326
|
+
const free_lanes=this.freeLanes(subject,worker,laneCapacity,claimCapacity);
|
|
3327
|
+
const reservedId=this.readyReservedLane(subject,worker,ready,laneCapacity,claimCapacity);
|
|
3328
|
+
return {ready,free_lanes,available:free_lanes+Number(!!reservedId),reservedId};
|
|
3148
3329
|
}
|
|
3149
3330
|
// A claimed assignment left its lane: the next reannounceQueued tick may wake the worker at once instead of waiting out rewakeMs.
|
|
3150
3331
|
laneFreed() { this.dispatchWake=true; }
|
|
@@ -3158,14 +3339,17 @@ export class Store {
|
|
|
3158
3339
|
.filter(c=>Date.parse(c.last_claim_activity_at??c.claimed_at)>=since).length;
|
|
3159
3340
|
}
|
|
3160
3341
|
// `applyHint:false` is for the bridge's own picks (a finish handoff), which must see every eligible row: the hint only shapes what a worker is told.
|
|
3161
|
-
nextQueued(free,exceptId=null,worker='dot',{applyHint=true,handoffExclusions=null}={}) {
|
|
3342
|
+
nextQueued(free,exceptId=null,worker='dot',{applyHint=true,handoffExclusions=null,reservedId=null}={}) {
|
|
3162
3343
|
const hint=applyHint?this.claimHint(worker):null,lanesFree=free;
|
|
3163
|
-
if(
|
|
3164
|
-
if(free<=0) return {};
|
|
3344
|
+
if(!reservedId&&free<=0) return {};
|
|
3165
3345
|
const all=this.listPending(worker,{handoffExclusions}).filter(x=>x.kind==='assignment'&&!x.blocked&&x.request_id!==exceptId);
|
|
3166
|
-
|
|
3346
|
+
const reserved=reservedId!==null&&all[0]?.request_id===reservedId;
|
|
3347
|
+
free+=Number(reserved);
|
|
3348
|
+
if(hint!==null) free=Math.min(free,Math.max(Number(reserved),hint-this.recentClaimCount(worker)));
|
|
3349
|
+
if(free<=0||!all.length) return {};
|
|
3167
3350
|
const next=all.slice(0,free).map(x=>Object.fromEntries(['request_id','title',...TRIAGE_KEYS].filter(k=>x[k]!==undefined).map(k=>[k,x[k]])));
|
|
3168
|
-
const lanes=
|
|
3351
|
+
const lanes=reserved?`1 reserved lane and ${lanesFree} free`:
|
|
3352
|
+
free<lanesFree?`${lanesFree} ${lanesFree===1?'lane':'lanes'} free, ${next.length} suggested`:`${free} ${free===1?'lane':'lanes'} free`;
|
|
3169
3353
|
return {next_queued:next,next_action:`${all.length} queued and ${lanes}: claim ${next.map(x=>x.request_id).join(', ')} now (oldest first)`};
|
|
3170
3354
|
}
|
|
3171
3355
|
// Every inactive-to-live transition must enforce the same worker cap.
|
|
@@ -3173,8 +3357,13 @@ export class Store {
|
|
|
3173
3357
|
assertWorkerClaimSlot(worker,id) {
|
|
3174
3358
|
if(!this.db.isTransaction)protocolError('transaction_required');
|
|
3175
3359
|
const max=this.workerMaxClaims(worker);
|
|
3176
|
-
|
|
3177
|
-
|
|
3360
|
+
const reserved=this.admissionReservation(worker);
|
|
3361
|
+
const held=reserved&&reserved.request_id!==id?1:0;
|
|
3362
|
+
if(max!==null) {
|
|
3363
|
+
const occupied=this.liveWorkerClaims(worker,id);
|
|
3364
|
+
if(occupied+held>=max) throw new Error(JSON.stringify({error:'capacity_full',worker,
|
|
3365
|
+
message:occupied>=max?`Worker ${worker} already holds its ${max} live claims`:`Worker ${worker} has a lane reserved for another request`}));
|
|
3366
|
+
}
|
|
3178
3367
|
if((this.limits?.workerCallerReserve?.[worker]??0)>0&&this.activeCallerReserve(worker)>0&&
|
|
3179
3368
|
this.db.prepare('SELECT caller_waiting FROM assignments WHERE request_id=?').get(id)?.caller_waiting!==1&&this.fillerRoom(worker,id)<=0)
|
|
3180
3369
|
throw new Error(JSON.stringify({error:'capacity_full',message:'No background lane is available because of the caller reserve.',worker}));
|
|
@@ -3200,7 +3389,10 @@ export class Store {
|
|
|
3200
3389
|
// Every live claim holds a lane, a running caller's too: room for a normal job is what is left after those and the lanes held for waiting callers.
|
|
3201
3390
|
const occupied=this.db.prepare("SELECT c.* FROM claims c JOIN assignments a USING(request_id) WHERE a.status='claimed' AND c.state='active' AND c.worker=? AND c.request_id IS NOT ?").all(worker,exceptId)
|
|
3202
3391
|
.filter(claim=>!this.leaseExpired(claim)).length;
|
|
3203
|
-
|
|
3392
|
+
const reserved=this.admissionReservation(worker);
|
|
3393
|
+
// The reserved request is already a waiting caller. Do not set aside its lane twice.
|
|
3394
|
+
const held=Math.max(this.activeCallerReserve(worker),reserved&&reserved.request_id!==exceptId?1:0);
|
|
3395
|
+
return this.callerCapacity(worker)-held-occupied;
|
|
3204
3396
|
}
|
|
3205
3397
|
workerMaxClaims(worker,limits=this.limits) {
|
|
3206
3398
|
const caps=limits.workerMaxClaims??{};
|
|
@@ -3210,10 +3402,18 @@ export class Store {
|
|
|
3210
3402
|
return this.db.prepare("SELECT c.* FROM claims c JOIN assignments a USING(request_id) WHERE a.status='claimed' AND c.state='active' AND c.worker=? AND c.request_id IS NOT ?").all(worker,exceptId)
|
|
3211
3403
|
.filter(claim=>!this.leaseExpired(claim)).length;
|
|
3212
3404
|
}
|
|
3213
|
-
|
|
3405
|
+
assertReservationLane(subject,worker,id) {
|
|
3406
|
+
const reserved=this.admissionReservation(worker);
|
|
3407
|
+
if(!reserved||reserved.request_id===id) return;
|
|
3408
|
+
const limit=Math.min(this.limits.laneCapacity??6,this.capacity);
|
|
3409
|
+
if(this.activeClaims(subject,worker,id).length+1>=limit) throw new Error('capacity_full');
|
|
3410
|
+
}
|
|
3411
|
+
freeLanes(subject,worker='dot',laneCapacity=this.limits.laneCapacity??6,claimCapacity=this.capacity,requestId=null) {
|
|
3214
3412
|
const legacy=Math.min(laneCapacity,claimCapacity)-this.activeClaims(subject,worker).length;
|
|
3215
3413
|
const max=this.workerMaxClaims(worker);
|
|
3216
|
-
|
|
3414
|
+
const reserved=this.admissionReservation(worker);
|
|
3415
|
+
const held=reserved&&reserved.request_id!==requestId?1:0;
|
|
3416
|
+
return Math.max(0,(max===null?legacy:Math.min(legacy,max-this.liveWorkerClaims(worker)))-held);
|
|
3217
3417
|
}
|
|
3218
3418
|
quiesceCounts() {
|
|
3219
3419
|
const live=this.db.prepare("SELECT c.* FROM claims c JOIN assignments a USING(request_id) WHERE a.status='claimed' AND c.state='active'").all();
|
|
@@ -3354,16 +3554,30 @@ export class Store {
|
|
|
3354
3554
|
static clipBytes(text,max) { const buf=Buffer.from(text); if(buf.length<=max) return text; let end=max; while(end>0&&(buf[end]&0xC0)===0x80) end--; return buf.subarray(0,end).toString(); }
|
|
3355
3555
|
static lateEvidenceLimits={summary:4096,result:64*1024};
|
|
3356
3556
|
finish(id,claimId,outcome,summary,result,subject='local-principal',evidence=null,worker='dot',ctx=null,captureEvidence=null,connectionId=null) {
|
|
3357
|
-
|
|
3358
|
-
|
|
3557
|
+
// The same deadline that closes keep also closes result authority, even before the sweep runs.
|
|
3558
|
+
this.applyFacadeWithdrawal(id);
|
|
3559
|
+
const protocol=this.isProtocolJob(id)&&this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id)?.status!=='cancelled';
|
|
3359
3560
|
// Older worker runtimes report their safety rejection through ordinary finish.
|
|
3360
3561
|
// Preserve the worker's text; only the explicit runtime cause changes classification.
|
|
3361
|
-
if (outcome==='blocked' && [summary,result].some(text => typeof text==='string' &&
|
|
3562
|
+
if (!protocol && outcome==='blocked' && [summary,result].some(text => typeof text==='string' &&
|
|
3362
3563
|
/(?:^|\n)(?:BLOCKED:\s*)?(?:The )?(?:claimed assignment content|claim tool result)\b[^\n]{0,240}\b(?:did not pass|failed)\b[^\n]{0,120}\b(?:safety|prompt-injection)[ -]check\b/i.test(text))) outcome=PROVIDER_REFUSAL;
|
|
3363
3564
|
const rollback=[];
|
|
3565
|
+
const writeReport=capture=>this.finishOnce(id,claimId,outcome,summary,result,subject,evidence,worker,capture,connectionId);
|
|
3364
3566
|
let done;
|
|
3365
|
-
try {
|
|
3366
|
-
|
|
3567
|
+
try {
|
|
3568
|
+
if(protocol) return finishProtocol(this,id,claimId,outcome,summary,result,subject,evidence,worker,ctx,captureEvidence,connectionId);
|
|
3569
|
+
done=this.transaction(()=>writeReport(captureEvidence?()=>captureEvidence(cleanup=>rollback.push(cleanup)):null));
|
|
3570
|
+
} catch(error) {
|
|
3571
|
+
for(const cleanup of rollback)cleanup();
|
|
3572
|
+
if(!(error instanceof FacadeFinishCutoff)) throw error;
|
|
3573
|
+
// Discard the attempted result and its artifacts before recording audit-only output.
|
|
3574
|
+
done=this.transaction(()=>{
|
|
3575
|
+
const claim=this.assertFinishClaim(id,claimId,subject,worker);
|
|
3576
|
+
this.assertMutationConnection(id,claim,connectionId);
|
|
3577
|
+
if(!this.applyFacadeWithdrawalInTransaction(id,error.at)) throw error;
|
|
3578
|
+
return writeReport(null);
|
|
3579
|
+
});
|
|
3580
|
+
}
|
|
3367
3581
|
// Thrown after the transaction commits so the evidence row stays. TERMINAL: the worker has nothing more to do for this request.
|
|
3368
3582
|
if(done.cancelled) throw new Error(JSON.stringify({error:'assignment_cancelled',message:`${id} was cancelled${done.reason?` (reason: ${done.reason})`:''} before this finish. Your output was kept as audit evidence only (not a result); nothing more is needed for ${id}; your other assignments are unaffected.${done.contradiction?' A different output was already kept for this request; this one was not stored.':''}`,request_id:id}));
|
|
3369
3583
|
return done;
|
|
@@ -3433,8 +3647,11 @@ export class Store {
|
|
|
3433
3647
|
}
|
|
3434
3648
|
if(captureEvidence) evidence=captureEvidence();
|
|
3435
3649
|
this.recordClaimDenials(id,`${summary}\n${result}`,worker);
|
|
3436
|
-
const receipt=`report_${randomUUID()}
|
|
3437
|
-
|
|
3650
|
+
const receipt=`report_${randomUUID()}`, encodedEvidence=evidence?JSON.stringify(evidence):null;
|
|
3651
|
+
// Authorize and timestamp the report at the insert, after evidence capture.
|
|
3652
|
+
const recordedAt=this.nowMs();
|
|
3653
|
+
if(this.facadeWithdrawalDue(id,recordedAt)) throw new FacadeFinishCutoff(recordedAt);
|
|
3654
|
+
this.db.prepare('INSERT INTO reports(request_id,claim_id,outcome,summary,result,receipt_id,created_at,late,workspace_evidence,worker) VALUES(?,?,?,?,?,?,?,?,?,?)').run(id,claimId,outcome,summary,result,receipt,iso(recordedAt),0,encodedEvidence,worker);
|
|
3438
3655
|
// completed means the worker filed its terminal report; acceptance is only ever the owner's accept event.
|
|
3439
3656
|
this.lifecycle(id,'completed',`worker:${subject}`,`outcome=${outcome}`,claim);
|
|
3440
3657
|
if(outcome==='blocked') this.lifecycle(id,'blocked',`worker:${subject}`,null,claim);
|
|
@@ -3446,6 +3663,84 @@ export class Store {
|
|
|
3446
3663
|
this.laneFreed();
|
|
3447
3664
|
return {receipt_id:receipt,request_id:id,duplicate:false,late:false,...Store.resultAuthority(false),...this.nextQueued(this.freeLanes(claim.subject,claim.worker),id,worker)};
|
|
3448
3665
|
}
|
|
3666
|
+
armFacadeWithdrawal(id, intent) {
|
|
3667
|
+
return this.transaction(() => {
|
|
3668
|
+
this.assertProtocolAvailable(id);
|
|
3669
|
+
const assignment = this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id);
|
|
3670
|
+
if (!assignment) throw new Error('assignment not found');
|
|
3671
|
+
const priorKeep=this.facadeKeepReceipt(id,intent);
|
|
3672
|
+
if(priorKeep) return {not_before:priorKeep.due_ms,kept:true};
|
|
3673
|
+
const due = this.nowMs()+FACADE_GRACE_MS;
|
|
3674
|
+
this.db.prepare(`INSERT INTO facade_withdrawals(request_id,intent,due_ms)
|
|
3675
|
+
VALUES(?,?,?) ON CONFLICT(request_id) DO NOTHING`).run(id,intent,due);
|
|
3676
|
+
const record = this.db.prepare('SELECT intent,due_ms FROM facade_withdrawals WHERE request_id=?').get(id);
|
|
3677
|
+
if (record.intent!==intent) throw new Error('another withdrawal is already pending');
|
|
3678
|
+
if(this.db.prepare('DELETE FROM admission_reservations WHERE request_id=?').run(id).changes>0) this.laneFreed();
|
|
3679
|
+
return {not_before:record.due_ms};
|
|
3680
|
+
});
|
|
3681
|
+
}
|
|
3682
|
+
facadeKeepReceipt(id, intent) {
|
|
3683
|
+
return this.db.prepare('SELECT due_ms FROM facade_withdrawal_keeps WHERE request_id=? AND intent=?').get(id,intent);
|
|
3684
|
+
}
|
|
3685
|
+
facadeWithdrawalBeforeAdmission(id,intent,action,token) {
|
|
3686
|
+
// This can affect only an eventual admission carrying the same owner capability.
|
|
3687
|
+
const ownerHash=hash(token),now=this.nowMs();
|
|
3688
|
+
return this.transaction(()=>{
|
|
3689
|
+
if(action==='arm') {
|
|
3690
|
+
this.db.prepare('DELETE FROM facade_withdrawal_admissions WHERE expires_ms<=?').run(now);
|
|
3691
|
+
const exists=this.db.prepare('SELECT 1 FROM facade_withdrawal_admissions WHERE request_id=? AND owner_hash=?').get(id,ownerHash);
|
|
3692
|
+
if(!exists && this.db.prepare('SELECT count(*) AS n FROM facade_withdrawal_admissions').get().n>=1024)
|
|
3693
|
+
throw new Error('too many cancellations awaiting admission');
|
|
3694
|
+
this.db.prepare(`INSERT INTO facade_withdrawal_admissions(request_id,owner_hash,intent,due_ms,expires_ms)
|
|
3695
|
+
VALUES(?,?,?,?,?) ON CONFLICT(request_id,owner_hash) DO NOTHING`).run(id,ownerHash,intent,now+FACADE_GRACE_MS,now+FACADE_PENDING_GRACE_TTL);
|
|
3696
|
+
}
|
|
3697
|
+
const row=this.db.prepare(`SELECT intent,due_ms,kept FROM facade_withdrawal_admissions
|
|
3698
|
+
WHERE request_id=? AND owner_hash=? AND expires_ms>?`).get(id,ownerHash,now);
|
|
3699
|
+
if(action==='arm') {
|
|
3700
|
+
if(row.intent!==intent) throw new Error('another withdrawal is already pending');
|
|
3701
|
+
return {not_before:row.due_ms,...(row.kept?{kept:true}:{})};
|
|
3702
|
+
}
|
|
3703
|
+
if(!row || row.intent!==intent) return {kept:false};
|
|
3704
|
+
if(row.kept || action!=='keep' || row.due_ms<=now) return {kept:!!row.kept};
|
|
3705
|
+
this.db.prepare('UPDATE facade_withdrawal_admissions SET kept=1 WHERE request_id=? AND owner_hash=?').run(id,ownerHash);
|
|
3706
|
+
return {kept:true};
|
|
3707
|
+
});
|
|
3708
|
+
}
|
|
3709
|
+
keepFacadeWork(id, intent) {
|
|
3710
|
+
return this.transaction(() => {
|
|
3711
|
+
if(this.facadeKeepReceipt(id,intent)) return {kept:true};
|
|
3712
|
+
const removed = this.db.prepare('DELETE FROM facade_withdrawals WHERE request_id=? AND intent=? AND due_ms>? RETURNING due_ms')
|
|
3713
|
+
.get(id,intent,this.nowMs());
|
|
3714
|
+
if(!removed) return {kept:false};
|
|
3715
|
+
this.db.prepare('INSERT INTO facade_withdrawal_keeps(request_id,intent,due_ms) VALUES(?,?,?)')
|
|
3716
|
+
.run(id,intent,removed.due_ms);
|
|
3717
|
+
return {kept:true};
|
|
3718
|
+
});
|
|
3719
|
+
}
|
|
3720
|
+
dueFacadeWithdrawals() {
|
|
3721
|
+
return this.db.prepare('SELECT request_id FROM facade_withdrawals WHERE due_ms<=? ORDER BY due_ms,request_id LIMIT 100')
|
|
3722
|
+
.all(this.nowMs()).map(row=>row.request_id);
|
|
3723
|
+
}
|
|
3724
|
+
applyFacadeWithdrawal(id) {
|
|
3725
|
+
if(!this.facadeWithdrawalDue(id,this.nowMs())) return false;
|
|
3726
|
+
return this.transaction(()=>this.applyFacadeWithdrawalInTransaction(id));
|
|
3727
|
+
}
|
|
3728
|
+
facadeWithdrawalDue(id, at) {
|
|
3729
|
+
return !!this.db.prepare('SELECT 1 FROM facade_withdrawals WHERE request_id=? AND due_ms<=?').get(id,at);
|
|
3730
|
+
}
|
|
3731
|
+
applyFacadeWithdrawalInTransaction(id,at=this.nowMs()) {
|
|
3732
|
+
if(!this.facadeWithdrawalDue(id,at)) return false;
|
|
3733
|
+
const row = this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id);
|
|
3734
|
+
const withdrew = row && ['queued','claimed'].includes(row.status);
|
|
3735
|
+
if (withdrew) {
|
|
3736
|
+
this.assertProtocolAvailable(id);
|
|
3737
|
+
const reason = 'facade_cancelled';
|
|
3738
|
+
this.cancelInTransaction(id,reason);
|
|
3739
|
+
if (this.isProtocolJob(id)) this.protocolEventInTransaction(id,'cancelled',{reason});
|
|
3740
|
+
}
|
|
3741
|
+
this.db.prepare('DELETE FROM facade_withdrawals WHERE request_id=?').run(id);
|
|
3742
|
+
return !!withdrew;
|
|
3743
|
+
}
|
|
3449
3744
|
cancel(id,reason=null,ctx=null,ownerToken=null) {
|
|
3450
3745
|
const workCancelled=this.pullQueue.cancel(id,reason);if(workCancelled)return workCancelled;
|
|
3451
3746
|
return this.isProtocolJob(id)?cancelProtocolJob(this,id,reason,ownerToken,ctx):this.transaction(()=>this.cancelInTransaction(id,reason));
|
|
@@ -3455,7 +3750,8 @@ export class Store {
|
|
|
3455
3750
|
const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found'); if(a.status==='finished') throw new Error('already finished');
|
|
3456
3751
|
if(a.status!=='cancelled') {
|
|
3457
3752
|
this.assertNoUncertainDelivery(id);
|
|
3458
|
-
|
|
3753
|
+
const released=this.db.prepare('DELETE FROM admission_reservations WHERE request_id=?').run(id).changes>0;
|
|
3754
|
+
if(a.status==='claimed'||released) this.laneFreed();
|
|
3459
3755
|
this.db.prepare("UPDATE assignments SET status='cancelled',cancelled_at=?,cancelled_reason=? WHERE request_id=?").run(this.stamp(),reason,id);
|
|
3460
3756
|
this.lifecycle(id,'withdraw_work','owner',reason,undefined,{scope:`job:${id}`,outcome:'done'});
|
|
3461
3757
|
this.lifecycle(id,'cancelled','owner',reason);
|
|
@@ -3474,6 +3770,7 @@ export class Store {
|
|
|
3474
3770
|
if(this.isProtocolJob(id)) throw new Error('protocol jobs require keyed /cancel with command_key and expected_revision');
|
|
3475
3771
|
const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
|
|
3476
3772
|
if(a.status!=='queued') return {request_id:id,status:a.status,cancelled:false};
|
|
3773
|
+
if(this.db.prepare('DELETE FROM admission_reservations WHERE request_id=?').run(id).changes>0) this.laneFreed();
|
|
3477
3774
|
this.db.prepare("UPDATE assignments SET status='cancelled',cancelled_at=? WHERE request_id=? AND status='queued'").run(this.stamp(),id);
|
|
3478
3775
|
this.lifecycle(id,'withdraw_work','owner',null,undefined,{scope:`job:${id}`,outcome:'done'});
|
|
3479
3776
|
this.lifecycle(id,'cancelled','owner');
|
|
@@ -3620,7 +3917,12 @@ export class Store {
|
|
|
3620
3917
|
}
|
|
3621
3918
|
paused() { return this.db.prepare('SELECT paused_at,reason FROM operator_state WHERE id=1').get().paused_at !== null; }
|
|
3622
3919
|
// Claims reopening restarts the skip clock: time claims were refused is not time the worker passed a job over.
|
|
3623
|
-
restartSkipClock(
|
|
3920
|
+
restartSkipClock({releaseReservations=false}={}) {
|
|
3921
|
+
return this.inTransaction(()=>{
|
|
3922
|
+
this.db.prepare("UPDATE assignments SET eligible_since=NULL WHERE status='queued'").run();
|
|
3923
|
+
if(releaseReservations&&this.db.prepare('DELETE FROM admission_reservations').run().changes>0) this.laneFreed();
|
|
3924
|
+
});
|
|
3925
|
+
}
|
|
3624
3926
|
setPause(reason) { return this.transaction(() => { this.db.prepare('UPDATE operator_state SET paused_at=?,reason=? WHERE id=1').run(reason?this.stamp():null,reason||null); if(!reason) this.restartSkipClock(); return {paused:!!reason,reason:reason||null}; }); }
|
|
3625
3927
|
suppressStaleQuestion(row) {
|
|
3626
3928
|
if(!row||!['blocker','wait'].includes(row.kind)||!row.body) return false;
|
|
@@ -3971,7 +4273,8 @@ export class Store {
|
|
|
3971
4273
|
const workerCounts=this.db.prepare(`SELECT status,count(*) count FROM assignments WHERE target_worker=? AND (status<>'queued' OR ${live(this.nowMs())}) GROUP BY status`).all(worker).filter(row=>row.count>0);
|
|
3972
4274
|
const liveQueued=this.queuedRows().filter(row=>row.target_worker===worker);
|
|
3973
4275
|
const queuedNormal=liveQueued.filter(row=>row.priority==='normal').length;
|
|
3974
|
-
|
|
4276
|
+
const hold=this.holdingBreak(worker);
|
|
4277
|
+
return [worker,{scope:'worker',...(hold?{worker_break:{active:true,source:hold.source,since:hold.since,...this.breakForecast(hold.id)}}:{}),...(Object.hasOwn(limits.workerHeartbeatMs??{},worker)?{heartbeat_ms:limits.workerHeartbeatMs[worker]}:{}),counts:workerCounts,queued_expired:expired,queued_expired_requeued:requeued,active_claims:liveness.claimed_outer_count,queued_live:liveQueued.length,queued_normal:queuedNormal,queued_waiting:liveQueued.filter(row=>row.priority==='normal'&&row.caller_waiting===1).length,queued_waiting_background:liveQueued.filter(row=>row.priority==='background'&&row.caller_waiting===1).length,subscriptions_active:workerSubscriptions.length,capacity:this.workerCapacityEvidence(worker,workerSubscriptions,limits,capacity),last_call_at:liveness.last_worker_call_at,last_list_pending_at:liveness.last_list_pending_at,stale_claims:liveness.stale_claims,queue_classes:liveness.queue_classes,unclaimed_after_reannounce:liveness.unclaimed_after_reannounce,oldest_claim_age_ms:liveness.oldest_claim_age_ms,oldest_claim_progress_age_ms:liveness.oldest_claim_progress_age_ms,oldest_unclaimed_event_2xx_age_ms:liveness.oldest_unclaimed_event_2xx_age_ms,silence_ms:liveness.worker_silence_ms}];
|
|
3975
4278
|
}));
|
|
3976
4279
|
dispatch.by_worker=Object.fromEntries([...this.workers.workers.keys()].sort().map(worker=>{
|
|
3977
4280
|
const evidence=by_worker[worker].capacity;
|