@promptdriven/runtime-client 1.2.1 → 1.2.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@promptdriven/runtime-client",
3
- "version": "1.2.1",
3
+ "version": "1.2.3",
4
4
  "description": "PDD Runtime Client (@promptdriven/runtime-client)",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -143,6 +143,10 @@ const LOST_READ_MS = 300_000;
143
143
  // without polling dead 404 runs for the full LOST_READ_MS.
144
144
  const MISSING_GRACE_MS = 15_000;
145
145
  const MISSING_MIN_POLLS = 3;
146
+ // Serialize large POST request bodies per Runtime client so concurrent multi-row uploads do not
147
+ // divide one client uplink across streams and trip server body-read deadlines.
148
+ const LARGE_POST_BYTES = 256 * 1024;
149
+ const INLINE_REQUEST_CLAUSE_SPLIT_BYTES = 60_000;
146
150
  // Unresolved prior local batch reservations automatically expire after 24 hours (override via PDD_PRIOR_RESERVATION_TTL_HOURS).
147
151
  const PRIOR_RESERVATION_TTL_MS = 24 * 60 * 60 * 1000;
148
152
  // Completed/reconciled local batch directories older than 14 days are eligible for automatic GC (override via PDD_BATCH_RETENTION_DAYS; 0 disables).
@@ -498,7 +502,7 @@ async function readBaselineReport(context, plan, identity) {
498
502
  try { saved = await read(join(folder,'batch.json')); }
499
503
  catch { partial=true;warn('Some saved Check batches are unreadable or corrupt.');continue; }
500
504
  if (diagnosticBatch(saved)) continue;
501
- if (saved?.intent !== 'check' && (Object.hasOwn(saved ?? {},'intent') || !Array.isArray(saved?.rows) || !saved.rows.every(row=>isObject(row) && validSavedCheck(row)))) continue;
505
+ if (saved?.intent !== 'check' && (Object.hasOwn(saved ?? {},'intent') || !Array.isArray(saved?.rows) || !saved.rows.every(row=>isObject(row) && validSavedCheck(row, { allowServerDefault: false })))) continue;
502
506
  if (saved.version !== 1 || saved.batch !== name || !Array.isArray(saved.rows) || typeof saved.root !== 'string') {
503
507
  partial=true;warn('Some saved Check batches have invalid original identity.');continue;
504
508
  }
@@ -577,7 +581,7 @@ async function readBaselineReport(context, plan, identity) {
577
581
  const ownSnapshots = snapshots.filter(story=>Array.isArray(story?.tests) && story.tests.includes(row.test));
578
582
  const snapshot = ownSnapshots[0];
579
583
  const sent = row.request_ids.length > 0;
580
- if (sent && !validSavedCheck(row)) { inconsistent();continue; }
584
+ if (sent && !validSavedCheck(row, { allowServerDefault: saved.intent === 'check' })) { inconsistent();continue; }
581
585
  const originalFootprint = originalSource?.stories?.find(story=>story.tests?.includes(row.test));
582
586
  const duplicate = saved.rows.filter(other=>other?.test === row.test).length !== 1;
583
587
  const storyName = typeof row.story === 'string' ? row.story : null;
@@ -738,7 +742,7 @@ async function readSavedStoryEvidence({ root, comparisonRoot = root, withTests =
738
742
  const legacy = !Object.hasOwn(batch, 'intent');
739
743
  if (batch.intent !== 'check') {
740
744
  if (!legacy) continue;
741
- if (!batch.rows.every(row => isObject(row) && validSavedCheck(row))) { legacyHint(); continue; }
745
+ if (!batch.rows.every(row => isObject(row) && validSavedCheck(row, { allowServerDefault: false }))) { legacyHint(); continue; }
742
746
  }
743
747
  const valid = batch.rows.every(row => isObject(row) && relativeFile(row.test) && relativeFile(row.story) && Array.isArray(row.request_ids));
744
748
  if (!valid) { warning(path, Error('invalid Story identity')); continue; }
@@ -1486,6 +1490,61 @@ class Runtime {
1486
1490
  this.syncedTrees = new Map();
1487
1491
  this.syncingTrees = new Map();
1488
1492
  this.blobSyncDisabled = false;
1493
+ this.largePostTail = Promise.resolve();
1494
+ }
1495
+ async withLargePostSlot(bytes, work, timeoutMs = this.ports.postMs, deadline = Infinity) {
1496
+ if (bytes < LARGE_POST_BYTES) {
1497
+ const effectiveMs = Number.isFinite(deadline) ? Math.min(timeoutMs, deadline - this.ports.now()) : timeoutMs;
1498
+ if (effectiveMs <= 0) return { lost: true, why: 'no answer in time' };
1499
+ return work(effectiveMs);
1500
+ }
1501
+ if (this.signal?.aborted) return { lost: true };
1502
+ const prior = this.largePostTail;
1503
+ let release;
1504
+ this.largePostTail = new Promise(done => { release = done; });
1505
+ let outcome = 'ready';
1506
+ let timer = null;
1507
+ let onAbort = null;
1508
+ try {
1509
+ const remaining = Number.isFinite(deadline) ? deadline - this.ports.now() : Infinity;
1510
+ if (this.signal?.aborted) {
1511
+ outcome = 'abort';
1512
+ } else if (remaining <= 0) {
1513
+ outcome = 'timeout';
1514
+ } else {
1515
+ const racers = [prior.then(() => 'ready')];
1516
+ if (this.signal) {
1517
+ racers.push(new Promise(done => {
1518
+ onAbort = () => done('abort');
1519
+ this.signal.addEventListener('abort', onAbort, { once: true });
1520
+ }));
1521
+ }
1522
+ if (Number.isFinite(remaining) && remaining <= 2_147_483_647) {
1523
+ racers.push(new Promise(done => {
1524
+ timer = setTimeout(() => done('timeout'), remaining);
1525
+ }));
1526
+ }
1527
+ outcome = await Promise.race(racers);
1528
+ }
1529
+ } finally {
1530
+ if (timer !== null) clearTimeout(timer);
1531
+ if (onAbort && this.signal) this.signal.removeEventListener('abort', onAbort);
1532
+ }
1533
+ if (outcome === 'abort' || this.signal?.aborted) {
1534
+ prior.finally(release);
1535
+ return { lost: true };
1536
+ }
1537
+ if (outcome === 'timeout') {
1538
+ prior.finally(release);
1539
+ return { lost: true, why: 'no answer in time' };
1540
+ }
1541
+ try {
1542
+ const effectiveMs = Number.isFinite(deadline) ? Math.min(timeoutMs, deadline - this.ports.now()) : timeoutMs;
1543
+ if (effectiveMs <= 0) return { lost: true, why: 'no answer in time' };
1544
+ return await work(effectiveMs);
1545
+ } finally {
1546
+ release();
1547
+ }
1489
1548
  }
1490
1549
  async sendOnce(path, init, ms) {
1491
1550
  const readSignal = init?.method === 'GET' ? init.signal : null;
@@ -1726,9 +1785,22 @@ class Runtime {
1726
1785
  return pending;
1727
1786
  }
1728
1787
  async post(path, request, tar, timeoutMs = this.ports.postMs, options = undefined) {
1788
+ const deadline = Number.isFinite(options?.deadline) ? options.deadline : Infinity;
1789
+ const requestJson = JSON.stringify(request);
1790
+ const requestBytes = Buffer.byteLength(requestJson, 'utf8');
1729
1791
  const makeForm = () => {
1730
1792
  const form = new FormData();
1731
- form.set('request', new Blob([JSON.stringify(request)], { type: 'application/json' }), 'request.json');
1793
+ let reqJson = requestJson;
1794
+ let clauseJson = null;
1795
+ if (request && Object.hasOwn(request, 'clause_table') && request.clause_table != null && requestBytes > INLINE_REQUEST_CLAUSE_SPLIT_BYTES) {
1796
+ const { clause_table, ...rest } = request;
1797
+ reqJson = JSON.stringify(rest);
1798
+ clauseJson = JSON.stringify(clause_table);
1799
+ }
1800
+ form.set('request', new Blob([reqJson], { type: 'application/json' }), 'request.json');
1801
+ if (clauseJson !== null) {
1802
+ form.set('clause_table', new Blob([clauseJson], { type: 'application/json' }), 'clause_table.json');
1803
+ }
1732
1804
  let source = this.sources.get(tar);
1733
1805
  if (!source) { source = new Blob([tar], { type: 'application/x-tar' }); this.sources.set(tar, source); }
1734
1806
  form.set('source', source, 'source.tar');
@@ -1736,8 +1808,14 @@ class Runtime {
1736
1808
  };
1737
1809
  const sha = options?.dedup === true && !this.sourceUploadDisabled && tar && typeof request?.source_sha256 === 'string' && /^[a-f0-9]{64}$/.test(request.source_sha256)
1738
1810
  ? request.source_sha256 : null;
1811
+ const inlineBytes = (tar?.length ?? 0) + requestBytes;
1739
1812
  const postInline = async () => {
1740
- const reply = await this.send(path, { method: 'POST', body: makeForm }, timeoutMs);
1813
+ const reply = await this.withLargePostSlot(
1814
+ inlineBytes,
1815
+ (ms) => this.send(path, { method: 'POST', body: makeForm }, ms),
1816
+ timeoutMs,
1817
+ deadline,
1818
+ );
1741
1819
  if (sha && [200, 202].includes(reply.status)) this.uploadedSources.add(sha);
1742
1820
  return reply;
1743
1821
  };
@@ -1745,11 +1823,20 @@ class Runtime {
1745
1823
  && Array.isArray(options?.sources) && typeof request?.source_sha256 === 'string' && /^[a-f0-9]{64}$/.test(request.source_sha256);
1746
1824
  if (useBlobSync) {
1747
1825
  const shaHex = request.source_sha256;
1748
- const sendViaTree = async (treeSha) => this.send(path, {
1749
- method: 'POST',
1750
- headers: { 'Content-Type': 'application/json' },
1751
- body: () => JSON.stringify({ ...request, tree_sha256: treeSha }),
1752
- }, timeoutMs);
1826
+ const sendViaTree = async (treeSha) => {
1827
+ const payload = JSON.stringify({ ...request, tree_sha256: treeSha });
1828
+ const payloadBytes = Buffer.byteLength(payload, 'utf8');
1829
+ return this.withLargePostSlot(
1830
+ payloadBytes,
1831
+ (ms) => this.send(path, {
1832
+ method: 'POST',
1833
+ headers: { 'Content-Type': 'application/json' },
1834
+ body: () => payload,
1835
+ }, ms),
1836
+ timeoutMs,
1837
+ deadline,
1838
+ );
1839
+ };
1753
1840
  let treeSha = await this.syncTree(shaHex, options.sources, timeoutMs);
1754
1841
  if (treeSha) {
1755
1842
  let reply = await sendViaTree(treeSha);
@@ -1784,11 +1871,16 @@ class Runtime {
1784
1871
  const uploaded = await this.uploadSource(sha, tar, timeoutMs);
1785
1872
  if (!uploaded) return postInline();
1786
1873
  }
1787
- const reply = await this.send(path, {
1788
- method: 'POST',
1789
- headers: { 'Content-Type': 'application/json' },
1790
- body: () => JSON.stringify(request),
1791
- }, timeoutMs);
1874
+ const reply = await this.withLargePostSlot(
1875
+ requestBytes,
1876
+ (ms) => this.send(path, {
1877
+ method: 'POST',
1878
+ headers: { 'Content-Type': 'application/json' },
1879
+ body: () => requestJson,
1880
+ }, ms),
1881
+ timeoutMs,
1882
+ deadline,
1883
+ );
1792
1884
  const code = reply.json?.error?.code ?? reply.json?.code;
1793
1885
  if ([404, 409, 422].includes(reply.status) && code === 'source-not-found'
1794
1886
  && reply.json?.job_created !== true && reply.json?.dispatch !== 'unknown') {
@@ -2552,7 +2644,7 @@ async function admission(context, kind, target, deadline = context.deadline) {
2552
2644
  // One answer to a POST, as the row table of the spec.
2553
2645
  function judgePost(reply, id, command, secrets) {
2554
2646
  if (reply.unreachable) return { kind: 'stop', note: { code: null, message: reply.unreachable } };
2555
- if (reply.lost) return { kind: 'unknown', why: 'The answer to the request was lost.' };
2647
+ if (reply.lost) return { kind: 'unknown', why: reply.why ? `The answer to the request was lost (${reply.why}).` : 'The answer to the request was lost.' };
2556
2648
  const stopLine = blockingAnswer(reply);
2557
2649
  if (stopLine) return { kind: 'stop', note: { code: 'blocked', message: stopLine }, blocked: true };
2558
2650
  const error = isObject(reply.json?.error) ? reply.json.error : null;
@@ -3830,8 +3922,12 @@ async function postJob(context, path, command, request, row, timeoutMs, deadline
3830
3922
  const inlineFirst = !blobSync
3831
3923
  && (command === 'lint' || (command === 'check' && pendingChecks <= 1))
3832
3924
  && (!dedup || Buffer.byteLength(JSON.stringify(request), 'utf8') <= 60_000);
3833
- const postOptions = (blobSync || dedup)
3834
- ? { ...(blobSync ? { blobSync: true, sources: context.capture.sources } : {}), ...(dedup ? { dedup: true, inlineFirst } : {}) }
3925
+ const postOptions = (blobSync || dedup || Number.isFinite(deadline))
3926
+ ? {
3927
+ ...(blobSync ? { blobSync: true, sources: context.capture.sources } : {}),
3928
+ ...(dedup ? { dedup: true, inlineFirst } : {}),
3929
+ ...(Number.isFinite(deadline) ? { deadline } : {}),
3930
+ }
3835
3931
  : undefined;
3836
3932
  const reply = await context.runtime.post(
3837
3933
  path,
@@ -4061,6 +4157,11 @@ function sourceProvenance(context, capture = context?.capture) {
4061
4157
  return { source_commit: capture.source_commit, source_dirty: Boolean(capture.source_dirty), dirty_files };
4062
4158
  }
4063
4159
 
4160
+ function stampRowEnd(row, observedAt) {
4161
+ if (row.sent_at && !row.ended_at && Number.isFinite(observedAt)) row.ended_at = Math.max(row.sent_at, observedAt);
4162
+ if (row.sent_at && Number.isFinite(row.ended_at)) row.seconds = Math.max(0, (row.ended_at - row.sent_at) / 1000);
4163
+ }
4164
+
4064
4165
  // GET one open row once.
4065
4166
  async function readRow(context, row, deadline = Infinity) {
4066
4167
  const rowEnd = rowDeadline(context, row);
@@ -4081,7 +4182,7 @@ async function readRow(context, row, deadline = Infinity) {
4081
4182
  if (row.missing_count >= MISSING_MIN_POLLS && verdict.observed_at - row.missing_since >= MISSING_GRACE_MS) {
4082
4183
  if (row.capacity_uncertain) markCapacityUnknown(context, row);
4083
4184
  else {
4084
- const notFoundWhy = 'The run was not found on the interpreter (HTTP 404).';
4185
+ const notFoundWhy = `The run (${id}) was not found on the interpreter (HTTP 404).`;
4085
4186
  const why = row.why && !row.why.includes('HTTP 404')
4086
4187
  ? `${row.why.replace(/\.$/, '')}. ${notFoundWhy}`
4087
4188
  : notFoundWhy;
@@ -4092,17 +4193,20 @@ async function readRow(context, row, deadline = Infinity) {
4092
4193
  can_retry: false,
4093
4194
  note: { code: 'not-found', message: why },
4094
4195
  why,
4196
+ next_step: null,
4095
4197
  lost: false,
4096
4198
  final: true,
4097
4199
  });
4098
4200
  }
4099
4201
  row.lost = false; row.final = true;
4202
+ stampRowEnd(row, verdict.observed_at);
4100
4203
  }
4101
4204
  }
4102
4205
  else if (verdict.kind === 'unknown') {
4103
4206
  if (row.capacity_uncertain) markCapacityUnknown(context, row);
4104
4207
  else Object.assign(row, { state: 'unknown', why: verdict.why, lost: false, final: true });
4105
4208
  row.lost = false; row.final = true;
4209
+ stampRowEnd(row, verdict.observed_at);
4106
4210
  }
4107
4211
  else if (verdict.kind === 'auth') context.readStop = AUTH_TEXT;
4108
4212
  else if (verdict.kind === 'blocked') context.readStop = verdict.message;
@@ -4651,8 +4755,16 @@ async function runScheduledChecks(context, rows, toSend) {
4651
4755
  ? stoppedPause(context, row, 'check') : row.request_ids.length
4652
4756
  ? 'The interpreter stayed busy. No checks ran for this attempt. Retry this batch later.' : 'Held locally; this check was not sent. Retry this batch later.' } });
4653
4757
  const rowEnd = rowDeadline(context, row);
4654
- if (row.state === 'unknown' && row.lost) row.why ??= stoppedEarly ? 'pdd stopped before it could read this run.'
4655
- : Number.isFinite(rowEnd) ? 'pdd could not read this run before the timeout.' : 'pdd could not read this run for 5 min after its answer was lost.';
4758
+ if (row.state === 'unknown' && row.lost) {
4759
+ row.why ??= stoppedEarly ? 'pdd stopped before it could read this run.'
4760
+ : Number.isFinite(rowEnd) ? 'pdd could not read this run before the timeout.' : 'pdd could not read this run for 5 min after its answer was lost.';
4761
+ }
4762
+ }
4763
+ for (const row of rows) {
4764
+ const rowEnd = rowDeadline(context, row);
4765
+ if (row.state === 'unknown' && row.lost && !stoppedEarly && !Number.isFinite(rowEnd) && ports.now() >= (row.read_until ?? Infinity)) {
4766
+ stampRowEnd(row, ports.now());
4767
+ }
4656
4768
  }
4657
4769
  }
4658
4770
 
@@ -5483,6 +5595,12 @@ async function runRead(context, batchWord, quiet = false, options = {}, retry =
5483
5595
  // A verified open receipt stays open when another row consumed this wait.
5484
5596
  if ((ports.now() >= (context.deadline ?? Infinity) || context.interrupted)
5485
5597
  && answer && sameJob(answer, id, 'check') && ['queued', 'running'].includes(answer.state)) { applyAnswer(row, answer, context); return; }
5598
+ // A saved finalized not-found row preserves its reason, advice, end time, and elapsed seconds across all --read calls.
5599
+ if (row.state === 'unknown' && row.note?.code === 'not-found' && Number.isFinite(row.ended_at)) {
5600
+ row.lost = false; row.final = true;
5601
+ stampRowEnd(row, row.ended_at);
5602
+ return;
5603
+ }
5486
5604
  // Polling an open cache is not evidence that its saved advice came from a lost read.
5487
5605
  if (!row.capacity_uncertain && !row.lost && (row.state !== 'unknown' || row.lost === false)) row.why = null;
5488
5606
  Object.assign(row, { state: 'unknown', calls: 'unknown', checks: null, criteria: null, failed_checks: [], all_checks: [], busy: false, can_retry: false, note: null, lost: true,
@@ -5595,7 +5713,7 @@ async function recoverRestarts(context) {
5595
5713
  lintDiagnostics(context, lint, context.rows);
5596
5714
  const selected = [];
5597
5715
  for (const row of admitted) {
5598
- if (context.interrupted || rowExpired(context, row) || !validSavedCheck(row)) continue;
5716
+ if (context.interrupted || rowExpired(context, row) || !validSavedCheck(row, { allowServerDefault: context.intent === 'check' })) continue;
5599
5717
  const transient = drops.includes(row);
5600
5718
  const decision = evaluateCheckBudget({
5601
5719
  max_total_calls: context.maxTotalCalls ?? null,