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