From 3e969d1221ec24c66fcfe6fe7b8050d47b6e9088 Mon Sep 17 00:00:00 2001 From: axinion Date: Fri, 4 Dec 2026 09:37:35 -0600 Subject: [PATCH 1/8] feat: add verified safetensors aspect extraction and permission gates --- .env.example | 2 + config.py | 6 +- database.py | 45 +++- docs/evidence/aspect-runtime-smoke.json | 252 +++++++++++++++++++ docs/evidence/source-permissions-status.json | 13 + docs/readiness/next-stage-plan.md | 10 + nlp/aspect_registry.json | 94 +++++++ nlp/aspects.py | 241 ++++++++++++++++++ nlp/sentiment_engine.py | 16 ++ pipeline/contracts.py | 1 + pipeline/permissions.py | 139 ++++++++++ pipeline/runner.py | 47 ++++ pipeline/source_permissions.json | 10 + pyproject.toml | 4 +- reports/report_generator.py | 7 +- reports/templates/weekly.html | 2 +- tests/integration/test_pipeline_api.py | 70 ++++++ tests/unit/test_aspects.py | 59 +++++ tests/unit/test_permissions.py | 65 +++++ 19 files changed, 1076 insertions(+), 7 deletions(-) create mode 100644 docs/evidence/aspect-runtime-smoke.json create mode 100644 docs/evidence/source-permissions-status.json create mode 100644 docs/readiness/next-stage-plan.md create mode 100644 nlp/aspect_registry.json create mode 100644 nlp/aspects.py create mode 100644 pipeline/permissions.py create mode 100644 pipeline/source_permissions.json create mode 100644 tests/unit/test_aspects.py create mode 100644 tests/unit/test_permissions.py diff --git a/.env.example b/.env.example index c5d6834..572ef31 100644 --- a/.env.example +++ b/.env.example @@ -16,7 +16,9 @@ MODEL_ID=cardiffnlp/twitter-roberta-base-sentiment-latest MODEL_REVISION=3216a57f2a0d9c45a2e6c20157c20c49fb4bf9c7 ENABLED_SOURCES= DATA_RIGHTS_CONFIRMED=false +PERMISSIONS_PATH=pipeline/source_permissions.json ALERTS_ENABLED=false +ASPECTS_ENABLED=false FRESHNESS_HOURS=192 LOG_LEVEL=INFO # Only needed for an authorized live NewsAPI run; paid production use is not provisioned. diff --git a/config.py b/config.py index 98428f0..3613ea8 100644 --- a/config.py +++ b/config.py @@ -28,7 +28,9 @@ class Settings(BaseModel): model_revision: str = "3216a57f2a0d9c45a2e6c20157c20c49fb4bf9c7" # pragma: allowlist secret -- public model commit enabled_sources: tuple[str, ...] = () data_rights_confirmed: bool = False + permissions_path: Path = ROOT / "pipeline/source_permissions.json" alerts_enabled: bool = False + aspects_enabled: bool = False freshness_hours: int = Field(default=192, ge=1, le=8760) log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR"] = "INFO" @@ -38,7 +40,7 @@ def valid_timezone(cls, value: str) -> str: ZoneInfo(value) return value - @field_validator("db_path", "output_dir", mode="before") + @field_validator("db_path", "output_dir", "permissions_path", mode="before") @classmethod def absolute_path(cls, value: str | Path) -> Path: p = Path(value).expanduser() @@ -48,6 +50,8 @@ def absolute_path(cls, value: str | Path) -> Path: def compatible(self): if not self.keywords or any(not x.strip() for x in self.keywords): raise ValueError("keywords must be nonempty") + if self.mode == "demo" and self.aspects_enabled: + raise ValueError("keyless demo cannot download real aspect weights; use model smoke") if self.mode == "demo" and (self.enabled_sources or self.alerts_enabled): raise ValueError("demo prohibits external sources and alerts") if self.enabled_sources and not self.data_rights_confirmed: diff --git a/database.py b/database.py index 28ec34f..b5e6ab8 100644 --- a/database.py +++ b/database.py @@ -36,6 +36,17 @@ term TEXT NOT NULL, category TEXT NOT NULL, label TEXT NOT NULL CHECK(label IN ('NEGATIVE','NEUTRAL','POSITIVE')), confidence REAL NOT NULL CHECK(confidence BETWEEN 0 AND 1), PRIMARY KEY(mention_id,model_version,term,category)); +CREATE TABLE IF NOT EXISTS aspect_inference( + mention_id TEXT NOT NULL REFERENCES mentions_v2(id), model_version TEXT NOT NULL, + status TEXT NOT NULL CHECK(status IN ('scored','empty')), payload TEXT NOT NULL, + run_id TEXT NOT NULL REFERENCES runs(id), PRIMARY KEY(mention_id,model_version)); +CREATE TABLE IF NOT EXISTS aspect_spans( + mention_id TEXT NOT NULL, model_version TEXT NOT NULL, start INTEGER NOT NULL CHECK(start>=0), + end INTEGER NOT NULL CHECK(end>start), term TEXT NOT NULL, category TEXT NOT NULL, + label TEXT NOT NULL CHECK(label IN ('NEGATIVE','NEUTRAL','POSITIVE','UNKNOWN','ABSTAIN')), + confidence REAL NOT NULL CHECK(confidence BETWEEN 0 AND 1), payload TEXT NOT NULL, + PRIMARY KEY(mention_id,model_version,start,end), + FOREIGN KEY(mention_id,model_version) REFERENCES aspect_inference(mention_id,model_version) ON DELETE CASCADE); CREATE TABLE IF NOT EXISTS ingestion_events( run_id TEXT NOT NULL REFERENCES runs(id), ordinal INTEGER NOT NULL, source TEXT NOT NULL, status TEXT NOT NULL CHECK(status IN ('accepted','duplicate','rejected')), reason TEXT, reference TEXT, @@ -107,6 +118,7 @@ def store_mention(db, mention: Mention): if old and old[0] != mention.fingerprint: db.execute("DELETE FROM predictions_v2 WHERE mention_id=?", (mention.id,)) db.execute("DELETE FROM aspects_v2 WHERE mention_id=?", (mention.id,)) + db.execute("DELETE FROM aspect_inference WHERE mention_id=?", (mention.id,)) return "duplicate" if old and old[0] == mention.fingerprint else "accepted" @@ -127,8 +139,39 @@ def store_predictions(db, predictions, fingerprints, run_id, aspects=()): "DELETE FROM aspects_v2 WHERE mention_id=? AND model_version=?", (p.mention_id, p.model_version), ) + db.execute( + "DELETE FROM aspect_inference WHERE mention_id=? AND model_version=?", + (p.mention_id, p.model_version), + ) for a in aspects: - db.execute("INSERT INTO aspects_v2 VALUES(?,?,?,?,?,?)", a) + if isinstance(a, dict): + db.execute( + "INSERT INTO aspect_inference VALUES(?,?,?,?,?)", + ( + a["mention_id"], + a["model_version"], + "scored" if a["spans"] else "empty", + json.dumps(a, allow_nan=False), + run_id, + ), + ) + for span in a["spans"]: + db.execute( + "INSERT INTO aspect_spans VALUES(?,?,?,?,?,?,?,?,?)", + ( + a["mention_id"], + a["model_version"], + span["start"], + span["end"], + span["term"], + span["category"], + span["label"], + span["confidence"], + json.dumps(span, allow_nan=False), + ), + ) + else: + db.execute("INSERT INTO aspects_v2 VALUES(?,?,?,?,?,?)", a) def migrate(path): diff --git a/docs/evidence/aspect-runtime-smoke.json b/docs/evidence/aspect-runtime-smoke.json new file mode 100644 index 0000000..17efd61 --- /dev/null +++ b/docs/evidence/aspect-runtime-smoke.json @@ -0,0 +1,252 @@ +{ + "status": "passed", + "platform": "macOS-27.0.1-arm64-arm-64bit", + "python": "3.11.11", + "torch": "2.15.0", + "device": "cpu", + "threads": 2, + "seconds": 8.94972695800243, + "weights_sha256": "8812932976c1a9f5668689b2675770aa63617a6370e12518b111825b84d0ffde", + "aspect_checkpoint": "yangheng/deberta-v3-base-end2end-absa@23e6d43431a5f96d8a7b7b9721d59bbda30cc63d:sha256=8812932976c1a9f5668689b2675770aa63617a6370e12518b111825b84d0ffde:tokens=256:bio=v1", + "data": "Original synthetic examples and authored fixture; no external source calls or human annotations", + "texts": [ + "The price is high, but the picture quality is excellent. Customer support is slow.", + "The user interface is easy to navigate, but the subscription price is terrible.", + "Caf\u00e9 prices are high. The picture quality is good \ud83d\ude0a." + ], + "results": [ + { + "format": "spans-v1", + "spans": [ + { + "start": 4, + "end": 9, + "term": "price", + "label": "NEUTRAL", + "category": "price", + "confidence": 0.478168249130249, + "reason": null, + "token_probabilities": [ + { + "B-ASP-Unknown": 2.4183094865293242e-05, + "B-ASP-Negative": 0.3433440327644348, + "B-ASP-Neutral": 0.478168249130249, + "B-ASP-Positive": 0.004016834311187267, + "I-ASP-Unknown": 1.3144773220119532e-05, + "I-ASP-Negative": 0.0005010048625990748, + "I-ASP-Neutral": 0.0003617316542658955, + "I-ASP-Positive": 6.458789721364155e-05, + "O": 0.1735062301158905 + } + ] + }, + { + "start": 27, + "end": 42, + "term": "picture quality", + "label": "NEUTRAL", + "category": "quality", + "confidence": 0.6913468241691589, + "reason": null, + "token_probabilities": [ + { + "B-ASP-Unknown": 7.2850871219998226e-06, + "B-ASP-Negative": 0.005060176830738783, + "B-ASP-Neutral": 0.7073110938072205, + "B-ASP-Positive": 0.24670100212097168, + "I-ASP-Unknown": 8.129643902066164e-06, + "I-ASP-Negative": 6.727148138452321e-05, + "I-ASP-Neutral": 0.0005984479794278741, + "I-ASP-Positive": 0.00044850329868495464, + "O": 0.039798006415367126 + }, + { + "B-ASP-Unknown": 7.3189085014746524e-06, + "B-ASP-Negative": 5.7850120356306434e-05, + "B-ASP-Neutral": 0.0009225469548255205, + "B-ASP-Positive": 0.0003867102786898613, + "I-ASP-Unknown": 2.0514293282758445e-05, + "I-ASP-Negative": 0.002463988959789276, + "I-ASP-Neutral": 0.6753825545310974, + "I-ASP-Positive": 0.2832928001880646, + "O": 0.037465643137693405 + } + ] + }, + { + "start": 57, + "end": 73, + "term": "Customer support", + "label": "NEUTRAL", + "category": "support", + "confidence": 0.6491011083126068, + "reason": null, + "token_probabilities": [ + { + "B-ASP-Unknown": 7.836704753572121e-06, + "B-ASP-Negative": 0.19053827226161957, + "B-ASP-Neutral": 0.7071368098258972, + "B-ASP-Positive": 0.008245534263551235, + "I-ASP-Unknown": 5.785790563095361e-06, + "I-ASP-Negative": 0.0003770570328924805, + "I-ASP-Neutral": 0.0004591158649418503, + "I-ASP-Positive": 0.00011032060137949884, + "O": 0.09311924874782562 + }, + { + "B-ASP-Unknown": 1.6358972061425447e-05, + "B-ASP-Negative": 0.0018965008202940226, + "B-ASP-Neutral": 0.0039908080361783504, + "B-ASP-Positive": 0.00014254589041229337, + "I-ASP-Unknown": 2.2313646695693024e-05, + "I-ASP-Negative": 0.32131361961364746, + "I-ASP-Neutral": 0.5910654067993164, + "I-ASP-Positive": 0.0073330095037817955, + "O": 0.07421950995922089 + } + ] + } + ], + "truncated": false, + "model_checkpoint": "yangheng/deberta-v3-base-end2end-absa@23e6d43431a5f96d8a7b7b9721d59bbda30cc63d:sha256=8812932976c1a9f5668689b2675770aa63617a6370e12518b111825b84d0ffde:tokens=256:bio=v1", + "token_count": 19, + "output_id": "151bb8257f213f6ae8ee484850227bb63cf8cbf68af8227f1270a3581c76a98c" + }, + { + "format": "spans-v1", + "spans": [ + { + "start": 4, + "end": 18, + "term": "user interface", + "label": "POSITIVE", + "category": "ux", + "confidence": 0.50560063123703, + "reason": null, + "token_probabilities": [ + { + "B-ASP-Unknown": 1.5088094187376555e-05, + "B-ASP-Negative": 0.0039153555408120155, + "B-ASP-Neutral": 0.30895447731018066, + "B-ASP-Positive": 0.5536561608314514, + "I-ASP-Unknown": 7.736553925496992e-06, + "I-ASP-Negative": 4.683678344008513e-05, + "I-ASP-Neutral": 0.0003446577466093004, + "I-ASP-Positive": 0.0007262051803991199, + "O": 0.13233350217342377 + }, + { + "B-ASP-Unknown": 1.7011869203997776e-05, + "B-ASP-Negative": 0.00020442561071831733, + "B-ASP-Neutral": 0.002549585420638323, + "B-ASP-Positive": 0.001738165388815105, + "I-ASP-Unknown": 4.750778680318035e-05, + "I-ASP-Negative": 0.0041831559501588345, + "I-ASP-Neutral": 0.4163798987865448, + "I-ASP-Positive": 0.45754510164260864, + "O": 0.11733519285917282 + } + ] + }, + { + "start": 48, + "end": 66, + "term": "subscription price", + "label": "NEGATIVE", + "category": "price", + "confidence": 0.44141194224357605, + "reason": null, + "token_probabilities": [ + { + "B-ASP-Unknown": 2.475888868502807e-05, + "B-ASP-Negative": 0.504509449005127, + "B-ASP-Neutral": 0.26735636591911316, + "B-ASP-Positive": 0.007293059956282377, + "I-ASP-Unknown": 2.7430118279880844e-05, + "I-ASP-Negative": 0.006033089943230152, + "I-ASP-Neutral": 0.0025854995474219322, + "I-ASP-Positive": 0.00024766966816969216, + "O": 0.2119225710630417 + }, + { + "B-ASP-Unknown": 0.00016230564506258816, + "B-ASP-Negative": 0.014436359517276287, + "B-ASP-Neutral": 0.008267653174698353, + "B-ASP-Positive": 0.0004294263490010053, + "I-ASP-Unknown": 0.00012536362919490784, + "I-ASP-Negative": 0.37831443548202515, + "I-ASP-Neutral": 0.24703125655651093, + "I-ASP-Positive": 0.005698208697140217, + "O": 0.34553492069244385 + } + ] + } + ], + "truncated": false, + "model_checkpoint": "yangheng/deberta-v3-base-end2end-absa@23e6d43431a5f96d8a7b7b9721d59bbda30cc63d:sha256=8812932976c1a9f5668689b2675770aa63617a6370e12518b111825b84d0ffde:tokens=256:bio=v1", + "token_count": 17, + "output_id": "fe346247d83dfe77c1031680add4c12c71db6ae29a62ba2622902f017e7af591" + }, + { + "format": "spans-v1", + "spans": [ + { + "start": 26, + "end": 41, + "term": "picture quality", + "label": "POSITIVE", + "category": "quality", + "confidence": 0.624382734298706, + "reason": null, + "token_probabilities": [ + { + "B-ASP-Unknown": 5.5219029491127e-06, + "B-ASP-Negative": 0.0010929688578471541, + "B-ASP-Neutral": 0.220868781208992, + "B-ASP-Positive": 0.5939896106719971, + "I-ASP-Unknown": 4.329679995862534e-06, + "I-ASP-Negative": 3.705256312969141e-05, + "I-ASP-Neutral": 0.000519462046213448, + "I-ASP-Positive": 0.0016134820180013776, + "O": 0.1818687468767166 + }, + { + "B-ASP-Unknown": 6.619089162995806e-06, + "B-ASP-Negative": 8.54172685649246e-05, + "B-ASP-Neutral": 0.003076008753851056, + "B-ASP-Positive": 0.002365590538829565, + "I-ASP-Unknown": 1.862865792645607e-05, + "I-ASP-Negative": 0.0009820475243031979, + "I-ASP-Neutral": 0.23677591979503632, + "I-ASP-Positive": 0.654775857925415, + "O": 0.10191385447978973 + } + ] + } + ], + "truncated": false, + "model_checkpoint": "yangheng/deberta-v3-base-end2end-absa@23e6d43431a5f96d8a7b7b9721d59bbda30cc63d:sha256=8812932976c1a9f5668689b2675770aa63617a6370e12518b111825b84d0ffde:tokens=256:bio=v1", + "token_count": 14, + "output_id": "dbd53852e06a3dfbb5947a5cd01abe376827f03d75831453f8b33ab72ca1be9c" + } + ], + "idempotent_database_counts": { + "mentions": 12, + "aspect_inference": 12, + "aspect_spans": 12 + }, + "aspect_status": { + "enabled": true, + "extractor_version": "yangheng/deberta-v3-base-end2end-absa@23e6d43431a5f96d8a7b7b9721d59bbda30cc63d:sha256=8812932976c1a9f5668689b2675770aa63617a6370e12518b111825b84d0ffde:tokens=256:bio=v1", + "independent_quality": "unvalidated_without_human_gold", + "mentions_processed": 12, + "mentions_without_spans": 0, + "truncated_mentions": 0, + "span_counts": { + "NEGATIVE": 5, + "NEUTRAL": 3, + "POSITIVE": 4 + } + }, + "quality_status": "Domain precision/recall/F1 unvalidated; smoke checks runtime, spans, persistence and repeat behavior only" +} diff --git a/docs/evidence/source-permissions-status.json b/docs/evidence/source-permissions-status.json new file mode 100644 index 0000000..557fafd --- /dev/null +++ b/docs/evidence/source-permissions-status.json @@ -0,0 +1,13 @@ +{ + "schema_version": 1, + "policy_sha256": "417f4dc52f94cc79dd6ef67a23ae12893d650a09aa5a92ea9d562abfe7986bab", + "source_status": { + "news": "pending", + "reddit": "pending", + "google_play": "pending", + "app_store": "pending", + "approved_export": "pending" + }, + "approved_sources": 0, + "note": "A valid file records owner evidence; it does not establish or grant legal rights." +} diff --git a/docs/readiness/next-stage-plan.md b/docs/readiness/next-stage-plan.md new file mode 100644 index 0000000..4984ad0 --- /dev/null +++ b/docs/readiness/next-stage-plan.md @@ -0,0 +1,10 @@ +# Next readiness stage — December 4, 2026 + +Owner decisions: keep code license undecided; no approved source access exists. Prepare a permissions checklist. No live collection, public deployment, merge or release is authorized. + +1. Integrate a hash-verified safetensors joint aspect extractor behind an explicit worker flag; preserve raw spans, unknowns and truncation; validate with synthetic tests and actual CPU smoke. +2. Extend prediction-blind annotation tooling to two independent annotation sets, validated adjudication, agreement and frozen accepted gold. Do not create human labels. +3. Supply development-only threshold/calibration selection and regression artifacts without re-tuning previously inspected test sets. +4. Run the Linux real-model workflow on the review branch, prepare and verify an aggregate-only deployment bundle and manual release commands; document the remaining owner-only gates. + +Keep source providers disabled until permission evidence is supplied. Commit and push incremental changes to the existing upgrade branch, following the user's standing push authorization. All runtime quality results must be labeled synthetic, weak or human according to their actual provenance. diff --git a/nlp/aspect_registry.json b/nlp/aspect_registry.json new file mode 100644 index 0000000..7bbc1c4 --- /dev/null +++ b/nlp/aspect_registry.json @@ -0,0 +1,94 @@ +{ + "model_id": "yangheng/deberta-v3-base-end2end-absa", + "revision": "23e6d43431a5f96d8a7b7b9721d59bbda30cc63d", + "license": "mit", + "task": "token-classification", + "files": { + "README.md": { + "size": 3778, + "blobId": "42d8f9bab8f4017a6c7280aada28b8822991ba3a" + }, + "config.json": { + "size": 1399, + "blobId": "e76fb768cbb23fe3ba5be9eaee08fd5539f98a3a" + }, + "model.safetensors": { + "size": 735378268, + "blobId": "653ada92b679ffac2405944d8421eaa7655331cf", + "lfs": { + "sha256": "8812932976c1a9f5668689b2675770aa63617a6370e12518b111825b84d0ffde", + "size": 735378268, + "pointerSize": 134 + } + }, + "tokenizer.json": { + "size": 8656722, + "blobId": "c108d5770d0608c1a196f739715bfd5932651af0" + }, + "tokenizer_config.json": { + "size": 1374, + "blobId": "5812b5982eb4581efd360e7f5975d21c1d4c043a" + } + }, + "config": { + "_num_labels": 3, + "architectures": [ + "DebertaV2ForTokenClassification" + ], + "attention_probs_dropout_prob": 0.1, + "hidden_act": "gelu", + "hidden_dropout_prob": 0.1, + "hidden_size": 768, + "id2label": { + "0": "B-ASP-Unknown", + "1": "B-ASP-Negative", + "2": "B-ASP-Neutral", + "3": "B-ASP-Positive", + "4": "I-ASP-Unknown", + "5": "I-ASP-Negative", + "6": "I-ASP-Neutral", + "7": "I-ASP-Positive", + "8": "O" + }, + "initializer_range": 0.02, + "intermediate_size": 3072, + "label2id": { + "B-ASP-Unknown": 0, + "B-ASP-Negative": 1, + "B-ASP-Neutral": 2, + "B-ASP-Positive": 3, + "I-ASP-Unknown": 4, + "I-ASP-Negative": 5, + "I-ASP-Neutral": 6, + "I-ASP-Positive": 7, + "O": 8 + }, + "layer_norm_eps": 1e-07, + "legacy": true, + "max_position_embeddings": 512, + "max_relative_positions": -1, + "model_type": "deberta-v2", + "norm_rel_ebd": "layer_norm", + "num_attention_heads": 12, + "num_hidden_layers": 12, + "pad_token_id": 0, + "pooler_dropout": 0, + "pooler_hidden_act": "gelu", + "pooler_hidden_size": 768, + "pos_att_type": [ + "p2c", + "c2p" + ], + "position_biased_input": false, + "position_buckets": 256, + "relative_attention": true, + "share_att_key": true, + "torch_dtype": "float32", + "transformers_version": "4.55.0", + "type_vocab_size": 0, + "vocab_size": 128100 + }, + "model_card_sha256": "d3d3399c4a69f49824b5a468563e743f98bd2e582e3379e1a1ba50d277064e59", + "model_card_url": "https://huggingface.co/yangheng/deberta-v3-base-end2end-absa/blob/23e6d43431a5f96d8a7b7b9721d59bbda30cc63d/README.md", + "selection": "Joint token classification with character spans and polarity; no pickle or remote model code required; domain quality unvalidated" +} diff --git a/nlp/aspects.py b/nlp/aspects.py new file mode 100644 index 0000000..1920f07 --- /dev/null +++ b/nlp/aspects.py @@ -0,0 +1,241 @@ +"""Pinned safetensors-only joint aspect span/polarity extraction; no remote code.""" + +import hashlib +import json +import math +import re +from functools import lru_cache +from pathlib import Path + +from pydantic import BaseModel, ConfigDict, Field, model_validator + +from nlp.taxonomy import map_to_taxonomy +from pipeline.contracts import stable_id + +REGISTRY = Path(__file__).with_name("aspect_registry.json") +SENTIMENTS = {"NEGATIVE", "NEUTRAL", "POSITIVE", "UNKNOWN"} + + +class AspectSpan(BaseModel): + model_config = ConfigDict(extra="forbid") + start: int = Field(ge=0) + end: int = Field(gt=0) + term: str = Field(min_length=1) + label: str + category: str + confidence: float = Field(ge=0, le=1) + reason: str | None = None + token_probabilities: list[dict[str, float]] = Field(default_factory=list) + + @model_validator(mode="after") + def valid(self): + if ( + self.end <= self.start + or not math.isfinite(self.confidence) + or self.label not in SENTIMENTS | {"ABSTAIN"} + ): + raise ValueError("invalid aspect span") + if self.label in {"UNKNOWN", "ABSTAIN"} and not self.reason: + raise ValueError("aspect reason required") + for probabilities in self.token_probabilities: + if ( + any(not math.isfinite(p) or not 0 <= p <= 1 for p in probabilities.values()) + or abs(sum(probabilities.values()) - 1) > 1e-5 + ): + raise ValueError("invalid token probabilities") + return self + + +def decode_spans(text, offsets, labels, probabilities, truncated=False): + """Strict BIO boundaries, original normalized-text offsets, no unknown→neutral mapping.""" + if not len(offsets) == len(labels) == len(probabilities): + raise ValueError("token output cardinality mismatch") + spans = [] + active = [] + previous_end = 0 + + def flush(): + if not active: + return + start = active[0][0] + end = active[-1][1] + sentiment = active[0][2] + while start < end and text[start].isspace(): + start += 1 + while end > start and text[end - 1].isspace(): + end -= 1 + if start == end: + active.clear() + return + term = text[start:end] + scores = [p[label] for _, _, _, label, p in active] + reason = "model_unknown_polarity" if sentiment == "UNKNOWN" else None + spans.append( + AspectSpan( + start=start, + end=end, + term=term, + label=sentiment, + category=map_to_taxonomy(term), + confidence=sum(scores) / len(scores), + reason=reason, + token_probabilities=[p for *_, p in active], + ).model_dump() + ) + active.clear() + + for (start, end), label, p in zip(offsets, labels, probabilities, strict=True): + if start == end == 0: + flush() + continue + if not 0 <= start < end <= len(text) or start < previous_end: + raise ValueError("invalid token offsets") + previous_end = end + if ( + label not in p + or any(not math.isfinite(value) or not 0 <= value <= 1 for value in p.values()) + or abs(sum(p.values()) - 1) > 1e-5 + ): + raise ValueError("invalid token probabilities") + if label == "O": + flush() + continue + match = re.fullmatch(r"([BI])-ASP-(Negative|Neutral|Positive|Unknown)", label) + if not match: + raise ValueError("unexpected aspect label schema") + prefix, sentiment = match[1], match[2].upper() + if ( + label not in p + or any(not math.isfinite(v) or not 0 <= v <= 1 for v in p.values()) + or abs(sum(p.values()) - 1) > 1e-5 + ): + raise ValueError("invalid token probabilities") + if ( + prefix == "B" + or active + and (active[0][2] != sentiment or text[active[-1][1] : start].strip()) + ): + flush() + # An orphan I begins a span deterministically; the transition policy is deterministic. + active.append((start, end, sentiment, label, p)) + flush() + if truncated and spans: + last_end = max((end for start, end in offsets if end > start), default=0) + if spans[-1]["end"] == last_end: + spans[-1]["label"] = "ABSTAIN" + spans[-1]["reason"] = "span_touches_truncation_boundary" + return spans + + +class SafeAspectExtractor: + def __init__(self, device="cpu", max_tokens=256): + if not 8 <= max_tokens <= 512: + raise ValueError("invalid aspect token limit") + import torch + from huggingface_hub import hf_hub_download + from transformers import AutoModelForTokenClassification, AutoTokenizer + + meta = json.loads(REGISTRY.read_text()) + revision = meta["revision"] + if not re.fullmatch("[a-f0-9]{40}", revision) or meta["license"] != "mit": + raise ValueError("unapproved aspect registry") + if device not in {"cpu", "cuda", "mps"}: + raise ValueError("invalid device") + if ( + device == "cuda" + and not torch.cuda.is_available() + or device == "mps" + and not torch.backends.mps.is_available() + ): + raise RuntimeError("requested aspect device unavailable") + path = hf_hub_download(meta["model_id"], "model.safetensors", revision=revision) + digest = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1024 * 1024), b""): + digest.update(block) + expected = meta["files"]["model.safetensors"]["lfs"]["sha256"] + if digest.hexdigest() != expected: + raise ValueError("aspect weight checksum mismatch") + self.tokenizer = AutoTokenizer.from_pretrained( + meta["model_id"], revision=revision, trust_remote_code=False, use_fast=True + ) + if not self.tokenizer.is_fast: + raise ValueError("offset-capable fast tokenizer required") + self.model, info = AutoModelForTokenClassification.from_pretrained( + meta["model_id"], + revision=revision, + trust_remote_code=False, + use_safetensors=True, + weights_only=True, + output_loading_info=True, + ) + if info.get("missing_keys") or info.get("mismatched_keys"): + raise ValueError("incomplete aspect checkpoint") + self.model = self.model.to(device).eval() + self.device = device + self.max_tokens = max_tokens + self.labels = [self.model.config.id2label[i] for i in range(self.model.config.num_labels)] + allowed = {"O"} | { + f"{prefix}-ASP-{sentiment}" + for prefix in ("B", "I") + for sentiment in ("Negative", "Neutral", "Positive", "Unknown") + } + if set(self.labels) != allowed: + raise ValueError("unexpected aspect model labels") + self.version = f"{meta['model_id']}@{revision}:sha256={expected}:tokens={max_tokens}:bio=v1" + self.weights_sha256 = expected + + def __call__(self, texts): + import torch + + if not texts: + return [] + encoded = self.tokenizer( + texts, + padding=True, + truncation=True, + max_length=self.max_tokens, + return_offsets_mapping=True, + return_special_tokens_mask=True, + return_tensors="pt", + ) + offsets = encoded.pop("offset_mapping").tolist() + special = encoded.pop("special_tokens_mask").tolist() + lengths = [len(self.tokenizer.encode(text, truncation=False)) for text in texts] + with torch.inference_mode(): + scores = ( + self.model(**{k: v.to(self.device) for k, v in encoded.items()}) + .logits.softmax(-1) + .cpu() + .tolist() + ) + if len(scores) != len(texts): + raise ValueError("aspect batch cardinality mismatch") + output = [] + for text, off, mask, values, length in zip( + texts, offsets, special, scores, lengths, strict=True + ): + tokens = [{self.labels[i]: float(v) for i, v in enumerate(prob)} for prob in values] + labels = [max(p, key=p.get) for p in tokens] + off = [ + (0, 0) if hidden else tuple(position) + for hidden, position in zip(mask, off, strict=True) + ] + truncated = length > self.max_tokens + spans = decode_spans(text, off, labels, tokens, truncated) + output.append( + { + "format": "spans-v1", + "spans": spans, + "truncated": truncated, + "model_checkpoint": self.version, + "token_count": length, + "output_id": stable_id(text), + } + ) + return output + + +@lru_cache(maxsize=1) +def get_extractor(device="cpu", max_tokens=256): + return SafeAspectExtractor(device, max_tokens) diff --git a/nlp/sentiment_engine.py b/nlp/sentiment_engine.py index 463a8e5..0465136 100644 --- a/nlp/sentiment_engine.py +++ b/nlp/sentiment_engine.py @@ -119,6 +119,22 @@ def get_classifier(model_id, revision, device="cpu", max_tokens=256): def validate_aspects(row, result, version): + if result.get("format") == "spans-v1": + from nlp.aspects import AspectSpan + + if result.get("output_id") != stable_id(row["normalized_text"]): + raise ValueError("aspect output order mismatch") + spans = [] + seen = set() + for raw in result["spans"]: + span = AspectSpan.model_validate(raw) + if row["normalized_text"][span.start : span.end] != span.term: + raise ValueError("aspect span text mismatch") + if (span.start, span.end) in seen: + raise ValueError("duplicate aspect offsets") + seen.add((span.start, span.end)) + spans.append(span.model_dump()) + return [dict(result, mention_id=row["id"], model_version=version, spans=spans)] terms, labels, confs = (result.get(k, []) for k in ("aspect", "sentiment", "confidence")) if not len(terms) == len(labels) == len(confs): raise ValueError("aspect_batch_cardinality") diff --git a/pipeline/contracts.py b/pipeline/contracts.py index 9980ee6..46f915f 100644 --- a/pipeline/contracts.py +++ b/pipeline/contracts.py @@ -213,6 +213,7 @@ class ReportSummary(BaseModel): evidence_ids: list[str] = Field(default_factory=list) daily: list[dict] = Field(default_factory=list) aspects: dict = Field(default_factory=dict) + aspect_status: dict = Field(default_factory=dict) alerts: list[dict] = Field(default_factory=list) monitoring: dict = Field(default_factory=dict) narrative_mode: str = "deterministic" diff --git a/pipeline/permissions.py b/pipeline/permissions.py new file mode 100644 index 0000000..ac50c70 --- /dev/null +++ b/pipeline/permissions.py @@ -0,0 +1,139 @@ +"""Validate recorded owner permissions; this records attestations, not legal approval.""" + +import hashlib +import json +from datetime import datetime, timezone +from pathlib import Path +from typing import Literal + +from pydantic import BaseModel, ConfigDict, Field, model_validator + +from pipeline.contracts import utc + +USES = {"collect", "infer", "annotate", "publish_aggregates"} + + +class SourcePermission(BaseModel): + model_config = ConfigDict(extra="forbid") + source: Literal["news", "reddit", "google_play", "app_store", "approved_export"] + status: Literal["pending", "approved", "denied"] = "pending" + access_method: str + terms_url: str + allowed_uses: set[Literal["collect", "infer", "annotate", "publish_aggregates"]] = Field( + default_factory=set + ) + reviewed_by: str | None = None + reviewed_at: str | None = None + expires_at: str | None = None + evidence_reference: str | None = None + retention_days: int | None = Field(default=None, ge=1, le=3650) + dataset_sha256: str | None = None + notes: str = "" + + @model_validator(mode="after") + def approved_evidence(self): + if not self.terms_url.startswith("https://"): + raise ValueError("HTTPS terms reference required") + if self.status == "approved": + if not all( + [ + self.reviewed_by, + self.reviewed_at, + self.expires_at, + self.evidence_reference, + self.retention_days, + self.allowed_uses, + ] + ): + raise ValueError("approval evidence is incomplete") + if datetime.fromisoformat(utc(self.expires_at)) <= datetime.fromisoformat( + utc(self.reviewed_at) + ): + raise ValueError("invalid approval interval") + if self.source == "approved_export" and ( + self.dataset_sha256 is None + or len(self.dataset_sha256) != 64 + or any(c not in "0123456789abcdef" for c in self.dataset_sha256) + ): + raise ValueError("approved export requires exact dataset SHA-256") + return self + + +def permission(path, source, uses, dataset_path=None, now=None): + now = now or datetime.now(timezone.utc) + raw = Path(path).read_bytes() + data = json.loads(raw) + if data.get("schema_version") != 1: + raise ValueError("unsupported permissions schema") + entries = [SourcePermission.model_validate(p) for p in data["sources"]] + if len({p.source for p in entries}) != len(entries): + raise ValueError("duplicate source permission") + selected = next((p for p in entries if p.source == source), None) + if not selected or selected.status != "approved": + raise PermissionError(f"{source}: permission pending or denied") + if not set(uses) <= selected.allowed_uses: + raise PermissionError(f"{source}: requested use not approved") + if ( + not datetime.fromisoformat(utc(selected.reviewed_at)) + <= now + < datetime.fromisoformat(utc(selected.expires_at)) + ): + raise PermissionError(f"{source}: approval expired or not yet active") + if selected.dataset_sha256: + if ( + dataset_path is None + or hashlib.sha256(Path(dataset_path).read_bytes()).hexdigest() + != selected.dataset_sha256 + ): + raise PermissionError("dataset does not match approved content hash") + return { + "source": source, + "uses": sorted(uses), + "policy_sha256": hashlib.sha256(raw).hexdigest(), + "retention_days": selected.retention_days, + } + + +def enforce_live_permissions(settings, input_path=None): + if not settings.data_rights_confirmed: + raise PermissionError( + "live processing requires explicit owner confirmation and a valid permission record" + ) + sources = ["approved_export"] if input_path else list(settings.enabled_sources) + if not sources: + raise PermissionError("no approved input source selected") + return [ + permission( + settings.permissions_path, + source, + {"infer"} if input_path else {"collect", "infer"}, + input_path, + ) + for source in sources + ] + + +def audit(path): + raw = Path(path).read_bytes() + data = json.loads(raw) + if data.get("schema_version") != 1: + raise ValueError("unsupported permissions schema") + entries = [SourcePermission.model_validate(p) for p in data["sources"]] + if len({p.source for p in entries}) != len(entries): + raise ValueError("duplicate source permission") + return { + "schema_version": 1, + "policy_sha256": hashlib.sha256(raw).hexdigest(), + "source_status": {p.source: p.status for p in entries}, + "approved_sources": sum(p.status == "approved" for p in entries), + "note": "A valid file records owner evidence; it does not establish or grant legal rights.", + } + + +if __name__ == "__main__": + import argparse + + p = argparse.ArgumentParser() + p.add_argument("--manifest", default=str(Path(__file__).with_name("source_permissions.json"))) + a = p.parse_args() + print(json.dumps(audit(a.manifest), indent=2)) diff --git a/pipeline/runner.py b/pipeline/runner.py index 23e05a1..da2c6fe 100644 --- a/pipeline/runner.py +++ b/pipeline/runner.py @@ -16,6 +16,7 @@ import database from nlp.sentiment_engine import DemoClassifier, get_classifier, infer_mentions, inference_version from pipeline.contracts import Mention, now_utc, stable_id, utc +from pipeline.permissions import enforce_live_permissions from reports.render_template import render_summary from reports.report_generator import build_summary @@ -110,6 +111,9 @@ def run( code_version(), ), ) + permission_evidence = ( + enforce_live_permissions(settings, input_path) if settings.mode == "live" else [] + ) # Model initialization happens before holding a write transaction. backend = classifier or ( DemoClassifier() @@ -118,6 +122,10 @@ def run( settings.model_id, settings.model_revision, settings.device, settings.max_tokens ) ) + if extractor is None and settings.aspects_enabled: + from nlp.aspects import get_extractor + + extractor = get_extractor(settings.device, settings.max_tokens) version = inference_version(backend, settings.threshold, extractor) if settings.mode == "live" and isinstance(backend, DemoClassifier): raise ValueError("synthetic model prohibited in live mode") @@ -251,6 +259,44 @@ def run( stage_start = time.perf_counter() summary = build_summary(db, settings, run_id, version, as_of, source_status) summary.model_checkpoint = backend.version + summary.aspect_status = { + "enabled": extractor is not None, + "extractor_version": getattr(extractor, "version", None), + "independent_quality": "unvalidated_without_human_gold", + } + if extractor is not None: + summary.aspect_status.update( + dict( + db.execute( + "SELECT COUNT(*) mentions_processed,SUM(status='empty') mentions_without_spans,SUM(json_extract(payload,'$.truncated')) truncated_mentions FROM aspect_inference a JOIN mentions_v2 m ON m.id=a.mention_id WHERE a.model_version=? AND m.brand=? AND m.synthetic=? AND m.timestamp>=? AND m.timestamp=? AND m.timestamp=? AND m.timestamp=? AND m.timestamp
Eligible mentions
{{ s.current.eligible }}
Scored coverage
{{ '%.1f%%'|format(s.current.coverage*100) if s.current.coverage is not none else 'Unavailable' }}
Heuristic health index
{{ '%.2f'|format(s.current.health_index) if s.current.health_index is not none else 'Unavailable' }}
Previous-period change
{{ '%+.2f'|format(s.health_change) if s.health_change is not none else 'Unavailable' }}

Overall sentiment counts

{% for label,n in s.current.counts.items() %}{% endfor %}
Semantic labelCountShare of scored mentions
{{ label }}{{ n }}{{ '%.1f%%'|format(n/s.current.scored*100) if s.current.scored else 'Unavailable' }}

Abstentions: {{ s.current.abstained }} · Failures: {{ s.current.failed }} · Missing: {{ s.current.missing }}

Deterministic analysis

{{ narrative }}

Source freshness

{% for source,detail in s.source_status.items() %}{% endfor %}
SourceStatusLatest publication UTC
{{ source }}{{ detail.status }}{{ s.freshness.get(source) or 'Unavailable' }}
-

Daily observations

{% for day in s.daily %}{% endfor %}
Date UTCScored mentionsHeuristic index
{{ day.date }}{{ day.count }}{{ '%.2f'|format(day.health_index) if day.health_index is not none else 'Unavailable' }}

Dates without observations remain gaps; no neutral observations are imputed.

Exploratory alerts

{% for alert in s.alerts %}

{{ alert.date }} · {{ alert.aspect }} · {{ alert.type }} · {{ alert.severity }}

{% else %}

No rule-triggered alerts in this window. This does not establish the absence of business risk.

{% endfor %}

Provenance and limitations

Previous window: {{ s.previous_start }} ≤ time < {{ s.period_start }}; {{ s.previous.eligible }} eligible mentions.

Run {{ s.run_id }}
Checkpoint {{ s.model_checkpoint or 'Unavailable' }}
Model/config version {{ s.model_version }}
+

Aspect sentiment

{% if s.aspects %}

One contribution per mention/category; multiple terms do not inflate mention totals. Scores use signed labels, not classifier confidence.

{% for category,value in s.aspects.items() %}{% if category != '_composite' %}{% endif %}{% endfor %}
CategoryMentionsMean signed sentiment
{{ category }}{{ value.count }}{{ '%.3f'|format(value.score) }}
{% elif s.aspect_status.get('enabled') %}

No mapped aspect spans in this window.

{% else %}

Aspect extraction is disabled for this run.

{% endif %}

Aspect-model domain precision/recall/F1 has not been independently validated. Unknown polarity and truncation are tracked separately.

Daily observations

{% for day in s.daily %}{% endfor %}
Date UTCScored mentionsHeuristic index
{{ day.date }}{{ day.count }}{{ '%.2f'|format(day.health_index) if day.health_index is not none else 'Unavailable' }}

Dates without observations remain gaps; no neutral observations are imputed.

Exploratory alerts

{% for alert in s.alerts %}

{{ alert.date }} · {{ alert.aspect }} · {{ alert.type }} · {{ alert.severity }}

{% else %}

No rule-triggered alerts in this window. This does not establish the absence of business risk.

{% endfor %}

Provenance and limitations

Previous window: {{ s.previous_start }} ≤ time < {{ s.period_start }}; {{ s.previous.eligible }} eligible mentions.

Run {{ s.run_id }}
Checkpoint {{ s.model_checkpoint or 'Unavailable' }}
Model/config version {{ s.model_version }}
diff --git a/tests/integration/test_pipeline_api.py b/tests/integration/test_pipeline_api.py index efb1fe0..20362cd 100644 --- a/tests/integration/test_pipeline_api.py +++ b/tests/integration/test_pipeline_api.py @@ -276,6 +276,7 @@ def unavailable(*args, **kwargs): raise RuntimeError("test download unavailable") monkeypatch.setattr("pipeline.runner.get_classifier", unavailable) + monkeypatch.setattr("pipeline.runner.enforce_live_permissions", lambda *_: []) with pytest.raises(RuntimeError): run(cfg) with database.connect(cfg.db_path, readonly=True) as db: @@ -305,3 +306,72 @@ def test_aggregate_only_publication(tmp_path): with pytest.raises(ValueError): snapshot(src, tmp_path / "invalid.db") assert not (tmp_path / "invalid.db").exists() + + +def test_repeated_aspect_terms_preserve_polarity_and_offsets(tmp_path): + from pipeline.contracts import stable_id + + cfg = settings(tmp_path) + + class Spans: + version = "span-fixture-v1" + + def __call__(self, texts): + results = [] + for text in texts: + # Identical term text at distinct offsets must retain opposing polarities. + first, second = next( + (i, j) + for i, c in enumerate(text) + for j, d in enumerate(text) + if i < j and c == d and c.isalpha() + ) + other = next( + i for i, c in enumerate(text) if i not in {first, second} and c.isalpha() + ) + spans = [ + dict( + start=first, + end=first + 1, + term=text[first : first + 1], + label="NEGATIVE", + category="price", + confidence=0.9, + ), + dict( + start=second, + end=second + 1, + term=text[second : second + 1], + label="POSITIVE", + category="price", + confidence=0.8, + ), + dict( + start=other, + end=other + 1, + term=text[other : other + 1], + label="UNKNOWN", + category="price", + confidence=0.6, + reason="model_unknown_polarity", + ), + ] + results.append( + dict(format="spans-v1", spans=spans, truncated=False, output_id=stable_id(text)) + ) + return results + + first = run(cfg, extractor=Spans()) + second = run(cfg, extractor=Spans()) + assert first.aspects["price"] == {"count": 12, "score": 0} + assert second.aspect_status["mentions_processed"] == 12 + with database.connect(cfg.db_path, readonly=True) as db: + assert db.execute("select count(*) from aspect_spans").fetchone()[0] == 36 + assert second.aspect_status["span_counts"]["UNKNOWN"] == 12 + assert ( + db.execute( + "SELECT COUNT(*) FROM (SELECT mention_id,term FROM aspect_spans GROUP BY mention_id,term HAVING COUNT(*)=2)" + ).fetchone()[0] + == 12 + ) + assert db.execute("pragma foreign_key_check").fetchall() == [] diff --git a/tests/unit/test_aspects.py b/tests/unit/test_aspects.py new file mode 100644 index 0000000..7597d35 --- /dev/null +++ b/tests/unit/test_aspects.py @@ -0,0 +1,59 @@ +import pytest + +from nlp.aspects import AspectSpan, decode_spans +from nlp.sentiment_engine import validate_aspects +from pipeline.contracts import stable_id + + +def probabilities(label): + return {label: 0.9, "O": 0.1} if label != "O" else {"O": 1.0} + + +def test_joint_bio_offsets_and_unknown(): + text = "price and price are different" + offsets = [(0, 5), (6, 9), (10, 15), (16, 19), (20, 29)] + labels = ["B-ASP-Negative", "O", "B-ASP-Positive", "O", "B-ASP-Unknown"] + spans = decode_spans(text, offsets, labels, [probabilities(label) for label in labels]) + assert [(r["term"], r["label"], r["start"]) for r in spans] == [ + ("price", "NEGATIVE", 0), + ("price", "POSITIVE", 10), + ("different", "UNKNOWN", 20), + ] + assert spans[-1]["reason"] == "model_unknown_polarity" + assert spans[0]["category"] == "price" + result = { + "format": "spans-v1", + "spans": spans, + "truncated": False, + "output_id": stable_id(text), + } + validated = validate_aspects({"id": "1", "normalized_text": text}, result, "test-version") + assert len(validated[0]["spans"]) == 3 + with pytest.raises(ValueError): + validate_aspects({"id": "1", "normalized_text": "wrong"}, result, "test-version") + + +def test_subwords_truncation_and_bad_outputs(): + text = "customer support" + labels = ["B-ASP-Negative", "I-ASP-Negative"] + p = [probabilities(label) for label in labels] + spans = decode_spans(text, [(0, 8), (9, 16)], labels, p, truncated=True) + assert spans[0]["term"] == text and spans[0]["label"] == "ABSTAIN" + assert decode_spans("okay", [(0, 4)], ["O"], [{"O": 1}]) == [] + with pytest.raises(ValueError): + decode_spans(text, [(0, 8)], labels, p) + with pytest.raises(ValueError): + decode_spans(text, [(0, 99)], labels[:1], p[:1]) + with pytest.raises(ValueError): + decode_spans(text, [(0, 8)], ["invalid"], p[:1]) + with pytest.raises(ValueError): + AspectSpan(start=4, end=2, term="x", label="NEUTRAL", category="other", confidence=0.8) + + +def test_offsets_trim_tokenizer_boundary_spaces_without_changing_text(): + spans = decode_spans( + " price is high", [(0, 6)], ["B-ASP-Negative"], [probabilities("B-ASP-Negative")] + ) + assert spans[0]["term"] == "price" and spans[0]["start"] == 1 and spans[0]["end"] == 6 + with pytest.raises(ValueError): + decode_spans("word", [(0, 4)], ["O"], [{"O": 1.5}]) diff --git a/tests/unit/test_permissions.py b/tests/unit/test_permissions.py new file mode 100644 index 0000000..b6e4820 --- /dev/null +++ b/tests/unit/test_permissions.py @@ -0,0 +1,65 @@ +import hashlib +import json +from datetime import datetime, timezone + +import pytest + +from config import Settings +from pipeline.permissions import audit, enforce_live_permissions, permission + + +def test_source_permissions_do_not_self_approve(tmp_path): + p = tmp_path / "rights.json" + entry = dict( + source="news", + status="pending", + access_method="fixture", + terms_url="https://example.com/terms", + allowed_uses=[], + ) + p.write_text(json.dumps(dict(schema_version=1, sources=[entry]))) + assert audit(p)["approved_sources"] == 0 + with pytest.raises(PermissionError): + permission(p, "news", {"infer"}) + entry |= dict( + status="approved", + allowed_uses=["infer"], + reviewed_by="TEST FIXTURE ONLY", + reviewed_at="2026-01-01T00:00:00Z", + expires_at="2027-01-01T00:00:00Z", + evidence_reference="Synthetic test evidence, not a real approval", + retention_days=30, + ) + p.write_text(json.dumps(dict(schema_version=1, sources=[entry]))) + now = datetime(2026, 12, 4, tzinfo=timezone.utc) + assert permission(p, "news", {"infer"}, now=now)["retention_days"] == 30 + with pytest.raises(PermissionError): + permission(p, "news", {"collect"}, now=now) + with pytest.raises(PermissionError): + permission(p, "news", {"infer"}, now=datetime(2028, 1, 1, tzinfo=timezone.utc)) + with pytest.raises(PermissionError): + enforce_live_permissions(Settings(), None) + + +def test_export_approval_binds_exact_file(tmp_path): + content = tmp_path / "input.json" + content.write_text("[]") + entry = dict( + source="approved_export", + status="approved", + access_method="synthetic fixture", + terms_url="https://example.com/test", + allowed_uses=["annotate"], + reviewed_by="TEST ONLY", + reviewed_at="2026-01-01T00:00:00Z", + expires_at="2099-01-01T00:00:00Z", + evidence_reference="test", + retention_days=7, + dataset_sha256=hashlib.sha256(content.read_bytes()).hexdigest(), + ) + path = tmp_path / "rights.json" + path.write_text(json.dumps(dict(schema_version=1, sources=[entry]))) + permission(path, "approved_export", {"annotate"}, content) + content.write_text("[1]") + with pytest.raises(PermissionError): + permission(path, "approved_export", {"annotate"}, content) From 8de863e3967e1df4d0d595418eb465039ef2695e Mon Sep 17 00:00:00 2001 From: axinion Date: Fri, 4 Dec 2026 09:37:35 -0600 Subject: [PATCH 2/8] feat: add blinded annotation, adjudication and dev-only calibration --- evaluation/annotation.py | 4 + evaluation/annotation_workflow.py | 454 ++++++++++++++++++++++++ evaluation/calibration.py | 191 ++++++++++ tests/unit/test_annotation_workflow.py | 122 +++++++ tests/unit/test_calibration_protocol.py | 58 +++ 5 files changed, 829 insertions(+) create mode 100644 evaluation/annotation_workflow.py create mode 100644 evaluation/calibration.py create mode 100644 tests/unit/test_annotation_workflow.py create mode 100644 tests/unit/test_calibration_protocol.py diff --git a/evaluation/annotation.py b/evaluation/annotation.py index bda3060..248e50a 100644 --- a/evaluation/annotation.py +++ b/evaluation/annotation.py @@ -76,8 +76,12 @@ def keys(rows): p.add_argument("--input", required=True, type=Path) p.add_argument("--output", required=True, type=Path) p.add_argument("--per-source", type=int, default=100) + p.add_argument("--permissions", required=True) a = p.parse_args() if a.per_source < 1: raise SystemExit("per-source must be positive") + from pipeline.permissions import permission + + permission(a.permissions, "approved_export", {"annotate"}, a.input) data = json.loads(a.input.read_text()) print(export_annotations(data["records"], a.output, a.per_source)) diff --git a/evaluation/annotation_workflow.py b/evaluation/annotation_workflow.py new file mode 100644 index 0000000..a05daca --- /dev/null +++ b/evaluation/annotation_workflow.py @@ -0,0 +1,454 @@ +"""Prediction-blind two-annotator packets, disagreement review and frozen consensus gold.""" + +import csv +import hashlib +import json +import random +from collections import Counter +from pathlib import Path + +from nlp.taxonomy import TAXONOMY +from pipeline.contracts import LABELS, stable_id +from pipeline.permissions import permission +from scrapers.normalizer import clean_text + +FIELDS = [ + "id", + "source", + "language", + "text", + "overall_label", + "ambiguous", + "aspect_spans_json", + "error_slices_json", + "annotator", + "notes", +] + + +def csv_text(text): + return "'" + text if text.lstrip().startswith(("=", "+", "-", "@")) else text + + +def _write_csv(path, rows, fields=FIELDS): + with Path(path).open("x", newline="", encoding="utf-8") as f: + writer = csv.DictWriter(f, fieldnames=fields) + writer.writeheader() + writer.writerows(rows) + + +def create_packet( + dataset, output, permissions_path=None, per_source=100, seed=42, synthetic_demo=False +): + if not 1 <= per_source <= 1000: + raise ValueError("per-source outside [1,1000]") + raw = Path(dataset).read_bytes() + data = json.loads(raw) + records = data["records"] + if synthetic_demo: + if not records or any(r.get("synthetic") is not True for r in records): + raise ValueError("synthetic demo requires exclusively explicit synthetic records") + rights = {"mode": "synthetic_demo", "human_gold": False} + else: + if permissions_path is None: + raise PermissionError("owner-approved dataset permissions file required") + rights = permission(permissions_path, "approved_export", {"annotate"}, dataset) + if any(r.get("synthetic") for r in records): + raise ValueError("synthetic records excluded from human gold packets") + groups = {} + seen = set() + native_seen = set() + for row in records: + if ( + not isinstance(row.get("text"), str) + or not row["text"].strip() + or not row.get("id") + or not row.get("source") + ): + raise ValueError("invalid annotation input") + text = clean_text(row["text"]) + if ( + not text + or row["source"] + not in { + "news", + "reddit", + "app_review", + "google_play", + "app_store", + "fixture", + "approved_export", + } + or row.get("language", "unknown") != "en" + ): + raise ValueError("unsupported source/language or empty annotation text") + native = stable_id(row["source"], row["id"]) + if native in native_seen: + raise ValueError("duplicate native item in annotation input") + native_seen.add(native) + identity = stable_id(row["id"], row["source"], text) + if identity in seen: + raise ValueError("duplicate annotation input identity") + seen.add(identity) + # Predictions, confidence, ratings and historic labels never enter the frozen packet. + record = { + "id": identity, + "native_id": stable_id(row["source"], row["id"]), + "source": row["source"], + "language": row.get("language", "unknown"), + "text": text, + "cluster_id": stable_id(text.casefold()), + "synthetic": synthetic_demo, + } + if row.get("timestamp"): + record["timestamp"] = row["timestamp"] + groups.setdefault(record["source"], []).append(record) + rng = random.Random(seed) + selected = [] + for source in sorted(groups): + choices = sorted(groups[source], key=lambda r: r["id"]) + selected.extend(rng.sample(choices, min(per_source, len(choices)))) + selected.sort(key=lambda r: r["id"]) + clusters = sorted({r["cluster_id"] for r in selected}, key=lambda key: stable_id(seed, key)) + if len(clusters) < 5: + raise ValueError("at least five independent clusters required") + splits = { + key: "train" + if i < int(0.6 * len(clusters)) + else "dev" + if i < int(0.8 * len(clusters)) + else "test" + for i, key in enumerate(clusters) + } + for record in selected: + record["split"] = splits[record["cluster_id"]] + out = Path(output) + if out.exists(): + raise FileExistsError("packet destination already exists") + out.mkdir(parents=True) + frozen = {"schema_version": 1, "synthetic": synthetic_demo, "records": selected} + payload = json.dumps(frozen, ensure_ascii=False, indent=2) + "\n" + (out / "frozen-input.json").write_text(payload) + rows = [ + {key: value for key, value in r.items() if key in FIELDS} | {"text": csv_text(r["text"])} + for r in selected + ] + for name in ("annotator-a.csv", "annotator-b.csv"): + _write_csv(out / name, rows) + manifest = { + "schema_version": 1, + "seed": seed, + "source_dataset_sha256": hashlib.sha256(raw).hexdigest(), + "frozen_sha256": hashlib.sha256(payload.encode()).hexdigest(), + "selected": len(selected), + "by_source": dict(Counter(r["source"] for r in selected)), + "rights": rights, + "synthetic": synthetic_demo, + "status": "awaiting_independent_human_annotations" + if not synthetic_demo + else "synthetic_engineering_demo_only", + "split_protocol": "hash-ranked exact normalized-text clusters, 60/20/20; no model tuning on eventual test labels", + } + (out / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") + return manifest + + +def _frozen(packet): + packet = Path(packet) + manifest = json.loads((packet / "manifest.json").read_text()) + raw = (packet / "frozen-input.json").read_bytes() + if hashlib.sha256(raw).hexdigest() != manifest["frozen_sha256"]: + raise ValueError("frozen annotation input changed") + frozen = json.loads(raw) + if frozen["synthetic"] != manifest["synthetic"] or any( + r["synthetic"] != manifest["synthetic"] for r in frozen["records"] + ): + raise ValueError("annotation provenance mismatch") + records = frozen["records"] + return manifest, {r["id"]: r for r in records} + + +def read_annotations(path, records, adjudication=False): + with Path(path).open(newline="", encoding="utf-8-sig") as f: + reader = csv.DictReader(f) + expected_fields = FIELDS + ["decision"] if adjudication else FIELDS + if reader.fieldnames != expected_fields: + raise ValueError("annotation schema changed") + rows = list(reader) + result = {} + for row in rows: + if set(row) != set(expected_fields) or any( + not isinstance(value, str) for value in row.values() + ): + raise ValueError("invalid annotation CSV cells") + identity = row["id"] + if identity not in records or identity in result: + raise ValueError("unknown or duplicate annotation ID") + original = records[identity] + if any( + row[k] != (csv_text(original[k]) if k == "text" else original[k]) + for k in ("source", "language", "text") + ): + raise ValueError("annotation input text or metadata changed") + label = row["overall_label"].strip().upper() + ambiguous = row["ambiguous"].strip().upper() + excluded = adjudication and row.get("decision") == "EXCLUDE" + if adjudication and row.get("decision") not in {"INCLUDE", "EXCLUDE"}: + raise ValueError("adjudication decision must be INCLUDE or EXCLUDE") + if ( + (label not in LABELS and not (excluded and label == "")) + or ambiguous not in {"YES", "NO"} + or not row["annotator"].strip() + ): + raise ValueError("incomplete human annotation") + spans = None + if row["aspect_spans_json"].strip(): + spans = json.loads(row["aspect_spans_json"]) + if not isinstance(spans, list): + raise ValueError("aspect annotations must be a JSON list") + seen = set() + for span in spans: + if ( + set(span) != {"start", "end", "category", "label"} + or type(span["start"]) is not int + or type(span["end"]) is not int + or not 0 <= span["start"] < span["end"] <= len(original["text"]) + or span["category"] not in set(TAXONOMY) | {"other"} + or span["label"] not in LABELS + ): + raise ValueError("invalid gold aspect span") + key = (span["start"], span["end"]) + if key in seen: + raise ValueError("duplicate gold span") + seen.add(key) + spans = sorted(spans, key=lambda s: (s["start"], s["end"])) + slices = None + if row["error_slices_json"].strip(): + slices = json.loads(row["error_slices_json"]) + if not isinstance(slices, list) or any( + s + not in { + "neutral", + "mixed", + "sarcasm", + "negation", + "short", + "long", + "truncated", + "unsupported_language", + "source_shift", + } + for s in slices + ): + raise ValueError("invalid error slice annotations") + slices = sorted(set(slices)) + result[identity] = { + "label": label, + "excluded": excluded, + "slices": slices, + "ambiguous": ambiguous == "YES", + "spans": spans, + "annotator": row["annotator"].strip(), + "notes": row["notes"], + } + if set(result) != set(records): + raise ValueError("missing annotation rows") + return result + + +def agreement(a, b): + pairs = [ + (a[key]["label"], b[key]["label"]) + for key in a + if not a[key]["ambiguous"] and not b[key]["ambiguous"] + ] + n = len(pairs) + observed = sum(x == y for x, y in pairs) / n if n else None + aa = Counter(x for x, y in pairs) + bb = Counter(y for x, y in pairs) + expected = sum(aa[label] * bb[label] for label in LABELS) / (n * n) if n else None + kappa = ( + (observed - expected) / (1 - expected) if expected is not None and expected < 1 else None + ) + return { + "eligible_nonambiguous_pairs": n, + "raw_agreement": observed, + "cohen_kappa": kappa, + "ambiguous_examples": sum(a[k]["ambiguous"] or b[k]["ambiguous"] for k in a), + "note": "Agreement describes supplied annotator records; the tool cannot prove annotator independence or identity.", + } + + +def compare(packet, a_path, b_path, output): + manifest, records = _frozen(packet) + a = read_annotations(a_path, records) + b = read_annotations(b_path, records) + if {r["annotator"] for r in a.values()} & {r["annotator"] for r in b.values()}: + raise ValueError("annotator identities must be independent") + disagreements = [] + for key in records: + if ( + a[key]["label"] != b[key]["label"] + or a[key]["ambiguous"] + or b[key]["ambiguous"] + or a[key]["spans"] != b[key]["spans"] + or a[key]["slices"] != b[key]["slices"] + ): + disagreements.append( + { + "id": key, + "source": records[key]["source"], + "language": records[key]["language"], + "text": csv_text(records[key]["text"]), + "overall_label": "", + "ambiguous": "", + "aspect_spans_json": "", + "annotator": "", + "notes": "", + } + ) + out = Path(output) + if out.exists(): + raise FileExistsError("review destination already exists") + out.mkdir(parents=True) + report = agreement(a, b) | { + "synthetic": manifest["synthetic"], + "disagreements": len(disagreements), + "records": len(records), + "adjudication_required_ids": [r["id"] for r in disagreements], + } + (out / "agreement.json").write_text(json.dumps(report, indent=2) + "\n") + _write_csv(out / "adjudication.csv", disagreements, fields=FIELDS + ["decision"]) + return report + + +def freeze(packet, a_path, b_path, output, adjudication_path=None, seed=None): + manifest, records = _frozen(packet) + a = read_annotations(a_path, records) + b = read_annotations(b_path, records) + if seed is not None and seed != manifest["seed"]: + raise ValueError("split seed was frozen before annotation") + seed = manifest["seed"] + if {r["annotator"] for r in a.values()} & {r["annotator"] for r in b.values()}: + raise ValueError("annotator identities must differ") + conflicts = { + k + for k in records + if a[k]["label"] != b[k]["label"] + or a[k]["ambiguous"] + or b[k]["ambiguous"] + or a[k]["spans"] != b[k]["spans"] + or a[k]["slices"] != b[k]["slices"] + } + decisions = {} + if conflicts: + if adjudication_path is None: + raise ValueError("unresolved disagreements; human adjudication required") + decisions = read_annotations( + adjudication_path, + {k: v for k, v in records.items() if k in conflicts}, + adjudication=True, + ) + if any( + (r["ambiguous"] and not r["excluded"]) or not r["notes"].strip() + for r in decisions.values() + ): + raise ValueError("adjudication requires resolved ambiguity and a rationale") + gold = [] + excluded = [] + for key, r in records.items(): + decision = decisions.get(key, a[key]) + if decision["excluded"]: + excluded.append( + {"id": key, "reason": decision["notes"], "adjudicator": decision["annotator"]} + ) + continue + gold.append( + r + | { + "true_label": decision["label"], + "split": r["split"], + "slices": decision["slices"] or [], + "slice_annotation_complete": decision["slices"] is not None, + "aspect_gold": decision["spans"], + "annotators": [a[key]["annotator"], b[key]["annotator"]], + "adjudicator": decision["annotator"] if key in decisions else None, + "annotation_status": ("synthetic_" if manifest["synthetic"] else "human_") + + ("adjudicated" if key in decisions else "two_annotator_agreement"), + } + ) + from nlp.evaluator import validate_splits + + validate_splits(gold) + data = { + "synthetic": manifest["synthetic"], + "label_source": "synthetic software-test annotations" + if manifest["synthetic"] + else "owner-supplied independent human annotations; identity/rights require owner verification", + "provenance": { + "packet_sha256": manifest["frozen_sha256"], + "agreement": agreement(a, b), + "adjudicated": len(decisions), + "input_examples": len(records), + "excluded_examples": excluded, + "annotation_files_sha256": [ + hashlib.sha256(Path(p).read_bytes()).hexdigest() + for p in [a_path, b_path] + ([adjudication_path] if adjudication_path else []) + ], + "split_seed": seed, + "split_strategy": "hash-ranked exact duplicate clusters; not a temporal generalization study", + }, + "records": gold, + } + path = Path(output) + with path.open("x", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) + f.write("\n") + return { + "records": len(gold), + "synthetic": manifest["synthetic"], + "split_counts": dict(Counter(r["split"] for r in gold)), + "class_counts": dict(Counter(r["true_label"] for r in gold)), + "aspect_gold_complete": all(r["aspect_gold"] is not None for r in gold), + "slice_annotations_complete": all(r["slice_annotation_complete"] for r in gold), + "excluded_examples": len(excluded), + } + + +def main(): + import argparse + + p = argparse.ArgumentParser() + sub = p.add_subparsers(dest="command", required=True) + c = sub.add_parser("create") + c.add_argument("--input", required=True) + c.add_argument("--output", required=True) + c.add_argument("--permissions") + c.add_argument("--per-source", type=int, default=100) + c.add_argument("--synthetic-demo", action="store_true") + for name in ("compare", "freeze"): + c = sub.add_parser(name) + c.add_argument("--packet", required=True) + c.add_argument("--a", required=True) + c.add_argument("--b", required=True) + c.add_argument("--output", required=True) + if name == "freeze": + c.add_argument("--adjudication") + args = p.parse_args() + if args.command == "create": + result = create_packet( + args.input, + args.output, + args.permissions, + args.per_source, + synthetic_demo=args.synthetic_demo, + ) + elif args.command == "compare": + result = compare(args.packet, args.a, args.b, args.output) + else: + result = freeze(args.packet, args.a, args.b, args.output, args.adjudication) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/evaluation/calibration.py b/evaluation/calibration.py new file mode 100644 index 0000000..8375d24 --- /dev/null +++ b/evaluation/calibration.py @@ -0,0 +1,191 @@ +"""Development-only probability calibration/abstention fitting; never tune on test rows.""" + +import hashlib +import json +import math +from pathlib import Path + +from nlp.evaluator import calibration, compute_metrics, validate_splits +from pipeline.contracts import LABELS + + +def temperature_scale(probabilities, temperature): + if not math.isfinite(temperature) or temperature <= 0: + raise ValueError("positive temperature required") + if ( + set(probabilities) != set(LABELS) + or any(not math.isfinite(p) or not 0 <= p <= 1 for p in probabilities.values()) + or abs(sum(probabilities.values()) - 1) > 1e-5 + ): + raise ValueError("invalid three-class probabilities") + logits = {label: math.log(max(p, 1e-12)) / temperature for label, p in probabilities.items()} + offset = max(logits.values()) + values = {label: math.exp(value - offset) for label, value in logits.items()} + total = sum(values.values()) + return {label: value / total for label, value in values.items()} + + +def fit_development( + rows, min_coverage, min_class_support, temperatures=(0.5, 0.75, 1.0, 1.5, 2.0, 3.0) +): + if not rows or not 0 < min_coverage <= 1 or min_class_support < 1: + raise ValueError("invalid development fitting protocol") + if any(r.get("split") != "dev" for r in rows): + raise ValueError("only frozen development rows may fit calibration") + if len({r["id"] for r in rows}) != len(rows): + raise ValueError("duplicate development IDs") + if any(sum(r["true_label"] == label for r in rows) < min_class_support for label in LABELS): + raise ValueError("development class support below declared protocol minimum") + for row in rows: + temperature_scale(row["probabilities"], 1) + + def nll(temperature): + return -sum( + math.log( + max(temperature_scale(r["probabilities"], temperature)[r["true_label"]], 1e-12) + ) + for r in rows + ) / len(rows) + + temperature = min(temperatures, key=lambda t: (nll(t), abs(math.log(t)))) + scaled = [ + r | {"probabilities": temperature_scale(r["probabilities"], temperature)} for r in rows + ] + thresholds = sorted({0.0, *[max(r["probabilities"].values()) for r in scaled]}) + candidates = [] + for threshold in thresholds: + scored = [ + r + | { + "predicted_label": max(r["probabilities"], key=r["probabilities"].get) + if max(r["probabilities"].values()) >= threshold + else "ABSTAIN" + } + for r in scaled + ] + metrics = compute_metrics(scored) + if metrics["coverage"] >= min_coverage: + candidates.append( + (metrics["macro_f1"], metrics["coverage"], -threshold, threshold, metrics) + ) + chosen = max(candidates, key=lambda c: c[:3]) + before = [ + r | {"predicted_label": max(r["probabilities"], key=r["probabilities"].get)} for r in rows + ] + after = [ + r | {"predicted_label": max(r["probabilities"], key=r["probabilities"].get)} for r in scaled + ] + return { + "temperature": temperature, + "abstention_threshold": chosen[3], + "development_ids": [r["id"] for r in rows], + "n": len(rows), + "protocol": { + "minimum_coverage": min_coverage, + "minimum_class_support": min_class_support, + "temperature_grid": list(temperatures), + "temperature_objective": "development negative log likelihood", + "threshold_objective": "full-population macro F1 subject to predeclared coverage; ties favor coverage then lower threshold", + }, + "nll_before": nll(1), + "nll_after": nll(temperature), + "calibration_before": calibration(before), + "calibration_after": calibration(after), + "selected_development_metrics": chosen[4], + "independent_test_status": "not evaluated by this fitting function", + } + + +def score_development(dataset, output, permissions_path=None, synthetic_demo=False): + from nlp.sentiment_engine import get_classifier, infer_mentions + + raw = Path(dataset).read_bytes() + data = json.loads(raw) + if synthetic_demo: + if data.get("synthetic") is not True or any( + r.get("synthetic") is not True for r in data["records"] + ): + raise ValueError("synthetic scoring requires explicit synthetic provenance") + rights = {"mode": "synthetic_demo"} + else: + from pipeline.permissions import permission + + if permissions_path is None: + raise PermissionError( + "owner-approved inference permission required for real development data" + ) + rights = permission(permissions_path, "approved_export", {"infer"}, dataset) + validate_splits(data["records"]) + rows = [r for r in data["records"] if r["split"] == "dev"] + registry = json.loads( + (Path(__file__).resolve().parents[1] / "nlp/model_registry.json").read_text() + ) + model_id = next(key for key in registry if "twitter-roberta" in key) + classifier = get_classifier(model_id, registry[model_id]["revision"]) + predictions, _ = infer_mentions( + [{"id": r["id"], "normalized_text": r["text"]} for r in rows], classifier + ) + if any(p.label == "ERROR" for p in predictions): + raise RuntimeError("development prediction failure") + result = { + "synthetic": data.get("synthetic", False), + "label_source": data.get("label_source"), + "annotation_provenance": data.get("provenance"), + "frozen_dataset_sha256": hashlib.sha256(raw).hexdigest(), + "model_checkpoint": classifier.version, + "head": "three_class", + "source_permissions": rights, + "records": [ + r | {"probabilities": p.probabilities} for r, p in zip(rows, predictions, strict=True) + ], + "test_rows_scored": 0, + } + with Path(output).open("x") as f: + json.dump(result, f, indent=2) + f.write("\n") + return { + "development_examples": len(rows), + "test_rows_scored": 0, + "model_checkpoint": classifier.version, + } + + +def main(): + import argparse + + p = argparse.ArgumentParser() + sub = p.add_subparsers(dest="command", required=True) + c = sub.add_parser("score-dev") + c.add_argument("--dataset", required=True) + c.add_argument("--output", required=True) + c.add_argument("--permissions") + c.add_argument("--synthetic-demo", action="store_true") + c = sub.add_parser("fit") + c.add_argument("--predictions", required=True) + c.add_argument("--output", required=True) + c.add_argument("--min-coverage", type=float, required=True) + c.add_argument("--min-class-support", type=int, required=True) + a = p.parse_args() + if a.command == "score-dev": + result = score_development(a.dataset, a.output, a.permissions, a.synthetic_demo) + else: + raw = Path(a.predictions).read_bytes() + data = json.loads(raw) + if data.get("head") != "three_class": + raise ValueError("only genuine three-class outputs may fit this calibrator") + result = fit_development(data["records"], a.min_coverage, a.min_class_support) | { + "model_checkpoint": data["model_checkpoint"], + "predictions_sha256": hashlib.sha256(raw).hexdigest(), + "synthetic": data.get("synthetic", False), + "label_source": data.get("label_source"), + "status": "development_fit_only_not_approved_for_deployment", + "note": "Needs representative independent human labels, provenance review and a subsequent untouched test evaluation; never auto-applied to live inference.", + } + with Path(a.output).open("x") as f: + json.dump(result, f, indent=2) + f.write("\n") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/tests/unit/test_annotation_workflow.py b/tests/unit/test_annotation_workflow.py new file mode 100644 index 0000000..6bd0dc1 --- /dev/null +++ b/tests/unit/test_annotation_workflow.py @@ -0,0 +1,122 @@ +import csv +import json + +import pytest + +from evaluation.annotation_workflow import compare, create_packet, freeze, read_annotations +from nlp.evaluator import validate_splits + + +def dataset(tmp_path): + path = tmp_path / "synthetic.json" + records = [ + dict( + id=str(i), + source="fixture", + language="en", + text=( + "=DANGER() text" if i == 0 else f"Original software verification phrase number {i}" + ), + synthetic=True, + predicted_label="SHOULD NOT EXPORT", + true_label="SHOULD NOT EXPORT", + rating=5, + ) + for i in range(10) + ] + path.write_text(json.dumps({"records": records})) + return path + + +def fill(path, annotator, disagree=False): + with path.open(newline="") as f: + rows = list(csv.DictReader(f)) + fields = list(rows[0]) + for i, row in enumerate(rows): + row.update( + overall_label="NEGATIVE" if disagree and i == 0 else "POSITIVE", + ambiguous="NO", + aspect_spans_json="[]", + annotator=annotator, + ) + with path.open("w", newline="") as f: + writer = csv.DictWriter(f, fieldnames=fields) + writer.writeheader() + writer.writerows(rows) + return rows + + +def test_blind_packet_agreement_and_freeze(tmp_path): + source = dataset(tmp_path) + packet = tmp_path / "packet" + with pytest.raises(PermissionError): + create_packet(source, tmp_path / "denied") + info = create_packet(source, packet, synthetic_demo=True) + assert info["selected"] == 10 and info["status"] == "synthetic_engineering_demo_only" + with (packet / "annotator-a.csv").open() as f: + rows = list(csv.DictReader(f)) + assert ( + rows[0]["overall_label"] == "" + and not {"predicted_label", "true_label", "rating"} & rows[0].keys() + ) + assert any(row["text"].startswith("'=DANGER") for row in rows) + fill(packet / "annotator-a.csv", "TEST A") + fill(packet / "annotator-b.csv", "TEST B") + report = compare( + packet, packet / "annotator-a.csv", packet / "annotator-b.csv", tmp_path / "review" + ) + assert report["raw_agreement"] == 1 and report["cohen_kappa"] is None + stats = freeze( + packet, packet / "annotator-a.csv", packet / "annotator-b.csv", tmp_path / "gold.json" + ) + data = json.loads((tmp_path / "gold.json").read_text()) + validate_splits(data["records"]) + assert stats["synthetic"] is True and stats["aspect_gold_complete"] + assert sorted(stats["split_counts"].values()) == [2, 2, 6] + + +def test_disagreement_needs_human_adjudication(tmp_path): + packet = tmp_path / "packet" + create_packet(dataset(tmp_path), packet, synthetic_demo=True) + fill(packet / "annotator-a.csv", "TEST A") + fill(packet / "annotator-b.csv", "TEST B", disagree=True) + report = compare( + packet, packet / "annotator-a.csv", packet / "annotator-b.csv", tmp_path / "review" + ) + assert report["disagreements"] == 1 and report["raw_agreement"] == 0.9 + with pytest.raises(ValueError, match="adjudication"): + freeze( + packet, packet / "annotator-a.csv", packet / "annotator-b.csv", tmp_path / "gold.json" + ) + rows = fill(tmp_path / "review/adjudication.csv", "TEST ADJUDICATOR") + rows[0]["notes"] = "Synthetic software fixture resolution rationale" + rows[0]["decision"] = "INCLUDE" + path = tmp_path / "review/adjudication.csv" + with path.open("w", newline="") as f: + writer = csv.DictWriter(f, fieldnames=rows[0].keys()) + writer.writeheader() + writer.writerows(rows) + freeze( + packet, packet / "annotator-a.csv", packet / "annotator-b.csv", tmp_path / "gold.json", path + ) + assert json.loads((tmp_path / "gold.json").read_text())["provenance"]["adjudicated"] == 1 + fill(packet / "annotator-b.csv", "TEST A") + with pytest.raises(ValueError, match="identit"): + compare(packet, packet / "annotator-a.csv", packet / "annotator-b.csv", tmp_path / "other") + + +def test_text_tampering_and_incomplete_rows_rejected(tmp_path): + packet = tmp_path / "packet" + create_packet(dataset(tmp_path), packet, synthetic_demo=True) + raw = json.loads((packet / "frozen-input.json").read_text()) + records = {r["id"]: r for r in raw["records"]} + with pytest.raises(ValueError, match="incomplete"): + read_annotations(packet / "annotator-a.csv", records) + rows = fill(packet / "annotator-a.csv", "TEST A") + rows[0]["text"] = "tampered" + with (packet / "annotator-a.csv").open("w", newline="") as f: + writer = csv.DictWriter(f, fieldnames=rows[0].keys()) + writer.writeheader() + writer.writerows(rows) + with pytest.raises(ValueError, match="changed"): + read_annotations(packet / "annotator-a.csv", records) diff --git a/tests/unit/test_calibration_protocol.py b/tests/unit/test_calibration_protocol.py new file mode 100644 index 0000000..9cf604f --- /dev/null +++ b/tests/unit/test_calibration_protocol.py @@ -0,0 +1,58 @@ +import pytest + +from evaluation.calibration import fit_development, temperature_scale + + +def records(): + rows = [] + for i, label in enumerate(("NEGATIVE", "NEUTRAL", "POSITIVE")): + rows.append( + dict( + id=str(i), + split="dev", + true_label=label, + probabilities={ + candidate: (0.6 if candidate == label else 0.2) + for candidate in ("NEGATIVE", "NEUTRAL", "POSITIVE") + }, + ) + ) + return rows + + +def test_development_only_calibration_and_coverage(): + result = fit_development(records(), min_coverage=1, min_class_support=1) + assert result["nll_after"] <= result["nll_before"] + assert result["selected_development_metrics"]["coverage"] == 1 + assert result["selected_development_metrics"]["macro_f1"] == 1 + assert sum(temperature_scale(records()[0]["probabilities"], 2).values()) == pytest.approx(1) + with pytest.raises(ValueError, match="development"): + fit_development([r | {"split": "test"} for r in records()], 1, 1) + with pytest.raises(ValueError, match="support"): + fit_development(records(), 1, 2) + with pytest.raises(ValueError): + temperature_scale({"NEGATIVE": float("nan"), "NEUTRAL": 0, "POSITIVE": 1}, 1) + with pytest.raises(ValueError): + temperature_scale(records()[0]["probabilities"], 0) + + +def test_development_scoring_never_predicts_test_examples(tmp_path, monkeypatch): + import json + from pathlib import Path + + from evaluation.calibration import score_development + from nlp.sentiment_engine import DemoClassifier + + seen = [] + + class Spy(DemoClassifier): + def predict(self, items): + seen.extend(row["id"] for row in items) + return super().predict(items) + + monkeypatch.setattr("nlp.sentiment_engine.get_classifier", lambda *_: Spy()) + dataset = Path(__file__).resolve().parents[2] / "evaluation/fixture.json" + result = score_development(dataset, tmp_path / "dev.json", synthetic_demo=True) + assert result["test_rows_scored"] == 0 and set(seen) == {"dev-0", "dev-1", "dev-2"} + data = json.loads((tmp_path / "dev.json").read_text()) + assert all(row["split"] == "dev" for row in data["records"]) From 39d89314b14f6c8015c55de38eb6536f3d6be5db Mon Sep 17 00:00:00 2001 From: axinion Date: Fri, 4 Dec 2026 09:37:35 -0600 Subject: [PATCH 3/8] feat: prepare immutable serving bundles and Linux real-model verification --- .github/workflows/ci.yml | 29 +++- .github/workflows/model-smoke.yml | 18 ++- Makefile | 2 +- pipeline/base_image.json | 44 ++++++ pipeline/cli.py | 14 ++ pipeline/release.py | 176 +++++++++++++++++++++++ scripts/model_smoke.py | 115 +++++++++++++++ scripts/verify.py | 2 + tests/integration/test_release_bundle.py | 44 ++++++ 9 files changed, 437 insertions(+), 7 deletions(-) create mode 100644 pipeline/base_image.json create mode 100644 pipeline/release.py create mode 100644 scripts/model_smoke.py create mode 100644 tests/integration/test_release_bundle.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fefbbb3..f195ed4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,7 +29,7 @@ jobs: - run: make test - run: brand-pipeline demo && brand-pipeline demo && brand-pipeline evaluate - name: Secret scan (working tree) - run: detect-secrets scan -n --exclude-files '(requirements.*lock|docs/evidence/|docs/history/|docs/samples/|nlp/model_registry.json|data/|outputs/|nlp/manual_labels.csv)' > /tmp/secrets.json && python -m scripts.check_secret_scan /tmp/secrets.json + run: detect-secrets scan -n --exclude-files '(requirements.*lock|docs/evidence/|docs/history/|docs/samples/|nlp/model_registry.json|nlp/aspect_registry.json|pipeline/base_image.json|data/|outputs/|nlp/manual_labels.csv)' > /tmp/secrets.json && python -m scripts.check_secret_scan /tmp/secrets.json - name: Dependency audit run: pip-audit -r requirements.lock - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 @@ -57,5 +57,30 @@ jobs: done curl -fsS http://127.0.0.1:8000/v1/summary test "$(curl -s -o /dev/null -w '%{http_code}' -X POST http://127.0.0.1:8000/run)" = "404" + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 + with: + python-version: '3.11' + - name: Prepare and build a hash-verified aggregate-only release + run: | + pip install -r requirements.lock + pip install -e . -c requirements.lock + mkdir -p runtime/release-source + brand-pipeline demo --db runtime/release-source/mentions.db --output runtime/release-source/reports > runtime/release-source/summary.json + brand-pipeline prepare-release --summary runtime/release-source/summary.json --destination runtime/release-bundle + brand-pipeline verify-release --directory runtime/release-bundle + docker build -t brand-reputation:release runtime/release-bundle + - name: Verify release image on a read-only filesystem + run: | + docker run -d --read-only --tmpfs /tmp --name reputation-release -p 127.0.0.1:8001:8000 brand-reputation:release + test "$(docker exec reputation-release id -u)" = "10001" + for attempt in $(seq 1 20); do + if curl -fsS http://127.0.0.1:8001/health/live; then break; fi + sleep 1 + done + curl -fsS http://127.0.0.1:8001/v1/summary + test "$(curl -s -o /dev/null -w '%{http_code}' -X POST http://127.0.0.1:8001/run)" = "404" - if: always() - run: docker logs reputation; docker rm -f reputation + run: | + docker logs reputation || true + docker logs reputation-release || true + docker rm -f reputation reputation-release || true diff --git a/.github/workflows/model-smoke.yml b/.github/workflows/model-smoke.yml index fbff2fe..7c7be28 100644 --- a/.github/workflows/model-smoke.yml +++ b/.github/workflows/model-smoke.yml @@ -1,13 +1,22 @@ name: Optional CPU model smoke on: workflow_dispatch: + push: + branches: [codex/flagship-upgrade] + paths: + - 'nlp/**' + - 'pipeline/**' + - 'evaluation/**' + - 'scripts/model_smoke.py' + - 'requirements-worker-linux.lock' + - '.github/workflows/model-smoke.yml' env: FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true" permissions: contents: read concurrency: group: cpu-model-smoke - cancel-in-progress: false + cancel-in-progress: true jobs: real-models: runs-on: ubuntu-latest @@ -26,11 +35,12 @@ jobs: cache-dependency-path: requirements-worker-linux.lock - run: pip install -r requirements-worker-linux.lock && pip install . -c requirements-worker-linux.lock && pip check - name: Synthetic-only real-model comparison (no human quality claim) - run: brand-pipeline evaluate --transformers --output runtime/smoke + run: python -m scripts.model_smoke --output runtime/smoke - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 with: name: cpu-model-smoke path: | - runtime/smoke/metrics.json - runtime/smoke/summary.csv + runtime/smoke/model-smoke.json + runtime/smoke/overall/metrics.json + runtime/smoke/overall/summary.csv retention-days: 14 diff --git a/Makefile b/Makefile index f19532a..c51afd8 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ install: demo: brand-pipeline demo test: - pytest --cov=config --cov=database --cov=pipeline --cov=analytics --cov=api --cov=nlp.evaluator --cov=nlp.sentiment_engine --cov=scrapers --cov=reports.report_generator --cov=reports.render_template --cov-report=term-missing --cov-report=xml + pytest --cov=config --cov=database --cov=pipeline --cov=analytics --cov=api --cov=nlp.evaluator --cov=nlp.sentiment_engine --cov=nlp.aspects --cov=evaluation --cov=scrapers --cov=reports.report_generator --cov=reports.render_template --cov-report=term-missing --cov-report=xml lint: ruff check . ruff format --check . diff --git a/pipeline/base_image.json b/pipeline/base_image.json new file mode 100644 index 0000000..29bfedb --- /dev/null +++ b/pipeline/base_image.json @@ -0,0 +1,44 @@ +{ + "image": "python:3.11-slim", + "digest": "sha256:7032841967d07aa3353905945dc186901c89b6b319c61425f4439f677a4a8a34", + "reference": "python:3.11-slim@sha256:7032841967d07aa3353905945dc186901c89b6b319c61425f4439f677a4a8a34", + "registry": "https://registry-1.docker.io/v2/library/python/", + "platforms": [ + { + "architecture": "amd64", + "os": "linux" + }, + { + "architecture": "arm", + "os": "linux", + "variant": "v5" + }, + { + "architecture": "arm", + "os": "linux", + "variant": "v7" + }, + { + "architecture": "arm64", + "os": "linux", + "variant": "v8" + }, + { + "architecture": "386", + "os": "linux" + }, + { + "architecture": "ppc64le", + "os": "linux" + }, + { + "architecture": "riscv64", + "os": "linux" + }, + { + "architecture": "s390x", + "os": "linux" + } + ], + "purpose": "Pinned official multi-platform base; no image or application deployed" +} diff --git a/pipeline/cli.py b/pipeline/cli.py index b54999d..f181eaf 100644 --- a/pipeline/cli.py +++ b/pipeline/cli.py @@ -41,6 +41,12 @@ def main(argv=None): p.add_argument("--summary", type=Path, required=True) p.add_argument("--destination", type=Path, required=True) p.add_argument("--approved-live", action="store_true") + p = sub.add_parser("prepare-release") + p.add_argument("--summary", type=Path, required=True) + p.add_argument("--destination", type=Path, required=True) + p.add_argument("--source-root", type=Path) + p = sub.add_parser("verify-release") + p.add_argument("--directory", type=Path, required=True) p = sub.add_parser("serve") p.add_argument("--port", type=int, default=8000) p.add_argument("--host", default="127.0.0.1") @@ -74,6 +80,14 @@ def main(argv=None): from pipeline.publication import snapshot print(json.dumps(snapshot(args.summary, args.destination, args.approved_live), indent=2)) + elif args.command == "prepare-release": + from pipeline.release import prepare + + print(json.dumps(prepare(args.summary, args.destination, args.source_root), indent=2)) + elif args.command == "verify-release": + from pipeline.release import verify + + print(json.dumps(verify(args.directory), indent=2)) elif args.command == "serve": import uvicorn diff --git a/pipeline/release.py b/pipeline/release.py new file mode 100644 index 0000000..ad5bb24 --- /dev/null +++ b/pipeline/release.py @@ -0,0 +1,176 @@ +"""Prepare an immutable, aggregate-only synthetic deployment bundle; never deploy it.""" + +import hashlib +import json +import re +import shutil +import sqlite3 +import subprocess +from contextlib import closing +from pathlib import Path, PurePosixPath + +import database +from pipeline.contracts import ReportSummary +from pipeline.publication import snapshot + +ROOT = Path(__file__).resolve().parents[1] +RESOURCE_FILES = { + "demo.json", + "fixture.json", + "model_registry.json", + "aspect_registry.json", + "base_image.json", +} + + +def sha256(path): + digest = hashlib.sha256() + with Path(path).open("rb") as f: + for block in iter(lambda: f.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def prepare(summary_path, destination, source_root=None): + summary = ReportSummary.model_validate_json(Path(summary_path).read_text()) + if summary.mode != "demo": + raise PermissionError( + "release preparation currently supports synthetic demo snapshots only; live data requires a separate approved release" + ) + source_root = Path(source_root).resolve() if source_root else ROOT + if not (source_root / "pyproject.toml").is_file(): + raise ValueError("release preparation requires a source checkout; pass --source-root") + base = json.loads(Path(__file__).with_name("base_image.json").read_text()) + if not re.fullmatch(r"python:3\.11-slim@sha256:[a-f0-9]{64}", base["reference"]): + raise ValueError("untrusted base image reference") + destination = Path(destination) + if destination.exists(): + raise FileExistsError("release destination exists; choose a new path") + destination.mkdir(parents=True) + snapshot(summary_path, destination / "snapshot.db") + # A standalone read-only image cannot create WAL shared-memory files in /app. + with closing(sqlite3.connect(destination / "snapshot.db")) as db: + db.execute("PRAGMA wal_checkpoint(TRUNCATE)") + mode = db.execute("PRAGMA journal_mode=DELETE").fetchone()[0] + if mode != "delete" or db.execute("PRAGMA integrity_check").fetchone()[0] != "ok": + raise ValueError("snapshot integrity failure") + source = destination / "source" + source.mkdir() + for name in ("config.py", "database.py", "pyproject.toml", "requirements.lock"): + shutil.copyfile(source_root / name, source / name) + for name in ("api", "pipeline", "scrapers", "nlp", "analytics", "reports", "evaluation"): + for path in (source_root / name).rglob("*"): + if path.is_symlink(): + raise ValueError("source symlinks are not permitted in release bundles") + if path.is_file() and (path.suffix in {".py", ".html"} or path.name in RESOURCE_FILES): + relative = path.relative_to(source_root) + target = source / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(path, target) + # No private/approved permissions manifest, raw CSV/DB, model weights or credentials are copied. + dockerfile = f"""FROM {base["reference"]} +ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 PIP_NO_CACHE_DIR=1 DB_PATH=/app/snapshot.db MODE=demo +WORKDIR /app +COPY source/ ./ +RUN python -m pip install -r requirements.lock && python -m pip install . -c requirements.lock && useradd --uid 10001 --create-home appuser +COPY snapshot.db ./snapshot.db +RUN chmod 0444 /app/snapshot.db +USER 10001:10001 +EXPOSE 8000 +HEALTHCHECK --interval=30s --timeout=5s CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health/live',timeout=3)" +CMD ["uvicorn", "api.main:app", "--host", "0.0.0.0", "--port", "8000"] +""" + (destination / "Dockerfile").write_text(dockerfile) + (destination / ".dockerignore").write_text(".env*\n__pycache__/\n*.pyc\n") + (destination / "summary.json").write_text(summary.model_dump_json(indent=2) + "\n") + try: + commit = subprocess.check_output( + ["git", "rev-parse", "HEAD"], + cwd=source_root, + text=True, + stderr=subprocess.DEVNULL, + timeout=5, + ).strip() + except (OSError, subprocess.SubprocessError): + commit = "unknown" + files = { + str(path.relative_to(destination)): sha256(path) + for path in sorted(destination.rglob("*")) + if path.is_file() + } + manifest = { + "schema_version": 1, + "status": "prepared_not_approved_or_deployed", + "source_commit": commit, + "mode": "demo", + "run_id": summary.run_id, + "base_image": base["reference"], + "model_checkpoint": summary.model_checkpoint, + "raw_mentions": 0, + "uid": 10001, + "files": files, + "owner_gates": [ + "Approve target account/service and explicit public deployment", + "Code license intentionally undecided; owner retains that decision", + "Live source permissions remain pending; this bundle contains only synthetic aggregates", + ], + "commands": { + "verify": "brand-pipeline verify-release --directory .", + "build": "docker build -t brand-reputation:review .", + "local_run": "docker run --rm -p 127.0.0.1:8000:8000 brand-reputation:review", + }, + } + (destination / "release-manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") + verify(destination) + return manifest + + +def verify(directory): + directory = Path(directory).resolve() + manifest = json.loads((directory / "release-manifest.json").read_text()) + if manifest.get("schema_version") != 1 or manifest.get("mode") != "demo": + raise ValueError("unsupported release bundle") + for name, digest in manifest["files"].items(): + relative = PurePosixPath(name) + target = (directory / name).resolve() + if ( + relative.is_absolute() + or ".." in relative.parts + or not target.is_relative_to(directory) + or not target.is_file() + or (directory / name).is_symlink() + ): + raise ValueError("unsafe release path") + if sha256(target) != digest: + raise ValueError("release file hash mismatch") + actual = { + str(path.relative_to(directory)) + for path in directory.rglob("*") + if path.is_file() and path.name != "release-manifest.json" + } + if actual != set(manifest["files"]): + raise ValueError("unexpected file in release bundle") + with closing(database.connect(directory / "snapshot.db", readonly=True)) as db: + if db.execute("PRAGMA integrity_check").fetchone()[0] != "ok": + raise ValueError("invalid snapshot") + for table in ( + "mentions_v2", + "predictions_v2", + "aspects_v2", + "aspect_inference", + "aspect_spans", + ): + if db.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]: + raise ValueError("private rows present in release") + summary = ReportSummary.model_validate_json( + db.execute("SELECT summary FROM snapshots").fetchone()[0] + ) + if summary.mode != "demo" or summary.run_id != manifest["run_id"]: + raise ValueError("snapshot manifest mismatch") + return { + "status": "verified", + "run_id": manifest["run_id"], + "files": len(manifest["files"]), + "raw_rows": 0, + "deployed": False, + } diff --git a/scripts/model_smoke.py b/scripts/model_smoke.py new file mode 100644 index 0000000..e611b15 --- /dev/null +++ b/scripts/model_smoke.py @@ -0,0 +1,115 @@ +"""Real CPU model/ABSA smoke on original synthetic inputs only; no human quality claim.""" + +import json +import platform +import tempfile +import time +from contextlib import closing +from pathlib import Path + +import database +from config import Settings +from nlp.aspects import get_extractor +from nlp.evaluator import evaluate +from nlp.sentiment_engine import get_classifier +from pipeline.runner import run + + +def smoke(output): + import torch + + torch.set_num_threads(2) + output = Path(output) + output.mkdir(parents=True, exist_ok=True) + started = time.perf_counter() + root = Path(__file__).resolve().parents[1] + comparison = evaluate(root / "evaluation/fixture.json", output / "overall", transformers=True) + from evaluation.calibration import fit_development, score_development + + dev_path = output / "synthetic-dev-predictions.json" + if dev_path.exists(): + raise FileExistsError("choose a fresh smoke destination") + score_development(root / "evaluation/fixture.json", dev_path, synthetic_demo=True) + dev = json.loads(dev_path.read_text()) + fitted = fit_development(dev["records"], min_coverage=1.0, min_class_support=1) + (output / "synthetic-calibration.json").write_text( + json.dumps( + fitted + | {"synthetic": True, "status": "software_smoke_only_not_an_operational_threshold"}, + indent=2, + ) + + "\n" + ) + for name, metrics in comparison["metrics"].items(): + if metrics["failed"] or metrics["missing"]: + raise RuntimeError(f"overall smoke failed: {name}") + extractor = get_extractor() + texts = [ + "The price is high, but the picture quality is excellent. Customer support is slow.", + "The user interface is easy to navigate, but the subscription price is terrible.", + "Café prices are high. The picture quality is good 😊.", + ] + results = extractor(texts) + if len(results) != len(texts) or not any(r["spans"] for r in results): + raise RuntimeError("aspect model returned no spans on the smoke workload") + model_id = next( + k for k in comparison["manifest"]["timing"].values() if "twitter-roberta" in k["version"] + )["version"].split("@")[0] + registry = json.loads((root / "nlp/model_registry.json").read_text()) + classifier = get_classifier(model_id, registry[model_id]["revision"]) + with tempfile.TemporaryDirectory() as temp: + settings = Settings(db_path=Path(temp) / "demo.db", output_dir=Path(temp) / "reports") + first = run(settings, classifier=classifier, extractor=extractor) + second = run(settings, classifier=classifier, extractor=extractor) + assert first.current == second.current and first.aspects == second.aspects + with closing(database.connect(settings.db_path, readonly=True)) as db: + assert db.execute("PRAGMA foreign_key_check").fetchall() == [] + run_meta = json.loads( + db.execute("SELECT metadata FROM runs WHERE id=?", (second.run_id,)).fetchone()[0] + ) + assert run_meta["counts"]["inference_eligible"] == 0 + counts = { + "mentions": db.execute("SELECT COUNT(*) FROM mentions_v2").fetchone()[0], + "aspect_inference": db.execute("SELECT COUNT(*) FROM aspect_inference").fetchone()[ + 0 + ], + "aspect_spans": db.execute("SELECT COUNT(*) FROM aspect_spans").fetchone()[0], + } + evidence = { + "status": "passed", + "platform": platform.platform(), + "python": platform.python_version(), + "torch": torch.__version__, + "device": "cpu", + "threads": 2, + "seconds": time.perf_counter() - started, + "weights_sha256": extractor.weights_sha256, + "aspect_checkpoint": extractor.version, + "data": "Original synthetic examples and authored fixture; no external source calls or human annotations", + "texts": texts, + "results": results, + "idempotent_database_counts": counts, + "aspect_status": second.aspect_status, + "quality_status": "Domain precision/recall/F1 unvalidated; smoke checks runtime, spans, persistence and repeat behavior only", + } + (output / "model-smoke.json").write_text(json.dumps(evidence, indent=2, allow_nan=False) + "\n") + print( + json.dumps( + { + "status": "passed", + "device": "cpu", + "aspect_spans": sum(len(r["spans"]) for r in results), + "database_counts": counts, + } + ) + ) + return evidence + + +if __name__ == "__main__": + import argparse + + p = argparse.ArgumentParser() + p.add_argument("--output", default="runtime/model-smoke") + a = p.parse_args() + smoke(a.output) diff --git a/scripts/verify.py b/scripts/verify.py index 8c8271d..27c2853 100644 --- a/scripts/verify.py +++ b/scripts/verify.py @@ -31,6 +31,8 @@ def verify(): "--cov=api", "--cov=nlp.evaluator", "--cov=nlp.sentiment_engine", + "--cov=nlp.aspects", + "--cov=evaluation", "--cov=scrapers", "--cov=reports.report_generator", "--cov=reports.render_template", diff --git a/tests/integration/test_release_bundle.py b/tests/integration/test_release_bundle.py new file mode 100644 index 0000000..5cc4501 --- /dev/null +++ b/tests/integration/test_release_bundle.py @@ -0,0 +1,44 @@ +import json + +import pytest + +from config import Settings +from pipeline.release import prepare, verify +from pipeline.runner import run + + +def test_release_has_no_raw_data_and_detects_tampering(tmp_path): + summary = run(Settings(db_path=tmp_path / "demo.db", output_dir=tmp_path / "reports")) + path = tmp_path / "summary.json" + path.write_text(summary.model_dump_json()) + bundle = tmp_path / "bundle" + manifest = prepare(path, bundle) + assert ( + verify(bundle)["raw_rows"] == 0 + and manifest["status"] == "prepared_not_approved_or_deployed" + ) + assert "USER 10001:10001" in (bundle / "Dockerfile").read_text() + assert "@sha256:" in manifest["base_image"] + assert not list(bundle.rglob("*.csv")) and not list(bundle.rglob("*.safetensors")) + assert not list(bundle.rglob("source_permissions.json")) + (bundle / "source/config.py").write_text("tampered") + with pytest.raises(ValueError, match="hash"): + verify(bundle) + with pytest.raises(FileExistsError): + prepare(path, bundle) + + +def test_release_rejects_live_mode_and_path_traversal(tmp_path): + summary = run(Settings(db_path=tmp_path / "demo.db", output_dir=tmp_path / "reports")) + path = tmp_path / "summary.json" + path.write_text(summary.model_copy(update={"mode": "live"}).model_dump_json()) + with pytest.raises(PermissionError): + prepare(path, tmp_path / "blocked") + path.write_text(summary.model_dump_json()) + bundle = tmp_path / "bundle" + prepare(path, bundle) + manifest = json.loads((bundle / "release-manifest.json").read_text()) + manifest["files"]["../../escape"] = "0" * 64 + (bundle / "release-manifest.json").write_text(json.dumps(manifest)) + with pytest.raises(ValueError, match="unsafe"): + verify(bundle) From 43265642666a67e482c14c40a5fd30bdaab23446 Mon Sep 17 00:00:00 2001 From: axinion Date: Fri, 4 Dec 2026 09:43:28 -0600 Subject: [PATCH 4/8] test: cover permission failures and human adjudication safeguards --- .github/workflows/model-smoke.yml | 1 + tests/unit/test_annotation_workflow.py | 88 +++++++++++++++++++++++++ tests/unit/test_calibration_protocol.py | 51 ++++++++++++++ tests/unit/test_legacy_preparation.py | 67 +++++++++++++++++++ tests/unit/test_permissions.py | 28 ++++++++ 5 files changed, 235 insertions(+) create mode 100644 tests/unit/test_legacy_preparation.py diff --git a/.github/workflows/model-smoke.yml b/.github/workflows/model-smoke.yml index 7c7be28..54c37f8 100644 --- a/.github/workflows/model-smoke.yml +++ b/.github/workflows/model-smoke.yml @@ -40,6 +40,7 @@ jobs: with: name: cpu-model-smoke path: | + runtime/smoke/synthetic-calibration.json runtime/smoke/model-smoke.json runtime/smoke/overall/metrics.json runtime/smoke/overall/summary.csv diff --git a/tests/unit/test_annotation_workflow.py b/tests/unit/test_annotation_workflow.py index 6bd0dc1..b36e139 100644 --- a/tests/unit/test_annotation_workflow.py +++ b/tests/unit/test_annotation_workflow.py @@ -120,3 +120,91 @@ def test_text_tampering_and_incomplete_rows_rejected(tmp_path): writer.writerows(rows) with pytest.raises(ValueError, match="changed"): read_annotations(packet / "annotator-a.csv", records) + + +def test_unresolvable_ambiguity_is_excluded_without_making_up_gold(tmp_path): + packet = tmp_path / "packet" + create_packet(dataset(tmp_path), packet, synthetic_demo=True, seed=7) + fill(packet / "annotator-a.csv", "TEST A") + fill(packet / "annotator-b.csv", "TEST B", disagree=True) + compare(packet, packet / "annotator-a.csv", packet / "annotator-b.csv", tmp_path / "review") + path = tmp_path / "review/adjudication.csv" + rows = fill(path, "TEST ADJUDICATOR") + excluded_id = rows[0]["id"] + rows[0].update( + decision="EXCLUDE", + overall_label="", + ambiguous="YES", + notes="Synthetic fixture: ambiguity cannot be resolved", + ) + with path.open("w", newline="") as f: + writer = csv.DictWriter(f, fieldnames=rows[0].keys()) + writer.writeheader() + writer.writerows(rows) + result = freeze( + packet, packet / "annotator-a.csv", packet / "annotator-b.csv", tmp_path / "gold.json", path + ) + assert result["excluded_examples"] == 1 and result["records"] == 9 + output = json.loads((tmp_path / "gold.json").read_text()) + assert excluded_id not in {r["id"] for r in output["records"]} + assert output["provenance"]["split_seed"] == 7 + with pytest.raises(ValueError, match="frozen"): + freeze( + packet, + packet / "annotator-a.csv", + packet / "annotator-b.csv", + tmp_path / "other.json", + path, + seed=42, + ) + + +def test_approved_input_binding_and_annotation_spans(tmp_path): + import hashlib + + source = dataset(tmp_path) + data = json.loads(source.read_text()) + for row in data["records"]: + row["synthetic"] = False + source.write_text(json.dumps(data)) + entry = dict( + source="approved_export", + status="approved", + access_method="SYNTHETIC TEST APPROVAL", + terms_url="https://example.com/test", + allowed_uses=["annotate"], + reviewed_by="TEST ONLY", + reviewed_at="2026-01-01T00:00:00Z", + expires_at="2099-01-01T00:00:00Z", + evidence_reference="Test only; not a real permission", + retention_days=7, + dataset_sha256=hashlib.sha256(source.read_bytes()).hexdigest(), + ) + policy = tmp_path / "policy.json" + policy.write_text(json.dumps(dict(schema_version=1, sources=[entry]))) + packet = tmp_path / "packet" + create_packet(source, packet, policy) + raw = json.loads((packet / "frozen-input.json").read_text()) + records = {r["id"]: r for r in raw["records"]} + path = packet / "annotator-a.csv" + rows = fill(path, "TEST A") + rows[0]["aspect_spans_json"] = json.dumps( + [dict(start=0, end=1, category="quality", label="POSITIVE")] + ) + rows[0]["error_slices_json"] = '["short"]' + + def write(): + with path.open("w", newline="") as f: + writer = csv.DictWriter(f, fieldnames=rows[0].keys()) + writer.writeheader() + writer.writerows(rows) + + write() + parsed = read_annotations(path, records) + assert parsed[rows[0]["id"]]["slices"] == ["short"] + rows[0]["aspect_spans_json"] = json.dumps( + [dict(start=0, end=99999, category="quality", label="POSITIVE")] + ) + write() + with pytest.raises(ValueError, match="span"): + read_annotations(path, records) diff --git a/tests/unit/test_calibration_protocol.py b/tests/unit/test_calibration_protocol.py index 9cf604f..878535d 100644 --- a/tests/unit/test_calibration_protocol.py +++ b/tests/unit/test_calibration_protocol.py @@ -56,3 +56,54 @@ def predict(self, items): assert result["test_rows_scored"] == 0 and set(seen) == {"dev-0", "dev-1", "dev-2"} data = json.loads((tmp_path / "dev.json").read_text()) assert all(row["split"] == "dev" for row in data["records"]) + + +def test_calibration_cli_keeps_synthetic_fits_non_deployable(tmp_path, monkeypatch, capsys): + import json + import sys + from pathlib import Path + + from evaluation.calibration import main + from nlp.sentiment_engine import DemoClassifier + + monkeypatch.setattr("nlp.sentiment_engine.get_classifier", lambda *_: DemoClassifier()) + dataset = Path(__file__).resolve().parents[2] / "evaluation/fixture.json" + predictions = tmp_path / "dev.json" + fit = tmp_path / "fit.json" + monkeypatch.setattr( + sys, + "argv", + [ + "calibration", + "score-dev", + "--dataset", + str(dataset), + "--output", + str(predictions), + "--synthetic-demo", + ], + ) + main() + assert json.loads(capsys.readouterr().out)["test_rows_scored"] == 0 + monkeypatch.setattr( + sys, + "argv", + [ + "calibration", + "fit", + "--predictions", + str(predictions), + "--output", + str(fit), + "--min-coverage", + "1", + "--min-class-support", + "1", + ], + ) + main() + output = json.loads(fit.read_text()) + assert ( + output["synthetic"] is True + and output["status"] == "development_fit_only_not_approved_for_deployment" + ) diff --git a/tests/unit/test_legacy_preparation.py b/tests/unit/test_legacy_preparation.py new file mode 100644 index 0000000..88eb743 --- /dev/null +++ b/tests/unit/test_legacy_preparation.py @@ -0,0 +1,67 @@ +"""All content/labels in this test are authored software fixtures, not human observations.""" + +import csv +import json +import sqlite3 + +from evaluation.prepare_legacy import prepare +from nlp.evaluator import validate_splits + + +def test_legacy_preparation_discards_historic_predictions_and_mock_ids(tmp_path): + dbpath = tmp_path / "legacy.db" + rows = [] + with sqlite3.connect(dbpath) as db: + db.execute("CREATE TABLE raw_mentions(id,timestamp,source)") + for i in range(20): + identity = f"test-native-{i}" + db.execute( + "INSERT INTO raw_mentions VALUES(?,?,?)", + (identity, f"2026-11-{i + 1:02d}T00:00:00Z", "news"), + ) + rows.append( + dict( + mention_id=identity, + text=f"Authored software text number {i}", + true_label=["NEGATIVE", "NEUTRAL", "POSITIVE"][i % 3], + predicted="DO NOT REUSE", + ) + ) + rows.extend( + [ + dict( + mention_id="mock_demo", + text="Synthetic ID must be excluded", + true_label="POSITIVE", + predicted="DO NOT REUSE", + ), + dict( + mention_id="not-found", + text="No metadata", + true_label="POSITIVE", + predicted="DO NOT REUSE", + ), + dict( + mention_id="bad", + text="Invalid label", + true_label="INVALID", + predicted="DO NOT REUSE", + ), + ] + ) + db.execute("INSERT INTO raw_mentions VALUES('bad','2026-11-01T00:00:00Z','news')") + source = tmp_path / "legacy.csv" + with source.open("w", newline="") as f: + writer = csv.DictWriter(f, fieldnames=rows[0].keys()) + writer.writeheader() + writer.writerows(rows) + target = tmp_path / "frozen.json" + stats = prepare(source, dbpath, target) + assert stats["included"] == 20 and stats["excluded"] == { + "synthetic": 1, + "missing_metadata": 1, + "invalid_label": 1, + } + frozen = json.loads(target.read_text()) + validate_splits(frozen["records"]) + assert all("predicted" not in r for r in frozen["records"]) diff --git a/tests/unit/test_permissions.py b/tests/unit/test_permissions.py index b6e4820..62b9f19 100644 --- a/tests/unit/test_permissions.py +++ b/tests/unit/test_permissions.py @@ -63,3 +63,31 @@ def test_export_approval_binds_exact_file(tmp_path): content.write_text("[1]") with pytest.raises(PermissionError): permission(path, "approved_export", {"annotate"}, content) + + +def test_invalid_manifests_cannot_authorize_a_source(tmp_path): + from pydantic import ValidationError + + from pipeline.permissions import SourcePermission + + base = dict( + source="news", + status="approved", + access_method="test", + terms_url="https://example.com/test", + allowed_uses=["infer"], + ) + with pytest.raises(ValidationError): + SourcePermission(**base) + with pytest.raises(ValidationError): + SourcePermission(**(base | {"terms_url": "http://example.com"})) + p = tmp_path / "unsupported.json" + p.write_text(json.dumps({"schema_version": 999, "sources": []})) + with pytest.raises(ValueError): + audit(p) + entry = base | dict(status="pending") + p.write_text(json.dumps(dict(schema_version=1, sources=[entry, entry]))) + with pytest.raises(ValueError, match="duplicate"): + permission(p, "news", {"infer"}) + with pytest.raises(ValueError, match="duplicate"): + audit(p) From d07ae9863693b9d30feb6e966c24af593926f915 Mon Sep 17 00:00:00 2001 From: axinion Date: Fri, 4 Dec 2026 09:47:23 -0600 Subject: [PATCH 5/8] fix: pin published Linux CPU wheel by official URL and SHA-256 --- requirements-linux-cpu.in | 3 +++ requirements-worker-linux.lock | 11 +++++------ scripts/lock_dependencies.py | 19 ++++--------------- 3 files changed, 12 insertions(+), 21 deletions(-) create mode 100644 requirements-linux-cpu.in diff --git a/requirements-linux-cpu.in b/requirements-linux-cpu.in new file mode 100644 index 0000000..2e0704f --- /dev/null +++ b/requirements-linux-cpu.in @@ -0,0 +1,3 @@ +# Official PyTorch CPU wheel for CPython 3.11 / Linux x86_64. +# URL and hash verified against https://download.pytorch.org/whl/cpu/torch/ on 2026-12-04. +torch @ https://download-r2.pytorch.org/whl/cpu/torch-2.15.0%2Bcpu-cp311-cp311-manylinux_2_28_x86_64.whl#sha256=cee15855a32ad89a9bb27b8a9d6e07a859dcd2e11ed1b5561f3d6206e31a103b diff --git a/requirements-worker-linux.lock b/requirements-worker-linux.lock index 45796bb..dbdddc0 100644 --- a/requirements-worker-linux.lock +++ b/requirements-worker-linux.lock @@ -1,8 +1,5 @@ ---extra-index-url https://download.pytorch.org/whl/cpu # This file was autogenerated by uv via the following command: -# uv --cache-dir /tmp/brp-uv-cache pip compile pyproject.toml --extra dev --extra nlp --extra orchestration --python-version 3.11 --python-platform x86_64-unknown-linux-gnu --torch-backend cpu --emit-index-url -o requirements-worker-linux.lock ---index-url https://pypi.org/simple - +# uv --cache-dir /tmp/brp-uv-cache pip compile pyproject.toml requirements-linux-cpu.in --extra dev --extra nlp --extra orchestration --python-version 3.11 --python-platform x86_64-unknown-linux-gnu -o requirements-worker-linux.lock aiosqlite==0.22.1 # via prefect alembic==1.20.1 @@ -441,8 +438,10 @@ tomli-w==1.2.0 # via pip-audit tomlkit==0.15.3 # via kernels -torch==2.15.0+cpu - # via brand-reputation-pipeline (pyproject.toml) +torch @ https://download-r2.pytorch.org/whl/cpu/torch-2.15.0%2Bcpu-cp311-cp311-manylinux_2_28_x86_64.whl#sha256=cee15855a32ad89a9bb27b8a9d6e07a859dcd2e11ed1b5561f3d6206e31a103b + # via + # -r requirements-linux-cpu.in + # brand-reputation-pipeline (pyproject.toml) tqdm==4.70.1 # via # huggingface-hub diff --git a/scripts/lock_dependencies.py b/scripts/lock_dependencies.py index 3eb0ccb..7fe3025 100644 --- a/scripts/lock_dependencies.py +++ b/scripts/lock_dependencies.py @@ -1,7 +1,6 @@ -"""Regenerate dependency locks from pyproject, recording the official Linux CPU index.""" +"""Regenerate dependency locks from pyproject, using the reviewed official Linux CPU wheel.""" import subprocess -from pathlib import Path def main(): @@ -16,20 +15,10 @@ def main(): for extra in extras: args += ["--extra", extra] if "linux" in name: - args += [ - "--python-platform", - "x86_64-unknown-linux-gnu", - "--torch-backend", - "cpu", - "--emit-index-url", - ] + # A reviewed direct wheel avoids index-discovery ambiguity and pins CPU content. + args += ["requirements-linux-cpu.in", "--python-platform", "x86_64-unknown-linux-gnu"] subprocess.run(args, check=True) - if "linux" in name: - p = Path(name) - s = p.read_text() - index = "--extra-index-url https://download.pytorch.org/whl/cpu\n" - if index not in s: - p.write_text(index + s) + if __name__ == "__main__": From ec1c752587b2f65e73e90a7a34f2681d8f32c22b Mon Sep 17 00:00:00 2001 From: axinion Date: Fri, 4 Dec 2026 09:47:34 -0600 Subject: [PATCH 6/8] style: format dependency lock regeneration helper --- scripts/lock_dependencies.py | 1 - 1 file changed, 1 deletion(-) diff --git a/scripts/lock_dependencies.py b/scripts/lock_dependencies.py index 7fe3025..82ed024 100644 --- a/scripts/lock_dependencies.py +++ b/scripts/lock_dependencies.py @@ -20,6 +20,5 @@ def main(): subprocess.run(args, check=True) - if __name__ == "__main__": main() From f0bdabdf63166a4db43d5d3300a0144dbdba7fe5 Mon Sep 17 00:00:00 2001 From: axinion Date: Fri, 4 Dec 2026 09:50:57 -0600 Subject: [PATCH 7/8] fix: preserve annotation permission provenance and independent adjudication --- evaluation/annotation_workflow.py | 5 +++++ tests/unit/test_annotation_workflow.py | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/evaluation/annotation_workflow.py b/evaluation/annotation_workflow.py index a05daca..9aa1010 100644 --- a/evaluation/annotation_workflow.py +++ b/evaluation/annotation_workflow.py @@ -349,6 +349,9 @@ def freeze(packet, a_path, b_path, output, adjudication_path=None, seed=None): {k: v for k, v in records.items() if k in conflicts}, adjudication=True, ) + annotator_ids = {r["annotator"] for r in a.values()} | {r["annotator"] for r in b.values()} + if annotator_ids & {r["annotator"] for r in decisions.values()}: + raise ValueError("adjudicator identity must differ from both annotators") if any( (r["ambiguous"] and not r["excluded"]) or not r["notes"].strip() for r in decisions.values() @@ -387,6 +390,8 @@ def freeze(packet, a_path, b_path, output, adjudication_path=None, seed=None): else "owner-supplied independent human annotations; identity/rights require owner verification", "provenance": { "packet_sha256": manifest["frozen_sha256"], + "source_dataset_sha256": manifest["source_dataset_sha256"], + "source_permissions": manifest["rights"], "agreement": agreement(a, b), "adjudicated": len(decisions), "input_examples": len(records), diff --git a/tests/unit/test_annotation_workflow.py b/tests/unit/test_annotation_workflow.py index b36e139..cacbfdf 100644 --- a/tests/unit/test_annotation_workflow.py +++ b/tests/unit/test_annotation_workflow.py @@ -72,6 +72,8 @@ def test_blind_packet_agreement_and_freeze(tmp_path): data = json.loads((tmp_path / "gold.json").read_text()) validate_splits(data["records"]) assert stats["synthetic"] is True and stats["aspect_gold_complete"] + assert data["provenance"]["source_permissions"]["human_gold"] is False + assert len(data["provenance"]["source_dataset_sha256"]) == 64 assert sorted(stats["split_counts"].values()) == [2, 2, 6] @@ -92,6 +94,24 @@ def test_disagreement_needs_human_adjudication(tmp_path): rows[0]["notes"] = "Synthetic software fixture resolution rationale" rows[0]["decision"] = "INCLUDE" path = tmp_path / "review/adjudication.csv" + with path.open("w", newline="") as f: + writer = csv.DictWriter(f, fieldnames=rows[0].keys()) + writer.writeheader() + writer.writerows(rows) + rows[0]["annotator"] = "TEST A" + with path.open("w", newline="") as f: + writer = csv.DictWriter(f, fieldnames=rows[0].keys()) + writer.writeheader() + writer.writerows(rows) + with pytest.raises(ValueError, match="adjudicator identity"): + freeze( + packet, + packet / "annotator-a.csv", + packet / "annotator-b.csv", + tmp_path / "bad-gold.json", + path, + ) + rows[0]["annotator"] = "TEST ADJUDICATOR" with path.open("w", newline="") as f: writer = csv.DictWriter(f, fieldnames=rows[0].keys()) writer.writeheader() From 7d2b7fc18ab160c683783603767d76de81fa2d38 Mon Sep 17 00:00:00 2001 From: axinion Date: Fri, 4 Dec 2026 09:54:24 -0600 Subject: [PATCH 8/8] docs: record readiness implementation, source checklist and verified Linux evidence --- CHANGELOG.md | 8 +- README.md | 8 +- docs/architecture.md | 8 +- docs/data-card.md | 4 + docs/evaluation.md | 4 + docs/evidence/demo-repeat.txt | 11 +- docs/evidence/demo.txt | 11 +- docs/evidence/format.txt | 2 +- docs/evidence/linux-model-runtime-smoke.json | 252 + .../evidence/linux-synthetic-calibration.json | 156 + .../linux-synthetic-model-evaluation.json | 5103 +++++++++++++++++ docs/evidence/readiness-verification.json | 93 + docs/evidence/release-bundle-manifest.json | 73 + .../evidence/release-bundle-verification.json | 7 + docs/evidence/tests.txt | 91 +- docs/evidence/verification-commands.json | 18 +- docs/flagship-upgrade-report.md | 2 + docs/history/tests-pre-readiness.txt | 53 + docs/history/verification-pre-readiness.json | 124 + docs/operations.md | 24 +- docs/publication-status.md | 6 +- docs/readiness/annotation-guide.md | 45 + docs/readiness/deployment-candidate.md | 21 + .../readiness/source-permissions-checklist.md | 38 + docs/readiness/stage-report.md | 56 + docs/security.md | 8 +- nlp/model_card.md | 14 +- 27 files changed, 6167 insertions(+), 73 deletions(-) create mode 100644 docs/evidence/linux-model-runtime-smoke.json create mode 100644 docs/evidence/linux-synthetic-calibration.json create mode 100644 docs/evidence/linux-synthetic-model-evaluation.json create mode 100644 docs/evidence/readiness-verification.json create mode 100644 docs/evidence/release-bundle-manifest.json create mode 100644 docs/evidence/release-bundle-verification.json create mode 100644 docs/history/tests-pre-readiness.txt create mode 100644 docs/history/verification-pre-readiness.json create mode 100644 docs/readiness/annotation-guide.md create mode 100644 docs/readiness/deployment-candidate.md create mode 100644 docs/readiness/source-permissions-checklist.md create mode 100644 docs/readiness/stage-report.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d7bda3..4290b97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,4 +6,10 @@ Added typed configuration/data/prediction/report contracts; Unicode-preserving n Security changes: removed unauthenticated execution endpoint; disabled unapproved source collectors; stopped weekly raw-data commits; removed conflicting scraper dependency hacks; updated dependencies after actual advisory findings. API v2 canonical summary changes the old `/health-score` payload. Old entrypoint names remain where safe; unsafe legacy live behavior fails explicitly. Existing data, historical metrics and Git history are preserved. -This candidate is **not released or production-ready**. Human/data rights, reproducible real ABSA, representative evaluation, hosted CI and deployment/runtime verification remain explicit release gates. +This candidate is **not released or production-ready**. Human/data rights, representative independent evaluation and public deployment remain explicit release gates. + +## Next-stage readiness work — December 4, 2026 + +Added current scoped source-permission gates and exact export hashes; two prediction-blind annotation packets, disagreement/kappa, adjudication/exclusion and frozen splits; dev-only temperature/coverage fitting; pinned safetensors joint aspect spans with unknown/truncation semantics and additive persistence; concrete hash-verified aggregate-only release bundles with pinned base image; Linux CPU model smoke and read-only container verification. The first actual Linux install exposed CPU index resolution failure; the lock now uses the official wheel URL and SHA-256. + +Owner confirmed no approved source access and deferred code-license selection. No source activation, human labels, operational threshold, public deployment, merge or release is claimed. See the readiness report for exact terminal outcomes. diff --git a/README.md b/README.md index 161b0a3..ddf460c 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ A local-first NLP engineering project for turning timestamped brand mentions into auditable sentiment summaries and a read-only API. Versioned predictions, explicit coverage, transactional SQLite snapshots, keyless reports, and reproducible evaluation make the evidence inspectable. -**Status: release gates remain open.** Local verification is recorded in [the upgrade report](docs/flagship-upgrade-report.md). [Linux CI and Docker smoke checks passed](https://github.com/Axinion/brand-reputation-pipeline/actions/runs/47359108300). Public deployment has not been performed. No production SLA or demonstrated business impact is claimed. +**Status: release gates remain open.** Local verification is recorded in [the upgrade report](docs/flagship-upgrade-report.md). [Linux CI and Docker smoke checks passed](https://github.com/Axinion/brand-reputation-pipeline/actions/runs/47369365445). Public deployment has not been performed. No production SLA or demonstrated business impact is claimed. The upgrade lives on `codex/flagship-upgrade`. The commands below check out that branch. See [publication status](docs/publication-status.md) for hosted verification. @@ -54,6 +54,8 @@ For real CPU models install `requirements-worker.lock`. See [evaluation](docs/ev **Actual exploratory ML result:** after excluding 81 synthetic historical annotations, only 19 legacy news examples remain (11 train / 4 development / 4 test). Train-majority, TF-IDF/logistic and RoBERTa each score 25% accuracy on those four test examples. This is not credible generalization evidence. Full per-class, coverage, calibration and uncertainty results are in [the executed artifact](docs/evidence/legacy-exploratory-evaluation.json). Historical metrics are preserved separately and must not be presented as current results. -Live Reddit/review adapters are disabled pending authorized access and rights review. NewsAPI is opt-in with explicit rights confirmation and credentials; its free developer plan is not a production hosting license. The weekly workflow now publishes synthetic aggregate artifacts, never raw databases. No source data, historical reports or Git history has been deleted. +[Next-stage readiness work](docs/readiness/stage-report.md) adds evidence-bound permission gates, blinded annotation/adjudication, development-only calibration, verified safetensors aspect extraction and immutable release preparation. Aspect extraction is opt-in and domain accuracy remains unvalidated. -Code license selection belongs to the owner. Existing source content and model weights have separate rights; this repository does not confer those rights. +Live Reddit/review adapters are disabled pending authorized access and rights review. NewsAPI is opt-in with a valid current owner permission record, explicit rights confirmation and credentials; its free developer plan is not a production hosting license. The weekly workflow now publishes synthetic aggregate artifacts, never raw databases. No source data, historical reports or Git history has been deleted. + +The owner has left the code license undecided. See the [source permissions checklist](docs/readiness/source-permissions-checklist.md), [annotation protocol](docs/readiness/annotation-guide.md) and [deployment candidate](docs/readiness/deployment-candidate.md). Existing source content and model weights have separate rights; this repository does not confer those rights. diff --git a/docs/architecture.md b/docs/architecture.md index 10dabe0..e151569 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -12,7 +12,9 @@ Private raw text and normalized text live in validated mention rows. Rejected ra Overall prediction is independent of aspects and review ratings. Each eligible input receives a valid prediction, abstention or error. The model/config version hashes checkpoint identity, threshold, taxonomy, normalization and extractor version. Predictions from old versions remain archived; active joins declare exactly one version and fingerprint. Changes invalidate outdated predictions/aspects. Batches use ordered IDs and strict cardinality/probability checks. Model objects load lazily once per process. CPU is default; unavailable explicitly requested accelerators fail instead of silently switching hardware. -The optional extractor interface returns separate term, polarity and confidence lists. Multiple terms in one category remain stored separately. Category aggregation collapses terms to a mean signed label per mention/category, then averages those mention scores; overall totals never count aspect rows. No reproducible PyABSA checkpoint artifact was supplied or verified, so default live extraction remains disabled rather than silently downloading an unpinned alias. Actual term/category/joint evaluation requires independent aspect annotations. +The optional pinned joint extractor loads standard Transformers code from verified safetensors with remote code disabled. It returns offset-preserving BIO spans with per-token probabilities and independent sentiment, not overall labels. Unknown polarity and truncated trailing spans are separate UNKNOWN/ABSTAIN states; neither becomes neutral. The legacy tuple extractor interface remains supported. Additive `aspect_inference` and `aspect_spans` tables preserve model-versioned processed/empty outcomes, repeated terms at distinct offsets and raw probabilities. Category aggregation averages known-polarity terms per mention/category; unknown/abstained/unmapped spans are excluded. Category mapping is heuristic. The report exposes aspect coverage and unvalidated quality. Default extraction stays disabled; `ASPECTS_ENABLED=true` is an explicit live-worker opt-in. No independent aspect gold or domain accuracy exists yet. + +Live processing now checks the private permission manifest before collection/model initialization: explicit confirmation, approved and currently valid scopes, plus exact SHA-256 for imports. A Boolean alone cannot enable collection. Permission evidence records owner attestations; software cannot grant legal rights. All default sources remain pending. Annotation creation strips predictions/ratings, freezes exact-text-cluster splits, requires two blinded annotators and adjudication, and supports exclusion of unresolved ambiguity. Calibration only fits development probabilities and never auto-applies a threshold. ## Storage and publication @@ -40,3 +42,7 @@ flowchart TB ``` Serving installs no ML stack, opens DB read-only, and runs sync database endpoints in FastAPI's threadpool. No subprocess/admin trigger is exposed. Configuration-only Render and Docker examples build a synthetic snapshot; ephemeral serving storage is never assumed to receive future workflow files. Live refresh and rollback remain explicit owner-controlled releases. `snapshot` creates an aggregate-only SQLite serving artifact from validated canonical JSON, re-renders HTML safely, and requires explicit rights approval for live-mode input; no raw mention/prediction rows are copied. + +## Immutable release preparation + +`prepare-release` copies a selected source/lock allowlist and aggregate-only synthetic snapshot into a new directory, pins the official Python image digest, and hashes each file. `verify-release` rejects path traversal, unexpected/tampered files and raw rows. The UID 10001 image supports a read-only root filesystem. This is a concrete reviewed artifact path; it does not authorize or execute public deployment. See [release candidate](readiness/deployment-candidate.md). diff --git a/docs/data-card.md b/docs/data-card.md index 901fcc4..9dd3d47 100644 --- a/docs/data-card.md +++ b/docs/data-card.md @@ -27,3 +27,7 @@ The migration creates `.pre-v2.bak`, preserves all original tables/IDs, maps acc Before any real data publication: approve per-provider rights, review content/PII, choose retention/deletion handling, establish source completeness windows and sign off the release manifest. Code licensing does not license source text or model weights. A separate private review-star experiment freezes 300 newest valid Google Play items from 7,186 eligible rows; 180 train / 60 dev / 60 test. Test class supports are 14 negative, 6 neutral and 40 positive. Labels come exclusively from review stars (1–2 negative, 3 neutral, 4–5 positive), not independent text annotations. Model/scored-row availability is not a selection criterion. Weak-label and human-label reports remain separate. The resulting per-example data stays under ignored `runtime/evaluation`; only aggregate evaluation evidence is included here pending owner publication review. + +## Owner follow-up + +The owner confirmed no approved access and requested a permissions checklist. All sources, including approved_export, remain pending in `pipeline/source_permissions.json`; runtime checks now require a current scoped record and exact export hash. [Checklist](readiness/source-permissions-checklist.md). Two-annotator packets, disagreement/adjudication, frozen cluster splits and development-only calibration are implemented, but no real packet or independent labels have been created. Synthetic software tests do not change dataset provenance. Code license remains undecided by owner instruction. diff --git a/docs/evaluation.md b/docs/evaluation.md index 3274d74..848c11b 100644 --- a/docs/evaluation.md +++ b/docs/evaluation.md @@ -57,3 +57,7 @@ Prediction-blind annotation export: `python -m evaluation.annotation --input APP | Three-class RoBERTa | 60 | 81.67% | 0.6724 | 100% | No model was fine-tuned and no test-based threshold optimization followed this run. These results are not comparable to historical 189-example metrics because selection, class balance and protocol differ. Star/text disagreement and six neutral examples severely limit interpretation. Accuracy gain against majority on this particular weak-label subset is not evidence of business impact or broad brand/source generalization. Human-gold threshold/calibration/regression gates remain open. The historical heuristic has no genuine neutral probability calibration and its calibration fields are null. Raw binary and three-class confidence values are not treated as interchangeable certainty measures. + +## Independent annotation and dev-only calibration follow-up + +The [annotation guide](readiness/annotation-guide.md) documents executable prediction-blind packets, two annotators, raw agreement/kappa, adjudication/exclusions, immutable cluster splits and structured aspect/slice gold. Inputs need exact-file annotation permission. No real annotations were manufactured. `evaluation.calibration` scores only dev rows and fits temperature/coverage thresholds with explicit support requirements; it does not apply a deployment threshold. Human-label model selection, independent aspect evaluation and operational calibration remain blocked by approved representative data and human work. diff --git a/docs/evidence/demo-repeat.txt b/docs/evidence/demo-repeat.txt index 0082f4e..9904b99 100644 --- a/docs/evidence/demo-repeat.txt +++ b/docs/evidence/demo-repeat.txt @@ -1,11 +1,11 @@ { "schema_version": 2, "brand": "Netflix", - "run_id": "2c2f84ae-0c37-4198-a1a6-8809863aed11", + "run_id": "5a0e0390-90d1-4849-8193-d1b232768040", "status": "complete", "mode": "demo", "as_of": "2026-12-03T00:00:00+00:00", - "generated_at": "2026-12-04T13:34:44.751649+00:00", + "generated_at": "2026-12-04T15:50:49.043775+00:00", "period_start": "2026-11-26T00:00:00+00:00", "previous_start": "2026-11-19T00:00:00+00:00", "model_version": "e0b9225bc52c1d995ec487375f63d7b6685bfe8678ab82a8b0a70fd194caaa67", @@ -92,6 +92,11 @@ } ], "aspects": {}, + "aspect_status": { + "enabled": false, + "extractor_version": null, + "independent_quality": "unvalidated_without_human_gold" + }, "alerts": [], "monitoring": { "label_distribution_total_variation": 0.0, @@ -108,4 +113,4 @@ "No external alerts or LLM narrative were sent." ] } -{"run_id": "2c2f84ae-0c37-4198-a1a6-8809863aed11", "stage": "complete", "status": "complete", "counts": {"ingested": 12, "duplicate": 12, "inference_eligible": 0, "inference_failed": 0, "inference_abstained": 0}, "duration_seconds": 0.018879165989346802} +{"run_id": "5a0e0390-90d1-4849-8193-d1b232768040", "stage": "complete", "status": "complete", "counts": {"ingested": 12, "duplicate": 12, "inference_eligible": 0, "inference_failed": 0, "inference_abstained": 0}, "duration_seconds": 0.030458334018476307} diff --git a/docs/evidence/demo.txt b/docs/evidence/demo.txt index 257e1ab..0310db0 100644 --- a/docs/evidence/demo.txt +++ b/docs/evidence/demo.txt @@ -1,11 +1,11 @@ { "schema_version": 2, "brand": "Netflix", - "run_id": "259abbd3-73e3-44a6-bdb0-74bd8b02a497", + "run_id": "76da32e5-10e5-43de-ad7f-e3184946a5c9", "status": "complete", "mode": "demo", "as_of": "2026-12-03T00:00:00+00:00", - "generated_at": "2026-12-04T13:34:44.627913+00:00", + "generated_at": "2026-12-04T15:50:48.881407+00:00", "period_start": "2026-11-26T00:00:00+00:00", "previous_start": "2026-11-19T00:00:00+00:00", "model_version": "e0b9225bc52c1d995ec487375f63d7b6685bfe8678ab82a8b0a70fd194caaa67", @@ -92,6 +92,11 @@ } ], "aspects": {}, + "aspect_status": { + "enabled": false, + "extractor_version": null, + "independent_quality": "unvalidated_without_human_gold" + }, "alerts": [], "monitoring": { "label_distribution_total_variation": 0.0, @@ -108,4 +113,4 @@ "No external alerts or LLM narrative were sent." ] } -{"run_id": "259abbd3-73e3-44a6-bdb0-74bd8b02a497", "stage": "complete", "status": "complete", "counts": {"ingested": 12, "duplicate": 12, "inference_eligible": 0, "inference_failed": 0, "inference_abstained": 0}, "duration_seconds": 0.021645958011504263} +{"run_id": "76da32e5-10e5-43de-ad7f-e3184946a5c9", "stage": "complete", "status": "complete", "counts": {"ingested": 12, "duplicate": 12, "inference_eligible": 0, "inference_failed": 0, "inference_abstained": 0}, "duration_seconds": 0.02571570800500922} diff --git a/docs/evidence/format.txt b/docs/evidence/format.txt index 65ab9f6..c674baa 100644 --- a/docs/evidence/format.txt +++ b/docs/evidence/format.txt @@ -1 +1 @@ -64 files already formatted +82 files already formatted diff --git a/docs/evidence/linux-model-runtime-smoke.json b/docs/evidence/linux-model-runtime-smoke.json new file mode 100644 index 0000000..9371840 --- /dev/null +++ b/docs/evidence/linux-model-runtime-smoke.json @@ -0,0 +1,252 @@ +{ + "status": "passed", + "platform": "Linux-7.0.0-1020-azure-x86_64-with-glibc2.43", + "python": "3.11.18", + "torch": "2.15.0+cpu", + "device": "cpu", + "threads": 2, + "seconds": 24.845893278999995, + "weights_sha256": "8812932976c1a9f5668689b2675770aa63617a6370e12518b111825b84d0ffde", + "aspect_checkpoint": "yangheng/deberta-v3-base-end2end-absa@23e6d43431a5f96d8a7b7b9721d59bbda30cc63d:sha256=8812932976c1a9f5668689b2675770aa63617a6370e12518b111825b84d0ffde:tokens=256:bio=v1", + "data": "Original synthetic examples and authored fixture; no external source calls or human annotations", + "texts": [ + "The price is high, but the picture quality is excellent. Customer support is slow.", + "The user interface is easy to navigate, but the subscription price is terrible.", + "Caf\u00e9 prices are high. The picture quality is good \ud83d\ude0a." + ], + "results": [ + { + "format": "spans-v1", + "spans": [ + { + "start": 4, + "end": 9, + "term": "price", + "label": "NEUTRAL", + "category": "price", + "confidence": 0.47816845774650574, + "reason": null, + "token_probabilities": [ + { + "B-ASP-Unknown": 2.418299118289724e-05, + "B-ASP-Negative": 0.3433440029621124, + "B-ASP-Neutral": 0.47816845774650574, + "B-ASP-Positive": 0.0040168147534132, + "I-ASP-Unknown": 1.314482869929634e-05, + "I-ASP-Negative": 0.0005010050954297185, + "I-ASP-Neutral": 0.0003617318288888782, + "I-ASP-Positive": 6.458743155235425e-05, + "O": 0.17350605130195618 + } + ] + }, + { + "start": 27, + "end": 42, + "term": "picture quality", + "label": "NEUTRAL", + "category": "quality", + "confidence": 0.6913471817970276, + "reason": null, + "token_probabilities": [ + { + "B-ASP-Unknown": 7.2850834840210155e-06, + "B-ASP-Negative": 0.005060202907770872, + "B-ASP-Neutral": 0.7073107361793518, + "B-ASP-Positive": 0.24670130014419556, + "I-ASP-Unknown": 8.129686648317147e-06, + "I-ASP-Negative": 6.727177242282778e-05, + "I-ASP-Neutral": 0.0005984487943351269, + "I-ASP-Positive": 0.0004485032695811242, + "O": 0.03979797288775444 + }, + { + "B-ASP-Unknown": 7.318906682485249e-06, + "B-ASP-Negative": 5.785021130577661e-05, + "B-ASP-Neutral": 0.0009225470712408423, + "B-ASP-Positive": 0.00038670943467877805, + "I-ASP-Unknown": 2.0514247808023356e-05, + "I-ASP-Negative": 0.0024639952462166548, + "I-ASP-Neutral": 0.6753836274147034, + "I-ASP-Positive": 0.283291757106781, + "O": 0.037465620785951614 + } + ] + }, + { + "start": 57, + "end": 73, + "term": "Customer support", + "label": "NEUTRAL", + "category": "support", + "confidence": 0.6491008698940277, + "reason": null, + "token_probabilities": [ + { + "B-ASP-Unknown": 7.836706572561525e-06, + "B-ASP-Negative": 0.19053876399993896, + "B-ASP-Neutral": 0.7071362733840942, + "B-ASP-Positive": 0.008245520293712616, + "I-ASP-Unknown": 5.785775556432782e-06, + "I-ASP-Negative": 0.00037705854629166424, + "I-ASP-Neutral": 0.00045911723282188177, + "I-ASP-Positive": 0.00011032092879759148, + "O": 0.09311926364898682 + }, + { + "B-ASP-Unknown": 1.635894295759499e-05, + "B-ASP-Negative": 0.001896491041406989, + "B-ASP-Neutral": 0.003990799188613892, + "B-ASP-Positive": 0.00014254602137953043, + "I-ASP-Unknown": 2.2313626686809584e-05, + "I-ASP-Negative": 0.3213132619857788, + "I-ASP-Neutral": 0.5910654664039612, + "I-ASP-Positive": 0.007333023939281702, + "O": 0.07421969622373581 + } + ] + } + ], + "truncated": false, + "model_checkpoint": "yangheng/deberta-v3-base-end2end-absa@23e6d43431a5f96d8a7b7b9721d59bbda30cc63d:sha256=8812932976c1a9f5668689b2675770aa63617a6370e12518b111825b84d0ffde:tokens=256:bio=v1", + "token_count": 19, + "output_id": "151bb8257f213f6ae8ee484850227bb63cf8cbf68af8227f1270a3581c76a98c" + }, + { + "format": "spans-v1", + "spans": [ + { + "start": 4, + "end": 18, + "term": "user interface", + "label": "POSITIVE", + "category": "ux", + "confidence": 0.5056000202894211, + "reason": null, + "token_probabilities": [ + { + "B-ASP-Unknown": 1.5088052350620274e-05, + "B-ASP-Negative": 0.003915346227586269, + "B-ASP-Neutral": 0.3089539706707001, + "B-ASP-Positive": 0.5536556839942932, + "I-ASP-Unknown": 7.73653209762415e-06, + "I-ASP-Negative": 4.683665611082688e-05, + "I-ASP-Neutral": 0.00034465728094801307, + "I-ASP-Positive": 0.0007262045401148498, + "O": 0.13233451545238495 + }, + { + "B-ASP-Unknown": 1.7011761883622967e-05, + "B-ASP-Negative": 0.00020442625100258738, + "B-ASP-Neutral": 0.0025495970621705055, + "B-ASP-Positive": 0.001738173421472311, + "I-ASP-Unknown": 4.750766311190091e-05, + "I-ASP-Negative": 0.004183163400739431, + "I-ASP-Neutral": 0.4163796305656433, + "I-ASP-Positive": 0.45754435658454895, + "O": 0.11733616888523102 + } + ] + }, + { + "start": 48, + "end": 66, + "term": "subscription price", + "label": "NEGATIVE", + "category": "price", + "confidence": 0.44141218066215515, + "reason": null, + "token_probabilities": [ + { + "B-ASP-Unknown": 2.475900146237109e-05, + "B-ASP-Negative": 0.5045102834701538, + "B-ASP-Neutral": 0.2673546373844147, + "B-ASP-Positive": 0.007293012924492359, + "I-ASP-Unknown": 2.743006007221993e-05, + "I-ASP-Negative": 0.006033126264810562, + "I-ASP-Neutral": 0.00258550769649446, + "I-ASP-Positive": 0.0002476707741152495, + "O": 0.2119235247373581 + }, + { + "B-ASP-Unknown": 0.00016230564506258816, + "B-ASP-Negative": 0.014436455443501472, + "B-ASP-Neutral": 0.008267679251730442, + "B-ASP-Positive": 0.00042942556319758296, + "I-ASP-Unknown": 0.00012536351277958602, + "I-ASP-Negative": 0.3783140778541565, + "I-ASP-Neutral": 0.2470300793647766, + "I-ASP-Positive": 0.005698181688785553, + "O": 0.34553641080856323 + } + ] + } + ], + "truncated": false, + "model_checkpoint": "yangheng/deberta-v3-base-end2end-absa@23e6d43431a5f96d8a7b7b9721d59bbda30cc63d:sha256=8812932976c1a9f5668689b2675770aa63617a6370e12518b111825b84d0ffde:tokens=256:bio=v1", + "token_count": 17, + "output_id": "fe346247d83dfe77c1031680add4c12c71db6ae29a62ba2622902f017e7af591" + }, + { + "format": "spans-v1", + "spans": [ + { + "start": 26, + "end": 41, + "term": "picture quality", + "label": "POSITIVE", + "category": "quality", + "confidence": 0.6243826150894165, + "reason": null, + "token_probabilities": [ + { + "B-ASP-Unknown": 5.521918865269981e-06, + "B-ASP-Negative": 0.0010929646668955684, + "B-ASP-Neutral": 0.2208690345287323, + "B-ASP-Positive": 0.5939884781837463, + "I-ASP-Unknown": 4.3296713556628674e-06, + "I-ASP-Negative": 3.70525594917126e-05, + "I-ASP-Neutral": 0.0005194642581045628, + "I-ASP-Positive": 0.0016134942416101694, + "O": 0.18186970055103302 + }, + { + "B-ASP-Unknown": 6.619048235734226e-06, + "B-ASP-Negative": 8.54168101795949e-05, + "B-ASP-Neutral": 0.003076037857681513, + "B-ASP-Positive": 0.0023656096309423447, + "I-ASP-Unknown": 1.8628594261826947e-05, + "I-ASP-Negative": 0.0009820404229685664, + "I-ASP-Neutral": 0.23677510023117065, + "I-ASP-Positive": 0.6547767519950867, + "O": 0.10191384702920914 + } + ] + } + ], + "truncated": false, + "model_checkpoint": "yangheng/deberta-v3-base-end2end-absa@23e6d43431a5f96d8a7b7b9721d59bbda30cc63d:sha256=8812932976c1a9f5668689b2675770aa63617a6370e12518b111825b84d0ffde:tokens=256:bio=v1", + "token_count": 14, + "output_id": "dbd53852e06a3dfbb5947a5cd01abe376827f03d75831453f8b33ab72ca1be9c" + } + ], + "idempotent_database_counts": { + "mentions": 12, + "aspect_inference": 12, + "aspect_spans": 12 + }, + "aspect_status": { + "enabled": true, + "extractor_version": "yangheng/deberta-v3-base-end2end-absa@23e6d43431a5f96d8a7b7b9721d59bbda30cc63d:sha256=8812932976c1a9f5668689b2675770aa63617a6370e12518b111825b84d0ffde:tokens=256:bio=v1", + "independent_quality": "unvalidated_without_human_gold", + "mentions_processed": 12, + "mentions_without_spans": 0, + "truncated_mentions": 0, + "span_counts": { + "NEGATIVE": 5, + "NEUTRAL": 3, + "POSITIVE": 4 + } + }, + "quality_status": "Domain precision/recall/F1 unvalidated; smoke checks runtime, spans, persistence and repeat behavior only" +} diff --git a/docs/evidence/linux-synthetic-calibration.json b/docs/evidence/linux-synthetic-calibration.json new file mode 100644 index 0000000..9ca9520 --- /dev/null +++ b/docs/evidence/linux-synthetic-calibration.json @@ -0,0 +1,156 @@ +{ + "temperature": 0.5, + "abstention_threshold": 0.0, + "development_ids": [ + "dev-0", + "dev-1", + "dev-2" + ], + "n": 3, + "protocol": { + "minimum_coverage": 1.0, + "minimum_class_support": 1, + "temperature_grid": [ + 0.5, + 0.75, + 1.0, + 1.5, + 2.0, + 3.0 + ], + "temperature_objective": "development negative log likelihood", + "threshold_objective": "full-population macro F1 subject to predeclared coverage; ties favor coverage then lower threshold" + }, + "nll_before": 0.14687988891642614, + "nll_after": 0.02010075641935587, + "calibration_before": { + "n": 3, + "ece": 0.1361125111579895, + "brier": 0.0340127463310294, + "reliability": [ + { + "lower": 0.8, + "upper": 0.9, + "n": 3, + "confidence": 0.8638874888420105, + "accuracy": 1.0 + } + ], + "risk_coverage": [ + { + "coverage": 0.3333333333333333, + "risk": 0.0 + }, + { + "coverage": 0.6666666666666666, + "risk": 0.0 + }, + { + "coverage": 1.0, + "risk": 0.0 + } + ] + }, + "calibration_after": { + "n": 3, + "ece": 0.01983866955720026, + "brier": 0.0010049687349003333, + "reliability": [ + { + "lower": 0.9, + "upper": 1.0, + "n": 3, + "confidence": 0.9801613304427997, + "accuracy": 1.0 + } + ], + "risk_coverage": [ + { + "coverage": 0.3333333333333333, + "risk": 0.0 + }, + { + "coverage": 0.6666666666666666, + "risk": 0.0 + }, + { + "coverage": 1.0, + "risk": 0.0 + } + ] + }, + "selected_development_metrics": { + "n": 3, + "accuracy": 1.0, + "accepted_accuracy": 1.0, + "macro_f1": 1.0, + "weighted_f1": 1.0, + "balanced_accuracy": 1.0, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 1 + }, + "NEUTRAL": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 1 + }, + "POSITIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 1 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 1, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 1, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 1, + 0, + 0, + 0 + ] + ] + }, + "independent_test_status": "not evaluated by this fitting function", + "synthetic": true, + "status": "software_smoke_only_not_an_operational_threshold" +} diff --git a/docs/evidence/linux-synthetic-model-evaluation.json b/docs/evidence/linux-synthetic-model-evaluation.json new file mode 100644 index 0000000..a1dc8a3 --- /dev/null +++ b/docs/evidence/linux-synthetic-model-evaluation.json @@ -0,0 +1,5103 @@ +{ + "manifest": { + "dataset_sha256": "a55b33d2252494e84a75b3be64bd5a3edcc2a3094b961084136ca6eb496cc81c", + "seed": 42, + "execution_date": "2026-12-04T15:53:05.306890+00:00", + "platform": "Linux-7.0.0-1020-azure-x86_64-with-glibc2.43", + "python": "3.11.18", + "synthetic": true, + "provenance": "Authored synthetic software fixture; no human annotation or generalization claim", + "label_source": "synthetic authorship", + "population": null, + "split_ids": { + "train": [ + "train-0", + "train-1", + "train-2", + "train-3", + "train-4", + "train-5", + "train-6", + "train-7", + "train-8", + "train-9", + "train-10", + "train-11" + ], + "dev": [ + "dev-0", + "dev-1", + "dev-2" + ], + "test": [ + "test-0", + "test-1", + "test-2", + "test-3", + "test-4", + "test-5" + ] + }, + "development_scores": { + "None": 0.5555555555555555, + "balanced": 0.5555555555555555 + }, + "selected_weight": "None", + "timing": { + "train_majority": { + "seconds_including_load": 7.280999994918602e-06, + "version": "train-majority-v1" + }, + "tfidf_logistic": { + "seconds_including_load": 0.0006972649999994474, + "version": "tfidf-logistic-seed42-weight=None" + }, + "synthetic_stub": { + "seconds_including_load": 0.000235566000000631, + "version": "synthetic-lexicon-v1" + }, + "binary_sst2": { + "seconds_including_load": 5.737245985000001, + "version": "distilbert/distilbert-base-uncased-finetuned-sst-2-english@714eb0fa89d2f80546fda750413ed43d93601a13:tokens=256:preprocess=v2" + }, + "three_class_roberta": { + "seconds_including_load": 5.559635177999979, + "version": "cardiffnlp/twitter-roberta-base-sentiment-latest@3216a57f2a0d9c45a2e6c20157c20c49fb4bf9c7:tokens=256:preprocess=v2" + } + }, + "threshold": { + "three_class": 0, + "binary": 0.75, + "note": "binary historical setting; no threshold optimized on test" + } + }, + "metrics": { + "train_majority": { + "n": 6, + "accuracy": 0.3333333333333333, + "accepted_accuracy": 0.3333333333333333, + "macro_f1": 0.16666666666666666, + "weighted_f1": 0.16666666666666666, + "balanced_accuracy": 0.3333333333333333, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": 0.0, + "f1": 0.0, + "support": 2 + }, + "NEUTRAL": { + "precision": null, + "recall": 0.0, + "f1": 0.0, + "support": 2 + }, + "POSITIVE": { + "precision": 0.3333333333333333, + "recall": 1.0, + "f1": 0.5, + "support": 2 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 2, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ] + ], + "calibration": { + "n": 6, + "ece": 0.6666666666666666, + "brier": 1.3333333333333333, + "reliability": [ + { + "lower": 0.9, + "upper": 1.0, + "n": 6, + "confidence": 1.0, + "accuracy": 0.3333333333333333 + } + ], + "risk_coverage": [ + { + "coverage": 0.16666666666666666, + "risk": 0.0 + }, + { + "coverage": 0.3333333333333333, + "risk": 0.5 + }, + { + "coverage": 0.5, + "risk": 0.6666666666666667 + }, + { + "coverage": 0.6666666666666666, + "risk": 0.5 + }, + { + "coverage": 0.8333333333333334, + "risk": 0.6 + }, + { + "coverage": 1.0, + "risk": 0.6666666666666667 + } + ] + }, + "by_source": { + "fixture": { + "n": 6, + "accuracy": 0.3333333333333333, + "accepted_accuracy": 0.3333333333333333, + "macro_f1": 0.16666666666666666, + "weighted_f1": 0.16666666666666666, + "balanced_accuracy": 0.3333333333333333, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": 0.0, + "f1": 0.0, + "support": 2 + }, + "NEUTRAL": { + "precision": null, + "recall": 0.0, + "f1": 0.0, + "support": 2 + }, + "POSITIVE": { + "precision": 0.3333333333333333, + "recall": 1.0, + "f1": 0.5, + "support": 2 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 2, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ] + ] + } + }, + "by_language": { + "en": { + "n": 6, + "accuracy": 0.3333333333333333, + "accepted_accuracy": 0.3333333333333333, + "macro_f1": 0.16666666666666666, + "weighted_f1": 0.16666666666666666, + "balanced_accuracy": 0.3333333333333333, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": 0.0, + "f1": 0.0, + "support": 2 + }, + "NEUTRAL": { + "precision": null, + "recall": 0.0, + "f1": 0.0, + "support": 2 + }, + "POSITIVE": { + "precision": 0.3333333333333333, + "recall": 1.0, + "f1": 0.5, + "support": 2 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 2, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ] + ] + } + }, + "error_slices": { + "neutral": { + "n": 2, + "accuracy": 0.0, + "accepted_accuracy": 0.0, + "macro_f1": 0.0, + "weighted_f1": 0.0, + "balanced_accuracy": 0.0, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": 0.0, + "f1": 0.0, + "support": 2 + }, + "POSITIVE": { + "precision": 0.0, + "recall": null, + "f1": 0.0, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "mixed": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "sarcasm": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "negation": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "short": { + "n": 6, + "accuracy": 0.3333333333333333, + "accepted_accuracy": 0.3333333333333333, + "macro_f1": 0.16666666666666666, + "weighted_f1": 0.16666666666666666, + "balanced_accuracy": 0.3333333333333333, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": 0.0, + "f1": 0.0, + "support": 2 + }, + "NEUTRAL": { + "precision": null, + "recall": 0.0, + "f1": 0.0, + "support": 2 + }, + "POSITIVE": { + "precision": 0.3333333333333333, + "recall": 1.0, + "f1": 0.5, + "support": 2 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 2, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ] + ] + }, + "long": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "source_shift": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "unsupported_language": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + } + } + }, + "tfidf_logistic": { + "n": 6, + "accuracy": 1.0, + "accepted_accuracy": 1.0, + "macro_f1": 1.0, + "weighted_f1": 1.0, + "balanced_accuracy": 1.0, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "NEUTRAL": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "POSITIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 2, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 2, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ] + ], + "calibration": { + "n": 6, + "ece": 0.5555208301824511, + "brier": 0.46590857859024587, + "reliability": [ + { + "lower": 0.3, + "upper": 0.4, + "n": 2, + "confidence": 0.39895875139231973, + "accuracy": 1.0 + }, + { + "lower": 0.4, + "upper": 0.5, + "n": 3, + "confidence": 0.4527472261161349, + "accuracy": 1.0 + }, + { + "lower": 0.5, + "upper": 0.6, + "n": 1, + "confidence": 0.5107158377722492, + "accuracy": 1.0 + } + ], + "risk_coverage": [ + { + "coverage": 0.16666666666666666, + "risk": 0.0 + }, + { + "coverage": 0.3333333333333333, + "risk": 0.0 + }, + { + "coverage": 0.5, + "risk": 0.0 + }, + { + "coverage": 0.6666666666666666, + "risk": 0.0 + }, + { + "coverage": 0.8333333333333334, + "risk": 0.0 + }, + { + "coverage": 1.0, + "risk": 0.0 + } + ] + }, + "by_source": { + "fixture": { + "n": 6, + "accuracy": 1.0, + "accepted_accuracy": 1.0, + "macro_f1": 1.0, + "weighted_f1": 1.0, + "balanced_accuracy": 1.0, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "NEUTRAL": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "POSITIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 2, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 2, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ] + ] + } + }, + "by_language": { + "en": { + "n": 6, + "accuracy": 1.0, + "accepted_accuracy": 1.0, + "macro_f1": 1.0, + "weighted_f1": 1.0, + "balanced_accuracy": 1.0, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "NEUTRAL": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "POSITIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 2, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 2, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ] + ] + } + }, + "error_slices": { + "neutral": { + "n": 2, + "accuracy": 1.0, + "accepted_accuracy": 1.0, + "macro_f1": 1.0, + "weighted_f1": 1.0, + "balanced_accuracy": 1.0, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 2, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "mixed": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "sarcasm": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "negation": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "short": { + "n": 6, + "accuracy": 1.0, + "accepted_accuracy": 1.0, + "macro_f1": 1.0, + "weighted_f1": 1.0, + "balanced_accuracy": 1.0, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "NEUTRAL": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "POSITIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 2, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 2, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ] + ] + }, + "long": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "source_shift": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "unsupported_language": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + } + } + }, + "synthetic_stub": { + "n": 6, + "accuracy": 1.0, + "accepted_accuracy": 1.0, + "macro_f1": 1.0, + "weighted_f1": 1.0, + "balanced_accuracy": 1.0, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "NEUTRAL": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "POSITIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 2, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 2, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ] + ], + "calibration": { + "n": 6, + "ece": 0.20000000000000007, + "brier": 0.05999999999999999, + "reliability": [ + { + "lower": 0.8, + "upper": 0.9, + "n": 6, + "confidence": 0.7999999999999999, + "accuracy": 1.0 + } + ], + "risk_coverage": [ + { + "coverage": 0.16666666666666666, + "risk": 0.0 + }, + { + "coverage": 0.3333333333333333, + "risk": 0.0 + }, + { + "coverage": 0.5, + "risk": 0.0 + }, + { + "coverage": 0.6666666666666666, + "risk": 0.0 + }, + { + "coverage": 0.8333333333333334, + "risk": 0.0 + }, + { + "coverage": 1.0, + "risk": 0.0 + } + ] + }, + "by_source": { + "fixture": { + "n": 6, + "accuracy": 1.0, + "accepted_accuracy": 1.0, + "macro_f1": 1.0, + "weighted_f1": 1.0, + "balanced_accuracy": 1.0, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "NEUTRAL": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "POSITIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 2, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 2, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ] + ] + } + }, + "by_language": { + "en": { + "n": 6, + "accuracy": 1.0, + "accepted_accuracy": 1.0, + "macro_f1": 1.0, + "weighted_f1": 1.0, + "balanced_accuracy": 1.0, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "NEUTRAL": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "POSITIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 2, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 2, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ] + ] + } + }, + "error_slices": { + "neutral": { + "n": 2, + "accuracy": 1.0, + "accepted_accuracy": 1.0, + "macro_f1": 1.0, + "weighted_f1": 1.0, + "balanced_accuracy": 1.0, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 2, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "mixed": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "sarcasm": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "negation": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "short": { + "n": 6, + "accuracy": 1.0, + "accepted_accuracy": 1.0, + "macro_f1": 1.0, + "weighted_f1": 1.0, + "balanced_accuracy": 1.0, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "NEUTRAL": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "POSITIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 2, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 2, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ] + ] + }, + "long": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "source_shift": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "unsupported_language": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + } + } + }, + "binary_sst2_legacy_heuristic": { + "n": 6, + "accuracy": 0.6666666666666666, + "accepted_accuracy": 0.6666666666666666, + "macro_f1": 0.5555555555555555, + "weighted_f1": 0.5555555555555555, + "balanced_accuracy": 0.6666666666666666, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "NEUTRAL": { + "precision": null, + "recall": 0.0, + "f1": 0.0, + "support": 2 + }, + "POSITIVE": { + "precision": 0.5, + "recall": 1.0, + "f1": 0.6666666666666666, + "support": 2 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 2, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ] + ], + "calibration": { + "n": 0, + "ece": null, + "brier": null, + "reliability": [], + "risk_coverage": [] + }, + "by_source": { + "fixture": { + "n": 6, + "accuracy": 0.6666666666666666, + "accepted_accuracy": 0.6666666666666666, + "macro_f1": 0.5555555555555555, + "weighted_f1": 0.5555555555555555, + "balanced_accuracy": 0.6666666666666666, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "NEUTRAL": { + "precision": null, + "recall": 0.0, + "f1": 0.0, + "support": 2 + }, + "POSITIVE": { + "precision": 0.5, + "recall": 1.0, + "f1": 0.6666666666666666, + "support": 2 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 2, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ] + ] + } + }, + "by_language": { + "en": { + "n": 6, + "accuracy": 0.6666666666666666, + "accepted_accuracy": 0.6666666666666666, + "macro_f1": 0.5555555555555555, + "weighted_f1": 0.5555555555555555, + "balanced_accuracy": 0.6666666666666666, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "NEUTRAL": { + "precision": null, + "recall": 0.0, + "f1": 0.0, + "support": 2 + }, + "POSITIVE": { + "precision": 0.5, + "recall": 1.0, + "f1": 0.6666666666666666, + "support": 2 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 2, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ] + ] + } + }, + "error_slices": { + "neutral": { + "n": 2, + "accuracy": 0.0, + "accepted_accuracy": 0.0, + "macro_f1": 0.0, + "weighted_f1": 0.0, + "balanced_accuracy": 0.0, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": 0.0, + "f1": 0.0, + "support": 2 + }, + "POSITIVE": { + "precision": 0.0, + "recall": null, + "f1": 0.0, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "mixed": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "sarcasm": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "negation": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "short": { + "n": 6, + "accuracy": 0.6666666666666666, + "accepted_accuracy": 0.6666666666666666, + "macro_f1": 0.5555555555555555, + "weighted_f1": 0.5555555555555555, + "balanced_accuracy": 0.6666666666666666, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "NEUTRAL": { + "precision": null, + "recall": 0.0, + "f1": 0.0, + "support": 2 + }, + "POSITIVE": { + "precision": 0.5, + "recall": 1.0, + "f1": 0.6666666666666666, + "support": 2 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 2, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ] + ] + }, + "long": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "source_shift": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "unsupported_language": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + } + } + }, + "binary_sst2": { + "n": 6, + "accuracy": 0.6666666666666666, + "accepted_accuracy": 0.6666666666666666, + "macro_f1": 0.5555555555555555, + "weighted_f1": 0.5555555555555555, + "balanced_accuracy": 0.6666666666666666, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "NEUTRAL": { + "precision": null, + "recall": 0.0, + "f1": 0.0, + "support": 2 + }, + "POSITIVE": { + "precision": 0.5, + "recall": 1.0, + "f1": 0.6666666666666666, + "support": 2 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 2, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ] + ], + "calibration": { + "n": 6, + "ece": 0.32572801907857263, + "brier": 0.6521626509933715, + "reliability": [ + { + "lower": 0.9, + "upper": 1.0, + "n": 6, + "confidence": 0.9923946857452393, + "accuracy": 0.6666666666666666 + } + ], + "risk_coverage": [ + { + "coverage": 0.16666666666666666, + "risk": 0.0 + }, + { + "coverage": 0.3333333333333333, + "risk": 0.0 + }, + { + "coverage": 0.5, + "risk": 0.0 + }, + { + "coverage": 0.6666666666666666, + "risk": 0.0 + }, + { + "coverage": 0.8333333333333334, + "risk": 0.19999999999999996 + }, + { + "coverage": 1.0, + "risk": 0.33333333333333337 + } + ] + }, + "by_source": { + "fixture": { + "n": 6, + "accuracy": 0.6666666666666666, + "accepted_accuracy": 0.6666666666666666, + "macro_f1": 0.5555555555555555, + "weighted_f1": 0.5555555555555555, + "balanced_accuracy": 0.6666666666666666, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "NEUTRAL": { + "precision": null, + "recall": 0.0, + "f1": 0.0, + "support": 2 + }, + "POSITIVE": { + "precision": 0.5, + "recall": 1.0, + "f1": 0.6666666666666666, + "support": 2 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 2, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ] + ] + } + }, + "by_language": { + "en": { + "n": 6, + "accuracy": 0.6666666666666666, + "accepted_accuracy": 0.6666666666666666, + "macro_f1": 0.5555555555555555, + "weighted_f1": 0.5555555555555555, + "balanced_accuracy": 0.6666666666666666, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "NEUTRAL": { + "precision": null, + "recall": 0.0, + "f1": 0.0, + "support": 2 + }, + "POSITIVE": { + "precision": 0.5, + "recall": 1.0, + "f1": 0.6666666666666666, + "support": 2 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 2, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ] + ] + } + }, + "error_slices": { + "neutral": { + "n": 2, + "accuracy": 0.0, + "accepted_accuracy": 0.0, + "macro_f1": 0.0, + "weighted_f1": 0.0, + "balanced_accuracy": 0.0, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": 0.0, + "f1": 0.0, + "support": 2 + }, + "POSITIVE": { + "precision": 0.0, + "recall": null, + "f1": 0.0, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "mixed": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "sarcasm": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "negation": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "short": { + "n": 6, + "accuracy": 0.6666666666666666, + "accepted_accuracy": 0.6666666666666666, + "macro_f1": 0.5555555555555555, + "weighted_f1": 0.5555555555555555, + "balanced_accuracy": 0.6666666666666666, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "NEUTRAL": { + "precision": null, + "recall": 0.0, + "f1": 0.0, + "support": 2 + }, + "POSITIVE": { + "precision": 0.5, + "recall": 1.0, + "f1": 0.6666666666666666, + "support": 2 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 2, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ] + ] + }, + "long": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "source_shift": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "unsupported_language": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + } + } + }, + "three_class_roberta": { + "n": 6, + "accuracy": 1.0, + "accepted_accuracy": 1.0, + "macro_f1": 1.0, + "weighted_f1": 1.0, + "balanced_accuracy": 1.0, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "NEUTRAL": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "POSITIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 2, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 2, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ] + ], + "calibration": { + "n": 6, + "ece": 0.09719387690226237, + "brier": 0.016747521843533154, + "reliability": [ + { + "lower": 0.8, + "upper": 0.9, + "n": 2, + "confidence": 0.8773524463176727, + "accuracy": 1.0 + }, + { + "lower": 0.9, + "upper": 1.0, + "n": 4, + "confidence": 0.9155329614877701, + "accuracy": 1.0 + } + ], + "risk_coverage": [ + { + "coverage": 0.16666666666666666, + "risk": 0.0 + }, + { + "coverage": 0.3333333333333333, + "risk": 0.0 + }, + { + "coverage": 0.5, + "risk": 0.0 + }, + { + "coverage": 0.6666666666666666, + "risk": 0.0 + }, + { + "coverage": 0.8333333333333334, + "risk": 0.0 + }, + { + "coverage": 1.0, + "risk": 0.0 + } + ] + }, + "by_source": { + "fixture": { + "n": 6, + "accuracy": 1.0, + "accepted_accuracy": 1.0, + "macro_f1": 1.0, + "weighted_f1": 1.0, + "balanced_accuracy": 1.0, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "NEUTRAL": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "POSITIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 2, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 2, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ] + ] + } + }, + "by_language": { + "en": { + "n": 6, + "accuracy": 1.0, + "accepted_accuracy": 1.0, + "macro_f1": 1.0, + "weighted_f1": 1.0, + "balanced_accuracy": 1.0, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "NEUTRAL": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "POSITIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 2, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 2, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ] + ] + } + }, + "error_slices": { + "neutral": { + "n": 2, + "accuracy": 1.0, + "accepted_accuracy": 1.0, + "macro_f1": 1.0, + "weighted_f1": 1.0, + "balanced_accuracy": 1.0, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 2, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "mixed": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "sarcasm": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "negation": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "short": { + "n": 6, + "accuracy": 1.0, + "accepted_accuracy": 1.0, + "macro_f1": 1.0, + "weighted_f1": 1.0, + "balanced_accuracy": 1.0, + "coverage": 1.0, + "abstention_rate": 0.0, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "NEUTRAL": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + }, + "POSITIVE": { + "precision": 1.0, + "recall": 1.0, + "f1": 1.0, + "support": 2 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 2, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 2, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 2, + 0, + 0, + 0 + ] + ] + }, + "long": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "source_shift": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + }, + "unsupported_language": { + "n": 0, + "accuracy": null, + "accepted_accuracy": null, + "macro_f1": null, + "weighted_f1": null, + "balanced_accuracy": null, + "coverage": null, + "abstention_rate": null, + "missing": 0, + "failed": 0, + "per_class": { + "NEGATIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "NEUTRAL": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + }, + "POSITIVE": { + "precision": null, + "recall": null, + "f1": null, + "support": 0 + } + }, + "labels": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE" + ], + "prediction_columns": [ + "NEGATIVE", + "NEUTRAL", + "POSITIVE", + "ABSTAIN", + "ERROR", + "MISSING" + ], + "confusion_matrix": [ + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0 + ] + ] + } + } + } + }, + "paired_comparison": { + "tfidf_logistic": { + "n": 6, + "clusters": 6, + "seed": 42, + "repeats": 500, + "accuracy_delta": 0.6666666666666667, + "accuracy_delta_ci95": [ + 0.33333333333333337, + 1.0 + ], + "macro_f1_delta_ci95": [ + 0.6, + 1.0 + ] + }, + "synthetic_stub": { + "n": 6, + "clusters": 6, + "seed": 42, + "repeats": 500, + "accuracy_delta": 0.6666666666666667, + "accuracy_delta_ci95": [ + 0.33333333333333337, + 1.0 + ], + "macro_f1_delta_ci95": [ + 0.6, + 1.0 + ] + }, + "binary_sst2_legacy_heuristic": { + "n": 6, + "clusters": 6, + "seed": 42, + "repeats": 500, + "accuracy_delta": 0.3333333333333333, + "accuracy_delta_ci95": [ + 0.0, + 0.6666666666666667 + ], + "macro_f1_delta_ci95": [ + 0.0, + 0.75 + ] + }, + "binary_sst2": { + "n": 6, + "clusters": 6, + "seed": 42, + "repeats": 500, + "accuracy_delta": 0.3333333333333333, + "accuracy_delta_ci95": [ + 0.0, + 0.6666666666666667 + ], + "macro_f1_delta_ci95": [ + 0.0, + 0.75 + ] + }, + "three_class_roberta": { + "n": 6, + "clusters": 6, + "seed": 42, + "repeats": 500, + "accuracy_delta": 0.6666666666666667, + "accuracy_delta_ci95": [ + 0.33333333333333337, + 1.0 + ], + "macro_f1_delta_ci95": [ + 0.6, + 1.0 + ] + } + } +} diff --git a/docs/evidence/readiness-verification.json b/docs/evidence/readiness-verification.json new file mode 100644 index 0000000..85a5bcb --- /dev/null +++ b/docs/evidence/readiness-verification.json @@ -0,0 +1,93 @@ +{ + "branch": "codex/flagship-upgrade", + "reviewed_source_commit": "f0bdabdf63166a4db43d5d3300a0144dbdba7fe5", + "local_verification": { + "tests": 58, + "covered_statements": 1712, + "total_statements": 2076, + "percent": 82.46628131021194, + "all_eight_verify_checks_exit": 0, + "evidence": "docs/evidence/verification-commands.json" + }, + "checks": { + "diff_check": "passed", + "documentation_links": "passed", + "historical_protected_paths_diff": "empty", + "source_permissions_approved": 0, + "new_human_annotations": 0, + "code_license": "owner_deferred", + "public_deployed": false, + "scoped_secret_findings": 0 + }, + "hosted": [ + { + "commit": "43265642666a67e482c14c40a5fd30bdaab23446", + "run": 47368002869, + "kind": "ci", + "conclusion": "success", + "jobs": [ + 145162964503, + 145162965155 + ] + }, + { + "commit": "43265642666a67e482c14c40a5fd30bdaab23446", + "run": 47368002836, + "kind": "real_models", + "conclusion": "failure", + "reason": "CPU Torch index lookup failed; no models ran" + }, + { + "commit": "d07ae9863693b9d30feb6e966c24af593926f915", + "run": 47368706433, + "kind": "real_models", + "conclusion": "success", + "job": 145165450288, + "artifact": 15859166721 + }, + { + "commit": "ec1c752587b2f65e73e90a7a34f2681d8f32c22b", + "run": 47368738326, + "kind": "ci", + "conclusion": "success", + "jobs": [ + 145165703030, + 145165703576 + ] + }, + { + "commit": "f0bdabdf63166a4db43d5d3300a0144dbdba7fe5", + "run": 47369365445, + "kind": "ci", + "conclusion": "success", + "jobs": [ + 145167777904, + 145167778430 + ], + "tests": 58, + "covered_statements": 1713, + "total_statements": 2076 + }, + { + "commit": "f0bdabdf63166a4db43d5d3300a0144dbdba7fe5", + "run": 47369365507, + "kind": "real_models", + "conclusion": "success", + "job": 145167778689, + "artifact": 15859152677, + "artifact_zip_sha256": "3b356f0d03841710e33c4eb1610d4fadb368fe19e24d6ea25abaed5fddba6672" + } + ], + "notes": [ + "Model smoke inputs are authored synthetic examples, not independent human gold.", + "Source permission manifests record owner evidence; no rights approval was granted.", + "Worker Linux lock correction uses an official direct CPU wheel URL and published hash." + ], + "artifact_sha256": { + "linux-model-runtime-smoke.json": "357f504e1142b9034fc90802b6a9e1e35a6a7ccabd870598d509de822e9aadaa", + "linux-synthetic-calibration.json": "cce57d8043d0ba0064314e240d11fc4deaacbc020f1a2f738353923088432392", + "linux-synthetic-model-evaluation.json": "24732bc2eb2dea84e4ae7b3eb1a91a1848cac480714fb1352bdc3c1aa9b3fa90", + "release-bundle-manifest.json": "7fe2e166b68661d988b000a9faf2bf40c223be84c3480f1f6a87f0cc07293262", + "release-bundle-verification.json": "a982ba820cd04c3c7089b939ae014e29e06e76cd976c3ae4bb486f2c3bf578e1" + } +} diff --git a/docs/evidence/release-bundle-manifest.json b/docs/evidence/release-bundle-manifest.json new file mode 100644 index 0000000..0856e58 --- /dev/null +++ b/docs/evidence/release-bundle-manifest.json @@ -0,0 +1,73 @@ +{ + "schema_version": 1, + "status": "prepared_not_approved_or_deployed", + "source_commit": "f0bdabdf63166a4db43d5d3300a0144dbdba7fe5", + "mode": "demo", + "run_id": "9e37d2af-7936-469a-b58c-1980bb8053a6", + "base_image": "python:3.11-slim@sha256:7032841967d07aa3353905945dc186901c89b6b319c61425f4439f677a4a8a34", + "model_checkpoint": "synthetic-lexicon-v1", + "raw_mentions": 0, + "uid": 10001, + "files": { + ".dockerignore": "a898fcffdfcb907badfba1025f600059c2d7fdc677ee033536945d0196616bf6", + "Dockerfile": "fec288c5f5d0b5f8f364bf3e1070d6583ffcf48a1e9f365d4d91e794c111b70a", + "snapshot.db": "9d96ddfc1767dc839cd50e819142bcadfcd520b50df093a85c44b070c5d26ced", + "source/analytics/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "source/analytics/aggregator.py": "318907e90bbce081c98587f0372b19ccdc6e2827d2cbb3ab41b479ac352f71b8", + "source/analytics/alert_engine.py": "f3f92db821365ca6fa45965c5ad94168f8b2b5c4ef87c4197d7ab3577c92fe30", + "source/analytics/health_score.py": "29fc6e54391fd27e7cf865710496bd7480d3a257ad5ff42051f6438dfab51140", + "source/analytics/monitoring.py": "d516172a8cdd30fbb6bc6ea226a77156d93d16a792cf1936f143c12974362619", + "source/analytics/trend_detector.py": "30d264b4f6865e4919f42ba2c600be8064cace4323423f4b7c6a24cdfe1b738e", + "source/api/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "source/api/main.py": "a16be67c2959577aa01bffb66eccd2107f06970c8fef83ba24d3cbde52d3a971", + "source/config.py": "96540dcfc027a36c35668b4041dd755717f56edb1bdce707ff04d551d597a333", + "source/database.py": "94d5231c8080564f443162c14806dd70004ea5a2b7fb205d2e7a37510b01e163", + "source/evaluation/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "source/evaluation/annotation.py": "464f885ccde0b29f4ca83c79ec3fa4c0782a7db4f8738f430d933ccfc4121348", + "source/evaluation/annotation_workflow.py": "9937766b16742ce0dbb387b38c4788b6c61c12bab3035408440517cceb51cf85", + "source/evaluation/calibration.py": "2beaa9ea3e47a829c130b0a2ae522c938bc7026fe26672b34cfa1473f30f855d", + "source/evaluation/fixture.json": "a55b33d2252494e84a75b3be64bd5a3edcc2a3094b961084136ca6eb496cc81c", + "source/evaluation/prepare_legacy.py": "6aff683a0babd3fff2017de215b5f31d7bd03caeeba15eda0bde5edc9681d2f0", + "source/evaluation/prepare_weak.py": "10e7df529920445f2b504447b28912473362b2851f5b9d44907cd92d4fffb4ad", + "source/nlp/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "source/nlp/aspect_registry.json": "00991a01a693817ad99e5dd3a6b440a73392be354ce6fd475cfc65d14cd9ccdd", + "source/nlp/aspects.py": "0e8bf59239b59b21fd73c2dd55d5d66854b785a161211806cef0c982b9ff3b78", + "source/nlp/evaluator.py": "c9f928b264f2832551536b15ce09079d87c2a43b3e264dca406791ee5ece6a82", + "source/nlp/model_registry.json": "828e537abb3fa16ba4050eae1bb67cc200e1f00af95a1a831b19d6e9b5a1caea", + "source/nlp/sentiment_engine.py": "9f601718c269c4275a8320d3daffb51ac3283606d8141528b1ab213deee7f651", + "source/nlp/taxonomy.py": "a0dcd6ba54f81b7d31e6d9adc2576e2aab168868e883ef0979c5f832df07d1d5", + "source/pipeline/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "source/pipeline/base_image.json": "6d942753477c015e852274c56554a72a46c8a09372d0a041d653c82e3f7c2538", + "source/pipeline/cli.py": "75012251c428ee3b10c244018b7a1f9c29a446ce3d1211f7b381df81f322a1ed", + "source/pipeline/contracts.py": "d4c34cab63e72c7759e965565f10647a461cb55b49fb1841749da0a45fb6b3ee", + "source/pipeline/fixtures/demo.json": "b98ad38a551a804c3c3505bec732c3aa736560e5a37d81ab47d0fec82a3893ac", + "source/pipeline/permissions.py": "fb7a46f0ba53e119d5e4cd797a1c5475acc477d81069eb590edb219be786f9ae", + "source/pipeline/prefect_flow.py": "8212e135d9f8679b05b4e06cf4f67812bfaa44e4f72b680291b60adf0625f02e", + "source/pipeline/publication.py": "07924bd62df0e634009d74a5eb7907963ff9fad1a1684bffded3e0e186a69b72", + "source/pipeline/release.py": "63ff8f6b367d7e6408f6c1469cbbf88deae51eb257942e1219df568e2f33de29", + "source/pipeline/runner.py": "4154946d3420993a16009d7edaddf6cc85decd7e52a852c391a39dbf59544ad3", + "source/pyproject.toml": "0b61347d4e9fd77f7d91cdb663072fdf89c6d4437fd197ba3afea34d5d859dd4", + "source/reports/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "source/reports/chart_generator.py": "e9f609667e1ce8784f29e1ab3a69d7be10afbc5b3904f0401304a1b194634386", + "source/reports/render_template.py": "fe2bcbd7979292b7ea88caa5a63feac87cc55de839e448dbcd5db55cda8e5ee3", + "source/reports/report_generator.py": "a3bc17b9bf8bb46b9bf39e184250de9ba7a7ef9cf876b248afdf92bca38c6ba4", + "source/reports/templates/weekly.html": "40fbe4898aaf3966188a9ccb63e8e8aef9d19651edbeacdb57a2790bf8e91a00", + "source/requirements.lock": "d5cf6bc4a7bc1e30c884571fc4e5a64e03692f8bc2b17e7e713a2f698355397a", + "source/scrapers/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "source/scrapers/news_scraper.py": "20a9fd3f220b00c0724f6cccc10f4dcea5c008c0a3603f037997854a7eabbfc2", + "source/scrapers/normalizer.py": "09a0c7e4c995aafe3236a3b3ae618adbc296b2f2899ef68284e3aa9766d94ca3", + "source/scrapers/reddit_scraper.py": "0efb04e605ef9b3f8bc490feebeaa83d1b7ee1601845ddb3d99e0a573b228662", + "source/scrapers/review_scraper.py": "a539a7c266e0a9208dd25012663f8e19864bc2e6534f9e22c331c988c28ef23f", + "summary.json": "92c3fa7a5170a282588e8fd80c99a56bda8d3fef46278fee2869d8e9910e5896" + }, + "owner_gates": [ + "Approve target account/service and explicit public deployment", + "Code license intentionally undecided; owner retains that decision", + "Live source permissions remain pending; this bundle contains only synthetic aggregates" + ], + "commands": { + "verify": "brand-pipeline verify-release --directory .", + "build": "docker build -t brand-reputation:review .", + "local_run": "docker run --rm -p 127.0.0.1:8000:8000 brand-reputation:review" + } +} diff --git a/docs/evidence/release-bundle-verification.json b/docs/evidence/release-bundle-verification.json new file mode 100644 index 0000000..2d4bec6 --- /dev/null +++ b/docs/evidence/release-bundle-verification.json @@ -0,0 +1,7 @@ +{ + "status": "verified", + "run_id": "9e37d2af-7936-469a-b58c-1980bb8053a6", + "files": 50, + "raw_rows": 0, + "deployed": false +} diff --git a/docs/evidence/tests.txt b/docs/evidence/tests.txt index 2470b82..cd72ac3 100644 --- a/docs/evidence/tests.txt +++ b/docs/evidence/tests.txt @@ -4,50 +4,65 @@ rootdir: /Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline configfile: pyproject.toml testpaths: tests plugins: cov-7.1.0, platformdirs-4.14.9, anyio-4.16.0 -collected 40 items +collected 58 items -tests/integration/test_evaluation_cli.py .. [ 5%] -tests/integration/test_pipeline_api.py ............. [ 37%] -tests/unit/test_alerts.py .. [ 42%] -tests/unit/test_analytics_reports.py ... [ 50%] +tests/integration/test_evaluation_cli.py .. [ 3%] +tests/integration/test_pipeline_api.py .............. [ 27%] +tests/integration/test_release_bundle.py .. [ 31%] +tests/unit/test_alerts.py .. [ 34%] +tests/unit/test_analytics_reports.py ... [ 39%] +tests/unit/test_annotation_workflow.py ..... [ 48%] +tests/unit/test_aspects.py ... [ 53%] +tests/unit/test_calibration_protocol.py ... [ 58%] tests/unit/test_contracts.py ........... [ 77%] -tests/unit/test_datasets.py . [ 80%] -tests/unit/test_evaluation.py .... [ 90%] -tests/unit/test_inference.py ... [ 97%] +tests/unit/test_datasets.py . [ 79%] +tests/unit/test_evaluation.py .... [ 86%] +tests/unit/test_inference.py ... [ 91%] +tests/unit/test_legacy_preparation.py . [ 93%] +tests/unit/test_permissions.py ... [ 98%] tests/unit/test_sources.py . [100%] ================================ tests coverage ================================ ______________ coverage: platform darwin, python 3.11.11-final-0 _______________ -Name Stmts Miss Cover Missing ------------------------------------------------------------ -analytics/__init__.py 0 0 100% -analytics/aggregator.py 10 0 100% -analytics/alert_engine.py 36 4 89% 64, 74-75, 86 -analytics/health_score.py 17 1 94% 15 -analytics/monitoring.py 8 1 88% 8 -analytics/trend_detector.py 19 1 95% 44 -api/__init__.py 0 0 100% -api/main.py 121 5 96% 67, 72, 85, 175-176 -config.py 70 5 93% 38-39, 50, 54, 56 -database.py 81 0 100% -nlp/evaluator.py 183 19 90% 21-22, 34, 41, 89, 157, 161, 168, 176, 178, 231, 234, 287, 290-296, 315, 426-427 -nlp/sentiment_engine.py 107 31 71% 27, 32, 56-89, 92-106, 118, 134, 143, 170, 202-205, 211 -pipeline/__init__.py 0 0 100% -pipeline/cli.py 60 16 73% 59-80, 84 -pipeline/contracts.py 145 6 96% 72, 117, 153, 165, 188, 192 -pipeline/prefect_flow.py 17 17 0% 3-29 -pipeline/publication.py 30 6 80% 18, 26, 31, 35, 65-67 -pipeline/runner.py 167 32 81% 37, 66-67, 123, 134-152, 158, 166, 170, 172, 174-188, 255, 315-316 -reports/render_template.py 9 2 78% 19-21 -reports/report_generator.py 56 4 93% 139, 148-150 -scrapers/__init__.py 0 0 100% -scrapers/news_scraper.py 70 17 76% 22, 29, 55, 59, 80, 83, 101-102, 104-106, 110-115 -scrapers/normalizer.py 33 1 97% 51 -scrapers/reddit_scraper.py 6 2 67% 9, 13 -scrapers/review_scraper.py 6 6 0% 4-15 ------------------------------------------------------------ -TOTAL 1251 176 86% +Name Stmts Miss Cover Missing +----------------------------------------------------------------- +analytics/__init__.py 0 0 100% +analytics/aggregator.py 10 0 100% +analytics/alert_engine.py 36 4 89% 64, 74-75, 86 +analytics/health_score.py 17 1 94% 15 +analytics/monitoring.py 8 1 88% 8 +analytics/trend_detector.py 19 1 95% 44 +api/__init__.py 0 0 100% +api/main.py 121 5 96% 67, 72, 85, 175-176 +config.py 74 6 92% 40-41, 52, 54, 58, 60 +database.py 87 0 100% +evaluation/__init__.py 0 0 100% +evaluation/annotation.py 44 13 70% 73-87 +evaluation/annotation_workflow.py 228 48 79% 44, 50, 57, 68, 84, 87, 91, 104, 114, 127, 161, 166, 176, 183, 186, 197, 208, 222, 243, 255, 312, 333, 359, 424-455, 459 +evaluation/calibration.py 95 10 89% 32, 36, 108, 111-117, 129, 175, 191 +evaluation/prepare_legacy.py 49 7 86% 91-98 +evaluation/prepare_weak.py 50 10 80% 29-31, 90-97 +nlp/aspects.py 145 66 54% 39, 45, 66, 68-69, 89-90, 105, 112, 132-186, 189-236, 241 +nlp/evaluator.py 183 19 90% 21-22, 34, 41, 89, 157, 161, 168, 176, 178, 231, 234, 287, 290-296, 315, 426-427 +nlp/sentiment_engine.py 122 33 73% 27, 32, 56-89, 92-106, 118, 132, 134, 150, 159, 186, 218-221, 227 +pipeline/__init__.py 0 0 100% +pipeline/cli.py 72 22 69% 65-94, 98 +pipeline/contracts.py 146 6 96% 72, 117, 153, 165, 188, 192 +pipeline/permissions.py 76 12 84% 52, 58, 67, 102-105, 134-139 +pipeline/prefect_flow.py 17 17 0% 3-29 +pipeline/publication.py 30 6 80% 18, 26, 31, 35, 65-67 +pipeline/release.py 90 11 88% 42, 45, 56, 64, 94-95, 132, 152, 155, 164, 169 +pipeline/runner.py 177 34 81% 38, 67-68, 126-128, 131, 142-160, 166, 174, 178, 180, 182-196, 301, 362-363 +reports/render_template.py 9 2 78% 19-21 +reports/report_generator.py 56 4 93% 142, 151-153 +scrapers/__init__.py 0 0 100% +scrapers/news_scraper.py 70 17 76% 22, 29, 55, 59, 80, 83, 101-102, 104-106, 110-115 +scrapers/normalizer.py 33 1 97% 51 +scrapers/reddit_scraper.py 6 2 67% 9, 13 +scrapers/review_scraper.py 6 6 0% 4-15 +----------------------------------------------------------------- +TOTAL 2076 364 82% Coverage XML written to file coverage.xml Coverage JSON written to file runtime/coverage.json -============================== 40 passed in 4.28s ============================== +============================== 58 passed in 5.51s ============================== diff --git a/docs/evidence/verification-commands.json b/docs/evidence/verification-commands.json index 4a1d05d..1a97bd6 100644 --- a/docs/evidence/verification-commands.json +++ b/docs/evidence/verification-commands.json @@ -10,7 +10,7 @@ ], "cwd": "/Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline", "exit_code": 0, - "seconds": 0.03529825000441633, + "seconds": 0.04646420798962936, "log": "docs/evidence/lint.txt" }, { @@ -25,7 +25,7 @@ ], "cwd": "/Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline", "exit_code": 0, - "seconds": 0.03362554099294357, + "seconds": 0.04004445797181688, "log": "docs/evidence/format.txt" }, { @@ -39,7 +39,7 @@ ], "cwd": "/Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline", "exit_code": 0, - "seconds": 0.22381545801181346, + "seconds": 0.24168475001351908, "log": "docs/evidence/typecheck.txt" }, { @@ -52,7 +52,7 @@ ], "cwd": "/Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline", "exit_code": 0, - "seconds": 0.402410290989792, + "seconds": 0.36250441599986516, "log": "docs/evidence/dependency-consistency.txt" }, { @@ -68,6 +68,8 @@ "--cov=api", "--cov=nlp.evaluator", "--cov=nlp.sentiment_engine", + "--cov=nlp.aspects", + "--cov=evaluation", "--cov=scrapers", "--cov=reports.report_generator", "--cov=reports.render_template", @@ -77,7 +79,7 @@ ], "cwd": "/Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline", "exit_code": 0, - "seconds": 4.834385583002586, + "seconds": 6.216372666996904, "log": "docs/evidence/tests.txt" }, { @@ -90,7 +92,7 @@ ], "cwd": "/Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline", "exit_code": 0, - "seconds": 0.13259545899927616, + "seconds": 0.2235107500164304, "log": "docs/evidence/demo.txt" }, { @@ -103,7 +105,7 @@ ], "cwd": "/Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline", "exit_code": 0, - "seconds": 0.12351937498897314, + "seconds": 0.1695872080163099, "log": "docs/evidence/demo-repeat.txt" }, { @@ -118,7 +120,7 @@ ], "cwd": "/Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline", "exit_code": 0, - "seconds": 1.1637162920087576, + "seconds": 2.1886084580037277, "log": "docs/evidence/fixture-evaluation.txt" } ] diff --git a/docs/flagship-upgrade-report.md b/docs/flagship-upgrade-report.md index 3da1b1a..fb86b4a 100644 --- a/docs/flagship-upgrade-report.md +++ b/docs/flagship-upgrade-report.md @@ -1,5 +1,7 @@ # Flagship upgrade completion and release-gate report +> December 4 follow-up: [next-stage implementation and evidence](readiness/stage-report.md) supersede earlier open ABSA/runtime/deployment-preparation statements. Owner keeps the license undecided; no source access is approved. Historical audit and requirement mappings below are retained. + Publication follow-up: see [publication status](publication-status.md) for the subsequently authorized branch push and hosted checks. The report below preserves its original pre-push evidence. Review date: December 4, 2026 (America/Chicago). **Verdict: NOT RELEASE-READY.** The local implementation is substantially upgraded and runnable; remaining P0/P1 gates below are real, not marked completed by documentation or fixture success. diff --git a/docs/history/tests-pre-readiness.txt b/docs/history/tests-pre-readiness.txt new file mode 100644 index 0000000..2470b82 --- /dev/null +++ b/docs/history/tests-pre-readiness.txt @@ -0,0 +1,53 @@ +============================= test session starts ============================== +platform darwin -- Python 3.11.11, pytest-9.2.0, pluggy-1.7.0 +rootdir: /Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline +configfile: pyproject.toml +testpaths: tests +plugins: cov-7.1.0, platformdirs-4.14.9, anyio-4.16.0 +collected 40 items + +tests/integration/test_evaluation_cli.py .. [ 5%] +tests/integration/test_pipeline_api.py ............. [ 37%] +tests/unit/test_alerts.py .. [ 42%] +tests/unit/test_analytics_reports.py ... [ 50%] +tests/unit/test_contracts.py ........... [ 77%] +tests/unit/test_datasets.py . [ 80%] +tests/unit/test_evaluation.py .... [ 90%] +tests/unit/test_inference.py ... [ 97%] +tests/unit/test_sources.py . [100%] + +================================ tests coverage ================================ +______________ coverage: platform darwin, python 3.11.11-final-0 _______________ + +Name Stmts Miss Cover Missing +----------------------------------------------------------- +analytics/__init__.py 0 0 100% +analytics/aggregator.py 10 0 100% +analytics/alert_engine.py 36 4 89% 64, 74-75, 86 +analytics/health_score.py 17 1 94% 15 +analytics/monitoring.py 8 1 88% 8 +analytics/trend_detector.py 19 1 95% 44 +api/__init__.py 0 0 100% +api/main.py 121 5 96% 67, 72, 85, 175-176 +config.py 70 5 93% 38-39, 50, 54, 56 +database.py 81 0 100% +nlp/evaluator.py 183 19 90% 21-22, 34, 41, 89, 157, 161, 168, 176, 178, 231, 234, 287, 290-296, 315, 426-427 +nlp/sentiment_engine.py 107 31 71% 27, 32, 56-89, 92-106, 118, 134, 143, 170, 202-205, 211 +pipeline/__init__.py 0 0 100% +pipeline/cli.py 60 16 73% 59-80, 84 +pipeline/contracts.py 145 6 96% 72, 117, 153, 165, 188, 192 +pipeline/prefect_flow.py 17 17 0% 3-29 +pipeline/publication.py 30 6 80% 18, 26, 31, 35, 65-67 +pipeline/runner.py 167 32 81% 37, 66-67, 123, 134-152, 158, 166, 170, 172, 174-188, 255, 315-316 +reports/render_template.py 9 2 78% 19-21 +reports/report_generator.py 56 4 93% 139, 148-150 +scrapers/__init__.py 0 0 100% +scrapers/news_scraper.py 70 17 76% 22, 29, 55, 59, 80, 83, 101-102, 104-106, 110-115 +scrapers/normalizer.py 33 1 97% 51 +scrapers/reddit_scraper.py 6 2 67% 9, 13 +scrapers/review_scraper.py 6 6 0% 4-15 +----------------------------------------------------------- +TOTAL 1251 176 86% +Coverage XML written to file coverage.xml +Coverage JSON written to file runtime/coverage.json +============================== 40 passed in 4.28s ============================== diff --git a/docs/history/verification-pre-readiness.json b/docs/history/verification-pre-readiness.json new file mode 100644 index 0000000..4a1d05d --- /dev/null +++ b/docs/history/verification-pre-readiness.json @@ -0,0 +1,124 @@ +[ + { + "name": "lint", + "argv": [ + "/Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline/.venv/bin/python", + "-m", + "ruff", + "check", + "." + ], + "cwd": "/Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline", + "exit_code": 0, + "seconds": 0.03529825000441633, + "log": "docs/evidence/lint.txt" + }, + { + "name": "format", + "argv": [ + "/Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline/.venv/bin/python", + "-m", + "ruff", + "format", + "--check", + "." + ], + "cwd": "/Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline", + "exit_code": 0, + "seconds": 0.03362554099294357, + "log": "docs/evidence/format.txt" + }, + { + "name": "typecheck", + "argv": [ + "/Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline/.venv/bin/python", + "-m", + "mypy", + "config.py", + "pipeline/contracts.py" + ], + "cwd": "/Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline", + "exit_code": 0, + "seconds": 0.22381545801181346, + "log": "docs/evidence/typecheck.txt" + }, + { + "name": "dependency-consistency", + "argv": [ + "/Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline/.venv/bin/python", + "-m", + "pip", + "check" + ], + "cwd": "/Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline", + "exit_code": 0, + "seconds": 0.402410290989792, + "log": "docs/evidence/dependency-consistency.txt" + }, + { + "name": "tests", + "argv": [ + "/Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline/.venv/bin/python", + "-m", + "pytest", + "--cov=config", + "--cov=database", + "--cov=pipeline", + "--cov=analytics", + "--cov=api", + "--cov=nlp.evaluator", + "--cov=nlp.sentiment_engine", + "--cov=scrapers", + "--cov=reports.report_generator", + "--cov=reports.render_template", + "--cov-report=term-missing", + "--cov-report=json:runtime/coverage.json", + "--cov-report=xml:coverage.xml" + ], + "cwd": "/Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline", + "exit_code": 0, + "seconds": 4.834385583002586, + "log": "docs/evidence/tests.txt" + }, + { + "name": "demo", + "argv": [ + "/Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline/.venv/bin/python", + "-m", + "pipeline.cli", + "demo" + ], + "cwd": "/Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline", + "exit_code": 0, + "seconds": 0.13259545899927616, + "log": "docs/evidence/demo.txt" + }, + { + "name": "demo-repeat", + "argv": [ + "/Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline/.venv/bin/python", + "-m", + "pipeline.cli", + "demo" + ], + "cwd": "/Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline", + "exit_code": 0, + "seconds": 0.12351937498897314, + "log": "docs/evidence/demo-repeat.txt" + }, + { + "name": "fixture-evaluation", + "argv": [ + "/Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline/.venv/bin/python", + "-m", + "pipeline.cli", + "evaluate", + "--output", + "runtime/evaluation/final-fixture" + ], + "cwd": "/Users/mihirpandya/Documents/ChatGPT/Projects/brand-reputation-pipeline", + "exit_code": 0, + "seconds": 1.1637162920087576, + "log": "docs/evidence/fixture-evaluation.txt" + } +] diff --git a/docs/operations.md b/docs/operations.md index be7d2b2..522321f 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -2,7 +2,7 @@ ## Environments and supported execution -Python 3.11.11 on macOS arm64 was executed. CPU model inference, independently installed API environment, package wheel CLI from `/private/tmp`, full pytest suite, dependency checks and optional Prefect flow have actual evidence. Linux CI and Docker runtime are configured but not locally executed; Docker CLI is unavailable on this host. MPS/CUDA are explicit options with capability checks, not verified hardware support. Do not infer cross-platform success from a successful resolver. +Python 3.11.11 on macOS arm64 was executed. CPU model inference, independently installed API environment, package wheel CLI from `/private/tmp`, full pytest suite, dependency checks and optional Prefect flow have actual evidence. Hosted Linux CI and Docker runtime passed for the prior upgrade; the latest checks are linked in the readiness follow-up. Docker CLI is unavailable locally. MPS/CUDA are explicit options with capability checks, not verified hardware support. Do not infer cross-platform success from a successful resolver. One source of direct dependency truth is `pyproject.toml`. Generated locks: @@ -10,9 +10,9 @@ One source of direct dependency truth is `pyproject.toml`. Generated locks: - `requirements-dev.lock`: API + tooling. - `requirements-test.lock`: tooling + lightweight evaluation; CI default. - `requirements-worker.lock`: tested macOS CPU NLP + evaluation + Prefect + tooling. -- `requirements-worker-linux.lock`: resolved Linux x86_64 CPU variant, explicitly sourced from PyTorch’s official CPU index; runtime not executed here. +- `requirements-worker-linux.lock`: Linux x86_64 CPU variant with an official direct wheel URL and SHA-256; actual hosted runtime passed. -Compatibility requirement files include the relevant lock. Regenerate with `uv pip compile pyproject.toml --python-version 3.11` and the relevant `--extra` flags. Locks pin exact transitive versions; platform-specific Linux Torch/CUDA wheels can differ from the tested macOS install. No conflicting app-store/PyABSA/no-deps workaround remains. Removed packages were legacy collector/model stack dependencies or unused environment tooling, not active API requirements. PyABSA reproducibility remains an external artifact requirement; it is not quietly replaced by claimed ABSA quality. +Compatibility requirement files include the relevant lock. Regenerate with `uv pip compile pyproject.toml --python-version 3.11` and the relevant `--extra` flags. Locks pin exact transitive versions; platform-specific Linux Torch/CUDA wheels can differ from the tested macOS install. No conflicting app-store/PyABSA/no-deps workaround remains. Removed packages were legacy collector/model stack dependencies or unused environment tooling, not active API requirements. The opt-in safe joint extractor is now pinned and CPU-executed; domain ABSA quality remains unvalidated. ```bash python3.11 -m venv .venv @@ -31,11 +31,11 @@ curl -fsS http://127.0.0.1:8000/health/ready curl -fsS http://127.0.0.1:8000/v1/summary ``` -For real inference: install worker lock, ensure data rights, provide a separate live DB and approved source export. Environment overrides defaults; no implicit `.env` search or credential loading occurs. +For real inference: install worker lock, complete the [permissions checklist](readiness/source-permissions-checklist.md), provide a valid private manifest, separate live DB and approved source export. All default permissions remain pending. Environment overrides defaults; no implicit `.env` search or credential loading occurs. ```bash MODE=live DB_PATH=runtime/live/mentions.db OUTPUT_DIR=runtime/live/reports \ -DATA_RIGHTS_CONFIRMED=true \ +DATA_RIGHTS_CONFIRMED=true PERMISSIONS_PATH=/absolute/private/permissions.json \ brand-pipeline run --input /absolute/path/to/approved-mentions.json --as-of 2026-12-04T00:00:00Z ``` @@ -56,9 +56,9 @@ Migration creates a non-overwriting backup, maps legacy IDs and preserves origin ## Deployment and refresh -`Dockerfile` runs as UID/GID 10001 and excludes historical DBs, raw labels, reports and secrets. It builds a synthetic snapshot and serves the API. `docker build -t brand-reputation:0.2.0rc1 .` and `docker run --rm -p 127.0.0.1:8000:8000 brand-reputation:0.2.0rc1` are prepared commands, **not executed container evidence**. Base image is a mutable Python 3.11 tag; record an owner-approved digest for a release build. +`Dockerfile` runs as UID/GID 10001 and excludes historical DBs, raw labels, reports and secrets. It builds a synthetic snapshot and serves the API. `docker build -t brand-reputation:0.2.0rc1 .` and `docker run --rm -p 127.0.0.1:8000:8000 brand-reputation:0.2.0rc1` were exercised by hosted Docker CI (local Docker is unavailable). The development Dockerfile uses a mutable Python 3.11 tag; the reviewed release-bundle path below pins a verified digest. -Render configuration installs only the API lock, builds a synthetic snapshot, binds `0.0.0.0:$PORT`, disables automatic deployment and requires no secrets. Liveness is used for static-demo process health; `/health/ready` separately refuses stale/degraded content. This intentionally avoids restart loops when an immutable historical demo becomes old. No deployment was requested or performed. Current [deployment](https://render.com/docs/deploys.md) and [health-check](https://render.com/docs/health-checks.md) references were read; runtime hosting behavior remains unverified here. +Render configuration installs only the API lock, builds a synthetic snapshot, binds `0.0.0.0:$PORT`, disables automatic deployment and requires no secrets. Liveness is used for static-demo process health; `/health/ready` separately refuses stale/degraded content. This intentionally avoids restart loops when an immutable historical demo becomes old. Deployment preparation was requested; no public deployment was authorized or performed. Current [deployment](https://render.com/docs/deploys.md) and [health-check](https://render.com/docs/health-checks.md) references were read; runtime hosting behavior remains unverified here. The weekly workflow preserves Sunday 06:00 UTC cadence but now only builds aggregate synthetic artifacts with 14-day retention. It does not update a serving filesystem, commit a database, send alerts or deploy. Live ingestion remains suspended until rights and source configuration are approved. A future owner-controlled release must validate the manifest, build a sanitized immutable snapshot, deploy it explicitly and smoke-test it. Keep the previous image/snapshot for rollback. A Render rollback is not a database restoration; treat database path selection and backup restoration separately. No paid services are provisioned. @@ -79,9 +79,9 @@ Structured stage/run logs contain IDs, counts, duration and error category; they ## Historical cancelled runs -Connected GitHub job logs for November 1 and 15, 2026 show repeated Reddit HTTP 403 blocks, a one-hour NLP task timeout, one retry after 60 seconds, and cancellation roughly 90 minutes after job start. The raw-data commit step was skipped. Timing is consistent with the configured 90-minute workflow limit; the log does not independently identify the cancellation actor, OOM, or a manual action. Evidence: `docs/evidence/historical-workflow-investigation.json`. Source authorization, incremental inference and bounded retry design address observed problems; no claim is made that an unpushed replacement workflow has passed hosted execution. +Connected GitHub job logs for November 1 and 15, 2026 show repeated Reddit HTTP 403 blocks, a one-hour NLP task timeout, one retry after 60 seconds, and cancellation roughly 90 minutes after job start. The raw-data commit step was skipped. Timing is consistent with the configured 90-minute workflow limit; the log does not independently identify the cancellation actor, OOM, or a manual action. Evidence: `docs/evidence/historical-workflow-investigation.json`. Source authorization, incremental inference and bounded retry design address observed problems; hosted branch CI passed; the replacement scheduled workflow still awaits an approved merge/default-branch execution. -Locks can also be regenerated together with `python -m scripts.lock_dependencies` (requires `uv` and package-network access). The script records the official PyTorch CPU index for pip because the resolver's Torch-backend selection alone does not emit that source. Linux resolution was executed, but Linux wheel installation/runtime is explicitly unverified on this macOS host. The optional manually dispatched model-smoke workflow uses this CPU lock and synthetic inputs only. +Locks can also be regenerated together with `python -m scripts.lock_dependencies` (requires `uv` and package-network access). Linux compilation consumes `requirements-linux-cpu.in`, which pins the official CPython 3.11 x86_64 CPU wheel URL and published hash. Verify a new wheel/platform before updating that input. The initial index-only installation failed in actual hosted CI; the corrected lock installed and ran all real models on Linux. The optional bounded model-smoke workflow uses original synthetic inputs only and requires no secrets. To prepare the actual sanitized serving artifact from a validated approved summary (no deployment): @@ -92,3 +92,9 @@ DB_PATH=runtime/public/snapshot.db brand-pipeline serve ``` This creates a new database containing run metadata and canonical aggregate JSON plus re-rendered HTML; raw mention/prediction tables are empty. It refuses overwrites, incomplete/corrupt denominators and unapproved live publication. The concrete refresh path is approved summary → aggregate-only snapshot → owner-approved image/build → manual deployment → liveness/readiness/data smoke → retain previous image/snapshot for rollback. No automatic source-data handoff, deployment or rights approval is implied. + +## Next-stage verification and releases + +The [readiness report](readiness/stage-report.md) supersedes earlier unverified Linux/model/ABSA statements above where new evidence is recorded. Use `requirements-worker-linux.lock` for Linux CPU; `python -m scripts.model_smoke --output runtime/fresh-smoke` downloads pinned real weights and exercises only authored synthetic data. Default CI/demo remain keyless and do not download models. Opt-in live extraction uses `ASPECTS_ENABLED=true`; safe loader and domain limitations are in the model card. Permission approval does not establish model validity. + +[Immutable release preparation](readiness/deployment-candidate.md) now pins an actual base digest, creates an aggregate-only snapshot, and verifies file hashes. The hosted container workflow builds this candidate and exercises read-only filesystem serving, UID and mutation rejection. Public deployment and license remain owner decisions. Existing root Docker/Render examples still represent synthetic demo builds; use the hash-verified bundle path for a reviewed release candidate. diff --git a/docs/publication-status.md b/docs/publication-status.md index d6e27f7..c88ca3b 100644 --- a/docs/publication-status.md +++ b/docs/publication-status.md @@ -15,6 +15,10 @@ The branch was pushed successfully. This publishes the review branch only; it do ## Remaining gates -Data rights, representative independent human labels, trusted real ABSA, optional Linux CPU real-model smoke, code-license selection and release approval remain open. Public deployment and the replacement weekly scheduled workflow have not been executed. Scheduled behavior changes take effect on the default branch only after an approved merge; pushing this review branch does not activate them there. +Data rights, representative independent human/aspect labels, domain model validity, owner-deferred code-license selection and release approval remain open. Trusted safetensors runtime integration, Linux real CPU model smoke and read-only release container verification now passed; see [next-stage evidence](readiness/stage-report.md). Public deployment and the replacement weekly scheduled workflow have not been executed. Scheduled behavior changes take effect on the default branch only after an approved merge; pushing this review branch does not activate them there. The project remains **not release-ready** despite passing engineering CI. No public deployment, merge or external alert delivery occurred. + +## Next-stage final verification + +Final implementation `f0bdabdf63166a4db43d5d3300a0144dbdba7fe5` passed [CI 47369365445](https://github.com/Axinion/brand-reputation-pipeline/actions/runs/47369365445) (58 tests, lint/types, dependency/secret checks, non-root/read-only containers) and [Linux CPU real-model smoke 47369365507](https://github.com/Axinion/brand-reputation-pipeline/actions/runs/47369365507). [Readiness report](readiness/stage-report.md) and `docs/evidence/readiness-verification.json` contain exact scope and artifacts. Source access and human evaluation remain pending; license stays undecided. diff --git a/docs/readiness/annotation-guide.md b/docs/readiness/annotation-guide.md new file mode 100644 index 0000000..a512694 --- /dev/null +++ b/docs/readiness/annotation-guide.md @@ -0,0 +1,45 @@ +# Independent annotation and evaluation protocol + +**Status: workflow implemented; zero approved real-data packets and zero new human annotations.** Historical predictions/ratings are excluded from new packets. Synthetic fixtures exercise the software only. + +Obtain `annotate` permission for an exact private export first. Input JSON has `records` with `id`, `source`, declared `language: en`, `text`, optional timestamp and explicit non-synthetic provenance. Review language, source completeness, duplicates/syndication and privacy manually. Plan representative source/date coverage before sampling; do not balance by model predictions. Default cap is 100 items per source; this is a sampling cap, not a validated statistical power target. Recruit two independent humans and a separate adjudicator; retain their consent and private pseudonym mapping. + +```bash +python -m evaluation.annotation_workflow create \ + --input /absolute/private/annotation-input.json \ + --permissions /absolute/private/permissions.json \ + --output runtime/private/packet --per-source 100 +``` + +Give each annotator only their own CSV. Keep frozen input/manifest/splits private from annotators. Do not expose ratings, historic labels, model outputs, confidence or the other annotator's decisions. Split membership is assigned before annotation by exact normalized-text clusters (60/20/20, seed 42); it is not a temporal-generalization study and does not solve near-duplicate leakage. + +Use `NEGATIVE`, `NEUTRAL`, `POSITIVE` for overall semantic sentiment. Neutral means no expressed positive/negative preference, not uncertainty. Mark `ambiguous` YES/NO; leave a rationale for mixed/unclear cases instead of guessing. Record the annotator pseudonym. Complete aspect spans as JSON arrays with `start`, `end`, `category`, `label` (Python character offsets into the frozen normalized text; end exclusive). Categories: price, quality, support, ux, delivery, other. The `label` is NEGATIVE/NEUTRAL/POSITIVE. `[]` means reviewed and no aspects; blank means not annotated. Keep distinct mentions of the same term as separate spans. Include negation/context when judging polarity, but mark only the aspect term itself. + +Record reviewed error slices in `error_slices_json`: a JSON array from neutral, mixed, sarcasm, negation, short, long, truncated, unsupported_language, source_shift. `[]` means reviewed with none; blank means unreviewed. `ux` corresponds to usability. The keyword category mapper is heuristic and needs independent category gold. + +```bash +python -m evaluation.annotation_workflow compare --packet runtime/private/packet \ + --a /absolute/private/completed-a.csv --b /absolute/private/completed-b.csv \ + --output runtime/private/disagreement-review +# Humans complete adjudication.csv; decisions INCLUDE or EXCLUDE require rationale. +python -m evaluation.annotation_workflow freeze --packet runtime/private/packet \ + --a /absolute/private/completed-a.csv --b /absolute/private/completed-b.csv \ + --adjudication runtime/private/disagreement-review/adjudication.csv \ + --output runtime/private/gold.json +``` + +Comparison reports actual raw agreement and Cohen's kappa (null when undefined). Aspect, ambiguity and slice conflicts also require review. EXCLUDE supports unresolved ambiguity without inventing neutral labels. Exclusions preserve original splits and retain provenance; a now-empty split fails rather than silently reshuffling. Import rejects changed text/metadata, invalid offsets, missing labels, overlapping annotator identities and adjudicators reusing either annotator identity. Frozen provenance retains the original dataset hash and permission attestation. Preserve file hashes and freeze artifacts without publishing source text. + +After provenance review and separate exact-file `infer` permission for gold, score development rows only: + +```bash +python -m evaluation.calibration score-dev --dataset runtime/private/gold.json \ + --permissions /absolute/private/gold-permissions.json \ + --output runtime/private/dev-predictions.json +python -m evaluation.calibration fit --predictions runtime/private/dev-predictions.json \ + --output runtime/private/calibration.json --min-coverage 0.90 --min-class-support 20 +``` + +The coverage/support numbers above are an example owner-selected protocol, not a validated policy. Set them before examining results and justify sample size. Temperature and threshold fit only dev probabilities and require all three classes with minimum support. The tool never changes live configuration. Lock model/calibration/config, then run the untouched test once with full-population coverage, abstention/error counts, confusion/per-class metrics, grouped uncertainty, source/slice analysis and aspect term/category/joint metrics. If test results guide changes, obtain a new holdout; do not reuse it as development data. Current model choice and operational thresholds remain unvalidated. + +For a safe software exercise use `evaluation/fixture.json` with explicit `--synthetic-demo` at creation/scoring, and a fresh output directory. Keep every resulting dataset/result marked synthetic; do not describe simulated CSV completions in tests as human labels. diff --git a/docs/readiness/deployment-candidate.md b/docs/readiness/deployment-candidate.md new file mode 100644 index 0000000..d4c5c13 --- /dev/null +++ b/docs/readiness/deployment-candidate.md @@ -0,0 +1,21 @@ +# Reviewable deployment candidate + +A concrete synthetic-only bundle was prepared and hash-verified locally. It contains 50 files, a pinned official Python image digest, a UID 10001 Dockerfile and an aggregate-only SQLite snapshot with **zero raw mention, prediction or aspect rows**. It contains no source permission evidence, model weights, raw CSVs or credentials. Evidence: [verification](../evidence/release-bundle-verification.json) and [manifest](../evidence/release-bundle-manifest.json). Local generated files live under ignored `runtime/readiness-release-bundle-final`. + +```bash +mkdir -p runtime/release-source +brand-pipeline demo --db runtime/release-source/mentions.db \ + --output runtime/release-source/reports > runtime/release-source/summary.json +brand-pipeline prepare-release --summary runtime/release-source/summary.json \ + --destination runtime/release-bundle +brand-pipeline verify-release --directory runtime/release-bundle +# Local Docker verification, when Docker is installed: +docker build -t brand-reputation:review runtime/release-bundle +docker run --rm --read-only --tmpfs /tmp -p 127.0.0.1:8000:8000 brand-reputation:review +``` + +Create `runtime/release-source` before redirecting the demo output. Commands refuse existing release destinations. The manifest hashes the copied source and lock, so dirty-checkout changes are identifiable by file hashes even when source_commit names the last commit. Verification detects tampering; it is not a signed provenance attestation. Build only a trusted, reviewed bundle. The base digest pins content but does not certify absence of vulnerabilities; repeat dependency/image review before release. + +The immutable demo period is December 1–2, 2026. `/health/live` checks the process; `/health/ready` can return 503 when historical data ages. This is truthful freshness reporting, not a failed container. An immutable release does not receive later workflow artifacts automatically. Refresh requires a newly reviewed snapshot/image; preserve the prior verified bundle/image for rollback. + +**Owner decisions pending:** leave code license undecided as requested; choose a target account/service and approve its cost/exposure; explicitly authorize deployment of the reviewed commit/image. No public deployment, release tag, merge, paid resource, source activation or external alert was performed. The candidate currently supports synthetic publication only. Real-data release additionally needs provider publication permission, privacy/retention review, independent ML validation and separate release approval. Render configuration remains a reviewed example, not a deployed service. diff --git a/docs/readiness/source-permissions-checklist.md b/docs/readiness/source-permissions-checklist.md new file mode 100644 index 0000000..0d7fa00 --- /dev/null +++ b/docs/readiness/source-permissions-checklist.md @@ -0,0 +1,38 @@ +# Source access and permissions checklist + +Owner decision, December 4, 2026: **no approved source access yet**. All five entries in `pipeline/source_permissions.json` remain pending. This checklist records review work; it grants no rights. No collection was enabled. + +| Source | Evidence the owner must obtain | Current access path | +| --- | --- | --- | +| News | Account/plan authorization for the intended environment; permission for content processing, retention and aggregate display; publisher restrictions | Official NewsAPI adapter, disabled by default | +| Reddit | Approved API access and permitted application/use; retention, deletion and model-processing conditions | Legacy unauthenticated adapter remains disabled | +| Google Play | Provider-authorized collection or an export the owner is entitled to process; review-content use and retention terms | Approved export only | +| App Store | Provider-authorized collection or an entitled export; review-content use and retention terms | Approved export only | +| Approved export | Dataset owner/provider identity, provenance, exact content hash and evidence covering inference/annotation separately | Hash-bound private JSON import | + +For each source, the owner should record: + +- [ ] Provider, application/account, intended purpose and access method. +- [ ] Current terms and any written permission, contract or plan restriction. Public availability and working scraper code do not establish permission. +- [ ] Separate scopes: `collect`, `infer`, `annotate`, `publish_aggregates`. Permission to read is not assumed to cover all four. +- [ ] Whether source text can be shown to independent annotators; who may access it and where. +- [ ] Allowed retention, deletion requests, privacy review, personal-content handling and redistribution limits. The manifest records retention days; it does not automatically delete existing data. +- [ ] Reviewer, UTC review date, expiry date, private evidence reference and review renewal process. +- [ ] For exports: SHA-256 of the exact input file. Derived gold/dev files need their own reviewed hashes before real inference. +- [ ] An independent check that proposed aggregate publication is permitted and does not expose personal information. + +Keep evidence and credentials outside Git. Copy the pending manifest to a private location, replace placeholder references, and change only sources actually approved. An approved entry requires `reviewed_by`, `reviewed_at`, `expires_at`, `evidence_reference`, `retention_days`, nonempty `allowed_uses`, and (for `approved_export`) `dataset_sha256`. Dates must have explicit timezones. The runtime checks current validity, requested scopes and exact export hash before loading models or collecting data. `DATA_RIGHTS_CONFIRMED=true` alone is insufficient. + +```bash +python -m pipeline.permissions --manifest /absolute/private/source-permissions.json +shasum -a 256 /absolute/private/approved-mentions.json +# Only after genuine owner approval and the matching private manifest: +MODE=live DATA_RIGHTS_CONFIRMED=true \ +PERMISSIONS_PATH=/absolute/private/source-permissions.json \ +DB_PATH=runtime/live/mentions.db OUTPUT_DIR=runtime/live/reports \ +brand-pipeline run --input /absolute/private/approved-mentions.json --as-of 2026-12-04T00:00:00Z +``` + +A manifest is an attestation, not an automated legal review. It cannot establish whether a reviewer had authority. All source access still needs owner review. Existing historical content has not been newly cleared, deleted or republished. + +Primary references: [NewsAPI terms](https://newsapi.org/terms), [Reddit Data API terms](https://redditinc.com/policies/data-api-terms), [Google Play terms](https://play.google.com/about/play-terms/), [Apple media-services terms](https://www.apple.com/legal/internet-services/itunes/). NewsAPI developer access must not be assumed to authorize production use. Google/Apple links are review starting points; the applicable API, account, jurisdiction and content terms still need owner verification. diff --git a/docs/readiness/stage-report.md b/docs/readiness/stage-report.md new file mode 100644 index 0000000..8e7f74b --- /dev/null +++ b/docs/readiness/stage-report.md @@ -0,0 +1,56 @@ +# Next-stage readiness implementation report + +December 4, 2026. **Verdict: NOT RELEASE-READY.** The requested engineering work is implemented; permissions, genuine independent labels and release decisions remain external gates. Owner explicitly confirmed no approved access and left the code license undecided. No license was chosen, live source activated, human label invented, threshold approved, merge/public deployment/release performed or external alert sent. + +## Scope and requirement status + +This follow-up starts after `505c449e98fa9a6a780f07c643a0e4ebeaff8ad7` on `codex/flagship-upgrade`. Implementation commits: `3e969d1` (safe aspects/permissions), `8de863e` (annotation/calibration), `39d8931` (release/smoke), `4326564` (integrity tests), `d07ae98` (Linux wheel correction), `ec1c752` (helper formatting), `f0bdabd` (permission-provenance chain and independent adjudicator checks). Later documentation commits record results without rewriting history. Final annotation review also preserved the source dataset hash/permission attestation in frozen gold and enforced a distinct adjudicator, with regression checks. Original requirement ledger remains in [the flagship report](../flagship-upgrade-report.md); this table updates the requested next work rather than replacing that contract. + +| Requested work / original contract | Implemented files and verification | Status / owner action | +| --- | --- | --- | +| Approve sources; provenance/security §2–3 | `pipeline/permissions.py`, pending manifest, tests for expiry/scopes/hash/invalid schema; [checklist](source-permissions-checklist.md) | Checklist and fail-closed gates completed. Actual approval blocked: owner has no approved access. Obtain provider permissions and private evidence. | +| Independent labeled evaluation §5 | `evaluation/annotation_workflow.py`; prediction/rating-blind CSVs, formula escaping, frozen exact-text splits, two annotators, kappa, adjudication/exclusion; integrity tests | Workflow completed. Dataset and human quality metrics blocked: permitted representative text and actual independent humans needed. | +| Validate confidence/model selection §4–5 | `evaluation/calibration.py`; only dev rows scored, temperature/coverage fitting, minimum all-class support, no automatic application; CLI tests | Framework completed. Operational threshold/model ranking blocked by independent labels. No new claim of domain superiority. | +| Trusted aspects §4–5, §13 | `nlp/aspect_registry.json`, `nlp/aspects.py`, model card; offset spans, safe load/hash/schema, additive DB tables, known/unknown/truncated states, category reporting; unit/integration + real CPU smoke | Safe runtime integration completed. Independent term/category/joint accuracy, calibration and taxonomy validation blocked by aspect gold. | +| Linux real models §10–11 | CPU lock, `scripts/model_smoke.py`, bounded optional workflow; real overall models, joint aspects, synthetic calibration, repeat persistence | Actual hosted status recorded below. Synthetic results validate runtime only. | +| Approved deployment preparation §9–10 | `pipeline/release.py`, CLI, pinned image digest, allowlisted source, aggregate snapshot, manifest and tamper tests | Candidate preparation completed. Public deployment blocked pending target/cost/exposure approval and explicit authorization. | +| Owner-selected license §13 | No LICENSE added; decision documented | Deferred by explicit owner instruction. Model/data terms remain separate. | + +## Actual verification + +`python -m scripts.verify` exited 0 for all eight checks: Ruff, formatting, focused mypy, pip check, tests, demo, repeated demo and synthetic baseline evaluation. [Command/exit ledger](../evidence/verification-commands.json), [test output](../evidence/tests.txt). **58 tests passed locally.** Expanded coverage: **1,712 / 2,076 statements, 82.4663%**. Scope includes config, database, pipeline, analytics, API, evaluator, sentiment engine, new aspect module, evaluation workflows, scrapers and report generation. This differs from the prior narrower 86% figure and is not a like-for-like regression. Network model loading is exercised separately, not by ordinary offline tests. Heavy loader branches are not covered by the standard suite. Prior logs are preserved under `docs/history/*pre-readiness*`. + +[Machine-readable follow-up evidence](../evidence/readiness-verification.json) identifies exact commits and run/job IDs. Latest source formatting/checks and `git diff --check` passed after the lock helper fix. The source wheel built successfully, was installed with uv into the independent 22-package API environment, passed dependency consistency, and its new model/permission/base-image resources were verified in isolated mode. API import loaded neither torch nor transformers. This environment intentionally has no pip module; uv performed installation/checking. All generated runtime weights, private intermediates and deployment candidate remain ignored. The original historical DB, manual-label CSV, metrics and generated output paths have no diff from baseline. + +### Real-model runtime and error evidence + +[macOS CPU smoke](../evidence/aspect-runtime-smoke.json): Python 3.11.11, Torch 2.15.0, CPU two threads, 8.9497 seconds for this cached synthetic smoke workload (includes multiple steps; not an isolated throughput benchmark). Three authored sentences produced six aspect spans. Real overall+aspect demo processing persisted 12 mentions / 12 aspect-inference records / 12 spans; repeat processing inferred zero eligible mentions and foreign-key checks passed. Weights hash and immutable checkpoint are recorded in the artifact. No real source collection occurred. + +The first mixed sentence produced NEUTRAL for price, picture quality and support. These observable outputs are retained as a failure example; they are not converted into a fabricated human-gold score. Unknown polarity never becomes neutral; truncated boundary spans abstain. Taxonomy mapping is heuristic. No independent ABSA precision/recall/F1 or operational confidence threshold exists. Prior real-model benchmarks and weak-label exploratory evaluations remain in the original report; this smoke provides no measured production improvement or SLA. + +### Hosted checks + +On implementation `43265642666a67e482c14c40a5fd30bdaab23446`, [Linux CI](https://github.com/Axinion/brand-reputation-pipeline/actions/runs/47368002869) passed both test and container jobs: 58 tests, 82% expanded coverage, lint/types/pip check, zero scoped secret findings, and no known API dependency vulnerabilities at execution. Container checks built the aggregate-only candidate and verified UID 10001, read-only filesystem serving and POST /run = 404. + +The [first real-model run](https://github.com/Axinion/brand-reputation-pipeline/actions/runs/47368002836) failed honestly during installation: pip could not find `torch==2.15.0+cpu` through the generated index configuration. Models did not run in that attempt. The resolver alone had not proved installation. Correction: independently inspect the official PyTorch CPU index and metadata, pin its CPython 3.11 Linux x86_64 wheel URL plus published SHA-256 in `requirements-linux-cpu.in`, and regenerate the Linux lock. No other dependency versions changed. The regeneration helper now consumes this reviewed input. The [corrected Linux CPU model run](https://github.com/Axinion/brand-reputation-pipeline/actions/runs/47368706433) **passed** on `d07ae9863693b9d30feb6e966c24af593926f915`. Actual artifact: [runtime](../evidence/linux-model-runtime-smoke.json), [synthetic comparison](../evidence/linux-synthetic-model-evaluation.json), [synthetic calibration](../evidence/linux-synthetic-calibration.json). The final downloaded runtime artifact records Linux x86_64/glibc 2.43, Python 3.11.18, Torch 2.15.0+cpu, two threads; 24.8459 seconds for this complete synthetic workload. Six aspect spans and 12/12/12 persisted counts passed, including zero repeat inference. These are software/runtime checks, not human quality results. The subsequent [standard CI](https://github.com/Axinion/brand-reputation-pipeline/actions/runs/47368738326) also passed on formatting-corrected `ec1c752`. + +### Deployment artifact + +[Manifest](../evidence/release-bundle-manifest.json), [verification](../evidence/release-bundle-verification.json): 50 hashed files; zero raw data rows; digest-pinned Python base; UID 10001; `deployed: false`. The release manifest's source commit identifies copied code, while file hashes bind exact bytes. No Docker CLI exists locally; hosted Docker supplies actual container evidence. [Reproduction and rollback](deployment-candidate.md). Demo freshness/readiness may expire; process liveness remains separate. + +## Remaining owner actions and acceptance limits + +1. Obtain legitimate source access, review privacy/retention/deletion/publication, and supply private scoped permission evidence. Do not treat historic accessibility as approval. +2. Recruit independent annotators/adjudicator for representative approved text. Freeze gold with aspect/slice labels, justify sample support, fit on development only, then evaluate untouched test data before selecting thresholds/model policy. +3. Review joint-aspect errors and category mapping against that gold. A trusted serialization path is not proof of useful domain quality. +4. Keep license undecided until the owner chooses. Review upstream model/data terms separately. +5. Approve a concrete deployment target/account/cost/exposure and explicitly authorize the reviewed image. Keep the prior image/snapshot for rollback. No paid infrastructure was provisioned. +6. Original unresolved specification deviations (including coarse single-task optional Prefect orchestration, declared rather than detected English, and exact-only duplicate grouping) remain visible in the original requirement ledger; they were not closed by this follow-up. + +The project can demonstrate ingestion contracts, independent model heads, reproducible evaluation software, transactional reporting and read-only serving. Production or flagship release acceptance still requires the unresolved P0/P1 evidence above. Branch commits/pushes publish reviewable engineering work; they do not satisfy those gates. + +## Final source verification + +Both terminal checks passed on final implementation **`f0bdabdf63166a4db43d5d3300a0144dbdba7fe5`**: [CI 47369365445](https://github.com/Axinion/brand-reputation-pipeline/actions/runs/47369365445) and [real-model CPU smoke 47369365507](https://github.com/Axinion/brand-reputation-pipeline/actions/runs/47369365507). Hosted tests: 58 passed; 1,713/2,076 statements (83% rounded), versus local 1,712/2,076 (82% rounded), reflecting one platform-dependent covered statement. The downloaded Linux JSON artifacts above are from this final run, not the earlier corrected run. Artifact ZIP digest is recorded in the machine-readable evidence. Zero scoped secret findings and no known API dependency vulnerabilities were reported at execution. Final runtime model results still carry synthetic-only limitations. + +The review branch is committed/pushed. Documentation-only commits after this source SHA do not change these tested implementations. Runtime files and weights remain ignored; all original protected data paths are unchanged. See the final response for the exact documentation HEAD. diff --git a/docs/security.md b/docs/security.md index 6bf1dac..d78bed9 100644 --- a/docs/security.md +++ b/docs/security.md @@ -6,7 +6,7 @@ The public API has no write, model execution or arbitrary-path/URL endpoint. It HTML uses Jinja autoescape, contains no model `safe` filter and never renders untrusted Markdown links. Source/provider text is not injected into reports or sent to external LLMs. An optional helper accepts only schema-validated evidence identifiers and still renders canonical numeric text. There is no tools/secrets access from a narrative model. HTML injection, malformed input, absent/corrupt/stale data, concurrent reads and disabled mutations are exercised with disposable fixtures. -External alert delivery is disabled. Explicit transport injection is available for owner-authorized integrations and mocked tests, using channel-specific transactional claims and bounded attempts. Slack text uses `plain_text`; email content is escaped. No built-in provider destination is accepted from API clients. Default scheduled work has no secrets and read-only repository permissions. Untrusted PR code receives no repository secrets. Action revisions are pinned; package installation follows generated locks. Public deployment/merge/push/history rewriting are owner actions and were not performed. +External alert delivery is disabled. Explicit transport injection is available for owner-authorized integrations and mocked tests, using channel-specific transactional claims and bounded attempts. Slack text uses `plain_text`; email content is escaped. No built-in provider destination is accepted from API clients. Default scheduled work has no secrets and read-only repository permissions. Untrusted PR code receives no repository secrets. Action revisions are pinned; package installation follows generated locks. The owner authorized branch commits/pushes, which were performed. Public deployment, merge and history rewriting were not performed. ## Models and dependencies @@ -18,6 +18,8 @@ The working-tree detector uses offline verification, with narrow allowlists for ## Remaining owner security actions -Approve source access, redistribution and retention; review historical content and decide private preservation/removal without an automatic history rewrite. Rotate any credentials identified by subsequent provider/history review. Choose a code license independently from data/model rights. Enable branch protection and required hosted checks after authorized push. Verify container runtime/non-root enforcement on a Docker-enabled host and deploy smoke tests only after approval. Configure log retention and access controls before using real private data. No security claim depends on secrets merely being absent in the demo. +Approve source access, redistribution and retention; review historical content and decide private preservation/removal without an automatic history rewrite. Rotate any credentials identified by subsequent provider/history review. Choose a code license independently from data/model rights. Enable branch protection and required hosted checks after authorized push. Hosted container checks verified non-root and read-only release serving; perform public deployment smoke tests only after explicit approval. Configure log retention and access controls before using real private data. No security claim depends on secrets merely being absent in the demo. -The original PyABSA path was also checked against [upstream extractor code](https://github.com/yangheng95/PyABSA/blob/v2/pyabsa/tasks/AspectTermExtraction/prediction/aspect_extractor.py): configuration deserialization uses Python pickle and several loader paths enable remote code. This is a verified trust boundary, not a claim that a particular checkpoint is malicious. The repository supplied no immutable, trusted extraction artifact or independently validated compatibility/security manifest. Default extraction therefore remains disabled pending an owner-approved trusted artifact or safe conversion plus compatibility validation. The independent extractor interface, category aggregation and version replacement are implemented/tested; real ABSA runtime and quality are not marked complete. +The original PyABSA loader trust boundary was reviewed against [upstream extractor code](https://github.com/yangheng95/PyABSA/blob/v2/pyabsa/tasks/AspectTermExtraction/prediction/aspect_extractor.py), including pickle/remote-code paths. New optional extraction uses standard Transformers code and an immutable, SHA-256-verified safetensors artifact with remote code disabled; label schema and loaded weight keys are checked. It ran on CPU. The safe loading path addresses that engineering blocker, but upstream training-data rights and independent domain quality are separate unresolved questions. Extraction remains opt-in. + +Live permission gates validate owner evidence, dates, scopes and import hashes before model/source work. All default entries remain pending. CSV annotation packets escape spreadsheet formula prefixes, freeze normalized text and reject altered cells. Software validates pseudonym separation but cannot prove human independence or authority. Private packets and source evidence belong outside Git. Immutable release preparation includes only allowlisted source plus synthetic aggregates, pins its base image and verifies all file hashes; verification is not a signature or a malware audit. diff --git a/nlp/model_card.md b/nlp/model_card.md index 9943992..58f66e6 100644 --- a/nlp/model_card.md +++ b/nlp/model_card.md @@ -10,12 +10,22 @@ No model was trained or domain-fine-tuned in this project. Predictions use pretr Upstream [Cardiff model card](https://huggingface.co/cardiffnlp/twitter-roberta-base-sentiment-latest) defines negative/neutral/positive and its training domain. [DistilBERT model card](https://huggingface.co/distilbert/distilbert-base-uncased-finetuned-sst-2-english) describes the binary classifier. Model registry metadata was retrieved directly and immutable weights ran locally on CPU. Weights remain outside the repository. This repository's missing code license is not a model-weight license. -All eligible mentions receive a separate overall prediction, abstention or explicit error. Aspects never substitute for overall labels; ratings/annotations are not passed into inference. Labels, full probabilities, truncation, preprocessing/inference/model version and run IDs are stored. Unknown confidence is not semantic neutral. Default threshold zero makes no selective-calibration claim. Explicit unavailable MPS/CUDA fails; verified hardware is CPU on macOS arm64, Python 3.11.11. +All eligible mentions receive a separate overall prediction, abstention or explicit error. Aspects never substitute for overall labels; ratings/annotations are not passed into inference. Labels, full probabilities, truncation, preprocessing/inference/model version and run IDs are stored. Unknown confidence is not semantic neutral. Default threshold zero makes no selective-calibration claim. Explicit unavailable MPS/CUDA fails; verified hardware is CPU on macOS arm64/Python 3.11.11 and hosted Linux x86_64/Python 3.11.18. Fresh local comparison uses 19 non-mock legacy news items, split 11/4/4. Label provenance and blinding remain unverified; only four test items means no strong model ranking. Majority, TF-IDF/logistic and three-class RoBERTa each initially measured 25% accuracy. Binary corrected baseline uses abstention and reports coverage separately; the historical neutral heuristic is also reproduced as a named comparator. Exact results, per-class support, confusion matrices, source/language/slice breakdowns, ECE/Brier, grouped uncertainty and execution manifests are in `docs/evidence/legacy-exploratory-evaluation.json`. Historic results are preserved unchanged under `docs/history`, not represented as rerun or improvement. -Default RoBERTa is a semantic-capability choice; it has not demonstrated domain superiority. CPU timing/parameter sizes appear in `docs/evidence/model-benchmark.json` on 24 identical synthetic inputs; warm throughput is not a production SLA. Historical manual metrics included 81 mock-linked examples. Better independent labels, source coverage, neutral/mixed/sarcastic annotations and data rights are release blockers. No ABSA accuracy is available: a reproducibly pinned extraction artifact and independent aspect gold are still needed. The optional extractor contract and exact term/category/joint metric implementation are tested with synthetic examples. +Default RoBERTa is a semantic-capability choice; it has not demonstrated domain superiority. CPU timing/parameter sizes appear in `docs/evidence/model-benchmark.json` on 24 identical synthetic inputs; warm throughput is not a production SLA. Historical manual metrics included 81 mock-linked examples. Better independent labels, source coverage, neutral/mixed/sarcastic annotations and data rights are release blockers. No ABSA accuracy is available. A pinned safetensors extractor now runs; independent aspect gold is still needed. The optional extractor contract and exact term/category/joint metric implementation are tested with synthetic examples. Failure risks: source/domain shift; sarcasm/negation; genuinely mixed sentiment; context beyond token truncation; selection/class imbalance; unvalidated language declaration; uncalibrated confidence; source freshness and collection gaps. Health index and alerts are descriptive heuristics, not business outcomes. Do not use these outputs for consequential decisions without validation and human review. A separate executed review-star test (60 reviews, selected newest-300 subset from 7,186 eligible rows) measured RoBERTa accuracy 81.67% and macro F1 0.6724, TF-IDF/logistic 78.33% and 0.5218, and train-majority 66.67% and 0.2667. Supports are 14 negative / 6 neutral / 40 positive. These are weak star-agreement metrics, not human text accuracy or a comparison on the historical 189-item population. See `docs/evidence/weak-review-evaluation.json` and the expanded protocol in `docs/evaluation.md`. + +## Opt-in joint aspect extraction + +`yangheng/deberta-v3-base-end2end-absa` at `23e6d43431a5f96d8a7b7b9721d59bbda30cc63d` declares MIT upstream. [Pinned card](https://huggingface.co/yangheng/deberta-v3-base-end2end-absa/blob/23e6d43431a5f96d8a7b7b9721d59bbda30cc63d/README.md). The 735,378,268-byte safetensors artifact is verified against SHA-256 `8812932976c1a9f5668689b2675770aa63617a6370e12518b111825b84d0ffde`. Remote code and pickle weight loading are disabled; unexpected/missing weights or label schema fail. See `nlp/aspect_registry.json` and `nlp/aspects.py`. Upstream license declaration does not validate training-data permissions or domain performance. + +The joint BIO head has positive/negative/neutral/unknown aspect states. Confidence is the mean selected-token probability, not calibrated accuracy or a quantity comparable to the overall classifier. Character offsets refer to normalized text; boundary whitespace is trimmed. Cut-off trailing spans abstain. The existing keyword taxonomy maps extracted terms to categories and remains heuristic. + +Actual macOS CPU smoke on three original authored sentences yielded six spans; a 12-mention real-model synthetic run persisted 12 inference records and 12 span rows, then performed zero repeat inference. `docs/evidence/aspect-runtime-smoke.json` contains exact inputs and outputs. The first mixed sentence's price, picture quality and support spans were all predicted NEUTRAL, a concrete reason not to claim domain accuracy. These examples were not independently annotated and yield no valid precision/recall/F1 estimate. New dev-only calibration software is exercised on synthetic data; no operational threshold has been selected or applied. + +The corrected Linux CPU smoke also passed: [run 47368706433](https://github.com/Axinion/brand-reputation-pipeline/actions/runs/47368706433), `docs/evidence/linux-model-runtime-smoke.json`. It ran both overall checkpoints and the joint aspect head, synthetic dev calibration, foreign-key checks and repeat behavior. This closes Linux compatibility evidence for this tested configuration, without validating domain accuracy or accelerators.