Spaces:
Running
Running
Upload 18 files
Browse filesFiles changed (5)
- DATASET_COLLECTION_GUIDANCE.md+43-27
- README.md+73-32
- _utils/_dataset_schema.py+127-24
- _utils/_shared_logic.py+1-1
- app.py+41-6
1234562 unmodified lines91011121314160 unmodified lines175176177178179180181588 unmodified lines7707717727737747757767771 unmodified line7797807817827837847854 unmodified lines790791792793794795796107 unmodified lines904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938685 unmodified lines1624162516261627162816291630# Dataset Collection and Multi-Store Operations Guide## Schema v3 privacy lifecycle β authoritative> **Run 6 policy:** where older historical sections below describe feedback as> training input, cross-source feedback/contribution joins, unversioned consent,2 unmodified lines- Ordinary `/v1/feedback` is rating telemetry only. Query, answer, note, model,page and conversation identity are discarded server-side; durable feedback isopt-in and marked `trainingStatus="telemetry"`.- `/v1/contribute` requires `consentFlag=true` and the current`consentVersion`. Accepted content enters the mutable contribution receiptledger with `trainingStatus="quarantined"`; it is not written directly to160 unmodified lines| `TRAINING_DATASET_REPO` | **Variable** | Legacy HF mode only | Repo ID is normally non-sensitive || `HF_DATASET_TOKEN` | **Secret** | Legacy HF mode | Actual HF credential || `HF_DATASET_TOKEN_TYPE` | **Variable** | Legacy HF mode | Classification only || `FEEDBACK_PERSIST_ENABLED` | **Variable** | Recommended | Boolean config |> **Attention β your existing `TRAINING_DATASET_REPO` Secret works, but it does> not normally need to be a Secret.**588 unmodified lines### Rating telemetryThe browser does not send rating telemetry until the reader explicitly enables**Send rating telemetry**. With that preference enabled and`FEEDBACK_PERSIST_ENABLED=true`, a rating may produce:```textfeedback/YYYY/MM/DD/fb_<recordId>.jsonl1 unmodified lineInspect the row and verify it contains rating/event mechanics only: no query,answer, note, model, page URL, or conversation identifier, and`trainingStatus="telemetry"`. Storage failure must not break the rating UI.### Contribution receipt lifecycle4 unmodified linesOnly an authorized operator review/promotion request may create durable`trainingStatus="eligible"` rows. Promotion uses an atomic lifecycle claim so asecond concurrent reviewer cannot write the same receipt again. After promotion,raw Q&A content is cleared from the receipt ledger; lifecycle metadata, server-owneddedup keys, provider paths, and only the delete-capability hash remain.The same receipt capability remains valid after promotion. DELETE then means107 unmodified lines---## 14. Why feedback and contributions must be deduplicatedThere are two intentional collection paths:| Path | Endpoint | Typical folder | Trigger ||---|---|---|---|| Immediate feedback | `POST /v1/feedback` | `feedback/` | user rates an answer || Explicit contribution | `POST /v1/contribute` | `contributions/` | user consents and contributes conversation data |The same Q&A may therefore appear once as feedback and later again as acontribution.Training both copies would overweight that example.### Canonical dedup key```text_dedup_key = <conversationId>:<answerIndex>```### Priority```textcontribution > feedback```For the same `_dedup_key`, the contribution wins.Within the same source type, the record with the newest server `_ts` wins.---685 unmodified lines- exact legacy duplicate records across mirrors suppressed;- same canonical record ID + different bytes fails closed;- guarded remote archive extraction;- historical schema normalization to current schema v3 when `_utils/_dataset_schema.py` is available;- default exclusion of feedback telemetry/quarantined/legacy-unreviewed records;- training acceptance only for `trainingStatus="eligible"` contributions;- tombstone/retraction handling where applicable;1234562 unmodified lines9101112131415161718192021222324252627160 unmodified lines188189190191192193194588 unmodified lines7837847857867877887897907917927937941 unmodified line7967977987998008018028038048054 unmodified lines810811812813814815816107 unmodified lines924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954685 unmodified lines1640164116421643164416451646# Dataset Collection and Multi-Store Operations Guide## Schema v4 privacy and contribution lifecycle β authoritative> **Run 6 policy:** where older historical sections below describe feedback as> training input, cross-source feedback/contribution joins, unversioned consent,2 unmodified lines- Ordinary `/v1/feedback` is rating telemetry only. Query, answer, note, model,page and conversation identity are discarded server-side; durable feedback isopt-in and marked `trainingStatus="telemetry"`.- Current schema v4 keeps feedback telemetry and explicit content contributionstructurally separate. Contribution has two record families: `recordType="qa"`for selected/rated Q&A and `recordType="conversation"` for one ordered`messages[]` record. Whole-conversation mode does not explode turns intoindependent training rows.- The browser's dedicated **Contribute to dataset** sheet is the only content-bearingcontribution surface. **This Q&A**, **Rated answers**, and **Whole conversation**converge on the same exact-JSON inspection, privacy preflight, consent, quarantine,receipt-delete, and post-promotion withdrawal lifecycle. Share/export owns nocontribution controls.- Schema v4 requires contribution consent `2.0.0`. Legacy schema v2/v3 clients maycontinue using historical consent `1.0.0` for compatibility; that legacy consentis not accepted for schema v4's broader conversation-record contract.- `/v1/contribute` requires `consentFlag=true` and the current`consentVersion`. Accepted content enters the mutable contribution receiptledger with `trainingStatus="quarantined"`; it is not written directly to160 unmodified lines| `TRAINING_DATASET_REPO` | **Variable** | Legacy HF mode only | Repo ID is normally non-sensitive || `HF_DATASET_TOKEN` | **Secret** | Legacy HF mode | Actual HF credential || `HF_DATASET_TOKEN_TYPE` | **Variable** | Legacy HF mode | Classification only || `FEEDBACK_PERSIST_ENABLED` | **Variable** | Recommended | Server persistence flag; never substitutes for reader telemetry consent |> **Attention β your existing `TRAINING_DATASET_REPO` Secret works, but it does> not normally need to be a Secret.**588 unmodified lines### Rating telemetryThe browser does not send rating telemetry until the reader explicitly enables**Send rating telemetry**. The permission is versioned and stored as a structuredbrowser consent record; missing, malformed, stale-version, or historical booleanpreferences fail closed to **Off**. Every network telemetry request carries`telemetryConsent=true`, `telemetryConsentVersion="1.0.0"`, and the grant timestamp;the bundled proxy/Worker reject requests that omit the current consent contract.With that user permission active and `FEEDBACK_PERSIST_ENABLED=true`, a rating may produce:```textfeedback/YYYY/MM/DD/fb_<recordId>.jsonl1 unmodified lineInspect the row and verify it contains rating/event mechanics only: no query,answer, note, model, page URL, or conversation identifier, and`trainingStatus="telemetry"`. Turning telemetry off must stop future rating andretraction network requests. Storage failure must not break the local rating UI.The public `ai-assistant-feedback` DOM event is content-free for the same reason:page listeners receive bounded rating mechanics, not the Q&A/note/model/page tuple.### Contribution receipt lifecycle4 unmodified linesOnly an authorized operator review/promotion request may create durable`trainingStatus="eligible"` rows. Promotion uses an atomic lifecycle claim so asecond concurrent reviewer cannot write the same receipt again. After promotion,raw contributed content is cleared from the receipt ledger; lifecycle metadata, server-owneddedup keys, provider paths, and only the delete-capability hash remain.The same receipt capability remains valid after promotion. DELETE then means107 unmodified lines---## 14. Contribution record identity and deduplicationThere are two intentionally separate collection paths:| Path | Endpoint | Typical folder | Content semantics ||---|---|---|---|| Rating telemetry | `POST /v1/feedback` | `feedback/` | bounded rating/event mechanics only; never training-eligible || Explicit contribution | `POST /v1/contribute` | `contributions/` | user-reviewed Q&A or one ordered conversation record |Feedback telemetry no longer carries query/answer content, so it is **not** joinedwith contributions to form training examples. It remains `trainingStatus="telemetry"`and is excluded from ordinary training output.Contribution dedup keys are server-owned and receipt-scoped rather than stablebrowser conversation identifiers:```textQ&A record: <receipt-id>:<answer-index>Conversation record: <receipt-id>:conversation```The same key is reused by later eligible/withdrawal lifecycle records solast-write-wins can suppress a withdrawn contribution without exposing a stableclient identity. Within a key, the newest server `_ts` wins. A whole conversationremains one record throughout quarantine, promotion, and withdrawal.---685 unmodified lines- exact legacy duplicate records across mirrors suppressed;- same canonical record ID + different bytes fails closed;- guarded remote archive extraction;- historical schema normalization to current schema v4 when `_utils/_dataset_schema.py` is available;- default exclusion of feedback telemetry/quarantined/legacy-unreviewed records;- training acceptance only for `trainingStatus="eligible"` contributions;- tombstone/retraction handling where applicable;
145 unmodified lines146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176103 unmodified lines280281282283284285286338 unmodified lines62562662762862963063132 unmodified lines664665666667668669670671672673674675676677678679680681682683684685686145 unmodified lines### `POST /v1/contribute` β payload schema```json{"schemaVersion": 1,"consentFlag": true,"consentVersion": "v1.0","sessionId": "uuid-string","page": "https://your-docs-site/index.html","model": { "id": "...", "provider": "...", "model": "..." },"records": [{"answerIndex": 0,"query": "What is a confusion matrix?","answer": "A confusion matrix is...","ratingValue": 2,"ratingLabel": "π","message": "optional free-text from user","ts": 1781002584724}]}```Each accepted record receives a stable content-derived ID, but raw accepted content is **not** written to the provider repositories immediately. It enters the mutable contribution receipt ledger first with `trainingStatus="quarantined"`. Only an independently authorized promotion writes an `eligible` row beneath `contributions/YYYY/MM/DD/<record-id>.jsonl` in the Primary/Mirrors. Only answers the user has explicitly rated are included β unrated answers are skipped by the browser widget before the request is sent.The receipt's delete capability remains meaningful after promotion. While pending it removes the content from the active review ledger. After promotion the same capability records a privacy-minimal `withdraw` tombstone keyed by the server-owned contribution dedup key and attempts best-effort removal from each provider's current branch/view. Dataset construction applies the withdrawal through last-write-wins and excludes both the withdrawn eligible row and the tombstone itself from training output. Versioned repository history, database pages/WAL remnants, backups, CDN/provider logs, and infrastructure snapshots are **not** claimed physically erased.---103 unmodified lines|---|---|---:|---|| `RECORD_STORAGE_TARGETS` | Variable | New multi-store mode | Provider-neutral JSON topology with exactly one Primary and optional Mirrors. Contains token environment-variable **names**, never token values. || `TRAINING_DATASET_REPO` | Variable | Legacy HF mode only | Backward-compatible HF Dataset repo ID. When `RECORD_STORAGE_TARGETS` is present, the explicit target topology is authoritative; this value may remain for rollback/older discovery consumers. || `FEEDBACK_PERSIST_ENABLED` | Variable | No | Opt-in persistence of privacy-minimal `/v1/feedback` telemetry. Default is `false`; feedback is never training-eligible. || `CONTRIBUTION_REVIEW_TOKEN` | Secret | For promotion | Operator-only token required to promote quarantined contribution intake to durable `trainingStatus=eligible` storage. || `CONTRIBUTION_LEDGER_BACKEND` | Variable | No | `memory` (default), `sqlite` (local transactional/restart-durable), or `redis` (shared transactional authority across replicas in one Redis consistency domain). Redis persistence durability is deployment-conditional and is not inferred by the proxy. || `CONTRIBUTION_LEDGER_SQLITE_PATH` | Variable | When using SQLite | Local SQLite database path. Keep it on deployment-owned persistent storage if restart durability is required. |338 unmodified lines# 1. Liveness probecurl $BASE/health# {"status":"ok","version":"6.5.2"}# Optional deterministic stub rig statuscurl -s $BASE/health | python3 -m json.tool32 unmodified linescurl $BASE/v1/contribute \-H "Content-Type: application/json" \-d '{"schemaVersion": 1,"consentFlag": true,"consentVersion": "v1.0","sessionId": "test-session-001","page": "https://example.com","model": null,"records": [{"answerIndex": 0,"query": "test query","answer": "test answer","ratingValue": 2,"ratingLabel": "π","message": "","ts": 1781002584724}]}'# {"contributed": true, "rows": 1, "recordId": "...", "primary": "...", "mirrors": {...}}```---145 unmodified lines146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217103 unmodified lines321322323324325326327338 unmodified lines66666766866967067167232 unmodified lines705706707708709710711712713714715716717718719720721722723724725726727145 unmodified lines### `POST /v1/contribute` β payload schemaThe current browser sends **schema v4** with consent **2.0.0**. The endpointsupports two explicit contribution record families. A whole conversation is oneordered record:```json{"schemaVersion": 4,"consentFlag": true,"consentVersion": "2.0.0","page": "https://your-docs-site/index.html","model": null,"records": [{"recordType": "conversation","messages": [{"role": "user", "content": "What is a confusion matrix?", "ts": 1781002584000},{"role": "assistant","content": "A confusion matrix is...","ts": 1781002584724,"model": {"id": "...", "provider": "...", "model": "..."},"feedback": {"ratingValue": 2, "ratingLabel": "helpful", "note": "optional"}}],"message": "optional contribution-level reviewer note","ts": 1781002585000}]}```The dedicated **Contribute to dataset** sheet also supports **This Q&A** and**Rated answers** scopes. Those produce `recordType="qa"` records using thehistorical `query` / `answer` shape. The current v4 envelope always requires`consentVersion="2.0.0"`; legacy schema v2/v3 clients remain accepted with theirhistorical `1.0.0` consent for compatibility, but legacy consent is not acceptedfor the broader v4 contract.Ordinary `/v1/feedback` remains privacy-minimal rating telemetry and never turnsinto content contribution automatically. The browser keeps ratings local unlessthe reader explicitly enables **Send rating telemetry**. Current telemetry uses aversioned permission (`telemetryConsent=true`, `telemetryConsentVersion="1.0.0"`)and the proxy rejects feedback requests that do not carry that current consentcontract. Enabling telemetry does not contribute the question, answer, note,page, model, or conversation content. Turning telemetry off stops future sends;it does not claim erasure of telemetry already accepted by a remote provider.Each accepted contribution record receives a server receipt-scoped dedup key,but raw accepted content is **not** written to provider repositories immediately.It enters the mutable contribution receipt ledger first with`trainingStatus="quarantined"`. Only an independently authorized promotion writesan `eligible` row beneath `contributions/YYYY/MM/DD/<record-id>.jsonl` in thePrimary/Mirrors. Whole-conversation mode contributes one ordered conversationrecord; rated-answer mode contributes only explicitly rated Q&A records; thesingle-Q&A shortcut contributes only the selected Q&A after the same inspect,privacy-review, and consent flow.The receipt's delete capability remains meaningful after promotion. Whilepending it removes the content from the active review ledger. After promotionthe same capability records a privacy-minimal `withdraw` tombstone keyed by theserver-owned contribution dedup key and attempts best-effort removal from eachprovider's current branch/view. Dataset construction applies the withdrawalthrough last-write-wins and excludes both the withdrawn eligible row and thetombstone itself from training output. Versioned repository history, databasepages/WAL remnants, backups, CDN/provider logs, and infrastructure snapshots are**not** claimed physically erased.---103 unmodified lines|---|---|---:|---|| `RECORD_STORAGE_TARGETS` | Variable | New multi-store mode | Provider-neutral JSON topology with exactly one Primary and optional Mirrors. Contains token environment-variable **names**, never token values. || `TRAINING_DATASET_REPO` | Variable | Legacy HF mode only | Backward-compatible HF Dataset repo ID. When `RECORD_STORAGE_TARGETS` is present, the explicit target topology is authoritative; this value may remain for rollback/older discovery consumers. || `FEEDBACK_PERSIST_ENABLED` | Variable | No | Server-side persistence permission for privacy-minimal `/v1/feedback` telemetry. Default is `false`; it cannot override the browser user-consent gate, and feedback is never training-eligible. || `CONTRIBUTION_REVIEW_TOKEN` | Secret | For promotion | Operator-only token required to promote quarantined contribution intake to durable `trainingStatus=eligible` storage. || `CONTRIBUTION_LEDGER_BACKEND` | Variable | No | `memory` (default), `sqlite` (local transactional/restart-durable), or `redis` (shared transactional authority across replicas in one Redis consistency domain). Redis persistence durability is deployment-conditional and is not inferred by the proxy. || `CONTRIBUTION_LEDGER_SQLITE_PATH` | Variable | When using SQLite | Local SQLite database path. Keep it on deployment-owned persistent storage if restart durability is required. |338 unmodified lines# 1. Liveness probecurl $BASE/health# {"status":"ok","version":"6.6.1"}# Optional deterministic stub rig statuscurl -s $BASE/health | python3 -m json.tool32 unmodified linescurl $BASE/v1/contribute \-H "Content-Type: application/json" \-d '{"schemaVersion": 4,"consentFlag": true,"consentVersion": "2.0.0","page": "https://example.com","model": {"id":"test-model","provider":"test"},"records": [{"recordType": "qa","answerIndex": 0,"query": "test query","answer": "test answer","ratingValue": 2,"ratingLabel": "helpful","message": "","ts": 1781002584724}]}'# {"contributed": true, "status": "quarantined", "rows": 1, "receiptId": "...", "deleteToken": "..."}```---
12342 unmodified lines7891011121314151617181920212217 unmodified lines40414243444546478 unmodified lines56575859606114 unmodified lines767778798081825 unmodified lines8889909192939414 unmodified lines10911011111211311411523 unmodified lines139140141142143144145146415 unmodified lines5625635645655665677 unmodified lines5755765775785795801 unmodified line5825835845855865872 unmodified lines5905915925935945955965975985996006014 unmodified lines6066076086096106116126136141 unmodified line6166176186196206214 unmodified lines62662762862963063163263363430 unmodified lines66566666766866967099 unmodified lines7707717727737747754 unmodified lines780781782783784785# scikitplot/_externals/_sphinx_ext/_sphinx_ai_assistant/_hf_spaces_proxy/dataset_schema.py## flake8: noqa: D213#2 unmodified lines"""Canonical schema and normalization for collection records.Schema v3 separates two data classes:* ``feedback`` is privacy-minimal rating telemetry. Content, model, page andconversation identity are discarded even when legacy/direct callers submit them;``trainingStatus`` is always ``telemetry``.* ``contribution`` is explicit-content intake. It carries versioned consent, isinitially ``quarantined``, labels model attribution ``client_reported``, and istraining-eligible only after an authorised review promotes it.Historical v1/v2 rows remain readable through :func:`normalize_record`, but oldcontributions become ``legacy_unreviewed`` rather than silently entering training.Client IP addresses are never dataset fields. See ``DATASET_COLLECTION_GUIDANCE.md``for lifecycle and retention policy.17 unmodified lines#: Increment when a breaking field-name change is introduced; additive#: changes (new optional columns, wider population of existing columns) bump#: this too so consumers can branch on ``schemaVersion`` to know which fields#: to expect. See "Schema version history" above for what changed in v2.SCHEMA_VERSION: int = 3#: Ordered list of canonical column names. Every stored JSONL row and every#: row in the pandas DataFrame will have these columns in exactly this order.8 unmodified lines"conversationId", # legacy field; v3 feedback/contribution normalization writes None"feedbackId", # feedback event id only; contributions write None# ββ Record descriptor βββββββββββββββββββββββββββββββββββββββββββββββββββββ"answerIndex", # 0-based position of answer in the conversation"action", # "rate" | "retract""prevFeedbackId", # feedbackId of the record this one supersedes/invalidates.14 unmodified lines"message", # contribution text only; feedback telemetry writes empty string# ββ Conversation content ββββββββββββββββββββββββββββββββββββββββββββββββββ"query", # contribution user question; feedback telemetry writes empty string"answer", # contribution model response; feedback telemetry writes empty string# ββ Model ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ"model", # dict | None: normalised 8-key model object (see MODEL_KEYS)"modelEvidence", # None | "client_reported" | "legacy_unverified"5 unmodified lines]#: Required keys for the normalised model sub-object.#: Both feedback (3-key shape) and contribution (8-key shape) are expanded to#: this full set; keys absent in the source are filled with ``None``.MODEL_KEYS: list[str] = ["id", # canonical model identifier (e.g. "Qwen2.5-Coder-7B-Instruct-hf")14 unmodified lines#: whenever the displayed contribution terms change materially and update the#: browser ``CONSENT_VERSION`` in the same run.CONSENT_VERSION_ENABLED: bool = TrueRESERVED_CONSENT_VERSION: str = "1.0.0"def _resolve_consent_version(raw: Any) -> str | None:23 unmodified linesExamples-------->>> _resolve_consent_version("1.0.0")'1.0.0'>>> _resolve_consent_version(None)"""if not CONSENT_VERSION_ENABLED:415 unmodified lines"_dedup_key": dedup,"conversationId": None,"feedbackId": feedback_id,"answerIndex": answer_index,"action": "retract" if is_retract else "rate","prevFeedbackId": prev_feedback_id,7 unmodified lines"message": "","query": "","answer": "","model": None,"modelEvidence": None,"page": "",1 unmodified line"ts": payload.get("ts"),})def normalize_contribution_record(rec: dict[str, Any],*,2 unmodified linestraining_status: str = "quarantined",submission_id: str | None = None,) -> dict[str, Any]:"""Normalize one explicitly consented contribution record.Model/provider metadata is a client report, not verified provenance.``training_status`` is server-owned and defaults to ``quarantined``; only anauthorised review/promotion path may create ``eligible`` records."""answer_index = rec.get("answerIndex")try:answer_index = int(answer_index) if answer_index is not None else None4 unmodified linesrating_mode=rec.get("ratingMode"), rating_title=rec.get("ratingTitle"),feedback_id=None,)if training_status not in {"quarantined", "eligible", "legacy_unreviewed"}:training_status = "quarantined"dedup_base = _safe_id(submission_id) or "pending"return _ordered({"schemaVersion": SCHEMA_VERSION,"_source": "contribution",1 unmodified line"_dedup_key": f"{dedup_base}:{answer_index}","conversationId": None,"feedbackId": None,"answerIndex": answer_index,"action": "rate","prevFeedbackId": None,4 unmodified lines"ratingSlug": rating_fields["ratingSlug"],"ratingTitle": rating_fields["ratingTitle"],"ratingMode": rating_fields["ratingMode"],"message": rec.get("message") or "","query": rec.get("query") or "","answer": rec.get("answer") or "","model": normalize_model(envelope.get("model")),"modelEvidence": "client_reported" if envelope.get("model") else None,"page": envelope.get("page") or "",30 unmodified lines"_dedup_key": key,"conversationId": None,"feedbackId": None,"answerIndex": answer_index,"action": "withdraw","prevFeedbackId": None,99 unmodified lines# ββ Back-fill missing canonical fields (schemaVersion: 1 β 2) βββββββββββββout["schemaVersion"] = SCHEMA_VERSIONout.setdefault("feedbackId", None)out.setdefault("action", "rate")out.setdefault("prevFeedbackId", None)# editCount: None for retraction tombstones (not applicable), 0 for any4 unmodified linesout.setdefault("message", "")out.setdefault("query", "")out.setdefault("answer", "")out.setdefault("page", "")out.setdefault("modelEvidence", "legacy_unverified" if out.get("model") else None)12342 unmodified lines789101112131415161718192021222317 unmodified lines41424344454647488 unmodified lines5758596061626314 unmodified lines78798081828384855 unmodified lines9192939495969714 unmodified lines11211311411511611711811912012123 unmodified lines145146147148149150151152415 unmodified lines5685695705715725735747 unmodified lines5825835845855865875881 unmodified line5905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536542 unmodified lines6576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017024 unmodified lines7077087097107117121 unmodified line7147157167177187197204 unmodified lines72572672772872973073173273373430 unmodified lines76576676776876977077199 unmodified lines8718728738748758768774 unmodified lines882883884885886887888# scikitplot/_externals/_sphinx_ext/_sphinx_ai_assistant/_hf_spaces_proxy/_utils/_dataset_schema.py## flake8: noqa: D213#2 unmodified lines"""Canonical schema and normalization for collection records.Schema v4 separates telemetry from two explicit contribution record families:* ``feedback`` is privacy-minimal rating telemetry. Content, model, page andconversation identity are discarded even when legacy/direct callers submit them;``trainingStatus`` is always ``telemetry``.* ``contribution`` is explicit-content intake. Q&A records retain the historical``query``/``answer`` shape while conversation records carry one ordered ``messages``array. Both carry versioned consent, enter ``quarantined`` state, and aretraining-eligible only after an authorised review promotes them.Historical v1/v2/v3 rows remain readable through :func:`normalize_record`, but oldcontributions become ``legacy_unreviewed`` rather than silently entering training.Client IP addresses are never dataset fields. See ``DATASET_COLLECTION_GUIDANCE.md``for lifecycle and retention policy.17 unmodified lines#: Increment when a breaking field-name change is introduced; additive#: changes (new optional columns, wider population of existing columns) bump#: this too so consumers can branch on ``schemaVersion`` to know which fields#: to expect. See the module docstring and collection guidance for version semantics.SCHEMA_VERSION: int = 4#: Ordered list of canonical column names. Every stored JSONL row and every#: row in the pandas DataFrame will have these columns in exactly this order.8 unmodified lines"conversationId", # legacy field; v3 feedback/contribution normalization writes None"feedbackId", # feedback event id only; contributions write None# ββ Record descriptor βββββββββββββββββββββββββββββββββββββββββββββββββββββ"recordType", # "qa" | "conversation" (feedback writes None)"answerIndex", # 0-based position of answer in the conversation"action", # "rate" | "retract""prevFeedbackId", # feedbackId of the record this one supersedes/invalidates.14 unmodified lines"message", # contribution text only; feedback telemetry writes empty string# ββ Conversation content ββββββββββββββββββββββββββββββββββββββββββββββββββ"query", # contribution user question; feedback telemetry writes empty string"answer", # Q&A contribution model response; feedback telemetry/conversations write empty string"messages", # conversation contribution ordered message list; otherwise None# ββ Model ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ"model", # dict | None: normalised 8-key model object (see MODEL_KEYS)"modelEvidence", # None | "client_reported" | "legacy_unverified"5 unmodified lines]#: Required keys for the normalised model sub-object.#: Legacy/model-bearing contribution shapes are expanded to#: this full set; keys absent in the source are filled with ``None``.MODEL_KEYS: list[str] = ["id", # canonical model identifier (e.g. "Qwen2.5-Coder-7B-Instruct-hf")14 unmodified lines#: whenever the displayed contribution terms change materially and update the#: browser ``CONSENT_VERSION`` in the same run.CONSENT_VERSION_ENABLED: bool = TrueRESERVED_CONSENT_VERSION: str = "2.0.0"FEEDBACK_TELEMETRY_CONSENT_VERSION: str = "1.0.0"FEEDBACK_TELEMETRY_SCHEMA_VERSION: int = 4LEGACY_CONSENT_VERSIONS: frozenset[str] = frozenset({"1.0.0"})def _resolve_consent_version(raw: Any) -> str | None:23 unmodified linesExamples-------->>> _resolve_consent_version("2.0.0")'2.0.0'>>> _resolve_consent_version(None)"""if not CONSENT_VERSION_ENABLED:415 unmodified lines"_dedup_key": dedup,"conversationId": None,"feedbackId": feedback_id,"recordType": None,"answerIndex": answer_index,"action": "retract" if is_retract else "rate","prevFeedbackId": prev_feedback_id,7 unmodified lines"message": "","query": "","answer": "","messages": None,"model": None,"modelEvidence": None,"page": "",1 unmodified line"ts": payload.get("ts"),})_MAX_CONVERSATION_MESSAGES: int = 100_MAX_CONVERSATION_MESSAGE_CHARS: int = 100_000_MAX_CONTRIBUTION_NOTE_CHARS: int = 2_000def _bounded_text(value: Any, *, limit: int) -> str:"""Return a bounded string for explicit contribution content."""if not isinstance(value, str):return ""return value[:limit]def normalize_conversation_messages(value: Any) -> list[dict[str, Any]]:"""Normalize one explicit whole-conversation message array.Only ``user`` and ``assistant`` roles are accepted. Error/tool/system rows aredeliberately excluded from this training/evaluation contribution family.Per-assistant model and rating metadata remain client-reported evidence."""if not isinstance(value, list):return []out: list[dict[str, Any]] = []for raw in value[:_MAX_CONVERSATION_MESSAGES]:if not isinstance(raw, dict):continuerole = raw.get("role")if role not in {"user", "assistant"}:continuecontent = _bounded_text(raw.get("content"), limit=_MAX_CONVERSATION_MESSAGE_CHARS)if not content:continueitem: dict[str, Any] = {"role": role,"content": content,"ts": raw.get("ts") if isinstance(raw.get("ts"), (int, float)) and not isinstance(raw.get("ts"), bool) else None,}if role == "assistant":raw_model = raw.get("model")item["model"] = normalize_model(raw_model) if isinstance(raw_model, dict) else Noneraw_feedback = raw.get("feedback")if isinstance(raw_feedback, dict):rating = normalize_rating(raw_feedback.get("ratingValue"), raw_feedback.get("ratingLabel"),rating_mode=raw_feedback.get("ratingMode"),rating_title=raw_feedback.get("ratingTitle"), feedback_id=None,)item["feedback"] = {"ratingValue": raw_feedback.get("ratingValue"),"ratingSlug": rating["ratingSlug"],"ratingTitle": rating["ratingTitle"],"ratingMode": rating["ratingMode"],"note": _bounded_text(raw_feedback.get("note"), limit=_MAX_CONTRIBUTION_NOTE_CHARS),}else:item["feedback"] = Noneout.append(item)return outdef normalize_contribution_record(rec: dict[str, Any],*,2 unmodified linestraining_status: str = "quarantined",submission_id: str | None = None,) -> dict[str, Any]:"""Normalize one explicitly consented Q&A or conversation contribution."""if training_status not in {"quarantined", "eligible", "legacy_unreviewed"}:training_status = "quarantined"dedup_base = _safe_id(submission_id) or "pending"declared_type = rec.get("recordType")record_type = "conversation" if declared_type == "conversation" else "qa"if record_type == "conversation":messages = normalize_conversation_messages(rec.get("messages"))return _ordered({"schemaVersion": SCHEMA_VERSION,"_source": "contribution","_ts": server_ts_ms,"_dedup_key": f"{dedup_base}:conversation","conversationId": None,"feedbackId": None,"recordType": "conversation","answerIndex": None,"action": "rate","prevFeedbackId": None,"editCount": 0,"status": "active","trainingStatus": training_status,"ratingValue": None,"ratingSlug": None,"ratingTitle": None,"ratingMode": None,"message": _bounded_text(rec.get("message"), limit=_MAX_CONTRIBUTION_NOTE_CHARS),"query": "","answer": "","messages": messages,"model": None,"modelEvidence": "client_reported_per_message" if any(isinstance(m.get("model"), dict) for m in messages if m.get("role") == "assistant") else None,"page": envelope.get("page") or "","consentVersion": _resolve_consent_version(envelope.get("consentVersion")),"ts": rec.get("ts"),})answer_index = rec.get("answerIndex")try:answer_index = int(answer_index) if answer_index is not None else None4 unmodified linesrating_mode=rec.get("ratingMode"), rating_title=rec.get("ratingTitle"),feedback_id=None,)return _ordered({"schemaVersion": SCHEMA_VERSION,"_source": "contribution",1 unmodified line"_dedup_key": f"{dedup_base}:{answer_index}","conversationId": None,"feedbackId": None,"recordType": "qa","answerIndex": answer_index,"action": "rate","prevFeedbackId": None,4 unmodified lines"ratingSlug": rating_fields["ratingSlug"],"ratingTitle": rating_fields["ratingTitle"],"ratingMode": rating_fields["ratingMode"],"message": _bounded_text(rec.get("message"), limit=_MAX_CONTRIBUTION_NOTE_CHARS),"query": _bounded_text(rec.get("query"), limit=_MAX_CONVERSATION_MESSAGE_CHARS),"answer": _bounded_text(rec.get("answer"), limit=_MAX_CONVERSATION_MESSAGE_CHARS),"messages": None,"model": normalize_model(envelope.get("model")),"modelEvidence": "client_reported" if envelope.get("model") else None,"page": envelope.get("page") or "",30 unmodified lines"_dedup_key": key,"conversationId": None,"feedbackId": None,"recordType": None,"answerIndex": answer_index,"action": "withdraw","prevFeedbackId": None,99 unmodified lines# ββ Back-fill missing canonical fields (schemaVersion: 1 β 2) βββββββββββββout["schemaVersion"] = SCHEMA_VERSIONout.setdefault("feedbackId", None)out.setdefault("recordType", "qa" if source == "contribution" else None)out.setdefault("action", "rate")out.setdefault("prevFeedbackId", None)# editCount: None for retraction tombstones (not applicable), 0 for any4 unmodified linesout.setdefault("message", "")out.setdefault("query", "")out.setdefault("answer", "")out.setdefault("messages", None)out.setdefault("page", "")out.setdefault("modelEvidence", "legacy_unverified" if out.get("model") else None)
219 unmodified lines220221222223224225226219 unmodified lines# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ#: Proxy release version β bump on every breaking change.PROXY_VERSION: str = "6.5.2"#: HuggingFace Inference Providers router base URL (no trailing slash).#: Only used for Path 3 (standard provider models) when ``BACKEND_URL`` is219 unmodified lines220221222223224225226219 unmodified lines# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ#: Proxy release version β bump on every breaking change.PROXY_VERSION: str = "6.6.1"#: HuggingFace Inference Providers router base URL (no trailing slash).#: Only used for Path 3 (standard provider models) when ``BACKEND_URL`` is
109 unmodified lines11011111211311411511663 unmodified lines1801811821831841852 unmodified lines1881891901911921931875 unmodified lines206920702071207220732074355 unmodified lines243024312432243324342435243624372438243924402441244219 unmodified lines246224632464246524662467667 unmodified lines31353136313731383139314031413142314310 unmodified lines315431553156315731583159109 unmodified lines# RATE_LIMIT_REQUIRE_SHARED When true, local rate limiting is rejected and# Redis initialization/runtime failure returns HTTP 503.# RATE_LIMIT_REDIS_TIMEOUT_SECONDS Redis operation timeout; clamped 0.25..10 s.# FEEDBACK_PERSIST_ENABLED Persist privacy-minimal rating telemetry only. Default false.# CONTRIBUTION_REVIEW_TOKEN Server/operator token required to promote quarantined# contributions into durable training-eligible storage.# CONTRIBUTION_QUARANTINE_TTL_SECONDS Pending contribution lifetime. Default 86400.63 unmodified linesfrom ._utils._dataset_schema import ( # type: ignore[import]CONSENT_VERSION_ENABLED,RESERVED_CONSENT_VERSION,normalize_contribution_record,normalize_contribution_withdrawal_record,normalize_feedback_record,2 unmodified linesfrom _utils._dataset_schema import ( # type: ignore[import]CONSENT_VERSION_ENABLED,RESERVED_CONSENT_VERSION,normalize_contribution_record,normalize_contribution_withdrawal_record,normalize_feedback_record,1875 unmodified lines"dataset_repo": None,"contribute_ready": _contribution_pipeline_ready(),"feedback_persist_enabled": FEEDBACK_PERSIST_ENABLED,},"tokens": {"hf_token_type": "unknown",355 unmodified linesraise HTTPException(status_code=422, detail="Contribution body must be a JSON object.")if payload.get("consentFlag") is not True:raise HTTPException(status_code=422, detail="Explicit contribution consent is required.")if payload.get("consentVersion") != RESERVED_CONSENT_VERSION:raise HTTPException(status_code=422,detail="Consent text changed or is missing. Reload the page and review consent again.",)if payload.get("schemaVersion") not in {2, 3}:raise HTTPException(status_code=422, detail="Unsupported contribution schemaVersion.")records = payload.get("records")if not isinstance(records, list) or not records:raise HTTPException(status_code=422, detail="records must be a non-empty list.")19 unmodified lines)for rec in records if isinstance(rec, dict)]if not normalized:raise HTTPException(status_code=422, detail="No valid contribution records were supplied.")encoded = ("\n".join(json.dumps(r, ensure_ascii=False) for r in normalized)).encode("utf-8")667 unmodified linesasync def feedback(request: Request) -> JSONResponse:"""Accept privacy-minimal rating telemetry.Legacy/direct callers may submit query, answer, comment, model, page orconversation identifiers, but the server normalizer discards them beforeoptional persistence. Persistence is server opt-in(``FEEDBACK_PERSIST_ENABLED=false`` by default) and persisted rows are``trainingStatus=telemetry`` so the training builder excludes them."""10 unmodified linesstatus_code=422, detail="Feedback body must be a JSON object.")# ββ Distinguish retraction tombstones from regular ratings βββββββββββββββ# Retractions are system-generated housekeeping records that invalidate a# previous rating in the training dataset. They carry action="retract" and109 unmodified lines11011111211311411511663 unmodified lines1801811821831841851861871882 unmodified lines1911921931941951961971981991875 unmodified lines20752076207720782079208020812082355 unmodified lines243824392440244124422443244424452446244724482449245024512452245324542455245619 unmodified lines2476247724782479248024812482248324842485667 unmodified lines315331543155315631573158315931603161316210 unmodified lines3173317431753176317731783179318031813182318331843185318631873188318931903191319231933194109 unmodified lines# RATE_LIMIT_REQUIRE_SHARED When true, local rate limiting is rejected and# Redis initialization/runtime failure returns HTTP 503.# RATE_LIMIT_REDIS_TIMEOUT_SECONDS Redis operation timeout; clamped 0.25..10 s.# FEEDBACK_PERSIST_ENABLED Persist privacy-minimal consent-gated rating telemetry only. Default false.# CONTRIBUTION_REVIEW_TOKEN Server/operator token required to promote quarantined# contributions into durable training-eligible storage.# CONTRIBUTION_QUARANTINE_TTL_SECONDS Pending contribution lifetime. Default 86400.63 unmodified linesfrom ._utils._dataset_schema import ( # type: ignore[import]CONSENT_VERSION_ENABLED,RESERVED_CONSENT_VERSION,LEGACY_CONSENT_VERSIONS,FEEDBACK_TELEMETRY_CONSENT_VERSION,FEEDBACK_TELEMETRY_SCHEMA_VERSION,normalize_contribution_record,normalize_contribution_withdrawal_record,normalize_feedback_record,2 unmodified linesfrom _utils._dataset_schema import ( # type: ignore[import]CONSENT_VERSION_ENABLED,RESERVED_CONSENT_VERSION,LEGACY_CONSENT_VERSIONS,FEEDBACK_TELEMETRY_CONSENT_VERSION,FEEDBACK_TELEMETRY_SCHEMA_VERSION,normalize_contribution_record,normalize_contribution_withdrawal_record,normalize_feedback_record,1875 unmodified lines"dataset_repo": None,"contribute_ready": _contribution_pipeline_ready(),"feedback_persist_enabled": FEEDBACK_PERSIST_ENABLED,"feedback_telemetry_schema_version": FEEDBACK_TELEMETRY_SCHEMA_VERSION,"feedback_telemetry_consent_version": FEEDBACK_TELEMETRY_CONSENT_VERSION,},"tokens": {"hf_token_type": "unknown",355 unmodified linesraise HTTPException(status_code=422, detail="Contribution body must be a JSON object.")if payload.get("consentFlag") is not True:raise HTTPException(status_code=422, detail="Explicit contribution consent is required.")schema_version = payload.get("schemaVersion")if schema_version not in {2, 3, 4}:raise HTTPException(status_code=422, detail="Unsupported contribution schemaVersion.")consent_version = payload.get("consentVersion")if schema_version == 4:consent_ok = consent_version == RESERVED_CONSENT_VERSIONelse:consent_ok = consent_version in (LEGACY_CONSENT_VERSIONS | {RESERVED_CONSENT_VERSION})if not consent_ok:raise HTTPException(status_code=422,detail="Consent text changed or is missing. Reload the page and review consent again.",)records = payload.get("records")if not isinstance(records, list) or not records:raise HTTPException(status_code=422, detail="records must be a non-empty list.")19 unmodified lines)for rec in records if isinstance(rec, dict)]normalized = [row for row in normalizedif row.get("recordType") != "conversation" or bool(row.get("messages"))]if not normalized:raise HTTPException(status_code=422, detail="No valid contribution records were supplied.")encoded = ("\n".join(json.dumps(r, ensure_ascii=False) for r in normalized)).encode("utf-8")667 unmodified linesasync def feedback(request: Request) -> JSONResponse:"""Accept privacy-minimal rating telemetry.Every request must carry the current explicit telemetry-consent marker.Direct callers may still submit query, answer, comment, model, page orconversation identifiers, but the server normalizer discards them beforeoptional persistence. Persistence is server opt-in(``FEEDBACK_PERSIST_ENABLED=false`` by default) and persisted rows are``trainingStatus=telemetry`` so the training builder excludes them."""10 unmodified linesstatus_code=422, detail="Feedback body must be a JSON object.")# Network feedback is user-consented telemetry, not an implicit side effect# of clicking a local rating button. Reject legacy/misbehaving clients that# do not carry the current explicit consent marker. This check occurs before# rate-limit/storage work so denied telemetry consumes minimal server state.if payload.get("telemetryConsent") is not True or payload.get("telemetryConsentVersion") != FEEDBACK_TELEMETRY_CONSENT_VERSION:logger.warning(json.dumps({"event": "feedback.consent_required"}))raise HTTPException(status_code=403,detail="Explicit feedback telemetry permission is required.",)if payload.get("schemaVersion") != FEEDBACK_TELEMETRY_SCHEMA_VERSION:raise HTTPException(status_code=422, detail="Unsupported feedback telemetry schema version.")consent_at = payload.get("telemetryConsentAt")if not isinstance(consent_at, (int, float)) or isinstance(consent_at, bool) or consent_at <= 0:raise HTTPException(status_code=422, detail="Feedback telemetry consent timestamp is required.")# ββ Distinguish retraction tombstones from regular ratings βββββββββββββββ# Retractions are system-generated housekeeping records that invalidate a# previous rating in the training dataset. They carry action="retract" and
DATASET_COLLECTION_GUIDANCE.md+43-27
README.md+73-32
_utils/_dataset_schema.py+127-24
_utils/_shared_logic.py+1-1
app.py+41-6