carrick 0.3.134 → 0.3.136

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.
@@ -74,16 +74,40 @@ export interface TypeInferrerOptions {
74
74
  */
75
75
  repoRoot: string;
76
76
  /**
77
- * How long the unwidened reading of one `infer` batch may take
78
- * (carrick#1516). Defaults to `UNWIDENED_BUDGET_MS`.
77
+ * How much work the unwidened reading of one `infer` batch may do
78
+ * (carrick#2629). Each field defaults to its `UNWIDENED_*` constant.
79
79
  */
80
- unwidenedBudgetMs?: number;
80
+ unwidenedLimits?: Partial<UnwidenedLimits>;
81
+ /**
82
+ * The clock the unwidened reading's last-resort time limit reads, in
83
+ * milliseconds. Defaults to `performance.now`; a test passes a slow one.
84
+ */
85
+ now?: () => number;
86
+ }
87
+ /**
88
+ * The bounds on one batch's unwidened reading (carrick#2629). The first two
89
+ * count work, so a batch reads the same on a quiet machine and a loaded one;
90
+ * the third is a wall-clock backstop for a reading that runs away.
91
+ */
92
+ export interface UnwidenedLimits {
93
+ /** Readings (requests re-read in the rewrite) one batch may make. */
94
+ readings: number;
95
+ /** Files one batch may type-check before and after its rewrite. */
96
+ files: number;
97
+ /** The longest the reading may run, from its start, before it stops. */
98
+ backstopMs: number;
81
99
  }
82
100
  /**
83
101
  * Called each time an `infer` batch is done with one of its requests,
84
102
  * whatever that request answered: skipped, refused, failed or inferred.
85
103
  */
86
104
  export type InferRequestDone = () => void;
105
+ /**
106
+ * Called each time the unwidened reading finishes a unit of its work: a file
107
+ * type-checked or a request re-read (carrick#2629). The reading runs after
108
+ * every request is done, so this is what keeps a long one from going silent.
109
+ */
110
+ export type UnwidenedStepDone = () => void;
87
111
  /**
88
112
  * TypeInferrer - Extracts types from source code, both explicit and inferred
89
113
  *
@@ -101,7 +125,8 @@ export declare class TypeInferrer {
101
125
  * unwidened reading re-reads from here (carrick#1516).
102
126
  */
103
127
  private readonly readNodes;
104
- private readonly unwidenedBudgetMs;
128
+ private readonly unwidenedLimits;
129
+ private readonly now;
105
130
  /**
106
131
  * The files a request has named to this inferrer, as the requests named
107
132
  * them (carrick#1985). It lives as long as the project does, so the first
@@ -122,9 +147,10 @@ export declare class TypeInferrer {
122
147
  * @param requests - Array of inference requests
123
148
  * @param extractionConfig - Agent-generated extraction config for payload unwrapping
124
149
  * @param onRequestDone - Called once per request, as the batch is done with it
150
+ * @param onUnwidenedStep - Called once per unit of the unwidened reading's work
125
151
  * @returns InferResult with inferred types or errors
126
152
  */
127
- infer(requests: InferRequestItem[], extractionConfig?: ExtractionConfig, onRequestDone?: InferRequestDone, modelSymbols?: ModelSymbol[], labels?: LabelledMembers): InferResult;
153
+ infer(requests: InferRequestItem[], extractionConfig?: ExtractionConfig, onRequestDone?: InferRequestDone, modelSymbols?: ModelSymbol[], labels?: LabelledMembers, onUnwidenedStep?: UnwidenedStepDone): InferResult;
128
154
  /** The types the model named, by the alias of the row each is for (carrick#2111). */
129
155
  private modelSymbols;
130
156
  /**
@@ -177,11 +203,15 @@ export declare class TypeInferrer {
177
203
  * and every file restored before returning, so the project other requests
178
204
  * read is the project the scan loaded.
179
205
  *
180
- * Nothing is read past `deadline`: a batch that runs out keeps the readings
181
- * it made and publishes none for the rest, and marks each of the rest
182
- * `unwidened_out_of_budget` (carrick#2100). A request that never needed a
183
- * reading (a declared return, nothing to mark) or lost it for a reason of
184
- * its own (a marking that added a diagnostic) is never marked.
206
+ * The reading is bounded by work, not time (carrick#2629): a batch makes at
207
+ * most `UnwidenedLimits.readings` readings over at most `.files` files,
208
+ * taken in request order, the responses first. The first request past
209
+ * either cap and every request after it are marked
210
+ * `unwidened_out_of_budget` (carrick#2100) and publish no reading, on any
211
+ * machine. A reading still running at the wall-clock backstop stops the
212
+ * same way and says so in the log. A request that never needed a reading
213
+ * (a declared return, nothing to mark) or lost it for a reason of its own
214
+ * (a marking that added a diagnostic) is never marked.
185
215
  */
186
216
  private addUnwidenedReadings;
187
217
  /**
@@ -893,20 +923,34 @@ export declare class TypeInferrer {
893
923
  * the chain ends in is what the caller computed from it, and publishing
894
924
  * that as the body is the false mismatch this rule exists for.
895
925
  *
896
- * Exactly one such cast across the whole chain answers. None, or more than
926
+ * A call that narrows that parameter (a schema validates it, or a function
927
+ * returns it unchanged) states it the same way (carrick#3004).
928
+ *
929
+ * Exactly one such read across the whole chain answers. None, or more than
897
930
  * one (a callback on the failure side can be handed an `unknown` too), and
898
- * the walk carries on as before. A parameter typed `any` is not read: an
899
- * unresolved library types every callback that way, success and failure
900
- * alike, so it says nothing about which one is the body.
931
+ * `handedUnread` says a callback was handed the body all the same: what it
932
+ * returns is a value built from the body (`.mapOk`, `.then`, `.andThen`,
933
+ * whatever the name), so the value the chain ends in is never the body
934
+ * (carrick#3004). A parameter typed `any` is not read: an unresolved
935
+ * library types every callback that way, success and failure alike, so it
936
+ * says nothing about which one is the body.
901
937
  */
902
938
  private bodyReadInCallbackChain;
903
939
  /**
904
- * The casts of a callback's first parameter, when the compiler types that
905
- * parameter `unknown`: `response as T` and `<T>response`, the operand being
906
- * the parameter itself. A cast that leaves a position open states nothing
907
- * about the body and is skipped.
940
+ * `type`, or a type argument it is instantiated with at any depth, is
941
+ * `any` or `unknown`: `Chain<unknown>`, `Task<Outcome<unknown, E>>`. The
942
+ * value such a carrier hands its callbacks is untyped (carrick#3004).
943
+ */
944
+ private holdsTopTypeArgument;
945
+ /**
946
+ * What a callback states about its first parameter, when the compiler types
947
+ * that parameter `unknown`, or `undefined` when it is not handed one. A
948
+ * statement is a cast whose operand is the parameter itself (`response as
949
+ * T`, `<T>response`), or a call that narrows it (`callStatesItsArgument`:
950
+ * a schema validates it, or a function returns it unchanged). A cast that
951
+ * leaves a position open states nothing about the body and is skipped.
908
952
  */
909
- private castsOfUnreadParameter;
953
+ private statementsOfUnreadParameter;
910
954
  /**
911
955
  * The zero-argument whole-body read taken in place on the value `callExpr`
912
956
  * yields, or `undefined` (carrick#1851): `(await fetch(url)).text()`. The
@@ -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,10 +469,10 @@ 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
477
  this.statedParams = this.statedParamsFor(labels ?? { sends: new Map(), bodies: new Set() });
470
478
  const inferredTypes = [];
@@ -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) {
@@ -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)
@@ -2151,7 +2208,11 @@ export class TypeInferrer {
2151
2208
  typeString = unwrapResult.typeString;
2152
2209
  isExplicit = unwrapResult.isExplicit;
2153
2210
  }
2154
- const explicitType = this.extractExplicitTypeFromAncestor(terminalNode);
2211
+ // carrick#3004: around a call whose body a chain callback reshapes, an
2212
+ // annotation or a cast further out states the reshaped value.
2213
+ const explicitType = use.handedUnreadBody
2214
+ ? null
2215
+ : this.extractExplicitTypeFromAncestor(terminalNode);
2155
2216
  if (explicitType) {
2156
2217
  typeString = explicitType;
2157
2218
  isExplicit = true;
@@ -2161,7 +2222,7 @@ export class TypeInferrer {
2161
2222
  // source narrows the value later (`return json as { data: Item[] }`).
2162
2223
  // The narrowed statement is the body, and it is reported as stated, so a
2163
2224
  // model symbol naming an element inside it is not kept as the body.
2164
- const narrowed = func ? this.narrowedBodyStatement(terminalNode, func) : undefined;
2225
+ const narrowed = func && !use.handedUnreadBody ? this.narrowedBodyStatement(terminalNode, func) : undefined;
2165
2226
  if (narrowed) {
2166
2227
  typeString = narrowed.text;
2167
2228
  isExplicit = true;
@@ -2341,6 +2402,28 @@ export class TypeInferrer {
2341
2402
  // typed parameter. A function that converts the value into something new
2342
2403
  // states nothing about it, and neither does a use on a failure path.
2343
2404
  const untypedAnswer = typeString.trim() === 'any' || typeString.trim() === 'unknown';
2405
+ // carrick#3004: the call's own value is untyped and a callback in its
2406
+ // chain is handed it unread and builds a new value from it. The function
2407
+ // around the call states that new value, not the body, so nothing here
2408
+ // is a response contract. The decision rides the row: a plain answer is
2409
+ // re-read by the capture's own locator, which publishes the chain end.
2410
+ // A carrier's payload or a rule's that is itself a carrier of an untyped
2411
+ // value (a transport response around `unknown`) is no read either.
2412
+ const callPayload = carrierPayload ??
2413
+ (unwrapResult.wasUnwrapped && !untypedAnswer ? unwrapResult.payloadType : undefined) ??
2414
+ returnType;
2415
+ if (use.handedUnreadBody && (untypedAnswer || this.holdsTopTypeArgument(callPayload))) {
2416
+ this.log(`Call result at ${where} is untyped and handed unread to a callback that builds a ` +
2417
+ 'new value from it; this site states no response contract');
2418
+ return this.decidedAbstain(request, this.getNodeLocation(callExpr), {
2419
+ path: '',
2420
+ kind: 'unknown',
2421
+ reason: 'reshaped_by_callback',
2422
+ detail: "this call's result is handed unread to a callback in its chain that builds a new " +
2423
+ 'value from it, and nothing in the chain states the body, so the value the chain ' +
2424
+ 'ends in is not the response this call receives',
2425
+ });
2426
+ }
2344
2427
  if (untypedAnswer && func && !explicitType && !unwrapResult.wasUnwrapped && !carrierPayload) {
2345
2428
  const stated = this.statedInFunction(callExpr, func, {
2346
2429
  returned: true,
@@ -3083,9 +3166,14 @@ export class TypeInferrer {
3083
3166
  // the body unread and casts it. That cast is the body read, and it comes
3084
3167
  // before the return-statement answer below, which for a chain is the
3085
3168
  // 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: [] };
3169
+ const chain = this.bodyReadInCallbackChain(callExpr);
3170
+ if (chain.read) {
3171
+ return { terminal: chain.read, projectionOnly: false, projections: [] };
3172
+ }
3173
+ // carrick#3004: a callback is handed the body unread and nothing states
3174
+ // it. The return below would answer the value that callback built.
3175
+ if (chain.handedUnread) {
3176
+ return { terminal: callExpr, projectionOnly: false, projections: [], handedUnreadBody: true };
3089
3177
  }
3090
3178
  // A return statement answers only for a call of the function it returns
3091
3179
  // from (carrick#2282). The nearest `return` above a call in a callback is
@@ -4315,14 +4403,21 @@ export class TypeInferrer {
4315
4403
  * the chain ends in is what the caller computed from it, and publishing
4316
4404
  * that as the body is the false mismatch this rule exists for.
4317
4405
  *
4318
- * Exactly one such cast across the whole chain answers. None, or more than
4406
+ * A call that narrows that parameter (a schema validates it, or a function
4407
+ * returns it unchanged) states it the same way (carrick#3004).
4408
+ *
4409
+ * Exactly one such read across the whole chain answers. None, or more than
4319
4410
  * 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.
4411
+ * `handedUnread` says a callback was handed the body all the same: what it
4412
+ * returns is a value built from the body (`.mapOk`, `.then`, `.andThen`,
4413
+ * whatever the name), so the value the chain ends in is never the body
4414
+ * (carrick#3004). A parameter typed `any` is not read: an unresolved
4415
+ * library types every callback that way, success and failure alike, so it
4416
+ * says nothing about which one is the body.
4323
4417
  */
4324
4418
  bodyReadInCallbackChain(callExpr) {
4325
4419
  const reads = [];
4420
+ let handedUnread = false;
4326
4421
  let receiver = callExpr;
4327
4422
  for (let link = 0; link < 64; link++) {
4328
4423
  const access = receiver.getParent();
@@ -4337,36 +4432,62 @@ export class TypeInferrer {
4337
4432
  }
4338
4433
  for (const arg of call.getArguments()) {
4339
4434
  if (Node.isArrowFunction(arg) || Node.isFunctionExpression(arg)) {
4340
- reads.push(...this.castsOfUnreadParameter(arg));
4435
+ const statements = this.statementsOfUnreadParameter(arg);
4436
+ if (statements) {
4437
+ handedUnread = true;
4438
+ reads.push(...statements);
4439
+ }
4341
4440
  }
4342
4441
  }
4343
4442
  receiver = call;
4344
4443
  }
4345
- return reads.length === 1 ? reads[0] : undefined;
4444
+ return reads.length === 1 ? { read: reads[0], handedUnread } : { handedUnread };
4445
+ }
4446
+ /**
4447
+ * `type`, or a type argument it is instantiated with at any depth, is
4448
+ * `any` or `unknown`: `Chain<unknown>`, `Task<Outcome<unknown, E>>`. The
4449
+ * value such a carrier hands its callbacks is untyped (carrick#3004).
4450
+ */
4451
+ holdsTopTypeArgument(type, depth = 0) {
4452
+ if (type.isAny() || type.isUnknown())
4453
+ return true;
4454
+ if (depth >= 6)
4455
+ return false;
4456
+ const args = [...type.getTypeArguments(), ...type.getAliasTypeArguments()];
4457
+ return args.some((arg) => this.holdsTopTypeArgument(arg, depth + 1));
4346
4458
  }
4347
4459
  /**
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.
4460
+ * What a callback states about its first parameter, when the compiler types
4461
+ * that parameter `unknown`, or `undefined` when it is not handed one. A
4462
+ * statement is a cast whose operand is the parameter itself (`response as
4463
+ * T`, `<T>response`), or a call that narrows it (`callStatesItsArgument`:
4464
+ * a schema validates it, or a function returns it unchanged). A cast that
4465
+ * leaves a position open states nothing about the body and is skipped.
4352
4466
  */
4353
- castsOfUnreadParameter(callback) {
4467
+ statementsOfUnreadParameter(callback) {
4354
4468
  const param = callback.getParameters()[0];
4355
4469
  const name = param?.getNameNode();
4356
4470
  if (!param || !name || !Node.isIdentifier(name) || !param.getType().isUnknown()) {
4357
- return [];
4471
+ return undefined;
4358
4472
  }
4359
4473
  const symbol = name.getSymbol();
4360
4474
  if (!symbol)
4361
4475
  return [];
4362
- return callback.getDescendants().filter((node) => {
4363
- if (!Node.isAsExpression(node) && !Node.isTypeAssertion(node))
4364
- return false;
4365
- let operand = node.getExpression();
4476
+ const isParameter = (node) => {
4477
+ let operand = node;
4366
4478
  while (Node.isParenthesizedExpression(operand)) {
4367
4479
  operand = operand.getExpression();
4368
4480
  }
4369
- if (!Node.isIdentifier(operand) || operand.getSymbol() !== symbol)
4481
+ return Node.isIdentifier(operand) && operand.getSymbol() === symbol;
4482
+ };
4483
+ return callback.getDescendants().filter((node) => {
4484
+ if (Node.isCallExpression(node)) {
4485
+ const index = node.getArguments().findIndex(isParameter);
4486
+ return index >= 0 && this.callStatesItsArgument(node, index);
4487
+ }
4488
+ if (!Node.isAsExpression(node) && !Node.isTypeAssertion(node))
4489
+ return false;
4490
+ if (!isParameter(node.getExpression()))
4370
4491
  return false;
4371
4492
  const stated = node.getType();
4372
4493
  const statedNode = node.getTypeNode();