carrick 0.3.135 → 0.3.137

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.
@@ -201,6 +201,7 @@ const DECIDED_ABSTAIN_REASONS = new Set([
201
201
  'projected_value_only',
202
202
  'serialised_body_unread',
203
203
  'body_built_by_callee',
204
+ 'reshaped_by_callback',
204
205
  ]);
205
206
  /** The provenance sentence for each reason a branch was not read. */
206
207
  const SERIALISED_BODY_UNREAD_DETAIL = {
@@ -397,21 +398,22 @@ function isBareStringText(text) {
397
398
  members.every((member) => member === 'string' || member === 'null' || member === 'undefined'));
398
399
  }
399
400
  /**
400
- * How long the unwidened reading of one batch may take by default. The
401
- * reading adds a field and never an answer, so running out costs only the
402
- * readings not yet made; the rewrite is always undone. It reports no
403
- * progress, so this is also the longest a batch goes silent after its last
404
- * request: well inside the 900s the scanner allows between two signs of life.
401
+ * How many readings one batch may make (carrick#2629). A count, not a time,
402
+ * so whether a reading is made never depends on the machine's load: a reading
403
+ * a batch cannot make marks its response `unwidened_out_of_budget`, and the
404
+ * check then abstains on every mismatch against it (carrick#2100). Sized well
405
+ * above the largest batch measured; see the PR that set it.
405
406
  */
406
- const UNWIDENED_BUDGET_MS = 120_000;
407
+ const UNWIDENED_MAX_READINGS = 5_000;
408
+ /** How many files one batch's reading may type-check (carrick#2629). */
409
+ const UNWIDENED_MAX_FILES = 5_000;
407
410
  /**
408
- * No reading starts or continues past this long after the batch began. The
409
- * number dates from when the scanner allowed a whole request 900s; it now
410
- * allows that long between progress reports (carrick#1914), so a batch can
411
- * run past this and still be read. A batch that does publishes no unwidened
412
- * reading, as before.
411
+ * The last resort: a reading still running this long after it started stops
412
+ * and says so in the log. The reading reports progress after every file it
413
+ * checks and every request it re-reads, so the scanner's limit on silence
414
+ * never needs it; it is here for a reading that runs away.
413
415
  */
414
- const UNWIDENED_LATEST_MS = 600_000;
416
+ const UNWIDENED_BACKSTOP_MS = 30 * 60_000;
415
417
  /**
416
418
  * TypeInferrer - Extracts types from source code, both explicit and inferred
417
419
  *
@@ -429,7 +431,8 @@ export class TypeInferrer {
429
431
  * unwidened reading re-reads from here (carrick#1516).
430
432
  */
431
433
  readNodes = new WeakMap();
432
- unwidenedBudgetMs;
434
+ unwidenedLimits;
435
+ now;
433
436
  /**
434
437
  * The files a request has named to this inferrer, as the requests named
435
438
  * them (carrick#1985). It lives as long as the project does, so the first
@@ -440,7 +443,12 @@ export class TypeInferrer {
440
443
  this.project = options.project;
441
444
  this.packageOf = options.packageOf;
442
445
  this.repoRoot = options.repoRoot;
443
- this.unwidenedBudgetMs = options.unwidenedBudgetMs ?? UNWIDENED_BUDGET_MS;
446
+ this.unwidenedLimits = {
447
+ readings: options.unwidenedLimits?.readings ?? UNWIDENED_MAX_READINGS,
448
+ files: options.unwidenedLimits?.files ?? UNWIDENED_MAX_FILES,
449
+ backstopMs: options.unwidenedLimits?.backstopMs ?? UNWIDENED_BACKSTOP_MS,
450
+ };
451
+ this.now = options.now ?? (() => performance.now());
444
452
  }
445
453
  /**
446
454
  * What the structural printer needs to tell the user's own declarations from
@@ -461,12 +469,12 @@ export class TypeInferrer {
461
469
  * @param requests - Array of inference requests
462
470
  * @param extractionConfig - Agent-generated extraction config for payload unwrapping
463
471
  * @param onRequestDone - Called once per request, as the batch is done with it
472
+ * @param onUnwidenedStep - Called once per unit of the unwidened reading's work
464
473
  * @returns InferResult with inferred types or errors
465
474
  */
466
- infer(requests, extractionConfig, onRequestDone, modelSymbols, labels) {
467
- const started = performance.now();
475
+ infer(requests, extractionConfig, onRequestDone, modelSymbols, labels, onUnwidenedStep) {
468
476
  this.modelSymbols = new Map((modelSymbols ?? []).map((symbol) => [symbol.alias, symbol]));
469
- this.statedParams = this.statedParamsFor(labels ?? { sends: new Map(), bodies: new Set() });
477
+ this.statedParams = this.statedParamsFor(labels ?? { sends: new Map(), sets: new Map(), returns: new Map(), bodies: new Set() });
470
478
  const inferredTypes = [];
471
479
  const errors = [];
472
480
  /** Response inferences the unwidened reading re-reads (carrick#1516). */
@@ -541,7 +549,14 @@ export class TypeInferrer {
541
549
  }
542
550
  }
543
551
  try {
544
- const deadline = Math.min(performance.now() + this.unwidenedBudgetMs, started + UNWIDENED_LATEST_MS);
552
+ // One allowance for the batch: the responses draw on it first, the
553
+ // bodies on what they leave.
554
+ const work = {
555
+ readings: this.unwidenedLimits.readings,
556
+ files: this.unwidenedLimits.files,
557
+ backstopAt: this.now() + this.unwidenedLimits.backstopMs,
558
+ step: onUnwidenedStep ?? (() => { }),
559
+ };
545
560
  // The responses' rewrite forgets every node of the files it touches, so
546
561
  // each body's read node is kept as its span, taken now and found again
547
562
  // in the restored file.
@@ -558,22 +573,22 @@ export class TypeInferrer {
558
573
  };
559
574
  });
560
575
  try {
561
- this.addUnwidenedReadings(responses, extractionConfig, deadline, 'response');
576
+ this.addUnwidenedReadings(responses, extractionConfig, work, 'response');
562
577
  }
563
578
  catch (err) {
564
579
  // The reading only ever adds a field; it never costs an answer.
565
580
  this.logError(`Unwidened reading failed: ${err instanceof Error ? err.message : String(err)}`);
566
581
  }
567
582
  try {
568
- // Second, and in a rewrite of its own: the bodies' files never delay a
569
- // response's reading, whose budget a spent deadline turns into an
570
- // abstention (carrick#2100).
571
- this.addUnwidenedReadings(bodySpans, extractionConfig, deadline, 'request_body');
583
+ // Second, and in a rewrite of its own: the bodies never take a
584
+ // response's share of the work, whose cap a spent allowance turns into
585
+ // an abstention (carrick#2100).
586
+ this.addUnwidenedReadings(bodySpans, extractionConfig, work, 'request_body');
572
587
  }
573
588
  catch (err) {
574
589
  this.logError(`Unwidened reading of request bodies failed: ${err instanceof Error ? err.message : String(err)}`);
575
590
  // carrick#2011: a body whose reading was not made is judged on its
576
- // widened type alone, so it is marked the way a spent budget marks it
591
+ // widened type alone, so it is marked the way a spent work cap marks it
577
592
  // and its pair abstains on a mismatch rather than report one.
578
593
  for (const body of bodies) {
579
594
  if (body.result.unwidened_type_string === undefined) {
@@ -599,7 +614,7 @@ export class TypeInferrer {
599
614
  * members the batch's verified server-framework labels name. Empty when
600
615
  * the batch carries no labels, and then it reads nothing.
601
616
  */
602
- statedParams = this.statedParamsFor({ sends: new Map(), bodies: new Set() });
617
+ statedParams = this.statedParamsFor({ sends: new Map(), sets: new Map(), returns: new Map(), bodies: new Set() });
603
618
  /**
604
619
  * carrick#2111: where the model named a type for the response this request
605
620
  * reads, record on `inferred` how that type relates to the compiler's type
@@ -693,25 +708,28 @@ export class TypeInferrer {
693
708
  * and every file restored before returning, so the project other requests
694
709
  * read is the project the scan loaded.
695
710
  *
696
- * Nothing is read past `deadline`: a batch that runs out keeps the readings
697
- * it made and publishes none for the rest, and marks each of the rest
698
- * `unwidened_out_of_budget` (carrick#2100). A request that never needed a
699
- * reading (a declared return, nothing to mark) or lost it for a reason of
700
- * its own (a marking that added a diagnostic) is never marked.
701
- */
702
- addUnwidenedReadings(responses, extractionConfig, deadline, read) {
711
+ * The reading is bounded by work, not time (carrick#2629): a batch makes at
712
+ * most `UnwidenedLimits.readings` readings over at most `.files` files,
713
+ * taken in request order, the responses first. The first request past
714
+ * either cap and every request after it are marked
715
+ * `unwidened_out_of_budget` (carrick#2100) and publish no reading, on any
716
+ * machine. A reading still running at the wall-clock backstop stops the
717
+ * same way and says so in the log. A request that never needed a reading
718
+ * (a declared return, nothing to mark) or lost it for a reason of its own
719
+ * (a marking that added a diagnostic) is never marked.
720
+ */
721
+ addUnwidenedReadings(responses, extractionConfig, work, read) {
722
+ const started = this.now();
703
723
  const outOfTime = (stage, unread) => {
704
- if (performance.now() <= deadline)
724
+ if (this.now() <= work.backstopAt)
705
725
  return false;
706
- this.log(`Unwidened reading stopped ${stage}: it ran out of its budget, ` +
707
- `${unread.length} reading(s) not made`);
726
+ this.log(`Unwidened reading stopped ${stage}: it ran past its last-resort time limit ` +
727
+ `(${this.unwidenedLimits.backstopMs} ms), ${unread.length} reading(s) not made`);
708
728
  for (const plan of unread)
709
729
  plan.result.unwidened_out_of_budget = true;
710
730
  return true;
711
731
  };
712
- const plans = [];
713
- const insertionsByFile = new Map();
714
- const checkedFiles = new Set();
732
+ const planned = [];
715
733
  // Every position is read before the first rewrite: a rewrite forgets
716
734
  // every node of its file.
717
735
  for (const { request, result, readSpan } of responses) {
@@ -724,25 +742,21 @@ export class TypeInferrer {
724
742
  if (!readNode)
725
743
  continue;
726
744
  const functions = pathOf(readNode);
727
- let marked = 0;
745
+ const planInsertions = [];
728
746
  for (const fn of functions) {
729
747
  const insertions = literalInsertions(fn, read === 'request_body' ? readNode : undefined);
730
- marked += insertions.length;
731
748
  if (insertions.length === 0)
732
749
  continue;
733
- const file = fn.getSourceFile();
734
- insertionsByFile.set(file, [...(insertionsByFile.get(file) ?? []), ...insertions]);
750
+ planInsertions.push([fn.getSourceFile(), insertions]);
735
751
  }
736
752
  // Nothing on the path to mark: the reading would equal the published type.
737
- if (marked === 0)
753
+ if (planInsertions.length === 0)
738
754
  continue;
739
755
  const path = functions.map((fn) => ({
740
756
  file: fn.getSourceFile(),
741
757
  start: fn.getStart(),
742
758
  end: fn.getEnd(),
743
759
  }));
744
- for (const fn of path)
745
- checkedFiles.add(fn.file);
746
760
  let locatedByText;
747
761
  if (request.expression_text && request.span_start === undefined) {
748
762
  const sourceFile = this.getSourceFile(request.file_path);
@@ -752,24 +766,62 @@ export class TypeInferrer {
752
766
  if (located)
753
767
  locatedByText = { start: located.getStart(), end: located.getEnd() };
754
768
  }
755
- plans.push({
769
+ planned.push({
756
770
  request,
757
771
  result,
758
772
  read: { file: readNode.getSourceFile(), start: readNode.getStart(), end: readNode.getEnd() },
759
773
  path,
774
+ insertions: planInsertions,
760
775
  locatedByText,
761
776
  });
762
777
  }
763
- if (plans.length === 0)
778
+ if (planned.length === 0)
764
779
  return;
780
+ // The work cap: requests are taken in order while both allowances last.
781
+ const checkedFiles = new Set();
782
+ let taken = 0;
783
+ for (const plan of planned) {
784
+ const added = new Set(plan.path.map((fn) => fn.file).filter((f) => !checkedFiles.has(f)));
785
+ if (work.readings < 1 || added.size > work.files)
786
+ break;
787
+ work.readings -= 1;
788
+ work.files -= added.size;
789
+ for (const file of added)
790
+ checkedFiles.add(file);
791
+ taken += 1;
792
+ }
793
+ const plans = planned.slice(0, taken);
794
+ const capped = planned.slice(taken);
795
+ if (capped.length > 0) {
796
+ this.log(`Unwidened reading stopped at its work cap (${this.unwidenedLimits.readings} readings, ` +
797
+ `${this.unwidenedLimits.files} files per batch): ${capped.length} reading(s) not made`);
798
+ for (const plan of capped)
799
+ plan.result.unwidened_out_of_budget = true;
800
+ }
801
+ /** Readings that came back narrower than the published type, and so were published. */
802
+ let narrower = 0;
803
+ const report = () => this.log(`Unwidened reading of ${read === 'response' ? 'responses' : 'request bodies'}: ` +
804
+ `${planned.length} planned, ${plans.length} taken over ${checkedFiles.size} file(s), ` +
805
+ `${narrower} narrower than published, ${Math.round(this.now() - started)} ms`);
806
+ if (plans.length === 0) {
807
+ report();
808
+ return;
809
+ }
810
+ const insertionsByFile = new Map();
811
+ for (const plan of plans) {
812
+ for (const [file, list] of plan.insertions) {
813
+ insertionsByFile.set(file, [...(insertionsByFile.get(file) ?? []), ...list]);
814
+ }
815
+ }
765
816
  const insertions = new Map();
766
817
  for (const [file, list] of insertionsByFile)
767
818
  insertions.set(file, normalise(list));
768
819
  const before = new Map();
769
820
  for (const file of checkedFiles) {
770
821
  if (outOfTime('before the rewrite', plans))
771
- return;
822
+ return report();
772
823
  before.set(file, fileDiagnostics(file));
824
+ work.step();
773
825
  }
774
826
  const originals = new Map();
775
827
  for (const file of insertions.keys())
@@ -784,9 +836,11 @@ export class TypeInferrer {
784
836
  const tainted = new Set();
785
837
  for (const file of checkedFiles) {
786
838
  if (outOfTime('while checking the rewrite', plans))
787
- return;
839
+ return report();
788
840
  const list = insertions.get(file) ?? [];
789
- for (const at of addedDiagnostics(before.get(file), fileDiagnostics(file), list)) {
841
+ const after = fileDiagnostics(file);
842
+ work.step();
843
+ for (const at of addedDiagnostics(before.get(file), after, list)) {
790
844
  const holders = plans.flatMap((plan) => plan.path).filter((fn) => fn.file === file && fn.start <= at && at < fn.end);
791
845
  for (const plan of plans) {
792
846
  const onPath = plan.path.some((fn) => holders.length > 0 ? holders.includes(fn) : fn.file === file);
@@ -797,7 +851,7 @@ export class TypeInferrer {
797
851
  }
798
852
  for (const [at, plan] of plans.entries()) {
799
853
  if (outOfTime('while re-reading', plans.slice(at).filter((rest) => !tainted.has(rest)))) {
800
- return;
854
+ return report();
801
855
  }
802
856
  if (tainted.has(plan)) {
803
857
  this.log(`Unwidened reading for ${plan.request.file_path}:${plan.request.line_number} ` +
@@ -812,6 +866,7 @@ export class TypeInferrer {
812
866
  catch {
813
867
  again = null;
814
868
  }
869
+ work.step();
815
870
  if (!again || again.type_string === plan.result.type_string)
816
871
  continue;
817
872
  // An invariant, not a case: `mappedRequest` is what keeps the re-read
@@ -830,7 +885,9 @@ export class TypeInferrer {
830
885
  continue;
831
886
  }
832
887
  plan.result.unwidened_type_string = again.type_string;
888
+ narrower += 1;
833
889
  }
890
+ report();
834
891
  }
835
892
  finally {
836
893
  for (const [file, text] of originals)
@@ -1094,7 +1151,8 @@ export class TypeInferrer {
1094
1151
  // annotates (`satisfies` / `as` / `<T>`): the developer stated the
1095
1152
  // contract, so it is a claim rather than a guess.
1096
1153
  const machinery = unwrapResult.verifiedMachinery === true ||
1097
- this.typeIsOrContainsResponseMachinery(awaitedType);
1154
+ this.typeIsOrContainsResponseMachinery(awaitedType) ||
1155
+ this.returnsLabelledSend(func);
1098
1156
  const unresolvable = awaitedType.isAny() || awaitedType.isUnknown();
1099
1157
  if (machinery || unresolvable) {
1100
1158
  const recovered = this.recoverPayloadFromReturnStatements(func, !machinery, this.wireFormatFor(request));
@@ -1841,8 +1899,20 @@ export class TypeInferrer {
1841
1899
  (func.getStartLineNumber() <= request.line_number &&
1842
1900
  request.line_number <= func.getEndLineNumber());
1843
1901
  const returnedBranches = this.responseReturnedExpressions(func).flatMap((expression) => this.expandResponseBranches(expression, 0));
1844
- const serialisers = this.calleesProvenSerialiser(returnedBranches);
1845
- const isSend = (candidate) => this.isResponseSend(candidate, extractionConfig, serialisers);
1902
+ // carrick#2472 C2: the service's labels answer first. A labelled send is
1903
+ // a send, an unlabelled member of a labelled reply object is a setter;
1904
+ // where no label speaks, the structural reading decides.
1905
+ const labelledSend = (candidate) => this.statedParams.sendAt(this.peelTransparentExpression(candidate));
1906
+ const isLabelledSend = (candidate) => {
1907
+ const labelled = labelledSend(candidate);
1908
+ return labelled !== undefined && labelled !== 'setter';
1909
+ };
1910
+ const isSend = (candidate) => {
1911
+ const labelled = labelledSend(candidate);
1912
+ if (labelled !== undefined)
1913
+ return labelled !== 'setter';
1914
+ return this.isResponseSend(candidate, extractionConfig);
1915
+ };
1846
1916
  // carrick#2427: a handler that sends through a parameter returns nothing,
1847
1917
  // its sends are statements, and the located one can be an error send.
1848
1918
  // Statement sends find and drop that branch. A call whose result is
@@ -1872,9 +1942,12 @@ export class TypeInferrer {
1872
1942
  branches = [
1873
1943
  ...returnedBranches,
1874
1944
  ...statementSends
1945
+ // A labelled send is a body wherever it sits (carrick#2472 C2).
1875
1946
  // FROZEN (old path, 2026-10-21): the `statementEndsFunctionPath` test
1876
1947
  // here; see that method.
1877
- .filter((s) => s.send === locatedBranch || this.statementEndsFunctionPath(s.statement, func))
1948
+ .filter((s) => s.send === locatedBranch ||
1949
+ isLabelledSend(s.send) ||
1950
+ this.statementEndsFunctionPath(s.statement, func))
1878
1951
  .map((s) => s.send),
1879
1952
  ];
1880
1953
  }
@@ -2003,19 +2076,31 @@ export class TypeInferrer {
2003
2076
  // wrong or missing types go in labelled sends (carrick#2472 C4). Delete when
2004
2077
  // a delete-and-replay on the four repos moves no row wrongly, after
2005
2078
  // carrick-cloud#2379 and carrick#2445 (carrick#2472, C6).
2079
+ /**
2080
+ * The handler returns a send the service's labels name (carrick#3053): a
2081
+ * `new` construction or a static call whose declaration a verified label
2082
+ * keys. Its result is transport whatever its type looks like, so the body
2083
+ * is read from the send's argument.
2084
+ */
2085
+ returnsLabelledSend(func) {
2086
+ if (!this.statedParams.readsReplies)
2087
+ return false;
2088
+ return this.responseReturnedExpressions(func)
2089
+ .flatMap((expression) => this.expandResponseBranches(expression, 0))
2090
+ .some((branch) => {
2091
+ const labelled = this.statedParams.sendAt(this.peelTransparentExpression(branch));
2092
+ return labelled !== undefined && labelled !== 'setter';
2093
+ });
2094
+ }
2006
2095
  /**
2007
2096
  * True when `candidate` is a response send: a call or `new` whose result is
2008
2097
  * transport machinery (by the extraction config's verified rule or the
2009
- * structural check), or whose callee this handler's own returns prove is a
2010
- * serialiser (`calleesProvenSerialiser`, which holds on a bare checkout).
2098
+ * structural check).
2011
2099
  */
2012
- isResponseSend(candidate, extractionConfig, serialisers) {
2100
+ isResponseSend(candidate, extractionConfig) {
2013
2101
  const call = this.peelTransparentExpression(candidate);
2014
2102
  if (!Node.isCallExpression(call) && !Node.isNewExpression(call))
2015
2103
  return false;
2016
- const identity = this.calleeIdentity(call);
2017
- if (identity !== undefined && serialisers.has(identity))
2018
- return true;
2019
2104
  const result = this.unwrapPromiseType(call.getType());
2020
2105
  if (result.isAny() || result.isUnknown())
2021
2106
  return false;
@@ -2151,7 +2236,11 @@ export class TypeInferrer {
2151
2236
  typeString = unwrapResult.typeString;
2152
2237
  isExplicit = unwrapResult.isExplicit;
2153
2238
  }
2154
- const explicitType = this.extractExplicitTypeFromAncestor(terminalNode);
2239
+ // carrick#3004: around a call whose body a chain callback reshapes, an
2240
+ // annotation or a cast further out states the reshaped value.
2241
+ const explicitType = use.handedUnreadBody
2242
+ ? null
2243
+ : this.extractExplicitTypeFromAncestor(terminalNode);
2155
2244
  if (explicitType) {
2156
2245
  typeString = explicitType;
2157
2246
  isExplicit = true;
@@ -2161,7 +2250,7 @@ export class TypeInferrer {
2161
2250
  // source narrows the value later (`return json as { data: Item[] }`).
2162
2251
  // The narrowed statement is the body, and it is reported as stated, so a
2163
2252
  // model symbol naming an element inside it is not kept as the body.
2164
- const narrowed = func ? this.narrowedBodyStatement(terminalNode, func) : undefined;
2253
+ const narrowed = func && !use.handedUnreadBody ? this.narrowedBodyStatement(terminalNode, func) : undefined;
2165
2254
  if (narrowed) {
2166
2255
  typeString = narrowed.text;
2167
2256
  isExplicit = true;
@@ -2341,6 +2430,28 @@ export class TypeInferrer {
2341
2430
  // typed parameter. A function that converts the value into something new
2342
2431
  // states nothing about it, and neither does a use on a failure path.
2343
2432
  const untypedAnswer = typeString.trim() === 'any' || typeString.trim() === 'unknown';
2433
+ // carrick#3004: the call's own value is untyped and a callback in its
2434
+ // chain is handed it unread and builds a new value from it. The function
2435
+ // around the call states that new value, not the body, so nothing here
2436
+ // is a response contract. The decision rides the row: a plain answer is
2437
+ // re-read by the capture's own locator, which publishes the chain end.
2438
+ // A carrier's payload or a rule's that is itself a carrier of an untyped
2439
+ // value (a transport response around `unknown`) is no read either.
2440
+ const callPayload = carrierPayload ??
2441
+ (unwrapResult.wasUnwrapped && !untypedAnswer ? unwrapResult.payloadType : undefined) ??
2442
+ returnType;
2443
+ if (use.handedUnreadBody && (untypedAnswer || this.holdsTopTypeArgument(callPayload))) {
2444
+ this.log(`Call result at ${where} is untyped and handed unread to a callback that builds a ` +
2445
+ 'new value from it; this site states no response contract');
2446
+ return this.decidedAbstain(request, this.getNodeLocation(callExpr), {
2447
+ path: '',
2448
+ kind: 'unknown',
2449
+ reason: 'reshaped_by_callback',
2450
+ detail: "this call's result is handed unread to a callback in its chain that builds a new " +
2451
+ 'value from it, and nothing in the chain states the body, so the value the chain ' +
2452
+ 'ends in is not the response this call receives',
2453
+ });
2454
+ }
2344
2455
  if (untypedAnswer && func && !explicitType && !unwrapResult.wasUnwrapped && !carrierPayload) {
2345
2456
  const stated = this.statedInFunction(callExpr, func, {
2346
2457
  returned: true,
@@ -3083,9 +3194,14 @@ export class TypeInferrer {
3083
3194
  // the body unread and casts it. That cast is the body read, and it comes
3084
3195
  // before the return-statement answer below, which for a chain is the
3085
3196
  // value the caller computed from the body, not the body.
3086
- const chainRead = this.bodyReadInCallbackChain(callExpr);
3087
- if (chainRead) {
3088
- return { terminal: chainRead, projectionOnly: false, projections: [] };
3197
+ const chain = this.bodyReadInCallbackChain(callExpr);
3198
+ if (chain.read) {
3199
+ return { terminal: chain.read, projectionOnly: false, projections: [] };
3200
+ }
3201
+ // carrick#3004: a callback is handed the body unread and nothing states
3202
+ // it. The return below would answer the value that callback built.
3203
+ if (chain.handedUnread) {
3204
+ return { terminal: callExpr, projectionOnly: false, projections: [], handedUnreadBody: true };
3089
3205
  }
3090
3206
  // A return statement answers only for a call of the function it returns
3091
3207
  // from (carrick#2282). The nearest `return` above a call in a callback is
@@ -4315,14 +4431,21 @@ export class TypeInferrer {
4315
4431
  * the chain ends in is what the caller computed from it, and publishing
4316
4432
  * that as the body is the false mismatch this rule exists for.
4317
4433
  *
4318
- * Exactly one such cast across the whole chain answers. None, or more than
4434
+ * A call that narrows that parameter (a schema validates it, or a function
4435
+ * returns it unchanged) states it the same way (carrick#3004).
4436
+ *
4437
+ * Exactly one such read across the whole chain answers. None, or more than
4319
4438
  * one (a callback on the failure side can be handed an `unknown` too), and
4320
- * the walk carries on as before. A parameter typed `any` is not read: an
4321
- * unresolved library types every callback that way, success and failure
4322
- * alike, so it says nothing about which one is the body.
4439
+ * `handedUnread` says a callback was handed the body all the same: what it
4440
+ * returns is a value built from the body (`.mapOk`, `.then`, `.andThen`,
4441
+ * whatever the name), so the value the chain ends in is never the body
4442
+ * (carrick#3004). A parameter typed `any` is not read: an unresolved
4443
+ * library types every callback that way, success and failure alike, so it
4444
+ * says nothing about which one is the body.
4323
4445
  */
4324
4446
  bodyReadInCallbackChain(callExpr) {
4325
4447
  const reads = [];
4448
+ let handedUnread = false;
4326
4449
  let receiver = callExpr;
4327
4450
  for (let link = 0; link < 64; link++) {
4328
4451
  const access = receiver.getParent();
@@ -4337,36 +4460,62 @@ export class TypeInferrer {
4337
4460
  }
4338
4461
  for (const arg of call.getArguments()) {
4339
4462
  if (Node.isArrowFunction(arg) || Node.isFunctionExpression(arg)) {
4340
- reads.push(...this.castsOfUnreadParameter(arg));
4463
+ const statements = this.statementsOfUnreadParameter(arg);
4464
+ if (statements) {
4465
+ handedUnread = true;
4466
+ reads.push(...statements);
4467
+ }
4341
4468
  }
4342
4469
  }
4343
4470
  receiver = call;
4344
4471
  }
4345
- return reads.length === 1 ? reads[0] : undefined;
4472
+ return reads.length === 1 ? { read: reads[0], handedUnread } : { handedUnread };
4346
4473
  }
4347
4474
  /**
4348
- * The casts of a callback's first parameter, when the compiler types that
4349
- * parameter `unknown`: `response as T` and `<T>response`, the operand being
4350
- * the parameter itself. A cast that leaves a position open states nothing
4351
- * about the body and is skipped.
4475
+ * `type`, or a type argument it is instantiated with at any depth, is
4476
+ * `any` or `unknown`: `Chain<unknown>`, `Task<Outcome<unknown, E>>`. The
4477
+ * value such a carrier hands its callbacks is untyped (carrick#3004).
4352
4478
  */
4353
- castsOfUnreadParameter(callback) {
4479
+ holdsTopTypeArgument(type, depth = 0) {
4480
+ if (type.isAny() || type.isUnknown())
4481
+ return true;
4482
+ if (depth >= 6)
4483
+ return false;
4484
+ const args = [...type.getTypeArguments(), ...type.getAliasTypeArguments()];
4485
+ return args.some((arg) => this.holdsTopTypeArgument(arg, depth + 1));
4486
+ }
4487
+ /**
4488
+ * What a callback states about its first parameter, when the compiler types
4489
+ * that parameter `unknown`, or `undefined` when it is not handed one. A
4490
+ * statement is a cast whose operand is the parameter itself (`response as
4491
+ * T`, `<T>response`), or a call that narrows it (`callStatesItsArgument`:
4492
+ * a schema validates it, or a function returns it unchanged). A cast that
4493
+ * leaves a position open states nothing about the body and is skipped.
4494
+ */
4495
+ statementsOfUnreadParameter(callback) {
4354
4496
  const param = callback.getParameters()[0];
4355
4497
  const name = param?.getNameNode();
4356
4498
  if (!param || !name || !Node.isIdentifier(name) || !param.getType().isUnknown()) {
4357
- return [];
4499
+ return undefined;
4358
4500
  }
4359
4501
  const symbol = name.getSymbol();
4360
4502
  if (!symbol)
4361
4503
  return [];
4362
- return callback.getDescendants().filter((node) => {
4363
- if (!Node.isAsExpression(node) && !Node.isTypeAssertion(node))
4364
- return false;
4365
- let operand = node.getExpression();
4504
+ const isParameter = (node) => {
4505
+ let operand = node;
4366
4506
  while (Node.isParenthesizedExpression(operand)) {
4367
4507
  operand = operand.getExpression();
4368
4508
  }
4369
- if (!Node.isIdentifier(operand) || operand.getSymbol() !== symbol)
4509
+ return Node.isIdentifier(operand) && operand.getSymbol() === symbol;
4510
+ };
4511
+ return callback.getDescendants().filter((node) => {
4512
+ if (Node.isCallExpression(node)) {
4513
+ const index = node.getArguments().findIndex(isParameter);
4514
+ return index >= 0 && this.callStatesItsArgument(node, index);
4515
+ }
4516
+ if (!Node.isAsExpression(node) && !Node.isTypeAssertion(node))
4517
+ return false;
4518
+ if (!isParameter(node.getExpression()))
4370
4519
  return false;
4371
4520
  const stated = node.getType();
4372
4521
  const statedNode = node.getTypeNode();
@@ -5334,11 +5483,8 @@ export class TypeInferrer {
5334
5483
  const candidates = [];
5335
5484
  const returned = expressions.flatMap((expression) => this.expandResponseBranches(expression, 0));
5336
5485
  // `alsoSerialisers` are callees a caller has its own evidence for
5337
- // (`calleeIdentity` keys), beside the ones these expressions prove.
5338
- const serialisers = this.calleesProvenSerialiser(returned);
5339
- for (const identity of alsoSerialisers ?? []) {
5340
- serialisers.add(identity);
5341
- }
5486
+ // (`calleeIdentity` keys).
5487
+ const serialisers = new Set(alsoSerialisers ?? []);
5342
5488
  for (const expression of returned) {
5343
5489
  const payloadNode = this.responseHelperPayloadNode(expression, 0, statedOnly, serialisers);
5344
5490
  if (!payloadNode)
@@ -6047,59 +6193,6 @@ export class TypeInferrer {
6047
6193
  }
6048
6194
  return flattened;
6049
6195
  }
6050
- // FROZEN (old path, 2026-10-21): this method only. Deletions and safety fixes
6051
- // only. Fixes for wrong or missing types go in labelled sends (carrick#2472
6052
- // C4). Delete when a delete-and-replay on the four repos moves no row
6053
- // wrongly, after carrick-cloud#2379 and carrick#2445 (carrick#2472, C6).
6054
- /**
6055
- * The callees these returned expressions PROVE are response serialisers.
6056
- *
6057
- * A return type of `any` says the callee could not be resolved, not that it
6058
- * was a serialiser — the reason the unresolvable-callee case is otherwise
6059
- * restricted to arguments the source annotates. But a handler that writes
6060
- *
6061
- * return f(problem, { status: 401 });
6062
- * return f(payload);
6063
- *
6064
- * has stated what `f` is in its own source: a call that takes a body and,
6065
- * beside it, an HTTP status is a response serialiser, and nothing else is
6066
- * written that way. That is evidence the compiler does not need to resolve
6067
- * anything to see, so it survives the bare checkout CI scans, and it makes
6068
- * the second call's unannotated argument a payload rather than a guess.
6069
- *
6070
- * Three deliberate limits, each a negative test:
6071
- * - only RETURNED expressions count. A handler may well call a logger with
6072
- * `{ status: 500 }`; what it returns is what it serialises.
6073
- * - the status-stating argument must sit at index >= 1. A status in FIRST
6074
- * position is a field of the body (`{ status: 503, note }`), and reading
6075
- * it as evidence would promote every callee that takes a status field.
6076
- * - the evidence is per HANDLER, never cached across files. It says what
6077
- * this handler does, and that is all it is used for.
6078
- *
6079
- * Callees are keyed by resolved symbol where one exists — an import alias
6080
- * resolves locally even when its module does not — and by callee text
6081
- * otherwise.
6082
- */
6083
- calleesProvenSerialiser(returned) {
6084
- const proven = new Set();
6085
- for (const expression of returned) {
6086
- const call = this.peelTransparentExpression(expression);
6087
- if (!Node.isCallExpression(call))
6088
- continue;
6089
- const args = call.getArguments().map((a) => this.peelTransparentExpression(a));
6090
- if (args.length < 2)
6091
- continue;
6092
- const statesStatus = args
6093
- .slice(1)
6094
- .some((arg) => Array.isArray(this.statedStatusCodes(arg)));
6095
- if (!statesStatus)
6096
- continue;
6097
- const key = this.calleeIdentity(call);
6098
- if (key)
6099
- proven.add(key);
6100
- }
6101
- return proven;
6102
- }
6103
6196
  /**
6104
6197
  * Stable identity for a call's callee within one file: its resolved symbol
6105
6198
  * when the compiler has one, else the callee's source text.
@@ -6129,9 +6222,7 @@ export class TypeInferrer {
6129
6222
  *
6130
6223
  * `statedOnly` narrows what counts as a payload to an argument the source
6131
6224
  * annotates; see `recoverPayloadFromReturnStatements`. It is lifted for a
6132
- * callee the handler's own returned calls PROVE is a serialiser
6133
- * (`calleesProvenSerialiser`): there the source has stated what the callee
6134
- * is, so its argument is the payload even unannotated.
6225
+ * callee a caller has its own evidence for (`serialisers`).
6135
6226
  */
6136
6227
  responseHelperPayloadNode(expression, depth, statedOnly, serialisers) {
6137
6228
  if (depth > RESPONSE_HELPER_MAX_DEPTH)
@@ -6151,6 +6242,16 @@ export class TypeInferrer {
6151
6242
  const status = this.responseSiteStatus(call);
6152
6243
  if (status === 'error' || status === 'redirect')
6153
6244
  return undefined;
6245
+ // carrick#3053: a send the service's labels name carries its body in the
6246
+ // slot the label states, read as a labelled call send reads it.
6247
+ const labelled = this.statedParams.sendAt(call);
6248
+ if (labelled !== undefined && labelled !== 'setter') {
6249
+ const body = args[labelled.arg];
6250
+ if (!body || Node.isSpreadElement(body))
6251
+ return undefined;
6252
+ const slotted = this.unwrapJsonStringifyArg(body);
6253
+ return this.nodeCarriesPayloadContract(slotted, false) ? slotted : undefined;
6254
+ }
6154
6255
  const identity = this.calleeIdentity(call);
6155
6256
  const proven = identity !== undefined && serialisers.has(identity);
6156
6257
  const effectiveStatedOnly = statedOnly && !proven;
@@ -8377,26 +8478,42 @@ export class TypeInferrer {
8377
8478
  if (sourceFile.isDeclarationFile())
8378
8479
  return false;
8379
8480
  return !isExternalOrigin(this.project.getProgram().compilerObject, sourceFile.compilerNode, this.repoRoot, externalImportsOf(this.project));
8380
- }, (call) => this.chainStatus(call));
8481
+ }, (call) => this.chainStatus(call), (value) => this.statusOfValue(value), (value) => this.unwrapJsonStringifyArg(this.unwrapExpressionNode(value)));
8381
8482
  }
8382
8483
  /**
8383
8484
  * carrick#2674: where today's reading of a route's response is empty
8384
8485
  * (nothing, `void`, or an `unknown` the inferrer did not decide), the reply
8385
8486
  * its handler's parameter states, cut to its success variants. A typed
8386
8487
  * reading, or a decided abstain, stands as it is.
8488
+ *
8489
+ * carrick#3054: a route whose receive op carries a `returns` label replies
8490
+ * with what its handler returns. A labelled send the handler's parameters
8491
+ * state wins over the return. The returned reply replaces a typed reading
8492
+ * only where it prints differently (the label names a part of the return,
8493
+ * or a nothing part is dropped); where it prints the same, today's reading
8494
+ * stands with everything it carries.
8387
8495
  */
8388
8496
  withStatedReply(sourceFile, request, today) {
8389
- if (!this.statedParams.readsReplies)
8497
+ const reads = this.statedParams.readsReplies;
8498
+ if (!reads && !this.statedParams.readsReturns)
8390
8499
  return today;
8391
- if (today && !this.isEmptyResponseReading(today))
8500
+ const empty = !today || this.isEmptyResponseReading(today);
8501
+ if (reads && !empty && !this.statedParams.readsReturns)
8392
8502
  return today;
8393
- const handler = this.registrationAtLine(sourceFile, request.line_number)?.handler ??
8394
- this.exportedFunctionOpeningOn(sourceFile, request.line_number);
8503
+ const at = this.registrationAtLine(sourceFile, request.line_number);
8504
+ const handler = at?.handler ?? this.exportedFunctionOpeningOn(sourceFile, request.line_number);
8395
8505
  if (!handler)
8396
8506
  return today;
8397
- const stated = this.statedParams.reply(handler);
8398
- if (!stated)
8507
+ const sent = reads ? this.statedParams.reply(handler) : undefined;
8508
+ if (sent) {
8509
+ return empty ? this.publishStatedReply(request, handler, sent, today, "its handler's reply parameter states the body") : today;
8510
+ }
8511
+ const returned = at ? this.statedParams.returned(at.registration, handler) : undefined;
8512
+ if (!returned)
8399
8513
  return today;
8514
+ return this.publishStatedReply(request, handler, returned, today, 'its handler returns the reply');
8515
+ }
8516
+ publishStatedReply(request, handler, stated, today, why) {
8400
8517
  const texts = [];
8401
8518
  for (const variant of stated.variants) {
8402
8519
  const text = this.structuralTextFromType(variant, stated.at);
@@ -8407,8 +8524,11 @@ export class TypeInferrer {
8407
8524
  return today;
8408
8525
  texts.push(text);
8409
8526
  }
8410
- this.log(`Route at ${request.file_path}:${request.line_number}: its handler's reply parameter states the body`);
8411
- return this.createInferredType(request, texts.length === 1 ? texts[0] : texts.map((text) => `(${text})`).join(' | '), true, this.getNodeLocation(handler));
8527
+ const printed = texts.length === 1 ? texts[0] : texts.map((text) => `(${text})`).join(' | ');
8528
+ if (today && today.type_string === printed)
8529
+ return today;
8530
+ this.log(`Route at ${request.file_path}:${request.line_number}: ${why}`);
8531
+ return this.createInferredType(request, printed, true, this.getNodeLocation(handler));
8412
8532
  }
8413
8533
  /** Nothing read: `void`, or an `unknown` with no decided reason at its root. */
8414
8534
  isEmptyResponseReading(inferred) {