@mailwoman/corpus 11.5.0 → 12.1.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 (232) hide show
  1. package/data/address-source-register.json +545 -11
  2. package/data/builds/v0.8.22-wofrank-overlay/OVERLAY_PLAN.json +51 -0
  3. package/data/builds/v0.8.24-everyplace/inputs.json +35 -0
  4. package/data/license-decisions.json +440 -9
  5. package/data/licenses/PROVENANCE.md +27 -18
  6. package/data/licenses/at-bev-adressregister-cc-by-4.0.md +25 -0
  7. package/data/licenses/br-ibge-cnefe-open-data.md +21 -0
  8. package/data/licenses/ca-qc-mrnf-cc-by-4.0.md +29 -0
  9. package/data/licenses/ca-statcan-open-licence.md +41 -0
  10. package/data/licenses/ca-yukon-ogl-2.0.md +19 -0
  11. package/data/licenses/dk-dmikg-cc-by-4.0.md +43 -0
  12. package/data/licenses/jp-mlit-isj-pdl-1.0.md +35 -0
  13. package/data/source-additions.json +90 -0
  14. package/data/source-resolutions.json +3 -2
  15. package/data/training-configs/v8.17.0-stage1-gazetteer-v0822-s42.yaml +557 -0
  16. package/data/training-configs/v8.17.0-stage2-corpus-v0822-s42.yaml +1008 -0
  17. package/data/training-configs/v8.18.0-gazetteer-then-mixture-v0822-s42.yaml +1225 -0
  18. package/data/training-configs/v8.20.0-wofrank-v0822-s42.yaml +863 -0
  19. package/data/training-configs/v8.21.0-outcomes-v0822-s42.yaml +873 -0
  20. package/data/training-configs/v8.22.0-stage1-everyplace-v0824-s42.yaml +374 -0
  21. package/data/training-configs/v8.22.0-stage2-corpus-v0824-s42.yaml +808 -0
  22. package/data/training-configs/v8.22.1-stage1-everyplace-v0824-s42.yaml +376 -0
  23. package/data/training-configs/v8.22.1-stage2-corpus-v0824-s42.yaml +793 -0
  24. package/data/training-configs/v9.0.0-bytestem-v090-s42.yaml +665 -0
  25. package/data/training-configs/v9.1.0-bytestem-global-v091-s42.yaml +710 -0
  26. package/data/training-configs/v9.2.0-bytestem-global-v092-s42.yaml +714 -0
  27. package/data/training-manifests/v0.8.22-wofrank-overlay.json +9000 -0
  28. package/data/training-manifests/v0.8.24-everyplace-overlay.json +9000 -0
  29. package/data/training-manifests/v0.9.0-compact.effective.json +2556 -0
  30. package/data/training-manifests/v0.9.0-compact.json +9000 -0
  31. package/data/training-manifests/v0.9.1-compact.json +9660 -0
  32. package/data/training-manifests/v0.9.2-compact.effective.json +2670 -0
  33. package/data/training-manifests/v0.9.2-compact.json +9660 -0
  34. package/lib/adapters/geonames/features/adapter.ts +29 -11
  35. package/lib/adapters/overture/adapter.ts +26 -6
  36. package/lib/adapters/street/line.ts +6 -5
  37. package/lib/adapters/street/unit.ts +7 -0
  38. package/lib/adapters/wof/admin/json/adapter.ts +38 -3
  39. package/lib/adapters/wof/json-rows.ts +84 -5
  40. package/lib/adapters/wof/sample.ts +42 -6
  41. package/lib/au/adapters/gnaf/source.ts +12 -0
  42. package/lib/build/code-hash.ts +1 -1
  43. package/lib/cjk/foreign-places.ts +1 -1
  44. package/lib/fr/adapters/ban/adapter.ts +57 -8
  45. package/lib/fr/recipes/admin-split.ts +14 -2
  46. package/lib/fr/recipes/lieudit.ts +1 -1
  47. package/lib/fr/recipes/order.ts +14 -5
  48. package/lib/international/recipes/locale.ts +1 -1
  49. package/lib/kr/adapters/localdata/permit-rows.ts +1 -1
  50. package/lib/parquet/schema.ts +7 -0
  51. package/lib/recipes/po/box/cedex/recipe.ts +1 -1
  52. package/lib/recipes/po/box/cedex/vocabulary.ts +4 -4
  53. package/lib/recipes/trailing-region.ts +147 -17
  54. package/lib/synthesizers/po-box.ts +51 -12
  55. package/lib/test-kit/corpus-recipe.ts +3 -0
  56. package/lib/tools/anthropic/batches.ts +221 -0
  57. package/lib/tools/anthropic/labeling.ts +263 -0
  58. package/lib/tools/compact-v9.ts +890 -0
  59. package/lib/tools/fetch/wikidata/vital-places/entities.ts +20 -2
  60. package/lib/tools/fetch/wikidata/vital-places/qrank.ts +5 -4
  61. package/lib/tools/fragment-assay.run.ts +2 -1
  62. package/lib/tools/name-roles/name-roles.run.ts +296 -0
  63. package/lib/tools/name-roles/prompt.ts +253 -0
  64. package/lib/tools/overlay/deletions.ts +1 -1
  65. package/lib/tools/overlay/draw-weight.ts +275 -0
  66. package/lib/tools/place-twins/place-twins.run.ts +528 -0
  67. package/lib/tools/place-twins/prompt.ts +276 -0
  68. package/lib/tools/prominent-shapes/prominent-shapes.run.ts +420 -0
  69. package/lib/tools/prominent-shapes/prompt.ts +189 -0
  70. package/lib/tools/prominent-shapes/read-seeds.ts +286 -0
  71. package/lib/tools/prominent-shapes/seeds.ts +281 -0
  72. package/lib/tools/prominent-shapes/validate.ts +563 -0
  73. package/lib/tools/source-register/build.ts +1 -0
  74. package/lib/training/config/admission.ts +9 -2
  75. package/lib/training/config/schema.ts +68 -1
  76. package/lib/types.ts +23 -0
  77. package/lib/us/adapters/usgov/usgs-structures/adapter.ts +103 -6
  78. package/lib/utils/split.ts +1 -1
  79. package/out/adapters/geonames/features/adapter.d.ts +2 -2
  80. package/out/adapters/geonames/features/adapter.d.ts.map +1 -1
  81. package/out/adapters/geonames/features/adapter.js +25 -11
  82. package/out/adapters/geonames/features/adapter.js.map +1 -1
  83. package/out/adapters/overture/adapter.d.ts.map +1 -1
  84. package/out/adapters/overture/adapter.js +21 -5
  85. package/out/adapters/overture/adapter.js.map +1 -1
  86. package/out/adapters/street/line.d.ts +4 -4
  87. package/out/adapters/street/line.d.ts.map +1 -1
  88. package/out/adapters/street/line.js +5 -5
  89. package/out/adapters/street/line.js.map +1 -1
  90. package/out/adapters/street/unit.d.ts +4 -0
  91. package/out/adapters/street/unit.d.ts.map +1 -1
  92. package/out/adapters/street/unit.js +3 -0
  93. package/out/adapters/street/unit.js.map +1 -1
  94. package/out/adapters/wof/admin/json/adapter.d.ts +7 -0
  95. package/out/adapters/wof/admin/json/adapter.d.ts.map +1 -1
  96. package/out/adapters/wof/admin/json/adapter.js +28 -3
  97. package/out/adapters/wof/admin/json/adapter.js.map +1 -1
  98. package/out/adapters/wof/json-rows.d.ts +8 -0
  99. package/out/adapters/wof/json-rows.d.ts.map +1 -1
  100. package/out/adapters/wof/json-rows.js +56 -4
  101. package/out/adapters/wof/json-rows.js.map +1 -1
  102. package/out/adapters/wof/sample.d.ts +12 -0
  103. package/out/adapters/wof/sample.d.ts.map +1 -1
  104. package/out/adapters/wof/sample.js +37 -6
  105. package/out/adapters/wof/sample.js.map +1 -1
  106. package/out/au/adapters/gnaf/source.d.ts +9 -0
  107. package/out/au/adapters/gnaf/source.d.ts.map +1 -1
  108. package/out/au/adapters/gnaf/source.js +9 -0
  109. package/out/au/adapters/gnaf/source.js.map +1 -1
  110. package/out/build/code-hash.js +1 -1
  111. package/out/build/code-hash.js.map +1 -1
  112. package/out/cjk/foreign-places.js +1 -1
  113. package/out/cjk/foreign-places.js.map +1 -1
  114. package/out/fr/adapters/ban/adapter.d.ts.map +1 -1
  115. package/out/fr/adapters/ban/adapter.js +49 -7
  116. package/out/fr/adapters/ban/adapter.js.map +1 -1
  117. package/out/fr/recipes/admin-split.d.ts.map +1 -1
  118. package/out/fr/recipes/admin-split.js +15 -2
  119. package/out/fr/recipes/admin-split.js.map +1 -1
  120. package/out/fr/recipes/lieudit.js +1 -1
  121. package/out/fr/recipes/lieudit.js.map +1 -1
  122. package/out/fr/recipes/order.d.ts.map +1 -1
  123. package/out/fr/recipes/order.js +16 -5
  124. package/out/fr/recipes/order.js.map +1 -1
  125. package/out/international/recipes/locale.js +1 -1
  126. package/out/international/recipes/locale.js.map +1 -1
  127. package/out/kr/adapters/localdata/permit-rows.js +1 -1
  128. package/out/kr/adapters/localdata/permit-rows.js.map +1 -1
  129. package/out/parquet/schema.d.ts +6 -0
  130. package/out/parquet/schema.d.ts.map +1 -1
  131. package/out/parquet/schema.js +6 -0
  132. package/out/parquet/schema.js.map +1 -1
  133. package/out/recipes/po/box/cedex/recipe.js +1 -1
  134. package/out/recipes/po/box/cedex/recipe.js.map +1 -1
  135. package/out/recipes/po/box/cedex/vocabulary.d.ts +1 -1
  136. package/out/recipes/po/box/cedex/vocabulary.d.ts.map +1 -1
  137. package/out/recipes/po/box/cedex/vocabulary.js +4 -4
  138. package/out/recipes/po/box/cedex/vocabulary.js.map +1 -1
  139. package/out/recipes/trailing-region.d.ts.map +1 -1
  140. package/out/recipes/trailing-region.js +122 -17
  141. package/out/recipes/trailing-region.js.map +1 -1
  142. package/out/synthesizers/po-box.d.ts +7 -0
  143. package/out/synthesizers/po-box.d.ts.map +1 -1
  144. package/out/synthesizers/po-box.js +36 -12
  145. package/out/synthesizers/po-box.js.map +1 -1
  146. package/out/test-kit/corpus-recipe.d.ts +3 -0
  147. package/out/test-kit/corpus-recipe.d.ts.map +1 -1
  148. package/out/test-kit/corpus-recipe.js.map +1 -1
  149. package/out/tools/anthropic/batches.d.ts +117 -0
  150. package/out/tools/anthropic/batches.d.ts.map +1 -0
  151. package/out/tools/anthropic/batches.js +141 -0
  152. package/out/tools/anthropic/batches.js.map +1 -0
  153. package/out/tools/anthropic/labeling.d.ts +97 -0
  154. package/out/tools/anthropic/labeling.d.ts.map +1 -0
  155. package/out/tools/anthropic/labeling.js +146 -0
  156. package/out/tools/anthropic/labeling.js.map +1 -0
  157. package/out/tools/compact-v9.d.ts +124 -0
  158. package/out/tools/compact-v9.d.ts.map +1 -0
  159. package/out/tools/compact-v9.js +507 -0
  160. package/out/tools/compact-v9.js.map +1 -0
  161. package/out/tools/fetch/wikidata/vital-places/entities.d.ts +3 -0
  162. package/out/tools/fetch/wikidata/vital-places/entities.d.ts.map +1 -1
  163. package/out/tools/fetch/wikidata/vital-places/entities.js +19 -1
  164. package/out/tools/fetch/wikidata/vital-places/entities.js.map +1 -1
  165. package/out/tools/fetch/wikidata/vital-places/qrank.d.ts.map +1 -1
  166. package/out/tools/fetch/wikidata/vital-places/qrank.js +4 -4
  167. package/out/tools/fetch/wikidata/vital-places/qrank.js.map +1 -1
  168. package/out/tools/fragment-assay.run.js +1 -1
  169. package/out/tools/fragment-assay.run.js.map +1 -1
  170. package/out/tools/name-roles/name-roles.run.d.ts +2 -0
  171. package/out/tools/name-roles/name-roles.run.d.ts.map +1 -0
  172. package/out/tools/name-roles/name-roles.run.js +230 -0
  173. package/out/tools/name-roles/name-roles.run.js.map +1 -0
  174. package/out/tools/name-roles/prompt.d.ts +166 -0
  175. package/out/tools/name-roles/prompt.d.ts.map +1 -0
  176. package/out/tools/name-roles/prompt.js +176 -0
  177. package/out/tools/name-roles/prompt.js.map +1 -0
  178. package/out/tools/overlay/deletions.js +1 -1
  179. package/out/tools/overlay/deletions.js.map +1 -1
  180. package/out/tools/overlay/draw-weight.d.ts +86 -0
  181. package/out/tools/overlay/draw-weight.d.ts.map +1 -0
  182. package/out/tools/overlay/draw-weight.js +131 -0
  183. package/out/tools/overlay/draw-weight.js.map +1 -0
  184. package/out/tools/place-twins/place-twins.run.d.ts +2 -0
  185. package/out/tools/place-twins/place-twins.run.d.ts.map +1 -0
  186. package/out/tools/place-twins/place-twins.run.js +385 -0
  187. package/out/tools/place-twins/place-twins.run.js.map +1 -0
  188. package/out/tools/place-twins/prompt.d.ts +169 -0
  189. package/out/tools/place-twins/prompt.d.ts.map +1 -0
  190. package/out/tools/place-twins/prompt.js +183 -0
  191. package/out/tools/place-twins/prompt.js.map +1 -0
  192. package/out/tools/prominent-shapes/prominent-shapes.run.d.ts +2 -0
  193. package/out/tools/prominent-shapes/prominent-shapes.run.d.ts.map +1 -0
  194. package/out/tools/prominent-shapes/prominent-shapes.run.js +302 -0
  195. package/out/tools/prominent-shapes/prominent-shapes.run.js.map +1 -0
  196. package/out/tools/prominent-shapes/prompt.d.ts +74 -0
  197. package/out/tools/prominent-shapes/prompt.d.ts.map +1 -0
  198. package/out/tools/prominent-shapes/prompt.js +156 -0
  199. package/out/tools/prominent-shapes/prompt.js.map +1 -0
  200. package/out/tools/prominent-shapes/read-seeds.d.ts +23 -0
  201. package/out/tools/prominent-shapes/read-seeds.d.ts.map +1 -0
  202. package/out/tools/prominent-shapes/read-seeds.js +219 -0
  203. package/out/tools/prominent-shapes/read-seeds.js.map +1 -0
  204. package/out/tools/prominent-shapes/seeds.d.ts +132 -0
  205. package/out/tools/prominent-shapes/seeds.d.ts.map +1 -0
  206. package/out/tools/prominent-shapes/seeds.js +178 -0
  207. package/out/tools/prominent-shapes/seeds.js.map +1 -0
  208. package/out/tools/prominent-shapes/validate.d.ts +152 -0
  209. package/out/tools/prominent-shapes/validate.d.ts.map +1 -0
  210. package/out/tools/prominent-shapes/validate.js +389 -0
  211. package/out/tools/prominent-shapes/validate.js.map +1 -0
  212. package/out/tools/source-register/build.d.ts.map +1 -1
  213. package/out/tools/source-register/build.js +1 -0
  214. package/out/tools/source-register/build.js.map +1 -1
  215. package/out/training/config/admission.d.ts +2 -1
  216. package/out/training/config/admission.d.ts.map +1 -1
  217. package/out/training/config/admission.js +9 -2
  218. package/out/training/config/admission.js.map +1 -1
  219. package/out/training/config/schema.d.ts +276 -1
  220. package/out/training/config/schema.d.ts.map +1 -1
  221. package/out/training/config/schema.js +64 -1
  222. package/out/training/config/schema.js.map +1 -1
  223. package/out/types.d.ts +21 -0
  224. package/out/types.d.ts.map +1 -1
  225. package/out/types.js +13 -0
  226. package/out/types.js.map +1 -1
  227. package/out/us/adapters/usgov/usgs-structures/adapter.d.ts.map +1 -1
  228. package/out/us/adapters/usgov/usgs-structures/adapter.js +78 -4
  229. package/out/us/adapters/usgov/usgs-structures/adapter.js.map +1 -1
  230. package/out/utils/split.js +1 -1
  231. package/out/utils/split.js.map +1 -1
  232. package/package.json +24 -24
@@ -0,0 +1,890 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * Two-tier base-row corpus compaction for the v9 training pipeline.
6
+ *
7
+ * Preserves all `val` and `test` rows untouched so evaluation splits and holdout admission remain intact.
8
+ * Filters `train` rows to `augmentation IS NULL` so build-time copies are dropped.
9
+ *
10
+ * Keeps all canonical base `train` rows for Tier-1 sources.
11
+ * Deduplicates Tier-2 train rows across sources and caps each digit-masked skeleton bucket
12
+ * while keeping rare unit, PO box, cedex, intersection, venue, and building patterns exempt.
13
+ */
14
+
15
+ import { sha256File } from "@mailwoman/core/crypto/hash"
16
+ import { readLocalJSONFile } from "@mailwoman/core/fs/readers"
17
+ import { isFile, pathExists, statPath } from "@mailwoman/core/fs/readers/stat"
18
+ import {
19
+ cloneFileTo,
20
+ makeDirectories,
21
+ movePath,
22
+ removePathIfPresent,
23
+ writeLocalJSONFile,
24
+ } from "@mailwoman/core/fs/writers"
25
+ import { PathBuilder, resolvePath, type PathBuilderLike } from "path-ts"
26
+
27
+ import { escapeSQLString, openDuckDB, type DisposableDuckDB, type DuckDBLimits } from "#parquet/duckdb"
28
+ import { PARQUET_COLUMNS, PARQUET_COMPRESSION, ROW_GROUP_SIZE, ROWS_PER_FILE } from "#parquet/schema"
29
+ import { baseManifestFiles, localManifestFilePath } from "#tools/overlay/manifest"
30
+ import { readSplitAttribute, splitAttributeFilename, type SplitAttributeFile } from "#tools/overlay/split/attribute"
31
+ import type { SplitName } from "#utils/split"
32
+
33
+ /**
34
+ * Default maximum number of Tier-2 train rows kept per digit-masked skeleton bucket.
35
+ */
36
+ export const DEFAULT_SKELETON_CAP = 6
37
+
38
+ /**
39
+ * Default Tier-2 dense register sources subject to cross-source deduplication and skeleton capping.
40
+ *
41
+ * The multi-country European `overture` source stays in Tier 1 rather than here:
42
+ * its rows span 16 countries at roughly 100k to 150k rows each.
43
+ * Skeleton-capping it dropped 700,104 of 1,825,956 rows in `v0.9.0-compact`,
44
+ * including ES and IT single-letter unit rows and CZ/SI addresses.
45
+ */
46
+ export const DEFAULT_TIER2_SOURCES = [
47
+ "usgov-nad",
48
+ "ban",
49
+ "ban-gp",
50
+ "ban-gf",
51
+ "ban-mq",
52
+ "ban-re",
53
+ "ban-yt",
54
+ "ban-bl",
55
+ "ban-mf",
56
+ "ban-pm",
57
+ "ban-wf",
58
+ "ban-pf",
59
+ "usgov-nppes",
60
+ "tiger",
61
+ "usgov-usgs-structures",
62
+ "state-ia-contractors",
63
+ "state-ny-notaries",
64
+ "state-tx-notaries",
65
+ "overture-latam",
66
+ "gleif-lei",
67
+ ] as const
68
+
69
+ /**
70
+ * Bare component tags identifying rare address structures exempt from standard Tier-2 skeleton capping.
71
+ */
72
+ const RARE_PATTERN_TAGS = [
73
+ "unit",
74
+ "po_box",
75
+ "cedex",
76
+ "intersection_a",
77
+ "venue",
78
+ "building_name",
79
+ "building_number",
80
+ ] as const
81
+
82
+ /**
83
+ * Options for {@linkcode compactCorpusV9}.
84
+ */
85
+ export interface CompactCorpusV9Options {
86
+ /**
87
+ * Input corpus directory holding `MANIFEST.json`, or direct path to `MANIFEST.json`.
88
+ */
89
+ inPath: PathBuilderLike
90
+ /**
91
+ * Output directory for compacted Parquet files, `MANIFEST.json`, and `COMPACTION_REPORT.json`.
92
+ */
93
+ outDir: PathBuilderLike
94
+ /**
95
+ * Output `corpus_version` recorded in `MANIFEST.json`.
96
+ *
97
+ * Defaults to `<input version>-v9-compact`.
98
+ */
99
+ version?: string
100
+ /**
101
+ * Maximum Tier-2 train rows kept per `(country, labels, digit-masked raw)` skeleton bucket.
102
+ *
103
+ * @default 6
104
+ */
105
+ skeletonCap?: number
106
+ /**
107
+ * Optional cap for rare Tier-2 pattern rows (`unit`, `po_box`, `cedex`,
108
+ * `intersection_a`, `venue`, `building_name`, `building_number`).
109
+ *
110
+ * A `null` value keeps rare patterns uncapped.
111
+ * Bare single-letter `unit` rows (one token matching a single letter, such as ES
112
+ * `CALLE LA CRUZ A, 45` or IT `VIA NAPOLI A 5`) stay uncapped even when `rareSkeletonCap` is set.
113
+ *
114
+ * @default null
115
+ */
116
+ rareSkeletonCap?: number | null
117
+ /**
118
+ * Sources treated as Tier-2 dense registers.
119
+ *
120
+ * Every other source is treated as Tier 1.
121
+ *
122
+ * @default {@linkcode DEFAULT_TIER2_SOURCES}
123
+ */
124
+ tier2Sources?: readonly string[]
125
+ /**
126
+ * Optional path prefix written into `MANIFEST.json` entries.
127
+ *
128
+ * Defaults to the local `outDir` path.
129
+ */
130
+ modalRoot?: string
131
+ /**
132
+ * Optional DuckDB memory/thread/spill settings.
133
+ */
134
+ limits?: DuckDBLimits
135
+ }
136
+
137
+ /**
138
+ * Per-source row counts across compaction stages.
139
+ */
140
+ export interface CompactSourceStats {
141
+ source: string
142
+ tier: 1 | 2
143
+ inputTrainRows: number
144
+ inputValRows: number
145
+ inputTestRows: number
146
+ keptTrainRows: number
147
+ keptValRows: number
148
+ keptTestRows: number
149
+ droppedAugmentationRows: number
150
+ droppedDedupRows: number
151
+ droppedSkeletonCapRows: number
152
+ }
153
+
154
+ /**
155
+ * Summary report written to `COMPACTION_REPORT.json` beside the compacted `MANIFEST.json`.
156
+ */
157
+ export interface CompactionReport {
158
+ compacted_at: string
159
+ input_manifest: string
160
+ corpus_version: string
161
+ skeleton_cap: number
162
+ rare_skeleton_cap: number | null
163
+ tier2_sources: string[]
164
+ totals: {
165
+ input_rows: number
166
+ kept_rows: number
167
+ input_train_rows: number
168
+ kept_train_rows: number
169
+ input_val_rows: number
170
+ kept_val_rows: number
171
+ input_test_rows: number
172
+ kept_test_rows: number
173
+ dropped_augmentation_rows: number
174
+ dropped_dedup_rows: number
175
+ dropped_skeleton_cap_rows: number
176
+ }
177
+ sources: CompactSourceStats[]
178
+ }
179
+
180
+ /**
181
+ * Result of {@linkcode compactCorpusV9}.
182
+ */
183
+ export interface CompactCorpusV9Result {
184
+ manifestPath: string
185
+ reportPath: string
186
+ report: CompactionReport
187
+ }
188
+
189
+ interface InputManifestFile {
190
+ path: string
191
+ source?: string
192
+ split?: SplitName
193
+ split_attribute?: {
194
+ path: string
195
+ sha256: string
196
+ policy_hash: string
197
+ counts: Record<SplitName, number>
198
+ }
199
+ rows?: number
200
+ bytes?: number
201
+ sha256?: string
202
+ first_source_id?: string
203
+ last_source_id?: string
204
+ compression?: string
205
+ format?: string
206
+ }
207
+
208
+ interface InputManifest {
209
+ corpus_version?: string
210
+ schema?: unknown
211
+ rows_per_file?: number
212
+ row_group_size?: number
213
+ files?: InputManifestFile[]
214
+ counts?: Record<SplitName, number>
215
+ total_rows?: number
216
+ evaluation_groups?: unknown
217
+ source_rights?: unknown
218
+ deletions?: unknown
219
+ }
220
+
221
+ interface OutputManifestDescriptor {
222
+ path: string
223
+ format: "parquet"
224
+ compression: typeof PARQUET_COMPRESSION
225
+ rows: number
226
+ bytes: number
227
+ sha256: string
228
+ first_source_id: string
229
+ last_source_id: string
230
+ source: string
231
+ split?: SplitName
232
+ split_attribute?: {
233
+ path: string
234
+ sha256: string
235
+ policy_hash: string
236
+ counts: Record<SplitName, number>
237
+ }
238
+ }
239
+
240
+ interface PreparedFile {
241
+ index: number
242
+ entry: InputManifestFile
243
+ localParquetPath: string
244
+ source: string
245
+ tier: 1 | 2
246
+ hasAugmentation: boolean
247
+ hasSpanTags: boolean
248
+ hasTokens: boolean
249
+ splitAttribute: SplitAttributeFile | null
250
+ }
251
+
252
+ async function resolveInputFilePath(recordedPath: string): Promise<string> {
253
+ if (await pathExists(recordedPath)) return recordedPath
254
+
255
+ const local = localManifestFilePath(recordedPath)
256
+
257
+ if (await pathExists(local)) return local
258
+
259
+ throw new Error(`compactCorpusV9: input file does not exist at ${recordedPath} or ${local}`)
260
+ }
261
+
262
+ function makeSourceStats(source: string, tier: 1 | 2): CompactSourceStats {
263
+ return {
264
+ source,
265
+ tier,
266
+ inputTrainRows: 0,
267
+ inputValRows: 0,
268
+ inputTestRows: 0,
269
+ keptTrainRows: 0,
270
+ keptValRows: 0,
271
+ keptTestRows: 0,
272
+ droppedAugmentationRows: 0,
273
+ droppedDedupRows: 0,
274
+ droppedSkeletonCapRows: 0,
275
+ }
276
+ }
277
+
278
+ function recordedOutPath(outDir: PathBuilder, relative: string, modalRoot: string | undefined): string {
279
+ if (!modalRoot) return outDir(relative).toString()
280
+
281
+ return `${modalRoot.replace(/\/+$/u, "")}/${relative.replace(/^\/+/u, "")}`
282
+ }
283
+
284
+ async function prepareInputFiles(
285
+ db: DisposableDuckDB,
286
+ manifestFiles: readonly InputManifestFile[],
287
+ tier2Set: ReadonlySet<string>,
288
+ statsFor: (source: string, tier: 1 | 2) => CompactSourceStats
289
+ ): Promise<PreparedFile[]> {
290
+ const prepared: PreparedFile[] = []
291
+
292
+ for (const [index, entry] of manifestFiles.entries()) {
293
+ const localParquetPath = await resolveInputFilePath(entry.path)
294
+
295
+ const columnsResult = await db.runAndReadAll(
296
+ `SELECT name FROM parquet_schema('${escapeSQLString(localParquetPath)}')`
297
+ )
298
+
299
+ const columns = new Set(columnsResult.getRowObjectsJson().map((row) => String(row["name"])))
300
+ let source = entry.source
301
+
302
+ if (!source) {
303
+ const srcResult = await db.runAndReadAll(
304
+ `SELECT DISTINCT source FROM read_parquet('${escapeSQLString(localParquetPath)}')`
305
+ )
306
+
307
+ const found = srcResult.getRowObjectsJson().map((row) => String(row["source"]))
308
+
309
+ if (found.length !== 1) {
310
+ throw new Error(
311
+ `compactCorpusV9: ${localParquetPath} declares no manifest source and holds ${found.length} sources`
312
+ )
313
+ }
314
+
315
+ source = found[0]!
316
+ }
317
+
318
+ if (!entry.split && !entry.split_attribute) {
319
+ throw new Error(`compactCorpusV9: manifest entry ${entry.path} declares neither split nor split_attribute`)
320
+ }
321
+
322
+ const splitAttribute = entry.split_attribute
323
+ ? await readSplitAttribute(await resolveInputFilePath(entry.split_attribute.path))
324
+ : null
325
+
326
+ const tier: 1 | 2 = tier2Set.has(source) ? 2 : 1
327
+
328
+ statsFor(source, tier)
329
+
330
+ prepared.push({
331
+ index,
332
+ entry,
333
+ localParquetPath,
334
+ source,
335
+ tier,
336
+ hasAugmentation: columns.has("augmentation"),
337
+ hasSpanTags: columns.has("span_tags"),
338
+ hasTokens: columns.has("tokens"),
339
+ splitAttribute,
340
+ })
341
+ }
342
+
343
+ return prepared
344
+ }
345
+
346
+ async function loadHeldOutTable(db: DisposableDuckDB, prepared: readonly PreparedFile[]): Promise<void> {
347
+ await db.run("CREATE TEMP TABLE held_out (file_idx INTEGER, source_id VARCHAR, split VARCHAR)")
348
+
349
+ const heldAppender = await db.createAppender("held_out")
350
+
351
+ for (const file of prepared) {
352
+ if (!file.splitAttribute) continue
353
+
354
+ for (const id of file.splitAttribute.val) {
355
+ heldAppender.appendInteger(file.index)
356
+ heldAppender.appendVarchar(id)
357
+ heldAppender.appendVarchar("val")
358
+ heldAppender.endRow()
359
+ }
360
+
361
+ for (const id of file.splitAttribute.test) {
362
+ heldAppender.appendInteger(file.index)
363
+ heldAppender.appendVarchar(id)
364
+ heldAppender.appendVarchar("test")
365
+ heldAppender.endRow()
366
+ }
367
+ }
368
+
369
+ heldAppender.closeSync()
370
+ }
371
+
372
+ async function buildTier2KeepTable(
373
+ db: DisposableDuckDB,
374
+ prepared: readonly PreparedFile[],
375
+ skeletonCap: number,
376
+ rareSkeletonCap: number | null,
377
+ statsFor: (source: string, tier: 1 | 2) => CompactSourceStats
378
+ ): Promise<void> {
379
+ await db.run(
380
+ "CREATE TEMP TABLE tier2_candidates (" +
381
+ "file_idx INTEGER, " +
382
+ "file_row_number BIGINT, " +
383
+ "source VARCHAR, " +
384
+ "source_id VARCHAR, " +
385
+ "dedup_key VARCHAR, " +
386
+ "skeleton_key VARCHAR, " +
387
+ "is_rare BOOLEAN, " +
388
+ "is_single_letter_unit BOOLEAN, " +
389
+ "tie_hash VARCHAR)"
390
+ )
391
+
392
+ const rareTagsSQL = `[${RARE_PATTERN_TAGS.map((tag) => `'${tag}'`).join(", ")}]`
393
+
394
+ for (const file of prepared) {
395
+ if (file.tier !== 2) continue
396
+
397
+ if (!file.splitAttribute && file.entry.split !== "train") continue
398
+
399
+ const scan = `read_parquet('${escapeSQLString(file.localParquetPath)}', file_row_number = true)`
400
+
401
+ const trainPredicate = file.splitAttribute
402
+ ? `p.source_id NOT IN (SELECT source_id FROM held_out WHERE file_idx = ${file.index})`
403
+ : "TRUE"
404
+
405
+ const augPredicate = file.hasAugmentation ? "p.augmentation IS NULL" : "TRUE"
406
+ const augDroppedExpr = file.hasAugmentation ? "count(*) FILTER (WHERE p.augmentation IS NOT NULL)" : "0"
407
+
408
+ const countsRow = (
409
+ await db.runAndReadAll(
410
+ `SELECT count(*) AS total_train, ${augDroppedExpr} AS dropped_aug FROM ${scan} p WHERE ${trainPredicate}`
411
+ )
412
+ ).getRowObjectsJson()[0]!
413
+
414
+ const sourceStats = statsFor(file.source, 2)
415
+
416
+ sourceStats.inputTrainRows += Number(countsRow["total_train"])
417
+ sourceStats.droppedAugmentationRows += Number(countsRow["dropped_aug"])
418
+
419
+ const rareExpr = file.hasSpanTags
420
+ ? `(list_has_any(list_transform(p.labels, lambda x: regexp_replace(x, '^[BI]-', '')), ${rareTagsSQL}) ` +
421
+ `OR list_has_any(p.span_tags, ${rareTagsSQL}))`
422
+ : `list_has_any(list_transform(p.labels, lambda x: regexp_replace(x, '^[BI]-', '')), ${rareTagsSQL})`
423
+
424
+ const unitTokensExpr = `list_filter(list_zip(p.tokens, p.labels), lambda x: x[2] IN ('B-unit', 'I-unit'))`
425
+
426
+ const singleLetterUnitExpr = file.hasTokens
427
+ ? `(CASE WHEN len(${unitTokensExpr}) = 1 ` +
428
+ `THEN regexp_matches(${unitTokensExpr}[1][1], '^\\p{L}$') ` +
429
+ `ELSE FALSE END)`
430
+ : "FALSE"
431
+
432
+ await db.run(
433
+ `INSERT INTO tier2_candidates ` +
434
+ `SELECT ${file.index}, p.file_row_number, '${escapeSQLString(file.source)}', p.source_id, ` +
435
+ `sha256(coalesce(p.country, '') || chr(0) || lower(trim(p.raw)) || chr(0) || array_to_string(p.labels, ',')), ` +
436
+ `sha256(coalesce(p.country, '') || chr(0) || array_to_string(p.labels, ',') || chr(0) || ` +
437
+ `regexp_replace(lower(p.raw), '[0-9]+', '#', 'g')), ` +
438
+ `${rareExpr}, ` +
439
+ `${singleLetterUnitExpr}, ` +
440
+ `md5(coalesce(p.source_id, '') || ':' || p.raw) ` +
441
+ `FROM ${scan} p WHERE (${trainPredicate}) AND (${augPredicate})`
442
+ )
443
+ }
444
+
445
+ await db.run(
446
+ "CREATE TEMP TABLE tier2_deduped AS " +
447
+ "SELECT file_idx, file_row_number, source, source_id, skeleton_key, is_rare, is_single_letter_unit, tie_hash, " +
448
+ "row_number() OVER (PARTITION BY dedup_key ORDER BY source, source_id, file_idx, file_row_number) AS dedup_rn " +
449
+ "FROM tier2_candidates"
450
+ )
451
+
452
+ await db.run("DROP TABLE tier2_candidates")
453
+
454
+ const dedupDrops = await db.runAndReadAll(
455
+ "SELECT source, count(*) AS dropped FROM tier2_deduped WHERE dedup_rn > 1 GROUP BY source"
456
+ )
457
+
458
+ for (const row of dedupDrops.getRowObjectsJson()) {
459
+ statsFor(String(row["source"]), 2).droppedDedupRows += Number(row["dropped"])
460
+ }
461
+
462
+ await db.run(
463
+ "CREATE TEMP TABLE tier2_ranked AS " +
464
+ "SELECT file_idx, file_row_number, source, is_rare, is_single_letter_unit, " +
465
+ "row_number() OVER (PARTITION BY skeleton_key ORDER BY tie_hash, source, source_id, file_idx, file_row_number) AS skel_rn " +
466
+ "FROM tier2_deduped WHERE dedup_rn = 1"
467
+ )
468
+
469
+ await db.run("DROP TABLE tier2_deduped")
470
+
471
+ const keepPredicate =
472
+ rareSkeletonCap == null
473
+ ? `(is_rare OR skel_rn <= ${skeletonCap})`
474
+ : `(is_single_letter_unit OR (is_rare AND skel_rn <= ${rareSkeletonCap}) OR (NOT is_rare AND skel_rn <= ${skeletonCap}))`
475
+
476
+ const skelDrops = await db.runAndReadAll(
477
+ `SELECT source, count(*) AS dropped FROM tier2_ranked WHERE NOT ${keepPredicate} GROUP BY source`
478
+ )
479
+
480
+ for (const row of skelDrops.getRowObjectsJson()) {
481
+ statsFor(String(row["source"]), 2).droppedSkeletonCapRows += Number(row["dropped"])
482
+ }
483
+
484
+ await db.run(
485
+ `CREATE TEMP TABLE tier2_kept AS ` + `SELECT file_idx, file_row_number FROM tier2_ranked WHERE ${keepPredicate}`
486
+ )
487
+
488
+ await db.run("DROP TABLE tier2_ranked")
489
+ }
490
+
491
+ async function writeCompactedFile(
492
+ db: DisposableDuckDB,
493
+ file: PreparedFile,
494
+ outDir: PathBuilder,
495
+ modalRoot: string | undefined,
496
+ sourceStats: CompactSourceStats,
497
+ splitCounts: Record<SplitName, number>
498
+ ): Promise<OutputManifestDescriptor | null> {
499
+ const scan = `read_parquet('${escapeSQLString(file.localParquetPath)}', file_row_number = true)`
500
+
501
+ // Case 1: Dedicated val or test split file — preserve verbatim.
502
+ if (!file.splitAttribute && file.entry.split && file.entry.split !== "train") {
503
+ const split = file.entry.split
504
+ const splitSubdir = outDir(split)
505
+
506
+ await makeDirectories(splitSubdir)
507
+
508
+ const summaryRow = (
509
+ await db.runAndReadAll(
510
+ `SELECT count(*) AS rows, arg_min(source_id, file_row_number) AS first_id, ` +
511
+ `arg_max(source_id, file_row_number) AS last_id FROM ${scan}`
512
+ )
513
+ ).getRowObjectsJson()[0]!
514
+
515
+ const rows = Number(summaryRow["rows"])
516
+
517
+ if (split === "val") {
518
+ sourceStats.inputValRows += rows
519
+ sourceStats.keptValRows += rows
520
+ } else {
521
+ sourceStats.inputTestRows += rows
522
+ sourceStats.keptTestRows += rows
523
+ }
524
+
525
+ splitCounts[split] += rows
526
+
527
+ const sha256 = await sha256File(file.localParquetPath)
528
+ const fileName = `${file.source}-${String(file.index).padStart(4, "0")}-${sha256.slice(0, 12)}.parquet`
529
+ const relative = `${split}/${fileName}`
530
+ const destination = outDir(relative)
531
+
532
+ await cloneFileTo(file.localParquetPath, destination)
533
+
534
+ return {
535
+ split,
536
+ path: recordedOutPath(outDir, relative, modalRoot),
537
+ format: "parquet",
538
+ compression: PARQUET_COMPRESSION,
539
+ rows,
540
+ bytes: (await statPath(destination)).size,
541
+ sha256,
542
+ first_source_id: String(summaryRow["first_id"] ?? ""),
543
+ last_source_id: String(summaryRow["last_id"] ?? ""),
544
+ source: file.source,
545
+ }
546
+ }
547
+
548
+ // Case 2: Dedicated train split file.
549
+ if (!file.splitAttribute && file.entry.split === "train") {
550
+ const trainSubdir = outDir("train")
551
+
552
+ await makeDirectories(trainSubdir)
553
+
554
+ const staging = trainSubdir(`${file.source}-${file.index}.parquet.partial`).toString()
555
+
556
+ if (file.tier === 1) {
557
+ const augPredicate = file.hasAugmentation ? "augmentation IS NULL" : "TRUE"
558
+ const augDroppedExpr = file.hasAugmentation ? "count(*) FILTER (WHERE augmentation IS NOT NULL)" : "0"
559
+
560
+ const countsRow = (
561
+ await db.runAndReadAll(`SELECT count(*) AS total, ${augDroppedExpr} AS dropped_aug FROM ${scan}`)
562
+ ).getRowObjectsJson()[0]!
563
+
564
+ sourceStats.inputTrainRows += Number(countsRow["total"])
565
+ sourceStats.droppedAugmentationRows += Number(countsRow["dropped_aug"])
566
+
567
+ await db.run(
568
+ `COPY (SELECT * EXCLUDE (file_row_number) FROM ${scan} ` +
569
+ `WHERE ${augPredicate} ORDER BY file_row_number) ` +
570
+ `TO '${escapeSQLString(staging)}' ` +
571
+ `(FORMAT PARQUET, COMPRESSION ${PARQUET_COMPRESSION}, ROW_GROUP_SIZE ${ROW_GROUP_SIZE})`
572
+ )
573
+ } else {
574
+ await db.run(
575
+ `COPY (SELECT p.* EXCLUDE (file_row_number) FROM ${scan} p ` +
576
+ `JOIN tier2_kept k ON k.file_idx = ${file.index} AND k.file_row_number = p.file_row_number ` +
577
+ `ORDER BY p.file_row_number) ` +
578
+ `TO '${escapeSQLString(staging)}' ` +
579
+ `(FORMAT PARQUET, COMPRESSION ${PARQUET_COMPRESSION}, ROW_GROUP_SIZE ${ROW_GROUP_SIZE})`
580
+ )
581
+ }
582
+
583
+ const summaryRow = (
584
+ await db.runAndReadAll(
585
+ `SELECT count(*) AS rows, arg_min(source_id, file_row_number) AS first_id, ` +
586
+ `arg_max(source_id, file_row_number) AS last_id ` +
587
+ `FROM read_parquet('${escapeSQLString(staging)}', file_row_number = true)`
588
+ )
589
+ ).getRowObjectsJson()[0]!
590
+
591
+ const keptRows = Number(summaryRow["rows"])
592
+
593
+ if (keptRows === 0) {
594
+ await removePathIfPresent(staging)
595
+
596
+ return null
597
+ }
598
+
599
+ sourceStats.keptTrainRows += keptRows
600
+ splitCounts.train += keptRows
601
+
602
+ const sha256 = await sha256File(staging)
603
+ const fileName = `${file.source}-${String(file.index).padStart(4, "0")}-${sha256.slice(0, 12)}.parquet`
604
+ const relative = `train/${fileName}`
605
+ const destination = outDir(relative)
606
+
607
+ await movePath(staging, destination)
608
+
609
+ return {
610
+ split: "train",
611
+ path: recordedOutPath(outDir, relative, modalRoot),
612
+ format: "parquet",
613
+ compression: PARQUET_COMPRESSION,
614
+ rows: keptRows,
615
+ bytes: (await statPath(destination)).size,
616
+ sha256,
617
+ first_source_id: String(summaryRow["first_id"]),
618
+ last_source_id: String(summaryRow["last_id"]),
619
+ source: file.source,
620
+ }
621
+ }
622
+
623
+ // Case 3: Split-attribute file holding train, val, and test rows together.
624
+ const attr = file.splitAttribute!
625
+ const staging = outDir(`${file.source}-${file.index}.parquet.partial`).toString()
626
+
627
+ const heldCounts = (
628
+ await db.runAndReadAll(
629
+ `SELECT count(*) FILTER (WHERE h.split = 'val') AS val_rows, ` +
630
+ `count(*) FILTER (WHERE h.split = 'test') AS test_rows ` +
631
+ `FROM ${scan} p JOIN held_out h ON h.file_idx = ${file.index} AND h.source_id = p.source_id`
632
+ )
633
+ ).getRowObjectsJson()[0]!
634
+
635
+ const valRows = Number(heldCounts["val_rows"])
636
+ const testRows = Number(heldCounts["test_rows"])
637
+
638
+ sourceStats.inputValRows += valRows
639
+ sourceStats.keptValRows += valRows
640
+ sourceStats.inputTestRows += testRows
641
+ sourceStats.keptTestRows += testRows
642
+
643
+ if (file.tier === 1) {
644
+ const augPredicate = file.hasAugmentation ? "p.augmentation IS NULL" : "TRUE"
645
+ const augDroppedExpr = file.hasAugmentation ? "count(*) FILTER (WHERE p.augmentation IS NOT NULL)" : "0"
646
+
647
+ const trainCounts = (
648
+ await db.runAndReadAll(
649
+ `SELECT count(*) AS total_train, ${augDroppedExpr} AS dropped_aug ` +
650
+ `FROM ${scan} p WHERE p.source_id NOT IN (SELECT source_id FROM held_out WHERE file_idx = ${file.index})`
651
+ )
652
+ ).getRowObjectsJson()[0]!
653
+
654
+ sourceStats.inputTrainRows += Number(trainCounts["total_train"])
655
+ sourceStats.droppedAugmentationRows += Number(trainCounts["dropped_aug"])
656
+
657
+ await db.run(
658
+ `COPY (SELECT p.* EXCLUDE (file_row_number) FROM ${scan} p ` +
659
+ `WHERE p.source_id IN (SELECT source_id FROM held_out WHERE file_idx = ${file.index}) ` +
660
+ `OR (${augPredicate}) ` +
661
+ `ORDER BY p.file_row_number) ` +
662
+ `TO '${escapeSQLString(staging)}' ` +
663
+ `(FORMAT PARQUET, COMPRESSION ${PARQUET_COMPRESSION}, ROW_GROUP_SIZE ${ROW_GROUP_SIZE})`
664
+ )
665
+ } else {
666
+ await db.run(
667
+ `COPY (SELECT p.* EXCLUDE (file_row_number) FROM ${scan} p ` +
668
+ `LEFT JOIN tier2_kept k ON k.file_idx = ${file.index} AND k.file_row_number = p.file_row_number ` +
669
+ `WHERE p.source_id IN (SELECT source_id FROM held_out WHERE file_idx = ${file.index}) ` +
670
+ `OR k.file_row_number IS NOT NULL ` +
671
+ `ORDER BY p.file_row_number) ` +
672
+ `TO '${escapeSQLString(staging)}' ` +
673
+ `(FORMAT PARQUET, COMPRESSION ${PARQUET_COMPRESSION}, ROW_GROUP_SIZE ${ROW_GROUP_SIZE})`
674
+ )
675
+ }
676
+
677
+ const summaryRow = (
678
+ await db.runAndReadAll(
679
+ `SELECT count(*) AS rows, arg_min(source_id, file_row_number) AS first_id, ` +
680
+ `arg_max(source_id, file_row_number) AS last_id ` +
681
+ `FROM read_parquet('${escapeSQLString(staging)}', file_row_number = true)`
682
+ )
683
+ ).getRowObjectsJson()[0]!
684
+
685
+ const keptTotal = Number(summaryRow["rows"])
686
+
687
+ if (keptTotal === 0) {
688
+ await removePathIfPresent(staging)
689
+
690
+ return null
691
+ }
692
+
693
+ const keptTrain = keptTotal - valRows - testRows
694
+
695
+ sourceStats.keptTrainRows += keptTrain
696
+ splitCounts.train += keptTrain
697
+ splitCounts.val += valRows
698
+ splitCounts.test += testRows
699
+
700
+ const sha256 = await sha256File(staging)
701
+ const fileName = `${file.source}-${String(file.index).padStart(4, "0")}-${sha256.slice(0, 12)}.parquet`
702
+ const destination = outDir(fileName)
703
+
704
+ await movePath(staging, destination)
705
+
706
+ const attrName = splitAttributeFilename(fileName, attr.policyHash)
707
+ const attrPath = outDir(attrName)
708
+
709
+ const updatedAttribute: SplitAttributeFile = {
710
+ ...attr,
711
+ file: { name: fileName, sha256, rows: keptTotal },
712
+ counts: { train: keptTrain, val: valRows, test: testRows },
713
+ }
714
+
715
+ await writeLocalJSONFile(updatedAttribute, attrPath)
716
+
717
+ const attrSHA256 = await sha256File(attrPath)
718
+
719
+ return {
720
+ path: recordedOutPath(outDir, fileName, modalRoot),
721
+ format: "parquet",
722
+ compression: PARQUET_COMPRESSION,
723
+ rows: keptTotal,
724
+ bytes: (await statPath(destination)).size,
725
+ sha256,
726
+ first_source_id: String(summaryRow["first_id"]),
727
+ last_source_id: String(summaryRow["last_id"]),
728
+ source: file.source,
729
+ split_attribute: {
730
+ path: recordedOutPath(outDir, attrName, modalRoot),
731
+ sha256: attrSHA256,
732
+ policy_hash: attr.policyHash,
733
+ counts: { train: keptTrain, val: valRows, test: testRows },
734
+ },
735
+ }
736
+ }
737
+
738
+ function summarizeTotals(sources: readonly CompactSourceStats[]): CompactionReport["totals"] {
739
+ const totals: CompactionReport["totals"] = {
740
+ input_rows: 0,
741
+ kept_rows: 0,
742
+ input_train_rows: 0,
743
+ kept_train_rows: 0,
744
+ input_val_rows: 0,
745
+ kept_val_rows: 0,
746
+ input_test_rows: 0,
747
+ kept_test_rows: 0,
748
+ dropped_augmentation_rows: 0,
749
+ dropped_dedup_rows: 0,
750
+ dropped_skeleton_cap_rows: 0,
751
+ }
752
+
753
+ for (const source of sources) {
754
+ totals.input_train_rows += source.inputTrainRows
755
+ totals.kept_train_rows += source.keptTrainRows
756
+ totals.input_val_rows += source.inputValRows
757
+ totals.kept_val_rows += source.keptValRows
758
+ totals.input_test_rows += source.inputTestRows
759
+ totals.kept_test_rows += source.keptTestRows
760
+ totals.dropped_augmentation_rows += source.droppedAugmentationRows
761
+ totals.dropped_dedup_rows += source.droppedDedupRows
762
+ totals.dropped_skeleton_cap_rows += source.droppedSkeletonCapRows
763
+ }
764
+
765
+ totals.input_rows = totals.input_train_rows + totals.input_val_rows + totals.input_test_rows
766
+ totals.kept_rows = totals.kept_train_rows + totals.kept_val_rows + totals.kept_test_rows
767
+
768
+ return totals
769
+ }
770
+
771
+ /**
772
+ * Compacts a corpus manifest into a two-tier base-row v9 corpus while preserving all `val`
773
+ * and `test` rows and split-attribute holdout boundaries untouched.
774
+ */
775
+ export async function compactCorpusV9(options: CompactCorpusV9Options): Promise<CompactCorpusV9Result> {
776
+ const skeletonCap = options.skeletonCap ?? DEFAULT_SKELETON_CAP
777
+ const rareSkeletonCap = options.rareSkeletonCap ?? null
778
+
779
+ if (!Number.isInteger(skeletonCap) || skeletonCap < 1) {
780
+ throw new Error(`compactCorpusV9: skeletonCap must be a positive integer, got ${skeletonCap}`)
781
+ }
782
+
783
+ if (rareSkeletonCap != null && (!Number.isInteger(rareSkeletonCap) || rareSkeletonCap < 1)) {
784
+ throw new Error(`compactCorpusV9: rareSkeletonCap must be null or a positive integer, got ${rareSkeletonCap}`)
785
+ }
786
+
787
+ const inputPathStr = resolvePath(options.inPath)
788
+ const manifestPath = (await isFile(inputPathStr)) ? inputPathStr : resolvePath(inputPathStr, "MANIFEST.json")
789
+ const manifest = await readLocalJSONFile<InputManifest>(manifestPath)
790
+ const manifestFiles = baseManifestFiles<InputManifestFile>(manifest)
791
+
792
+ const tier2List = [...new Set(options.tier2Sources ?? DEFAULT_TIER2_SOURCES)].toSorted()
793
+ const tier2Set = new Set(tier2List)
794
+ const outDir = PathBuilder.from(options.outDir)
795
+
796
+ await makeDirectories(outDir)
797
+
798
+ const corpusVersion = options.version ?? `${manifest.corpus_version ?? "v0.9.0"}-v9-compact`
799
+ const statsBySource = new Map<string, CompactSourceStats>()
800
+
801
+ const statsFor = (source: string, tier: 1 | 2): CompactSourceStats => {
802
+ let entry = statsBySource.get(source)
803
+
804
+ if (!entry) {
805
+ entry = makeSourceStats(source, tier)
806
+ statsBySource.set(source, entry)
807
+ }
808
+
809
+ return entry
810
+ }
811
+
812
+ using db = await openDuckDB(options.limits)
813
+
814
+ const prepared = await prepareInputFiles(db, manifestFiles, tier2Set, statsFor)
815
+
816
+ await loadHeldOutTable(db, prepared)
817
+ await buildTier2KeepTable(db, prepared, skeletonCap, rareSkeletonCap, statsFor)
818
+
819
+ // Switch to single-threaded insertion-order-preserving mode for deterministic Parquet COPY output.
820
+ await db.run("SET preserve_insertion_order=true")
821
+ await db.run("SET threads=1")
822
+
823
+ const outputFiles: OutputManifestDescriptor[] = []
824
+ const splitCounts: Record<SplitName, number> = { train: 0, val: 0, test: 0 }
825
+
826
+ for (const file of prepared) {
827
+ const descriptor = await writeCompactedFile(
828
+ db,
829
+ file,
830
+ outDir,
831
+ options.modalRoot,
832
+ statsFor(file.source, file.tier),
833
+ splitCounts
834
+ )
835
+
836
+ if (descriptor) {
837
+ outputFiles.push(descriptor)
838
+ }
839
+ }
840
+
841
+ const sortedFiles = outputFiles.toSorted((a, b) => {
842
+ const splitA = a.split ?? ""
843
+ const splitB = b.split ?? ""
844
+
845
+ return splitA === splitB ? a.path.localeCompare(b.path) : splitA.localeCompare(splitB)
846
+ })
847
+
848
+ const totalRows = splitCounts.train + splitCounts.val + splitCounts.test
849
+
850
+ const outManifest = {
851
+ corpus_version: corpusVersion,
852
+ schema: manifest.schema ?? PARQUET_COLUMNS,
853
+ rows_per_file: manifest.rows_per_file ?? ROWS_PER_FILE,
854
+ row_group_size: ROW_GROUP_SIZE,
855
+ files: sortedFiles,
856
+ counts: splitCounts,
857
+ total_rows: totalRows,
858
+ ...(manifest.evaluation_groups ? { evaluation_groups: manifest.evaluation_groups } : {}),
859
+ ...(manifest.source_rights ? { source_rights: manifest.source_rights } : {}),
860
+ ...(manifest.deletions ? { deletions: manifest.deletions } : {}),
861
+ compaction_report: "COMPACTION_REPORT.json",
862
+ }
863
+
864
+ const outManifestPath = outDir("MANIFEST.json")
865
+
866
+ await writeLocalJSONFile(outManifest, outManifestPath)
867
+
868
+ const sources = [...statsBySource.values()].toSorted((a, b) => a.source.localeCompare(b.source))
869
+
870
+ const report: CompactionReport = {
871
+ compacted_at: new Date().toISOString(),
872
+ input_manifest: manifestPath,
873
+ corpus_version: corpusVersion,
874
+ skeleton_cap: skeletonCap,
875
+ rare_skeleton_cap: rareSkeletonCap,
876
+ tier2_sources: tier2List,
877
+ totals: summarizeTotals(sources),
878
+ sources,
879
+ }
880
+
881
+ const reportPath = outDir("COMPACTION_REPORT.json")
882
+
883
+ await writeLocalJSONFile(report, reportPath)
884
+
885
+ return {
886
+ manifestPath: outManifestPath.toString(),
887
+ reportPath: reportPath.toString(),
888
+ report,
889
+ }
890
+ }