OpenIslet

scripts/generate_release_manifest.py

Generate the Wave-0 / P0-8 Release & Provenance Manifest (`manifest.json`) and

script Release v0.8.0 gen-eb955f8266035aba 148 KB · 11 sections

Use this file in any AI chat (paste-only or attachment-capable):

Download as text (.txt) Download section (.txt)

Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/generate_release_manifest.py · SHA-256: 9b8e7a9ff4998368…

                        if ev and not _is_authentic_redaction_marker(ev):
                            ch[f"hop{h_idx}_evidence"] = f"{_redaction_prefix_for_pmid(pm)} see PMID:{pm} field=hop{h_idx}_evidence quote_sha256={hashlib.sha256(ev.encode('utf-8')).hexdigest()}]"
            for edge in g_obj.get("all_causal_edges") or g_obj.get("causal_edges_all") or []:
                pm = _extract_pmid(edge.get("study", ""))
                if pm in non_oa_pmids:
                    for nfield in ("upstream_node", "downstream_node"):
                        nval = edge.get(nfield) or ""
                        edge[nfield] = _strip_node_quote_suffix(nval, pm)
                    esrc = edge.get("evidence_source") or ""
                    if esrc and not _is_authentic_redaction_marker(esrc):
                        edge["evidence_source"] = f"{_redaction_prefix_for_pmid(pm)} see PMID:{pm} field=evidence_source quote_sha256={hashlib.sha256(esrc.encode('utf-8')).hexdigest()}]"

            # Recursive graph-wide shingle budget enforcement sharing `pmid_shingle_used[pm]` with study JSONs:
            normalized_sources={pm:_normalized_source(source) for pm,(source,_) in dossier_source_cache.items() if source}
            unbound_match_cache={}
            def _unbound_source_match(value,key):
                if _is_bounded_public_metadata(value,key):
                    return ''
                if _is_authentic_redaction_marker(value) or _is_fixed_public_schema_metadata(value,key):return ''
                words=_source_words(value)
                if not words:return ''
                cache_key=tuple(words)
                if cache_key not in unbound_match_cache:
                    width=min(6,len(words))
                    shingles=[' '+' '.join(words[i:i+width])+' ' for i in range(len(words)-width+1)]
                    unbound_match_cache[cache_key]=next((pm for pm,source in normalized_sources.items() if any(shingle in source for shingle in shingles)),'')
                return unbound_match_cache[cache_key]
            def _enforce_graph_shingle_budget(obj: object, current_pm: str = "", parent_key: str = "") -> object:
                if isinstance(obj, dict):
                    for key in obj:
                        if len(_source_words(key))>=6 and _unbound_source_match(key,''):
                            raise ValueError('Graph field name contains source-derived prose')
                    pm_here = current_pm
                    lab = obj.get("pmid") or obj.get("study")
                    if lab:
                        cand_pm = _extract_pmid(str(lab))
                        if cand_pm in non_oa_pmids:
                            pm_here = cand_pm
                    for k in list(obj.keys()):
                        k_pm = pm_here
                        if k in ("hop1_from", "hop1_to", "hop1_evidence", "origin_node", "bridge_node") and obj.get("hop1_study"):
                            c1 = _extract_pmid(str(obj.get("hop1_study")))
                            if c1 in non_oa_pmids:
                                k_pm = c1
                        elif k in ("hop2_to", "hop2_evidence", "terminal_node") and obj.get("hop2_study"):
                            c2 = _extract_pmid(str(obj.get("hop2_study")))
                            if c2 in non_oa_pmids:
                                k_pm = c2
                        obj[k] = _enforce_graph_shingle_budget(obj[k], k_pm, k)
                    return obj
                if isinstance(obj, list):
                    for idx in range(len(obj)):
                        obj[idx] = _enforce_graph_shingle_budget(obj[idx], current_pm, parent_key)
                    return obj
                if isinstance(obj,str) and current_pm not in non_oa_pmids:
                    source_pm=_unbound_source_match(obj,parent_key)
                    if source_pm:
                        digest=hashlib.sha256(obj.encode('utf-8')).hexdigest()
                        field=_public_redaction_field(parent_key or 'field')
                        return f'{_redaction_prefix_for_pmid(source_pm)} see PMID:{source_pm} field={field} quote_sha256={digest}]'
                if isinstance(obj, str) and current_pm in non_oa_pmids:
                    if _is_bounded_public_metadata(obj,parent_key):
                        return obj
                    if not dossier_source_cache.get(current_pm, ('', 0))[0] and _source_free_effect_identifier(obj, parent_key):
                        return obj
                    if _is_authentic_redaction_marker(obj) or _is_fixed_public_schema_metadata(obj, parent_key):
                        return obj
                    f_tok = _public_redaction_field(parent_key or "field")
                    if obj.startswith("[REDACTED_NON_OA_EXCERPT:") or obj.startswith("[REDACTED_CONSERVATIVE_EXCERPT:"):
                        s_sha = hashlib.sha256(obj.encode("utf-8")).hexdigest()
                        return f"{_redaction_prefix_for_pmid(current_pm)} see PMID:{current_pm} field={f_tok} quote_sha256={s_sha}]"
                    full_src_t, c_budget = dossier_source_cache.get(current_pm, ("", 0))
                    v_len = _max_verbatim_shingle_chars(obj, full_src_t) if full_src_t else len(obj)
                    if v_len > 0:
                        if pmid_shingle_used.get(current_pm, 0) + v_len <= c_budget:
                            pmid_shingle_used[current_pm] = pmid_shingle_used.get(current_pm, 0) + v_len
                        else:
                            s_sha = hashlib.sha256(obj.encode("utf-8")).hexdigest()
                            return f"{_redaction_prefix_for_pmid(current_pm)} see PMID:{current_pm} field={f_tok} quote_sha256={s_sha}]"
                return obj

            _enforce_graph_shingle_budget(g_obj)
            graph_path.write_text(json.dumps(g_obj, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")

        public_graph=json.loads(graph_path.read_text(encoding='utf-8')) if graph_path.exists() else {}
        recomputed_totals=public_article_verbatim_totals(redacted_studies,public_graph,dossier_source_cache)
        if any(total>dossier_source_cache[pmid][1] for pmid,total in recomputed_totals.items()):
            raise ValueError('Combined study/graph excerpt budget post-condition failed')

        from jsonschema import Draft202012Validator
        export_schema = Draft202012Validator(json.loads(schema_bytes))
        for study_path in study_paths:
            exported_study = json.loads(study_path.read_text(encoding="utf-8"))
            export_schema.validate(exported_study)
            arm_ids = {arm["arm_id"] for arm in exported_study.get("arms", [])}
            for effect in exported_study.get("atomic_effects", []):
                if effect.get("focal_arm_id") not in arm_ids or (effect.get("comparator_arm_id") is not None and effect["comparator_arm_id"] not in arm_ids):
                    raise ValueError("Public export broke a study arm foreign key")

        # Post-condition shingle verification across all exported non-OA study JSONs
        for sp in study_paths:
            doc = json.loads(sp.read_text(encoding="utf-8"))
            pmid = str((doc.get("study_metadata") or {}).get("pmid", sp.stem))
            if pmid not in non_oa_pmids:
                continue
            full_src_text, char_budget = dossier_source_cache.get(pmid, ("", 0))
            title_str = str((doc.get("study_metadata") or {}).get("title") or "")

            def _walk_verbatim_chars(obj: object, parent_key: str = "",bibliographic: bool = False) -> int:
                if isinstance(obj, dict):
                    return sum(_walk_verbatim_chars(v, k,parent_key=='study_metadata') for k, v in obj.items())
                if isinstance(obj, list):
                    return sum(_walk_verbatim_chars(v, parent_key,bibliographic) for v in obj)
                if isinstance(obj, str):
                    if _is_bounded_public_metadata(obj,parent_key,bibliographic=bibliographic):
                        return 0
                    if not full_src_text and _source_free_effect_identifier(obj, parent_key):
                        return 0
                    if _is_authentic_redaction_marker(obj) or _is_fixed_public_schema_metadata(obj, parent_key):
                        return 0
                    if not full_src_text:
                        return len(obj)
                    return _max_verbatim_shingle_chars(obj, full_src_text)
                return 0

            _validate_imported_redaction_tokens(doc, pmid, None)
            total_v_chars = _walk_verbatim_chars(doc)
            if total_v_chars > char_budget:
                raise RuntimeError(
                    f"Public bundle post-condition violation for PMID:{pmid}: {total_v_chars} verbatim chars > budget {char_budget}"
                )

        # Rebind the prior plane to the actual public effects bytes, requiring all
        # numerical/semantic outputs to survive rights redaction unchanged.
        public_l2_path = work_dir / "data/extracted/layer2_regulatory_and_perturbation_atlas.json"
        public_effects_path = work_dir / "data/extracted/ring1_atomic_effects_v0.5.jsonl"
        if public_l2_path.exists() and public_effects_path.exists():
            import importlib.util
            plane_spec = importlib.util.spec_from_file_location("openislet_public_layer2_replay", work_dir / "scripts/run_layer2_perturbation_and_regulatory_plane.py")
            plane_module = importlib.util.module_from_spec(plane_spec)
            plane_spec.loader.exec_module(plane_module)
            plane_module.REPO_ROOT = work_dir
            public_l2 = json.loads(public_l2_path.read_text(encoding="utf-8"))
            original_plane = public_l2["stage0_to_stage7_perturbation_plane"]
            replayed_plane = plane_module.simulate_stage0_to_stage7_perturbation_plane(
                json.loads((work_dir / "data/raw/layer2_genomic_and_jaspar_reference.json").read_text(encoding="utf-8")),
                public_l2["construct_sequence_and_grammar_verification"],
                public_l2["jaspar_pwm_regulatory_motif_scans"],
                effects_path=public_effects_path,
            )
            semantic = lambda plane: {k: v for k, v in plane.items() if k != "input_provenance"}
            if semantic(original_plane) != semantic(replayed_plane):
                raise ValueError("Rights transformation changed Layer 2 prior-plane semantics; refusing publication")
            public_l2["stage0_to_stage7_perturbation_plane"] = replayed_plane
            public_l2.setdefault("public_effects_provenance_rebinding", {
                "canonical_original_effects_sha256": original_plane["input_provenance"]["ring1_atomic_effects"]["sha256"],
                "status": "REPLAYED_PUBLIC_BYTES_NUMERICAL_AND_SEMANTIC_OUTPUTS_IDENTICAL",
                "qualification": "Source redaction changes byte identity; only input fingerprints are rebound. No new prediction or assay is claimed."
            })
            public_l2_path.write_text(json.dumps(public_l2, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")

        # Update artifact digests in work_dir/manifest.json for the exported public bundle files
        pub_manifest = json.loads((work_dir / "manifest.json").read_text(encoding="utf-8"))
        pub_manifest["public_export_file_inventory"] = sorted(included - {"manifest.json"})
        pub_manifest["public_export_inventory_scope"] = "Exact shipped relative file paths; manifest.json and .openislet_public_bundle marker are the only omitted self/marker files"
        pub_manifest["public_arm_identifier_policy"] = {
            "format": "pmid<PMID>_arm<one-based arm position>",
            "arm_count": len(arm_identifier_map),
            "scope": "Deterministic opaque IDs; all exact foreign-key references transformed bijectively. Private source identifiers remain in the local audit tree."
        }
        for rel, entry in pub_manifest.get("artifacts", {}).items():
            fp = work_dir / rel
            if fp.exists():
                new_sha = sha256_file(fp)
                if new_sha != entry["sha256"]:
                    if "public_export_file_inventory" not in manifest:
                        entry["local_audit_tree_sha256"] = entry["sha256"]
                    entry["sha256"] = new_sha
                    entry["bytes"] = fp.stat().st_size
        (work_dir / "manifest.json").write_text(
            json.dumps(pub_manifest, indent=2, ensure_ascii=False) + "\n",
            encoding="utf-8",
        )
        if manifest_integrity_errors(work_dir,pub_manifest,public=True):
            raise ValueError('Transformed public bundle failed its exact inventory and digest post-condition')
        for study in redacted_studies:
            if public_token_errors(study,str(study['study_metadata']['pmid'])):
                raise ValueError('Public study contains an invalid opaque reference')
        if graph_path.exists() and public_token_errors(json.loads(graph_path.read_text(encoding='utf-8'))):
            raise ValueError('Public graph contains an invalid opaque reference')
        ceg_export_path = work_dir / 'data/extracted/context_evidence_graph_v1.json'
        if ceg_export_path.exists() and public_token_errors(json.loads(ceg_export_path.read_text(encoding='utf-8'))):
            raise ValueError('Public Context-Evidence Graph contains an invalid opaque reference')
        verify_public_bundle_privacy_guard(
            work_dir,
            source_root=ROOT,
            require_private_pattern_file=("public_export_file_inventory" not in manifest),
        )
    except BaseException:
        if staging_dir.exists():
            shutil.rmtree(staging_dir, ignore_errors=True)
        raise
    finally:
        if policy_token is not None:_PUBLIC_POLICY_SNAPSHOT.reset(policy_token)
        sys.dont_write_bytecode = previous_bytecode
        sys.path[:] = previous_sys_path

    # Refuse publication if source inputs changed after their first validation.
    try:
        if _regular_file_bytes(ROOT, "manifest.json") != manifest_bytes:
            raise ValueError("Canonical manifest changed during export")
        for rel in sorted(included - {"manifest.json"}):
            _verify_pinned_source(ROOT, rel, manifest)
        for source in dossier_inputs:
            _verify_pinned_source(ROOT, source.relative_to(ROOT).as_posix(), manifest)
    except Exception:
        shutil.rmtree(staging_dir)
        raise

    backup_dir = None
    try:
        require_lease()
        backup_dir = Path(tempfile.mkdtemp(prefix=f".{final_dest_dir.name}.rollback-", dir=final_dest_dir.parent))
        backup_dir.rmdir()
        had_existing_bundle = final_dest_dir.exists()
        if had_existing_bundle:
            final_dest_dir.rename(backup_dir)
            require_lease()
        staging_dir.rename(final_dest_dir)
        require_lease()
    except BaseException:
        owned=publication_lease is None or publication_lease.owns_lock()
        if owned and backup_dir is not None and backup_dir.exists() and not final_dest_dir.exists():
            backup_dir.rename(final_dest_dir)
        if staging_dir.exists():
            shutil.rmtree(staging_dir, ignore_errors=True)
        raise
    if backup_dir is not None and backup_dir.exists():
        require_lease()
        shutil.rmtree(backup_dir)
    return sorted(included)


def verify_public_bundle_snapshot(bundle_root: Path | None = None) -> dict[str, int | bool]:
    """Verify shipped public bundle files against manifest.json without requiring private dossiers or decision logs."""
    root = Path(bundle_root) if bundle_root is not None else ROOT
    manifest_path = root / "manifest.json"
    if not manifest_path.is_file():
        raise FileNotFoundError(f"manifest.json not found at {manifest_path}")
    import math as _math