@mailwoman/core 8.5.0 → 9.0.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.
Files changed (209) hide show
  1. package/README.md +2 -2
  2. package/api/clock.ts +1 -1
  3. package/api/disk-storage.ts +7 -4
  4. package/api/test-clocks.ts +57 -9
  5. package/api/test-transport.ts +182 -0
  6. package/coarse-placer/coarse-placer.ts +2 -1
  7. package/coarse-placer/tools/build-outlier-latin.ts +1 -0
  8. package/coarse-placer/tools/build-outlier-oa.ts +1 -0
  9. package/coarse-placer/tools/eval-latin-offmap.ts +7 -5
  10. package/coarse-placer/tools/eval-openset.ts +19 -10
  11. package/coarse-placer/tools/eval-quant-compare.ts +7 -7
  12. package/coarse-placer/tools/eval.ts +29 -21
  13. package/coarse-placer/tools/probe-frontier.ts +8 -4
  14. package/coarse-placer/tools/quantize.ts +2 -1
  15. package/coarse-placer/tools/train.ts +9 -8
  16. package/collections.ts +2 -128
  17. package/crypto/node.ts +68 -0
  18. package/env/schema.ts +49 -2
  19. package/identifiers.ts +48 -0
  20. package/layers/manifest.ts +2 -1
  21. package/locale/profiles/en-us.ts +2 -3
  22. package/locale/profiles/fr-fr.ts +1 -1
  23. package/locale/profiles/ja-jp.ts +7 -7
  24. package/objects.ts +40 -8
  25. package/out/api/clock.d.ts +1 -1
  26. package/out/api/clock.js +1 -1
  27. package/out/api/disk-storage.d.ts +1 -1
  28. package/out/api/disk-storage.d.ts.map +1 -1
  29. package/out/api/disk-storage.js +5 -5
  30. package/out/api/disk-storage.js.map +1 -1
  31. package/out/api/test-clocks.d.ts +2 -2
  32. package/out/api/test-clocks.d.ts.map +1 -1
  33. package/out/api/test-clocks.js +51 -9
  34. package/out/api/test-clocks.js.map +1 -1
  35. package/out/api/test-transport.d.ts +112 -0
  36. package/out/api/test-transport.d.ts.map +1 -0
  37. package/out/api/test-transport.js +84 -0
  38. package/out/api/test-transport.js.map +1 -0
  39. package/out/coarse-placer/coarse-placer.d.ts.map +1 -1
  40. package/out/coarse-placer/coarse-placer.js +2 -1
  41. package/out/coarse-placer/coarse-placer.js.map +1 -1
  42. package/out/coarse-placer/tools/build-outlier-latin.d.ts.map +1 -1
  43. package/out/coarse-placer/tools/build-outlier-latin.js +1 -0
  44. package/out/coarse-placer/tools/build-outlier-latin.js.map +1 -1
  45. package/out/coarse-placer/tools/build-outlier-oa.d.ts.map +1 -1
  46. package/out/coarse-placer/tools/build-outlier-oa.js +1 -0
  47. package/out/coarse-placer/tools/build-outlier-oa.js.map +1 -1
  48. package/out/coarse-placer/tools/eval-latin-offmap.d.ts.map +1 -1
  49. package/out/coarse-placer/tools/eval-latin-offmap.js +4 -5
  50. package/out/coarse-placer/tools/eval-latin-offmap.js.map +1 -1
  51. package/out/coarse-placer/tools/eval-openset.d.ts.map +1 -1
  52. package/out/coarse-placer/tools/eval-openset.js +11 -9
  53. package/out/coarse-placer/tools/eval-openset.js.map +1 -1
  54. package/out/coarse-placer/tools/eval-quant-compare.d.ts.map +1 -1
  55. package/out/coarse-placer/tools/eval-quant-compare.js +6 -7
  56. package/out/coarse-placer/tools/eval-quant-compare.js.map +1 -1
  57. package/out/coarse-placer/tools/eval.d.ts.map +1 -1
  58. package/out/coarse-placer/tools/eval.js +19 -19
  59. package/out/coarse-placer/tools/eval.js.map +1 -1
  60. package/out/coarse-placer/tools/probe-frontier.d.ts.map +1 -1
  61. package/out/coarse-placer/tools/probe-frontier.js +7 -5
  62. package/out/coarse-placer/tools/probe-frontier.js.map +1 -1
  63. package/out/coarse-placer/tools/quantize.d.ts.map +1 -1
  64. package/out/coarse-placer/tools/quantize.js +2 -1
  65. package/out/coarse-placer/tools/quantize.js.map +1 -1
  66. package/out/coarse-placer/tools/train.d.ts.map +1 -1
  67. package/out/coarse-placer/tools/train.js +6 -8
  68. package/out/coarse-placer/tools/train.js.map +1 -1
  69. package/out/collections.d.ts +1 -59
  70. package/out/collections.d.ts.map +1 -1
  71. package/out/collections.js +2 -90
  72. package/out/collections.js.map +1 -1
  73. package/out/crypto/node.d.ts +43 -0
  74. package/out/crypto/node.d.ts.map +1 -0
  75. package/out/crypto/node.js +43 -0
  76. package/out/crypto/node.js.map +1 -0
  77. package/out/env/index.d.ts +5 -0
  78. package/out/env/index.d.ts.map +1 -1
  79. package/out/env/schema.d.ts +6 -1
  80. package/out/env/schema.d.ts.map +1 -1
  81. package/out/env/schema.js +46 -2
  82. package/out/env/schema.js.map +1 -1
  83. package/out/identifiers.d.ts +23 -0
  84. package/out/identifiers.d.ts.map +1 -1
  85. package/out/identifiers.js +39 -0
  86. package/out/identifiers.js.map +1 -1
  87. package/out/layers/manifest.d.ts.map +1 -1
  88. package/out/layers/manifest.js +2 -1
  89. package/out/layers/manifest.js.map +1 -1
  90. package/out/locale/profiles/en-us.d.ts +2 -3
  91. package/out/locale/profiles/en-us.d.ts.map +1 -1
  92. package/out/locale/profiles/en-us.js +2 -3
  93. package/out/locale/profiles/en-us.js.map +1 -1
  94. package/out/locale/profiles/fr-fr.d.ts +1 -1
  95. package/out/locale/profiles/fr-fr.js +1 -1
  96. package/out/locale/profiles/ja-jp.d.ts +7 -7
  97. package/out/locale/profiles/ja-jp.js +7 -7
  98. package/out/objects.d.ts +18 -2
  99. package/out/objects.d.ts.map +1 -1
  100. package/out/objects.js +29 -3
  101. package/out/objects.js.map +1 -1
  102. package/out/pipeline/index.d.ts +2 -2
  103. package/out/pipeline/index.d.ts.map +1 -1
  104. package/out/pipeline/index.js +1 -1
  105. package/out/pipeline/index.js.map +1 -1
  106. package/out/pipeline/runtime-pipeline.d.ts +1 -1
  107. package/out/pipeline/runtime-pipeline.d.ts.map +1 -1
  108. package/out/pipeline/runtime-pipeline.js +57 -17
  109. package/out/pipeline/runtime-pipeline.js.map +1 -1
  110. package/out/pipeline/span-proposer.d.ts +24 -0
  111. package/out/pipeline/span-proposer.d.ts.map +1 -1
  112. package/out/pipeline/span-proposer.js +36 -1
  113. package/out/pipeline/span-proposer.js.map +1 -1
  114. package/out/pipeline/types.d.ts +40 -1
  115. package/out/pipeline/types.d.ts.map +1 -1
  116. package/out/pipeline/types.js +11 -1
  117. package/out/pipeline/types.js.map +1 -1
  118. package/out/resolver/types.d.ts +41 -0
  119. package/out/resolver/types.d.ts.map +1 -1
  120. package/out/resolver/types.js.map +1 -1
  121. package/out/resources/index.d.ts +0 -1
  122. package/out/resources/index.d.ts.map +1 -1
  123. package/out/resources/index.js +0 -1
  124. package/out/resources/index.js.map +1 -1
  125. package/out/resources/libpostal.d.ts.map +1 -1
  126. package/out/resources/libpostal.js +3 -4
  127. package/out/resources/libpostal.js.map +1 -1
  128. package/out/resources/whosonfirst/index.d.ts +1 -0
  129. package/out/resources/whosonfirst/index.d.ts.map +1 -1
  130. package/out/resources/whosonfirst/index.js +1 -0
  131. package/out/resources/whosonfirst/index.js.map +1 -1
  132. package/out/resources/whosonfirst/placetypes/Placetype.d.ts.map +1 -1
  133. package/out/resources/whosonfirst/placetypes/Placetype.js +5 -4
  134. package/out/resources/whosonfirst/placetypes/Placetype.js.map +1 -1
  135. package/out/resources/whosonfirst/placetypes/admin.d.ts +17 -3
  136. package/out/resources/whosonfirst/placetypes/admin.d.ts.map +1 -1
  137. package/out/resources/whosonfirst/placetypes/admin.js +1 -1
  138. package/out/resources/whosonfirst/placetypes/admin.js.map +1 -1
  139. package/out/resources/whosonfirst/sharded-repo.d.ts +28 -0
  140. package/out/resources/whosonfirst/sharded-repo.d.ts.map +1 -0
  141. package/out/resources/whosonfirst/sharded-repo.js +58 -0
  142. package/out/resources/whosonfirst/sharded-repo.js.map +1 -0
  143. package/out/tools/download-libpostal-resources.d.ts.map +1 -1
  144. package/out/tools/download-libpostal-resources.js +1 -0
  145. package/out/tools/download-libpostal-resources.js.map +1 -1
  146. package/out/tools/generate-language-types.d.ts.map +1 -1
  147. package/out/tools/generate-language-types.js +5 -11
  148. package/out/tools/generate-language-types.js.map +1 -1
  149. package/out/utils/data-root.d.ts +20 -6
  150. package/out/utils/data-root.d.ts.map +1 -1
  151. package/out/utils/data-root.js +24 -5
  152. package/out/utils/data-root.js.map +1 -1
  153. package/out/utils/hash.d.ts +6 -0
  154. package/out/utils/hash.d.ts.map +1 -1
  155. package/out/utils/hash.js +8 -0
  156. package/out/utils/hash.js.map +1 -1
  157. package/out/utils/index.d.ts +1 -0
  158. package/out/utils/index.d.ts.map +1 -1
  159. package/out/utils/index.js +1 -0
  160. package/out/utils/index.js.map +1 -1
  161. package/out/utils/jsonl.d.ts +17 -3
  162. package/out/utils/jsonl.d.ts.map +1 -1
  163. package/out/utils/jsonl.js +23 -6
  164. package/out/utils/jsonl.js.map +1 -1
  165. package/out/utils/python-json.d.ts +3 -3
  166. package/out/utils/python-json.js +9 -9
  167. package/out/utils/python-numeric.d.ts +33 -0
  168. package/out/utils/python-numeric.d.ts.map +1 -0
  169. package/out/utils/python-numeric.js +149 -0
  170. package/out/utils/python-numeric.js.map +1 -0
  171. package/out/utils/python-random.d.ts +26 -1
  172. package/out/utils/python-random.d.ts.map +1 -1
  173. package/out/utils/python-random.js +43 -7
  174. package/out/utils/python-random.js.map +1 -1
  175. package/out/utils/repo.d.ts.map +1 -1
  176. package/out/utils/repo.js +18 -0
  177. package/out/utils/repo.js.map +1 -1
  178. package/out/utils/sealed-db.d.ts +12 -0
  179. package/out/utils/sealed-db.d.ts.map +1 -1
  180. package/out/utils/sealed-db.js +32 -1
  181. package/out/utils/sealed-db.js.map +1 -1
  182. package/package.json +22 -6
  183. package/pipeline/index.ts +2 -1
  184. package/pipeline/runtime-pipeline.ts +69 -26
  185. package/pipeline/span-proposer.ts +64 -1
  186. package/pipeline/types.ts +43 -1
  187. package/resolver/types.ts +41 -0
  188. package/resources/index.ts +0 -1
  189. package/resources/libpostal.ts +8 -7
  190. package/resources/whosonfirst/index.ts +1 -0
  191. package/resources/whosonfirst/placetypes/Placetype.ts +12 -7
  192. package/resources/whosonfirst/placetypes/admin.ts +17 -2
  193. package/resources/whosonfirst/sharded-repo.ts +69 -0
  194. package/tools/download-libpostal-resources.ts +1 -0
  195. package/tools/generate-language-types.ts +5 -14
  196. package/utils/data-root.ts +27 -6
  197. package/utils/hash.ts +9 -0
  198. package/utils/index.ts +1 -0
  199. package/utils/jsonl.ts +26 -7
  200. package/utils/python-json.ts +10 -10
  201. package/utils/python-numeric.ts +168 -0
  202. package/utils/python-random.ts +49 -8
  203. package/utils/repo.ts +18 -0
  204. package/utils/sealed-db.ts +38 -1
  205. package/out/resources/collections.d.ts +0 -22
  206. package/out/resources/collections.d.ts.map +0 -1
  207. package/out/resources/collections.js +0 -69
  208. package/out/resources/collections.js.map +0 -1
  209. package/resources/collections.ts +0 -96
@@ -9,7 +9,7 @@
9
9
  * injected; the coordinator handles composition, timing, fast-path routing, and graceful
10
10
  * degradation when stages are absent.
11
11
  *
12
- * Implementation contract per `docs/articles/plan/reference/STAGES.md`.
12
+ * Implementation contract per `docs/engineering/reference/STAGES.md`.
13
13
  */
14
14
 
15
15
  import type { AddressNode, AddressTree } from "../decoder/types.ts"
@@ -18,7 +18,7 @@ import { prefetchReconcileLookups } from "./reconcile-lookups.ts"
18
18
  import type { ClassifierCandidate } from "./reconcile.ts"
19
19
  import { reconcileSpans } from "./reconcile.ts"
20
20
  import { aggregateSpanLogits } from "./span-logit-aggregation.ts"
21
- import { WORD_CONSISTENCY_SHIP_DEFAULT, deriveInputMode } from "./types.ts"
21
+ import { PipelineFaultStage, WORD_CONSISTENCY_SHIP_DEFAULT, deriveInputMode } from "./types.ts"
22
22
  import type {
23
23
  AddressClassifier,
24
24
  ClassifierOpts,
@@ -28,6 +28,7 @@ import type {
28
28
  LocaleTag,
29
29
  NormalizedInputLite,
30
30
  PhraseProposal,
31
+ PipelineFault,
31
32
  PipelineOpts,
32
33
  PipelineResult,
33
34
  PlacetypePairPassthrough,
@@ -308,6 +309,9 @@ export async function runPipeline(
308
309
  opts?: PipelineOpts
309
310
  ): Promise<PipelineResult> {
310
311
  const timing: Record<string, number> = {}
312
+ // One list per run, threaded into each `safe*` wrapper. Every return site below surfaces it, so an empty array is a
313
+ // positive statement ("no stage faulted"), not a field that happened not to be set.
314
+ const faults: PipelineFault[] = []
311
315
  const t0 = performance.now()
312
316
 
313
317
  const normalize = stages.normalize ?? identityNormalize
@@ -407,6 +411,7 @@ export async function runPipeline(
407
411
  tree,
408
412
  poiIntent: poiOutcome,
409
413
  timing,
414
+ faults,
410
415
  path: "poi",
411
416
  }
412
417
  }
@@ -422,7 +427,7 @@ export async function runPipeline(
422
427
  if (stages.resolver) {
423
428
  throwIfAborted(opts)
424
429
  const tResolve = performance.now()
425
- tree = await safeResolve(stages.resolver, tree, effectiveOpts)
430
+ tree = await safeResolve(faults, stages.resolver, tree, effectiveOpts)
426
431
  timing["resolve"] = performance.now() - tResolve
427
432
  }
428
433
 
@@ -435,6 +440,7 @@ export async function runPipeline(
435
440
  phraseProposals: [],
436
441
  tree,
437
442
  timing,
443
+ faults,
438
444
  path: "fast-path",
439
445
  }
440
446
  }
@@ -447,7 +453,7 @@ export async function runPipeline(
447
453
  if (stages.groupPhrases) {
448
454
  throwIfAborted(opts)
449
455
  const tGroup = performance.now()
450
- phraseProposals = await safeGroupPhrases(stages.groupPhrases, normalized, queryShape, locale)
456
+ phraseProposals = await safeGroupPhrases(faults, stages.groupPhrases, normalized, queryShape, locale)
451
457
  timing["phrase-grouper"] = performance.now() - tGroup
452
458
  }
453
459
 
@@ -553,17 +559,14 @@ export async function runPipeline(
553
559
  throwIfAborted(opts)
554
560
  const tClassify = performance.now()
555
561
 
556
- tree = await safeClassify(
557
- stages.classifier,
558
- normalized.normalized,
559
- queryShape,
560
- stages.fst,
561
- opts?.normalizeCase,
562
- opts?.placetypePair,
563
- stages.streetMorphology,
562
+ tree = await safeClassify(faults, stages.classifier, normalized.normalized, queryShape, {
563
+ fst: stages.fst,
564
+ normalizeCase: opts?.normalizeCase,
565
+ placetypePair: opts?.placetypePair,
566
+ streetMorphology: stages.streetMorphology,
564
567
  // Decision A: explicit caller register wins; otherwise the kind verdict decides. NEVER case-keyed.
565
- opts?.inputMode ?? deriveInputMode(kind.kind)
566
- )
568
+ inputMode: opts?.inputMode ?? deriveInputMode(kind.kind),
569
+ })
567
570
 
568
571
  timing["token-classify"] = performance.now() - tClassify
569
572
  }
@@ -584,7 +587,7 @@ export async function runPipeline(
584
587
  effectiveOpts = opts
585
588
  }
586
589
 
587
- tree = await safeResolve(stages.resolver, tree, effectiveOpts)
590
+ tree = await safeResolve(faults, stages.resolver, tree, effectiveOpts)
588
591
  timing["resolve"] = performance.now() - tResolve
589
592
  }
590
593
 
@@ -597,6 +600,7 @@ export async function runPipeline(
597
600
  phraseProposals,
598
601
  tree,
599
602
  timing,
603
+ faults,
600
604
  path: "full",
601
605
  }
602
606
  }
@@ -615,18 +619,47 @@ function throwIfAborted(opts?: PipelineOpts): void {
615
619
  }
616
620
 
617
621
  /**
618
- * Defensive wrapper: if the classifier throws, return an empty tree rather than abort the pipeline.
622
+ * Normalize a caught throw into a {@link PipelineFault} and append it to the run's fault list.
623
+ *
624
+ * The wrappers below all call this instead of `catch {}`. A bare `catch {}` is what made a classifier crash
625
+ * indistinguishable from a clean no-match (#40 / mailfail finding 4) — the tree came back empty, the grouper-audit
626
+ * refilled it from rule-based proposals, and the caller saw a tidy parse. Degrading is still the right behavior; doing
627
+ * it silently was not.
628
+ */
629
+ function recordFault(faults: PipelineFault[], stage: PipelineFaultStage, cause: unknown): void {
630
+ faults.push({
631
+ stage,
632
+ name: cause instanceof Error ? cause.name : "Error",
633
+ message: cause instanceof Error ? cause.message : String(cause),
634
+ cause,
635
+ })
636
+ }
637
+
638
+ /**
639
+ * Defensive wrapper: if the classifier throws, return an empty tree rather than abort the pipeline — and record the
640
+ * throw on `faults` so the degrade is visible to the caller.
641
+ *
642
+ * The measured reason this matters (mailfail, 2026-08-02): with the 128-piece `pieces`/`logits` desync live, 10 of 110
643
+ * probe inputs crashed the classifier while the pipeline reported success. `size-10kb` — 10 KB of repeated addresses —
644
+ * came back as `{"house_number":"350","street":"5th Ave","locality":"Ave","region":"NY","postcode":"10118"}` off a
645
+ * 3,031-node tree, which reads exactly like a correct parse of one address. The fault list is what lets a caller tell
646
+ * those apart without instrumenting the classifier.
619
647
  */
620
648
  async function safeClassify(
649
+ faults: PipelineFault[],
621
650
  classifier: AddressClassifier,
622
651
  text: string,
623
652
  queryShape: QueryShapeLite,
624
- fst?: FSTMatcherLike,
625
- normalizeCase?: boolean,
626
- placetypePair?: PlacetypePairPassthrough,
627
- streetMorphology?: FSTMatcherLike,
628
- inputMode?: InputMode
653
+ knobs: {
654
+ fst?: FSTMatcherLike
655
+ normalizeCase?: boolean
656
+ placetypePair?: PlacetypePairPassthrough
657
+ streetMorphology?: FSTMatcherLike
658
+ inputMode?: InputMode
659
+ } = {}
629
660
  ): Promise<AddressTree> {
661
+ const { fst, normalizeCase, placetypePair, streetMorphology, inputMode } = knobs
662
+
630
663
  try {
631
664
  // Postcode regex repair on by default (v0.7 #35, operator-signed). #690 normalizeCase forwards as-is —
632
665
  // default-ON at the classifier since #895 (unset runs it; explicit false pins the raw-case parse).
@@ -645,7 +678,9 @@ async function safeClassify(
645
678
  ...(placetypePair !== undefined ? { placetypePair } : {}),
646
679
  ...streetContextGateFor({ fst, streetMorphology }),
647
680
  })
648
- } catch {
681
+ } catch (error) {
682
+ recordFault(faults, PipelineFaultStage.Classifier, error)
683
+
649
684
  return { raw: text, roots: [] }
650
685
  }
651
686
  }
@@ -682,9 +717,10 @@ function streetContextGateFor(stages: { fst?: FSTMatcherLike; streetMorphology?:
682
717
  }
683
718
 
684
719
  /**
685
- * Defensive wrapper: a grouper failure returns an empty proposal list rather than abort.
720
+ * Defensive wrapper: a grouper failure returns an empty proposal list rather than abort, and records the throw.
686
721
  */
687
722
  async function safeGroupPhrases(
723
+ faults: PipelineFault[],
688
724
  groupPhrases: NonNullable<RuntimePipelineStages["groupPhrases"]>,
689
725
  normalized: NormalizedInputLite,
690
726
  shape: QueryShapeLite,
@@ -692,7 +728,9 @@ async function safeGroupPhrases(
692
728
  ): Promise<PhraseProposal[]> {
693
729
  try {
694
730
  return await groupPhrases(normalized, shape, locale)
695
- } catch {
731
+ } catch (error) {
732
+ recordFault(faults, PipelineFaultStage.PhraseGrouper, error)
733
+
696
734
  return []
697
735
  }
698
736
  }
@@ -829,16 +867,21 @@ export function grouperAudit(
829
867
  }
830
868
 
831
869
  /**
832
- * Defensive wrapper: a resolver failure leaves the classifier tree intact.
870
+ * Defensive wrapper: a resolver failure leaves the classifier tree intact, and records the throw. Unresolved-because-
871
+ * the-backend-threw and unresolved-because-nothing-matched produce the same tree, so without the fault the caller
872
+ * cannot tell a dead gazetteer from a genuine no-match.
833
873
  */
834
874
  async function safeResolve(
875
+ faults: PipelineFault[],
835
876
  resolver: NonNullable<RuntimePipelineStages["resolver"]>,
836
877
  tree: AddressTree,
837
878
  opts?: PipelineOpts
838
879
  ): Promise<AddressTree> {
839
880
  try {
840
881
  return await resolver.resolveTree(tree, opts?.resolveOpts)
841
- } catch {
882
+ } catch (error) {
883
+ recordFault(faults, PipelineFaultStage.Resolver, error)
884
+
842
885
  return tree
843
886
  }
844
887
  }
@@ -121,6 +121,30 @@ export interface SpanProposerLexicon {
121
121
  * rather than a unit ("[Building A]" describes; "[Suite 9]" addresses).
122
122
  */
123
123
  weakDesignators: ReadonlySet<string>
124
+ /**
125
+ * The subset of {@link unitDesignators} naming venue-INTERIOR structure ("concourse", "terminal", "wing", "gate", …)
126
+ * rather than a postal secondary unit. Sourced from WOF placetypes + OSM `aeroway`, never from a mail standard — see
127
+ * `@mailwoman/neural`'s `venue-structure.ts`.
128
+ *
129
+ * Membership is carried through to the proposal's `source` so the consuming prior can weight the two provenances
130
+ * differently. It has to: measured 2026-08-02, the model's margin against `I-unit` on a sub-venue IDENTIFIER runs
131
+ * 4.6–5.0 nats (`B` after `Concourse` scores `B-venue` 4.24 while `I-unit` sits 17th of 33), which the shipped
132
+ * unit-designator scale cannot reach — while raising that shared scale far enough drags quote marks and commas into
133
+ * unit spans elsewhere in the corpus. The two classes need different magnitudes because the model has different
134
+ * opinions about them, so the lexicon has to keep them distinguishable.
135
+ */
136
+ venueStructureDesignators: ReadonlySet<string>
137
+ /**
138
+ * Positional words that may PRECEDE a designator ("West Wing", "Upper Concourse") — the mirror of the
139
+ * designator+identifier shape, where the qualifier leads instead of following.
140
+ */
141
+ venueStructureModifiers: ReadonlySet<string>
142
+ /**
143
+ * The subset of {@link venueStructureDesignators} that may take a preceding modifier. Narrower than the full set
144
+ * because some designators form ordinary STREET names in exactly this shape — "East Gate" is a street, "West Wing" is
145
+ * not — so a rule spanning all of them converts correct street parses into sub-venue ones.
146
+ */
147
+ modifierEligibleStructureDesignators: ReadonlySet<string>
124
148
  /**
125
149
  * Global scan regex for delivery-service designator+identifier phrases, built from the codex po_box /
126
150
  * delivery-service tables. Must carry the `g` flag.
@@ -136,6 +160,9 @@ export const EMPTY_SPAN_PROPOSER_LEXICON: SpanProposerLexicon = {
136
160
  unitDesignators: new Set(),
137
161
  levelDesignators: new Set(),
138
162
  weakDesignators: new Set(),
163
+ venueStructureDesignators: new Set(),
164
+ venueStructureModifiers: new Set(),
165
+ modifierEligibleStructureDesignators: new Set(),
139
166
  }
140
167
 
141
168
  //#region Tokenization
@@ -381,13 +408,49 @@ function proposeDesignatorPhrases(
381
408
  // cue family 3 owns punctuated ids
382
409
  if (!isShortIdentifier(next.stripped)) continue
383
410
  const weak = lexicon.weakDesignators.has(lead)
411
+ // Provenance rides the source string: a venue-INTERIOR designator and a postal one produce the same
412
+ // span shape but face different model margins, and the consuming prior weights them apart on this.
413
+ const venueStructure = !isLevel && lexicon.venueStructureDesignators.has(lead)
384
414
 
385
415
  out.push({
386
416
  start: tokens[i]!.strippedStart,
387
417
  end: next.strippedEnd,
388
418
  kind: isLevel ? "LEVEL_PHRASE" : "UNIT_PHRASE",
389
419
  confidence: weak ? 0.5 : 0.85,
390
- source: `designator:${isLevel ? "level" : "unit"}`,
420
+ source: venueStructure ? "designator:venue-structure" : `designator:${isLevel ? "level" : "unit"}`,
421
+ })
422
+ }
423
+
424
+ // MODIFIER + DESIGNATOR ("West Wing", "Upper Concourse") — the mirror of the shape above, where the
425
+ // qualifier leads rather than follows. Emitted at a lower confidence: an identifier AFTER a designator is
426
+ // nearly unambiguous, while a positional word BEFORE one is a shape ordinary street names also take, so
427
+ // this proposal should lose to a confident encoder more readily than that one does.
428
+ for (let i = 1; i < tokens.length; i++) {
429
+ const designator = tokens[i]!.stripped.toLowerCase()
430
+
431
+ if (!lexicon.modifierEligibleStructureDesignators.has(designator)) continue
432
+
433
+ const modifier = tokens[i - 1]!.stripped.toLowerCase()
434
+
435
+ if (!lexicon.venueStructureModifiers.has(modifier)) continue
436
+
437
+ const beforeModifier = tokens[i - 2]
438
+
439
+ // A house number before the modifier makes this a STREET line — "12 East Gate" is an address on East
440
+ // Gate, not a sub-venue of anything. The number is the discriminator the surface itself provides.
441
+ if (beforeModifier && /^\d{1,6}[A-Za-z]?$/.test(beforeModifier.stripped)) continue
442
+
443
+ // A capitalized word before the modifier means the pair sits INSIDE a longer proper name rather than
444
+ // opening one: "Grand Central Terminal" contains "Central Terminal", and proposing that as a unit
445
+ // carves a sub-venue out of the venue's own name. Sub-venue lines lead their segment.
446
+ if (beforeModifier && /^\p{Lu}/u.test(beforeModifier.stripped)) continue
447
+
448
+ out.push({
449
+ start: tokens[i - 1]!.strippedStart,
450
+ end: tokens[i]!.strippedEnd,
451
+ kind: "UNIT_PHRASE",
452
+ confidence: 0.6,
453
+ source: "designator:venue-structure-modifier",
391
454
  })
392
455
  }
393
456
 
package/pipeline/types.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  * query-shape / resolver packages while still composing them at runtime when callers wire them
11
11
  * up.
12
12
  *
13
- * See `docs/articles/plan/reference/STAGES.md` for the full contract this implements.
13
+ * See `docs/engineering/reference/STAGES.md` for the full contract this implements.
14
14
  */
15
15
 
16
16
  import type { AddressTree } from "../decoder/types.ts"
@@ -436,6 +436,42 @@ export interface RuntimePipelineStages {
436
436
 
437
437
  export type PipelineTiming = Record<string, number>
438
438
 
439
+ /**
440
+ * The stages whose defensive wrapper degrades instead of aborting the pipeline. One id per `safe*` wrapper in
441
+ * `runtime-pipeline.ts`; the ids are the wrapper's, not the timing map's, because a fault is about the injected stage
442
+ * (`classifier`), not the phase that ran it (`token-classify`).
443
+ */
444
+ export const PipelineFaultStage = {
445
+ Classifier: "classifier",
446
+ PhraseGrouper: "phrase-grouper",
447
+ Resolver: "resolver",
448
+ } as const
449
+
450
+ export type PipelineFaultStage = (typeof PipelineFaultStage)[keyof typeof PipelineFaultStage]
451
+
452
+ /**
453
+ * One stage crash the coordinator caught and degraded past.
454
+ *
455
+ * A fault is NOT an error return: `runPipeline` still resolves, and `tree` still carries whatever the remaining stages
456
+ * could prove. What the fault buys the caller is the ability to tell "the model faulted and the rule-based stages
457
+ * filled the tree back in" apart from "the model ran and found nothing" — which, before #40, was impossible from the
458
+ * outside. See the `safeClassify` docstring for the measured failure this was written against.
459
+ */
460
+ export interface PipelineFault {
461
+ stage: PipelineFaultStage
462
+ /**
463
+ * The thrown value's `name` (`TypeError`, `RangeError`, …), or `"Error"` when something that isn't an `Error` was
464
+ * thrown. Machine-stable enough to branch on; the `cause` carries the rest.
465
+ */
466
+ name: string
467
+ message: string
468
+ /**
469
+ * The value the stage threw, verbatim — kept so a caller can rethrow it or read its stack. Not JSON-serializable in
470
+ * the useful sense; serialize `stage`/`name`/`message` when you need this on a wire.
471
+ */
472
+ cause: unknown
473
+ }
474
+
439
475
  /**
440
476
  * Result of one `runPipeline` call.
441
477
  */
@@ -457,6 +493,12 @@ export interface PipelineResult {
457
493
  */
458
494
  poiIntent?: POIIntentOutcome
459
495
  timing: PipelineTiming
496
+ /**
497
+ * Every stage crash the coordinator caught and degraded past, in the order they happened. **Always present** — an
498
+ * empty array is the coordinator stating that no stage faulted, which is a different claim from a missing field.
499
+ * Non-empty means the tree you are holding was produced with at least one stage down; see {@link PipelineFault}.
500
+ */
501
+ faults: PipelineFault[]
460
502
  /**
461
503
  * Which path the coordinator took. `"fast-path"` skipped stages 3-5; `"poi"` took the intent branch.
462
504
  */
package/resolver/types.ts CHANGED
@@ -585,6 +585,47 @@ export interface ResolveOpts {
585
585
  * re-picked or demoted. Default 50.
586
586
  */
587
587
  postcodeConsistencyGateKm?: number
588
+ /**
589
+ * Postcode-country coherence (#42) — the ONLY mechanism permitted to override {@link defaultCountry}, and the only
590
+ * one that runs BEFORE the walk rather than re-picking after it.
591
+ *
592
+ * `12 Rue de Rivoli, 75001 Paris` under the en-US locale resolves to Paris, **Texas**: the locale's region subtag
593
+ * becomes `defaultCountry: "US"`, the backend turns that into a hard `spr.country = 'US'` filter, and the candidate
594
+ * pool is all-US before ranking begins — so a coarse placer that called the address FR at confidence 0.9999908844 has
595
+ * nothing to promote (a soft re-rank downstream of a hard filter is inert by construction). With the postal shards
596
+ * attached it degrades further: the postcode resolves to ZIP 75001 (Addison TX) and {@link postcodeConsistency} then
597
+ * drags the locality onto that point.
598
+ *
599
+ * The postcode's SHAPE cannot settle this — `75001` is a valid US ZIP, French CP and German PLZ, and the gazetteer
600
+ * holds the literal string in four countries. Its GEOMETRY can: this pass asks, per candidate country from codex's
601
+ * shape test, whether the postcode resolves there AND a same-named locality sits within
602
+ * {@link postcodeCountryCoherenceGateKm} of it — then scopes the whole walk to the country where the pair is
603
+ * consistent. Measured over 800 real pairs (400 US ZIP+city, 400 FR CP+commune): **zero** border crossings at both
604
+ * the 15 km and 25 km gates.
605
+ *
606
+ * Soft by construction, per the positive-evidence-only rule: the caller's `defaultCountry` is tested FIRST and a
607
+ * coherent default always wins (returning immediately, ≤2 lookups, byte-identical walk), and both zero coherent
608
+ * countries and two-or-more abstain. It fires only when a `defaultCountry` is in force AND the tree carries both a
609
+ * postcode and a locality AND the default cannot make them consistent.
610
+ *
611
+ * **Default ON** (operator-promoted 2026-08-05 after the D-rule evidence in
612
+ * `docs/records/evals/2026-08-05-postcode-coherence-default-on-evidence.md`: the standard gauntlet run pinned both
613
+ * ways produced ZERO newly-failing gated cases — 65/68 either way, the same three unrelated failures — and 56,000
614
+ * pair evaluations across BOTH backends (28,000 FTS + 28,000 candidate; OpenAddresses US/FR + OSM GB, domestic and
615
+ * mis-scoped legs) returned zero false positives. The rescue leg fixes ~9 in 10 mis-scoped defaults. Set `false` to
616
+ * opt out (byte-stable then). Costs 2 lookups on the byte-stable path, at most 8 when it fires.
617
+ *
618
+ * Reach is bounded by codex's `candidateSystemsForPostcode` and the attached gazetteer: measured 2026-08-05 it can
619
+ * speak for US/DE/FR/GB on the production FTS shard set and additionally CA/AU on the candidate table; JP and NZ have
620
+ * a codex slice with no postcode rows behind it, so the pass abstains there at the cost of its two lookups.
621
+ */
622
+ postcodeCountryCoherence?: boolean
623
+ /**
624
+ * Gate radius (km) for {@link postcodeCountryCoherence} — how near a same-named locality must sit to the resolved
625
+ * postcode to count that country as consistent. Default 25 (what the 800-pair scale run measured; the confound board
626
+ * returned identical verdicts at 15, 25 and 50, so the pass is not gate-tuned).
627
+ */
628
+ postcodeCountryCoherenceGateKm?: number
588
629
  /**
589
630
  * Admin descendant-consistency (#263). When a region resolved but its child locality did NOT — the greedy region pick
590
631
  * (name + population) chose a foreign namesake whose descendants hold no such locality ("Portland, ME" → Messina IT;
@@ -4,7 +4,6 @@
4
4
  * @author Teffen Ellis, et al.
5
5
  */
6
6
 
7
- export * from "./collections.ts"
8
7
  export * from "./debugging.ts"
9
8
  export * from "./git.ts"
10
9
  export * from "./languages/index.ts"
@@ -12,10 +12,9 @@ import type { Alpha2LanguageCode } from "@mailwoman/core/resources/languages"
12
12
  import { TextNormalizer, type TextNormalizerInit } from "@mailwoman/core/tokenization"
13
13
  import type { PathBuilder } from "path-ts"
14
14
  import pluralize from "pluralize"
15
- import { TextSpliterator } from "spliterator"
15
+ import { AsyncSequence, TextSpliterator } from "spliterator"
16
16
 
17
17
  import { resourceDictionaryPathBuilder } from "../utils/repo.ts"
18
- import { takeAsync } from "./collections.ts"
19
18
  import { LocaleIndex } from "./LocaleIndex.ts"
20
19
 
21
20
  const batchSize = availableParallelism()
@@ -104,7 +103,10 @@ export async function prepareLocaleIndex(
104
103
 
105
104
  // Default resolves lazily (#481 — the former TLA value).
106
105
  const codes = languageCodes ?? (await getAvailableLanguages())
107
- const fileEntries = takeAsync(findFilesMatchingLocale(filename, libPostalDataDirectory, codes), batchSize)
106
+
107
+ const fileEntries = AsyncSequence.from(findFilesMatchingLocale(filename, libPostalDataDirectory, codes)).chunks(
108
+ batchSize
109
+ )
108
110
 
109
111
  for await (const batch of fileEntries) {
110
112
  await Promise.all(
@@ -122,10 +124,9 @@ export async function prepareLocaleIndex(
122
124
  )
123
125
  }
124
126
 
125
- const internalFileEntries = takeAsync(
126
- findFilesMatchingLocale(filename, libPostalInternalDataDirectory, codes),
127
- batchSize
128
- )
127
+ const internalFileEntries = AsyncSequence.from(
128
+ findFilesMatchingLocale(filename, libPostalInternalDataDirectory, codes)
129
+ ).chunks(batchSize)
129
130
 
130
131
  for await (const batch of internalFileEntries) {
131
132
  await Promise.all(
@@ -7,4 +7,5 @@
7
7
  export * from "./DataSourceCache.ts"
8
8
  export * from "./loader.ts"
9
9
  export * from "./PlacetypeDataSource.ts"
10
+ export * from "./sharded-repo.ts"
10
11
  export * from "./placetypes/index.ts"
@@ -8,8 +8,9 @@ import * as fs from "node:fs/promises"
8
8
 
9
9
  import FastGlob from "fast-glob"
10
10
  import type { PathBuilder } from "path-ts"
11
+ import { parallelMap } from "spliterator"
11
12
 
12
- import { takeInParallel } from "../../collections.ts"
13
+ import { parseJSONStrict } from "../../../objects.ts"
13
14
  import { prepareRepositoryDirectories, type RepositorySource } from "../../git.ts"
14
15
  import {
15
16
  normalizePlacetypeDefinition,
@@ -79,14 +80,18 @@ export class Placetype implements Disposable {
79
80
  absolute: true,
80
81
  })
81
82
 
82
- const batchIterator = takeInParallel(definitionPaths, batchSize, async (definitionPath) => {
83
- const definitionContent = await fs.readFile(definitionPath, "utf8")
84
- const definition: PlacetypeDefinition = JSON.parse(definitionContent)
83
+ const batchIterator = parallelMap(
84
+ definitionPaths,
85
+ async (definitionPath) => {
86
+ const definitionContent = await fs.readFile(definitionPath, "utf8")
87
+ const definition = parseJSONStrict<PlacetypeDefinition>(definitionContent)
85
88
 
86
- Placetype.register(definition)
89
+ Placetype.register(definition)
87
90
 
88
- return definition
89
- })
91
+ return definition
92
+ },
93
+ { concurrency: batchSize }
94
+ )
90
95
 
91
96
  await Array.fromAsync(batchIterator)
92
97
  }
@@ -11,7 +11,7 @@ import {
11
11
  isAlpha2LanguageCode,
12
12
  isAlpha3bLanguageCode,
13
13
  } from "@mailwoman/core/resources/languages"
14
- import type { Feature, Geometry } from "geojson"
14
+ import type { GeoFeature, GeometryLiteral } from "@mailwoman/spatial"
15
15
 
16
16
  import type { WhosOnFirstPlacetype } from "./definition.ts"
17
17
 
@@ -26,10 +26,21 @@ export interface WOFBaseProperties {
26
26
  "wof:supersedes"?: number[]
27
27
  "wof:country"?: string
28
28
  "wof:concordances"?: Record<string, string | number>
29
+ /**
30
+ * Every ancestor chain the place belongs to, coarsest key first — `[{ country_id, region_id, locality_id }, …]`. More
31
+ * than one entry means the place has multiple parents, which is what `wof:parent_id` records as the `-4` sentinel;
32
+ * the keys present vary by branch, so a missing rung is absent rather than null.
33
+ */
34
+ "wof:hierarchy"?: Array<Record<string, number>>
29
35
  "wof:population"?: number
30
36
  "wof:lastmodified"?: number
31
37
  "geom:latitude"?: number
32
38
  "geom:longitude"?: number
39
+ /**
40
+ * `"minLon,minLat,maxLon,maxLat"` — WOF writes the bbox as a comma-joined string, not an array. Read by the gazetteer
41
+ * ingest for the resolver's point-in-box proximity.
42
+ */
43
+ "geom:bbox"?: string
33
44
  "gn:population"?: number
34
45
  "mz:is_current"?: number | string
35
46
  "edtf:deprecated"?: string
@@ -50,7 +61,10 @@ export type WOFLanguageProperties = Partial<Record<LanguageSpecificKey, string |
50
61
 
51
62
  export type WOFProperties = WOFBaseProperties & WOFLanguageProperties
52
63
 
53
- export type WOFFeature = Feature<Geometry, WOFProperties>
64
+ /**
65
+ * A single record from the Who's On First GeoJSON distribution.
66
+ */
67
+ export type WOFFeature = GeoFeature<GeometryLiteral, WOFProperties>
54
68
 
55
69
  type LocalizedPlacetypePropMap = Map<WOFNameKind, string>
56
70
 
@@ -95,6 +109,7 @@ export function pluckPlacetypeSpec({
95
109
  "wof:supersedes": supersedes,
96
110
  "wof:country": country,
97
111
  "wof:concordances": concordances,
112
+ "wof:hierarchy": _hierarchy,
98
113
  "wof:population": wofPopulation,
99
114
  "wof:lastmodified": lastmodified,
100
115
  "geom:latitude": latitude,
@@ -0,0 +1,69 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Reading a place out of a cloned Who's On First data repo.
7
+ *
8
+ * WOF stores each record at a path derived from its own id: the decimal id split into three-character directories,
9
+ * then `<id>.geojson`. `85977539` lives at `859/775/39/85977539.geojson`. The rule is not written down in the data —
10
+ * it is layout knowledge every reader has to carry — so it lives here once, next to the {@link WOFFeature} type the
11
+ * parsed record has.
12
+ */
13
+
14
+ import { existsSync, readFileSync } from "node:fs"
15
+
16
+ import { resolvePath } from "path-ts"
17
+
18
+ import { tryParsingJSON } from "../../objects.ts"
19
+ import type { WOFFeature } from "./placetypes/admin.ts"
20
+
21
+ /**
22
+ * Characters per directory level. A trailing group shorter than this is its own directory — `85977539` ends in `39`,
23
+ * not `390`.
24
+ */
25
+ const ID_CHUNK = 3
26
+
27
+ /**
28
+ * A WOF id → its repo-relative path segments, ending in `<id>.geojson`.
29
+ *
30
+ * Segments rather than a joined string so a caller can append them to whatever root it already holds — the repos layout
31
+ * puts a `data` directory under each `whosonfirst-data-*` clone, and callers reach it differently.
32
+ */
33
+ export function wofIDPathSegments(id: number): string[] {
34
+ const digits = String(id)
35
+ const segments: string[] = []
36
+
37
+ for (let i = 0; i < digits.length; i += ID_CHUNK) {
38
+ segments.push(digits.slice(i, i + ID_CHUNK))
39
+ }
40
+
41
+ segments.push(`${digits}.geojson`)
42
+
43
+ return segments
44
+ }
45
+
46
+ /**
47
+ * Read a place's GeoJSON from the first `root` that holds it, or `null` when no root does or the file will not parse.
48
+ *
49
+ * `null` conflates "absent" with "unparseable" on purpose: every caller so far treats both as "no evidence for this
50
+ * place" and continues. A caller that needs to tell them apart should read the file itself.
51
+ */
52
+ export function readWOFFeature(id: number, roots: readonly string[]): WOFFeature | null {
53
+ const segments = wofIDPathSegments(id)
54
+
55
+ for (const root of roots) {
56
+ const path = resolvePath(root, ...segments)
57
+
58
+ if (!existsSync(path)) continue
59
+
60
+ try {
61
+ return tryParsingJSON<WOFFeature>(readFileSync(path, "utf8"))
62
+ } catch {
63
+ // The file vanished or turned unreadable between existsSync and the read — same "no evidence" verdict.
64
+ return null
65
+ }
66
+ }
67
+
68
+ return null
69
+ }
@@ -41,6 +41,7 @@ const DICTIONARIES_DIR = resourceDictionaryPath("libpostal")
41
41
  async function sortFileInPlace(path: string): Promise<void> {
42
42
  const text = await readFile(path, "utf8")
43
43
  const hadTrailingNewline = text.endsWith("\n")
44
+ // oxlint-disable-next-line mailwoman/prefer-spliterator -- Sorting needs every line resident; the largest libpostal dictionary is 409 KB.
44
45
  const lines = text.split("\n")
45
46
 
46
47
  // Drop the empty element produced by a trailing newline so it isn't re-sorted as a blank line.