Datasets:
File size: 24,938 Bytes
31d8236 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 | """Transactionally append a proven-disjoint audited source to a screened release.
Existing parquet shards are hard-linked and never rewritten. Exact scoped-task,
normalized-prompt and declared-lineage overlap require a full rebuild, because
representative selection and held-out propagation would otherwise change old rows.
"""
from __future__ import annotations
import argparse
from collections import Counter
from datetime import datetime, timezone
from itertools import zip_longest
import json
import os
from pathlib import Path
import re
import shutil
import sqlite3
import pyarrow as pa
import pyarrow.parquet as pq
import yaml
import assemble_task_dataset as assembly
from full_curation_common import BASE, ROOT, STAGING
from screen_task_difficulty import DIFFICULTY_SCHEMA, TIERS, render_difficulty_card
from task_difficulty import annotate_difficulty
def dump(path, value):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n')
def inventory(directory):
return {str(p.relative_to(directory)): p for p in directory.rglob('*') if p.is_file()}
def verify_release(release, manifest):
files = inventory(release)
if set(files) != set(manifest['files']) | {'release_manifest.json'}:
raise ValueError('Release inventory differs from its audited manifest')
for name, expected in manifest['files'].items():
path = files[name]
if (path.is_symlink() or not path.resolve().is_relative_to(release.resolve())
or path.stat().st_size != expected['bytes']
or assembly.digest(path) != expected['sha256']):
raise ValueError(f'Release checksum/path mismatch: {name}')
def load_source(source, audit_path):
folder = STAGING / source
manifest = json.loads((folder / 'manifest.json').read_text())
audit = json.loads(audit_path.read_text())
if audit.get('status') != 'passed' or audit.get('source', source) != source:
raise ValueError(f'A passed audit for {source} is required')
if not manifest.get('completed') or manifest.get('source') != source or manifest['records'] <= 0:
raise ValueError('Source manifest is incomplete or empty')
listed = {s['file'] for s in manifest['shards']}
if listed != {p.name for p in folder.glob('*.parquet')} or len(listed) != len(manifest['shards']):
raise ValueError('Source has duplicate, missing or unmanifested shards')
if sum(s['rows'] for s in manifest['shards']) != manifest['records']:
raise ValueError('Source manifest row count mismatch')
return manifest, audit
def index_counts(db, schema='main'):
# Schema names are internal constants, never caller input.
values = db.execute(f'SELECT COUNT(*),SUM(eligible>0),SUM(eligible=0),'
f'SUM(eligible>0 AND protected=1) FROM {schema}.tasks').fetchone()
counts = dict(zip(('task_groups', 'eligible_task_groups', 'quarantined_task_groups',
'heldout_eligible_task_groups'), (int(v or 0) for v in values)))
counts['annotation_records'] = db.execute(f'SELECT COUNT(*) FROM {schema}.records').fetchone()[0]
counts['duplicate_annotation_records'] = counts['annotation_records'] - counts['task_groups']
counts['cross_source_task_groups'] = db.execute(
f'SELECT COUNT(*) FROM {schema}.tasks WHERE (sources & (sources-1)) != 0').fetchone()[0]
return counts
def prove_disjoint(db, prior_index, old_counts, source):
db.execute('ATTACH DATABASE ? AS prior', (prior_index.resolve().as_uri() + '?mode=ro',))
try:
prior_counts = index_counts(db, 'prior')
if any(old_counts.get(k) != v for k, v in prior_counts.items()):
raise ValueError('Existing index does not match the release counts; perform a full rebuild')
if db.execute('SELECT 1 FROM prior.records WHERE id LIKE ? LIMIT 1', (source + ':%',)).fetchone():
raise ValueError('Source record prefix already exists; perform a full rebuild')
checks = {
'scoped_task_id': 'SELECT n.id FROM main.tasks n JOIN prior.tasks p ON p.id=n.id LIMIT 1',
'normalized_prompt_hash': 'SELECT n.prompt FROM main.tasks n JOIN prior.tasks p ON p.prompt=n.prompt LIMIT 1',
'declared_lineage': 'SELECT n.lineage FROM main.lineage n JOIN prior.lineage p ON p.lineage=n.lineage LIMIT 1',
}
for name, query in checks.items():
if db.execute(query).fetchone():
raise ValueError(f'{name} overlaps the existing release; perform a full rebuild')
return {'status': 'passed', 'prior_index_counts': prior_counts,
'scoped_task_id_overlaps': 0, 'normalized_prompt_hash_overlaps': 0,
'declared_lineage_overlaps': 0, 'source_record_prefix_present': False}
finally:
db.execute('DETACH DATABASE prior')
class PrefixedShards(assembly.Shards):
def __init__(self, directory, prefix, schema=DIFFICULTY_SCHEMA):
super().__init__(directory, schema=schema)
self.prefix = prefix
def flush(self):
if not self.buffer:
return
path = self.directory / f'{self.prefix}-part-{len(self.files):05d}.parquet'
if path.exists():
raise ValueError(f'Append would overwrite an existing shard: {path}')
pq.write_table(pa.Table.from_pylist(self.buffer, schema=self.schema), path,
compression='zstd', row_group_size=500)
self.files.append({'file': str(path), 'rows': len(self.buffer),
'bytes': path.stat().st_size, 'sha256': assembly.digest(path)})
self.buffer.clear()
def relative_config(writer, release):
config = writer.close()
for shard in config['shards']:
shard['file'] = str(Path(shard['file']).relative_to(release))
return config
def add_config(configs, name, addition):
config = configs.setdefault(name, {'rows': 0, 'shards': []})
config['rows'] += addition['rows']
config['shards'].extend(addition['shards'])
def export_source(working, source, manifest, db):
source_writer = assembly.Shards(working / 'data' / source)
quarantine = assembly.Shards(working / 'data/quarantine' / source)
tiers = {tier: PrefixedShards(working / 'data/tasks' / tier, source) for tier in TIERS}
families, leaves, counts, evidence, samples = Counter(), Counter(), Counter(), Counter(), {}
annotation_tiers, eligible_annotation_tiers, annotation_evidence = Counter(), Counter(), Counter()
for shard in manifest['shards']:
path = STAGING / source / shard['file']
for batch in pq.ParquetFile(path).iter_batches(batch_size=256):
rows = batch.to_pylist()
keys = sorted({assembly.scoped_task_id(r) for r in rows})
matches = db.execute('SELECT id,representative,annotations,eligible,protected,training '
'FROM tasks WHERE id IN (' + ','.join('?' for _ in keys) + ')', keys)
groups = {r[0]: r[1:] for r in matches}
for row in rows:
original_id = row['task_id']
task_id = assembly.scoped_task_id(row)
representative, annotations, eligible, protected, training = groups[task_id]
reasons = assembly.classification(row)
row.update(task_id=task_id, prompt_context_id=original_id,
annotation_count=annotations, eligible_annotation_count=eligible,
group_sources=[source], source_split_status='held_out' if protected else ('source_train' if training else 'unspecified'),
curation_status='quarantined' if reasons else 'curated_candidate', curation_reasons=reasons)
labels = annotate_difficulty(row)
if set(labels) != set(DIFFICULTY_SCHEMA.names) - set(assembly.RELEASE_SCHEMA.names) or labels['difficulty_tier'] not in TIERS:
raise ValueError('Difficulty classifier returned an invalid annotation')
annotation_tiers[labels['difficulty_tier']] += 1
if not reasons:
eligible_annotation_tiers[labels['difficulty_tier']] += 1
if labels['difficulty_tier'] != 'uncalibrated':
annotation_evidence.update(labels['difficulty_evidence'])
source_writer.add(row.copy())
if reasons:
quarantine.add(row.copy())
if eligible and row['record_id'] == representative:
row.update(labels)
tier = labels['difficulty_tier']
tiers[tier].add(row)
counts[tier] += 1; evidence.update(labels['difficulty_evidence'])
families[row['family']] += 1; leaves[row['leaf'] or 'unassigned'] += 1
sample_key = source + ':' + tier
if len(samples.setdefault(sample_key, [])) < 3:
samples[sample_key].append({'record_id': row['record_id'], 'prompt_excerpt': row['prompt'][:400],
'evidence': labels['difficulty_evidence']})
# Ensure source staging stayed unchanged between indexing and export.
if path.stat().st_size != shard['bytes'] or assembly.digest(path) != shard['sha256']:
raise ValueError(f'Source changed during append: {shard["file"]}')
return {'source': relative_config(source_writer, working), 'quarantine': relative_config(quarantine, working),
'tiers': {k: relative_config(v, working) for k, v in tiers.items()},
'families': families, 'leaves': leaves, 'counts': counts,
'evidence': evidence, 'samples': samples,
'annotation_difficulty': {'annotations': dict(annotation_tiers), 'eligible_annotations': dict(eligible_annotation_tiers),
'tier_evidence_counts': dict(annotation_evidence)}}
def merge_index(prior_path, added_path, combined_path, source, expected_counts):
prior = sqlite3.connect(prior_path.resolve().as_uri() + '?mode=ro', uri=True)
combined = sqlite3.connect(combined_path)
try:
prior.backup(combined)
combined.execute('ATTACH DATABASE ? AS added', (added_path.resolve().as_uri() + '?mode=ro',))
bit = 1 << assembly.SOURCE_NAMES.index(source)
with combined:
combined.execute('INSERT INTO records SELECT * FROM added.records')
combined.execute('INSERT INTO tasks SELECT id,representative,rank,annotations,eligible,?,protected,training,prompt FROM added.tasks', (bit,))
combined.execute('INSERT INTO lineage SELECT * FROM added.lineage')
combined.execute('INSERT OR IGNORE INTO heldout_prompts SELECT * FROM added.heldout_prompts')
if any(expected_counts.get(k) != v for k, v in index_counts(combined).items()):
raise ValueError('Combined index count mismatch')
if combined.execute('PRAGMA quick_check').fetchone()[0] != 'ok':
raise ValueError('Combined index integrity check failed')
finally:
combined.close(); prior.close()
def copy_source_notices(working, manifest):
"""Copy declared README/license artifacts only after checking their hashes."""
entries = [entry for entry in manifest.get('auxiliary_input_files', [])
if 'README' in Path(entry['file']).name.upper()
or Path(entry['file']).name.upper().startswith(('LICENSE', 'NOTICE', 'COPYING'))]
if not entries:
return
repos = {manifest['source_repo']} | {entry['repo'] for entry in entries}
candidates = []
for repo in repos:
for separator in ('--', '__'):
folder = BASE / 'downloads' / repo.replace('/', separator)
if folder.exists():
candidates.extend(p for p in folder.rglob('*') if p.is_file()
and ('README' in p.name.upper() or p.name.upper().startswith(('LICENSE', 'NOTICE', 'COPYING'))))
target = working / 'source_notices/upstream' / manifest['source_repo'].replace('/', '__')
target.mkdir(parents=True, exist_ok=True)
notices = []
for entry in entries:
matches = [p for p in candidates if p.stat().st_size == entry['bytes'] and assembly.digest(p) == entry['sha256']]
if not matches:
raise ValueError(f"Declared source notice is missing or changed: {entry['repo']}:{entry['file']}")
name = entry['repo'].replace('/', '__') + '__' + Path(entry['file']).name
destination = target / name
shutil.copyfile(matches[0], destination)
notices.append(dict(entry, bundled_file=str(destination.relative_to(working))))
dump(target / 'notice_manifest.json', notices)
def update_documents(working, source, manifest, audit_path, quality, difficulty, inventory_manifest):
dump(working / 'manifests' / f'{source}.json', manifest)
shutil.copyfile(audit_path, working / 'audit' / audit_path.name)
shutil.copyfile(audit_path, working / 'curation/outputs/full_curation' / audit_path.name)
metadata_path = BASE / 'source_metadata.json'
all_metadata = json.loads(metadata_path.read_text())
matching = [m for m in all_metadata if m['repo'] == manifest['source_repo'] and m['sha'] == manifest['revision']]
if len(matching) != 1:
raise ValueError('Pinned source metadata is missing or ambiguous')
public_metadata_path = working / 'manifests/source_metadata.json'
public_metadata = json.loads(public_metadata_path.read_text())
public_metadata.append({k: matching[0][k] for k in ('repo', 'sha', 'license', 'files') if k in matching[0]})
dump(public_metadata_path, public_metadata)
shutil.copyfile(metadata_path, working / 'curation/outputs/full_curation/source_metadata.json')
repo, revision = manifest['source_repo'], manifest['revision']
url = f'https://github.com/{repo[7:]}/tree/{revision}' if repo.startswith('github:') else f'https://huggingface.co/datasets/{repo}/tree/{revision}'
with (working / 'LICENSES.md').open('a') as out:
out.write(f'\n## {source}\n\nDeclared license: {manifest["license"]}\n\nPinned source: {url}\n\nPer-record attribution and upstream article/component terms remain applicable.\n')
(working / 'source_notices' / f'{source}.md').write_text(f'# {source}\n\nPinned source: {url}\n\nDeclared source license: {manifest["license"]}\n\nPer-record attribution and upstream component licenses are retained.\n')
copy_source_notices(working, manifest)
manifests = {name: json.loads((working / 'manifests' / f'{name}.json').read_text()) for name in quality['sources']}
if set(manifests) != set(assembly.SOURCE_NAMES):
raise ValueError('Source registry differs from release sources; perform a full rebuild')
(working / 'README.md').write_text(assembly.render_card(quality, manifests))
render_difficulty_card(working, difficulty)
card = working / 'README.md'
_, header, body = card.read_text().split('---', 2)
card_meta = yaml.safe_load(header)
for config in card_meta['configs']:
if config['config_name'] == 'quarantine':
config['data_files'][0]['path'] = 'data/quarantine/**/*.parquet'
patterns = config['data_files'][0]['path']
patterns = [patterns] if isinstance(patterns, str) else patterns
matched = {str(p.relative_to(working)) for pattern in patterns for p in working.glob(pattern)}
listed = {s['file'] for s in inventory_manifest['configs'][config['config_name']]['shards']}
if matched != listed:
raise ValueError(f'Card paths disagree with manifest: {config["config_name"]}')
card.write_text('---\n' + yaml.safe_dump(card_meta, sort_keys=False) + '---\n' + body.lstrip())
adapters = sorted((ROOT / 'scripts').glob(f'curate*{source}*.py'))
if len(adapters) != 1:
raise ValueError(f'Expected one reproducible adapter for {source}, found {len(adapters)}')
scripts = [Path(__file__), ROOT / 'scripts/assemble_task_dataset.py', ROOT / 'scripts/publish_task_dataset.py', ROOT / 'scripts/screen_task_difficulty.py',
ROOT / 'scripts/task_difficulty.py', *adapters, *sorted((ROOT / 'scripts').glob(f'audit*{source}*.py'))]
for path in scripts:
shutil.copyfile(path, working / 'curation/scripts' / path.name)
shutil.copyfile(ROOT / 'pyproject.toml', working / 'curation/pyproject.toml')
reproduction = working / 'curation/README.md'
text = reproduction.read_text()
command = f'.venv/bin/python scripts/{adapters[0].name}\n'
if command not in text:
text = text.replace('.venv/bin/python scripts/assemble_task_dataset.py\n', command + '.venv/bin/python scripts/assemble_task_dataset.py\n')
reproduction.write_text(text)
def install_pair(release, working, release_backup, index, combined, index_backup):
moved_release = moved_index = installed_release = installed_index = False
try:
release.rename(release_backup); moved_release = True
index.rename(index_backup); moved_index = True
working.rename(release); installed_release = True
combined.rename(index); installed_index = True
except BaseException:
if installed_index:
index.rename(combined)
if installed_release:
release.rename(working)
if moved_index:
index_backup.rename(index)
if moved_release:
release_backup.rename(release)
raise
def append_source(source, release, prior_index=None, audit_path=None):
if not re.fullmatch(r'[a-z0-9_]+', source) or source not in assembly.SOURCE_NAMES:
raise ValueError('Source must be registered in SOURCE_NAMES')
prior_index = prior_index or BASE / 'curation_index.sqlite'
audit_path = audit_path or BASE / f'audit_{source}_sources.json'
working = release.with_name(release.name + f'.append-{source}-build')
release_backup = release.with_name(release.name + f'_before_{source}')
new_index = BASE / f'append_{source}_index.sqlite'
combined = prior_index.with_name(prior_index.name + f'.append-{source}-build')
index_backup = prior_index.with_name(prior_index.name + f'.before-{source}')
for path in (working, release_backup, new_index, combined, index_backup):
if path.exists():
raise ValueError(f'An append artifact already exists; inspect before retrying: {path}')
old = json.loads((release / 'release_manifest.json').read_text())
quality = json.loads((release / 'audit/quality_report.json').read_text())
difficulty = json.loads((release / 'audit/difficulty_report.json').read_text())
if source in old['configs'] or (release / 'data' / source).exists():
raise ValueError('Source already belongs to this release; perform a full rebuild')
if quality.get('status') != 'passed' or difficulty.get('status') != 'passed' or quality['counts'] != old['counts']:
raise ValueError('A complete audited and difficulty-screened release is required')
if tuple(quality['sources']) != tuple(s for s in assembly.SOURCE_NAMES if s != source) or assembly.SOURCE_NAMES[-1] != source:
raise ValueError('Source must extend the existing ordered registry; perform a full rebuild')
verify_release(release, old)
prior_manifest_digest = assembly.digest(release / 'release_manifest.json')
prior_index_digest = assembly.digest(prior_index)
source_manifest, source_audit = load_source(source, audit_path)
db, new_stats, new_counts = assembly.build_index({source: source_manifest}, new_index)
try:
proof = prove_disjoint(db, prior_index, old['counts'], source)
proof.update(source=source, previous_release_manifest_sha256=prior_manifest_digest,
previous_index_sha256=prior_index_digest, source_audit_sha256=assembly.digest(audit_path),
source_manifest_sha256=assembly.digest(STAGING / source / 'manifest.json'))
def clone_file(src, dst):
if Path(src).suffix == '.parquet':
os.link(src, dst)
return dst
return shutil.copy2(src, dst)
shutil.copytree(release, working, copy_function=clone_file)
added = export_source(working, source, source_manifest, db)
if (added['source']['rows'] != new_counts['annotation_records']
or sum(added['counts'].values()) != new_counts['eligible_task_groups']
or added['quarantine']['rows'] != new_stats[source]['quarantined_annotations']):
raise ValueError('New source export counts differ from its index')
finally:
db.close()
counts = old['counts']
for key, value in new_counts.items():
if key == 'heldout_propagation_rounds':
counts[key] = [a + b for a, b in zip_longest(counts.get(key, []), value, fillvalue=0)]
else:
counts[key] = counts.get(key, 0) + value
tier_counts = {tier: difficulty['difficulty_tiers'].get(tier, 0) + added['counts'][tier] for tier in TIERS}
counts['difficulty_tiers'] = dict(tier_counts)
counts['qwen_core_task_groups'] = tier_counts['core_candidate'] + tier_counts['uncalibrated']
old['configs'][source] = added['source']
add_config(old['configs'], 'quarantine', added['quarantine'])
for tier, config in added['tiers'].items():
add_config(old['configs'], 'tasks', config)
add_config(old['configs'], 'foundational' if tier == 'foundational' else 'qwen_core', config)
now = datetime.now(timezone.utc).isoformat()
difficulty.update(generated_at=now, unique_tasks_screened=counts['eligible_task_groups'],
difficulty_tiers=dict(tier_counts), qwen_core_task_groups=counts['qwen_core_task_groups'])
difficulty['source_counts'][source] = dict(added['counts'])
difficulty['evidence_counts'] = dict(Counter(difficulty['evidence_counts']) + added['evidence'])
difficulty['illustrative_samples'].update(added['samples'])
quality.update(generated_at=now, counts=counts)
quality['sources'].update(new_stats)
quality['task_families'] = dict(Counter(quality['task_families']) + added['families'])
quality['task_leaves'] = dict(Counter(quality['task_leaves']) + added['leaves'])
quality['difficulty_screen'] = {k: difficulty[k] for k in ('target_model', 'difficulty_tiers', 'qwen_core_task_groups', 'empirical_difficulty_measured')}
quality['checks'].extend(['incremental_source_disjoint_task_prompt_lineage_proof', 'prior_parquet_shards_preserved'])
proof.update(generated_at=now, new_source_counts=new_counts, difficulty_tiers=dict(added['counts']),
full_source_annotations_preserved=True, empirical_difficulty_measured=False)
dump(working / 'audit' / f'append_{source}_report.json', proof)
dump(working / 'audit/quality_report.json', quality)
dump(working / 'audit/difficulty_report.json', difficulty)
source_difficulty_path = working / 'audit/audit_difficulty_sources.json'
if source_difficulty_path.exists():
source_difficulty = json.loads(source_difficulty_path.read_text())
source_difficulty['sources'][source] = added['annotation_difficulty']
dump(source_difficulty_path, source_difficulty)
update_documents(working, source, source_manifest, audit_path, quality, difficulty, old)
merge_index(prior_index, new_index, combined, source, counts)
final_files = {name: {'bytes': p.stat().st_size, 'sha256': assembly.digest(p)}
for name, p in sorted(inventory(working).items()) if name != 'release_manifest.json'}
for name, entry in old['files'].items():
if name.endswith('.parquet') and final_files.get(name) != entry:
raise ValueError(f'Prior parquet shard changed during append: {name}')
if assembly.digest(prior_index) != prior_index_digest or assembly.digest(release / 'release_manifest.json') != prior_manifest_digest:
raise ValueError('Original release or index changed concurrently; append aborted')
old['files'] = final_files
dump(working / 'release_manifest.json', old)
install_pair(release, working, release_backup, prior_index, combined, index_backup)
print(json.dumps({'status': 'passed', 'source': source, 'appended_source_counts': new_counts,
'release_counts': counts, 'prior_parquet_shards_unchanged': True}, indent=2), flush=True)
return proof
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--source', required=True)
parser.add_argument('--release', type=Path, default=BASE / 'release')
parser.add_argument('--index', type=Path)
parser.add_argument('--audit', type=Path)
args = parser.parse_args()
append_source(args.source, args.release, args.index, args.audit)
if __name__ == '__main__':
main()
|