) is not None: return True if field == "outcome_variable_Y": _m_ep = _re.fullmatch( r"\[Endpoint: ([A-Za-z0-9_]+) \| polarity=([A-Za-z0-9_]+) \| orientation_sign=(-1|0|1) \| unit=([^\|\]]+?)(?: \| erratum_pmid=([1-9][0-9]{6,7}))?\]", value, ) if _m_ep is not None: return ( _m_ep.group(1) in by_field.get("outcome_domain", ()) and _m_ep.group(2) in by_field.get("polarity_class", ()) and _m_ep.group(4) in by_field.get("measurement_unit", ()) ) return value in by_field.get(field, ()) or (field == "source_span" and span_pattern.fullmatch(value) is not None) def _source_free_effect_identifier(value, field): # Source-free replay retains this bounded legacy identifier; it cannot # authenticate its original prose. With a private source available it is # deliberately counted for overlap, just like any source-derived slug. return field == 'effect_id' and isinstance(value, str) and _re.fullmatch(r'[a-z][a-z0-9_]{5,96}', value) is not None def _rewrite_exact_arm_references(obj: object, identifier_map: dict[str, str]) -> object: """Publish opaque arm IDs, preserving every exact foreign-key reference.""" if isinstance(obj, dict): return {k: _rewrite_exact_arm_references(v, identifier_map) for k, v in obj.items()} if isinstance(obj, list): return [_rewrite_exact_arm_references(v, identifier_map) for v in obj] if isinstance(obj, str): return identifier_map.get(obj, obj) return obj def _validate_imported_redaction_tokens(obj: object, pmid: str, dossier: dict | None, parent: dict | None = None, parent_key: str = "") -> None: """Input-origin references must not acquire trust merely by matching a regex.""" if isinstance(obj, dict): for key, value in obj.items(): _validate_imported_redaction_tokens(value, pmid, dossier, obj, key) elif isinstance(obj, list): for value in obj: _validate_imported_redaction_tokens(value, pmid, dossier, parent, parent_key) elif _has_redaction_prefix(obj): source_quote = None if dossier is not None: span = str((parent or {}).get("source_span") or "") m = _re.fullmatch(r"(.+)\[(\d+):(\d+)\]\|norm=exact", span) if m: value: object = dossier try: tokens = _re.findall(r"([A-Za-z_][A-Za-z0-9_]*)|\[([0-9]+)\]", m[1]) rebuilt = "" for key, index in tokens: rebuilt += ("." if rebuilt and key else "") + key if key else f"[{index}]" value = value[key] if key else value[int(index)] if rebuilt != m[1]: raise KeyError("Unsupported source path syntax") if isinstance(value, str) and 0 <= int(m[2]) < int(m[3]) <= len(value): source_quote = value[int(m[2]):int(m[3])] except (KeyError, TypeError, IndexError): pass if source_quote is None: raise ValueError(f"Opaque input token for PMID {pmid} cannot be bound to the available source") if not _validate_public_redaction_token(obj, expected_pmid=pmid, source_quote=source_quote, expected_field=parent_key): raise ValueError(f"Invalid or unauthenticated public redaction token for PMID {pmid}") def _has_symlink_component(path: Path, stop_at: Path | None = None) -> bool: """Return True if `path` or any parent up to `stop_at` is a symbolic link.""" cur = path stop_res = stop_at.resolve() if stop_at is not None and not stop_at.is_symlink() else stop_at while True: if cur.is_symlink(): return True if stop_res is not None and cur == stop_res: break if cur.parent == cur: break cur = cur.parent return False def _source_words(text: str) -> list[str]: import unicodedata normalized = unicodedata.normalize('NFKD', text).casefold() normalized = ''.join(c for c in normalized if unicodedata.category(c) not in {'Cf','Mn','Me'}) return _re.findall(r'[^\W_]+', normalized) @lru_cache(maxsize=16) def _normalized_source(text: str) -> str: # Complete immutable source content is the cache key, never a path/mtime. return " " + " ".join(_source_words(text)) + " " def _max_verbatim_shingle_chars(text: object, source_text: str, shingle_words: int = 6, parent_key: str = "", title_str: str = "", bibliographic: bool = False) -> int: """Count source-overlapping prose, excluding only bounded metadata in its typed field. Exact short fragments count too. This is the same metadata scope used by enforcement and its post-condition; free-text enum lookalikes still count. """ if not source_text or text is None: return 0 if isinstance(text, dict): t_str = title_str or str((text.get("study_metadata") or {}).get("title") or "") return sum(_max_verbatim_shingle_chars(v, source_text, shingle_words, k, t_str, parent_key=='study_metadata') for k, v in text.items()) if isinstance(text, list): return sum(_max_verbatim_shingle_chars(v, source_text, shingle_words, parent_key, title_str,bibliographic) for v in text) if not isinstance(text, str): return 0 if _is_bounded_public_metadata(text,parent_key,bibliographic=bibliographic): return 0 if not text or _is_authentic_redaction_marker(text) or _is_fixed_public_schema_metadata(text, parent_key): return 0 w_txt = _source_words(text) src_norm = _normalized_source(source_text) if len(w_txt) < shingle_words: # A whole short source fragment is still verbatim. Otherwise source # sentences split across <=5-word leaves evade the aggregate budget. short_fragment = " " + " ".join(w_txt) + " " return len(text) if w_txt and short_fragment in src_norm else 0 for i in range(len(w_txt) - shingle_words + 1): shingle = " " + " ".join(w_txt[i : i + shingle_words]) + " " if shingle in src_norm: return len(text) return 0 def _public_discovery_record(record: dict) -> dict: """Discovery metadata ships identifiers and abstract digests, never abstracts. A future live harvest may restore inline source text in the private raw cache. Export must independently enforce this boundary on every run. """ if not isinstance(record, dict): raise ValueError("Discovery records must be JSON objects") # A shallow allowlist lets an adapter hide full text in authors/keywords. # Preserve the harvest's flat bibliographic schema; unexpected shapes fail # before publication rather than being silently converted or truncated. scalar_limits={'title':2000,'journal':1000,'first_author':512,'senior_author':512,'source_db':128} list_limits={'authors':(10000,512),'mesh_terms':(256,256),'keywords':(256,256), 'publication_types':(256,128),'matched_pillars':(256,128)} identifiers={'pmid':r'[1-9][0-9]{0,8}','pmcid':r'PMC[1-9][0-9]{0,9}', 'doi':r'10\.[0-9]{4,9}/[^\s\x00-\x1f\x7f]+','abstract_sha256':r'[0-9a-f]{64}'} flags={'has_abstract','has_open_pmc_fulltext'} metadata_fields=set(scalar_limits)|set(list_limits)|set(identifiers)|flags|{'pub_year'} def bounded_text(value, limit): return isinstance(value,str) and len(value)<=limit and _re.search(r'[\x00-\x1f\x7f]',value) is None public={} for key,value in record.items(): if key not in metadata_fields: continue if value is None: valid=True elif key in scalar_limits: valid=bounded_text(value,scalar_limits[key]) elif key in list_limits: count,limit=list_limits[key] valid=isinstance(value,list) and len(value)<=count and all(bounded_text(item,limit) for item in value) elif key in identifiers: valid=isinstance(value,str) and len(value)<=256 and _re.fullmatch(identifiers[key],value) is not None elif key in flags: valid=type(value) is bool else: valid=type(value) is int and 1<=value<=9999 if not valid: raise ValueError(f'Discovery metadata field {key} has invalid type, shape or bounds') public[key]=value if "abstract" in record: abstract = record['abstract'] if abstract is not None and not isinstance(abstract, str): raise ValueError("Discovery abstract must be text or null") public["has_abstract"] = bool(abstract) if abstract: public["abstract_sha256"] = hashlib.sha256(abstract.encode("utf-8")).hexdigest() return public def public_token_errors(obj, expected_pmid=None, parent_key=''): """Check every opaque reference, including graph hops, without private text. This is a syntax/identity/field check only. Source-free public verification cannot authenticate the absent private source or its scientific meaning. """ errors=[] def visit(value,pmid,key,path): if isinstance(value,dict): label=value.get('pmid') or value.get('study') if label: match=_re.search(r'(?