from pathlib import Path
from fractions import Fraction as F
import json,hashlib,os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
os.umask(0o077)
p=Path(__file__).resolve().parent;r=p
sources=[r/'verifier-controlled-dependence-exact-diagnostic-v1-20261007',r/'verifier-pairwise-insufficiency-exact-v1-20261007']
def require(condition, message):
 if not condition: raise ValueError(message)
data=[]
for s in sources:
 m=json.loads((s/'manifest.json').read_bytes())
 pins=m.get('sha256',m.get('sources'))
 if not isinstance(pins,dict) or not pins or 'result.json' not in pins: raise ValueError('Missing diagnostic source commitments')
 for name,h in pins.items():
  if hashlib.sha256((s/name).read_bytes()).hexdigest()!=h:raise ValueError('Source hash mismatch: '+name)
 data.append(json.loads((s/'result.json').read_bytes()))
a,b=data
# Check the plotted quantities independently with rational arithmetic.
for row in a['rows']:
 rho=F(row['rho']);j0=F(1,100)+rho*F(9,100);j1=F(1,25)+rho*F(4,25)
 coverage=F(3,4)+rho*F(1,4)
 require(F(row['agreement_coverage'])==coverage, 'Coverage formula mismatch')
 require(F(row['error_given_agreement'])==(j0+j1)/2/coverage, 'Conditional risk formula mismatch')
for row in b['rows']:
 q=[F(x['numerator'],x['denominator']) for x in row['error_count_probabilities']]
 require(all(v>=0 for v in q) and sum(q)==1 and sum(k*q[k] for k in range(5))==F(3,5), 'Probability law or first moment mismatch')
 require(sum(k*(k-1)*q[k] for k in range(5))/12==F(9,400), 'Pair error moment mismatch')
 acc=q[0]+q[1]+q[2]/2
 require(acc==F(row['majority_random_tie_accuracy']['numerator'],row['majority_random_tie_accuracy']['denominator']), 'Voting accuracy mismatch')
fig,axes=plt.subplots(1,3,figsize=(12,3.8),layout='constrained')
x=[float(F(t['rho'])) for t in a['rows']]
axes[0].plot(x,[100*float(F(t['error_given_agreement'])) for t in a['rows']],marker='o')
axes[0].set(xlabel='Class-conditional error correlation',ylabel='Error among agreement outputs (%)',title='Agreement risk')
axes[1].plot(x,[100*float(F(t['agreement_coverage'])) for t in a['rows']],marker='o',color='#a65d00')
axes[1].set(xlabel='Class-conditional error correlation',ylabel='Non-abstaining coverage (%)',title='Coverage changes too')
axes[2].plot([float(F(t['delta']['numerator'],t['delta']['denominator'])) for t in b['rows']],[100*float(F(t['majority_random_tie_accuracy']['numerator'],t['majority_random_tie_accuracy']['denominator'])) for t in b['rows']],marker='o',color='#476447')
axes[2].set(xlabel='Higher-order probability perturbation',ylabel='Majority accuracy (%)',title='Same marginals and covariance')
for ax in axes:ax.grid(alpha=.25)
fig.suptitle('Exact synthetic diagnostics — no empirical model or selection result')
for ext in ['pdf','svg','png']:fig.savefig(p/('dependence-diagnostics.'+ext),dpi=180, metadata={'Creator':'Verifier dependence diagnostic builder'} if ext != 'png' else None)
md='''# Verifier dependence: controlled examples and limits

Draft methods appendix. These are exact authored binary-classification constructions, not observations of LLMs, code-selection results, new algorithm claims or established novelty. The frozen H1 protocol is unchanged.

## Agreement changes both risk and coverage

Within truth class y, two judges have error probability p_y. With probability rho they share a Bernoulli error; otherwise errors are independent. Thus joint error equals p_y² + rho p_y(1−p_y), and error correlation equals rho. This models positive dependence only. Truth prevalence is one half, false-positive marginal is 1/10, and false-negative marginal is 1/5.

Predicting only on agreement gives coverage 3/4 + rho/4. Joint error among all examples is 1/40 + rho/8; divide by coverage to obtain error conditional on agreement. At rho=0, conditional error is 1/30 with 75% coverage. At rho=1, it is 3/20 with 100% coverage. Correct non-abstaining predictions cover 72.5% versus 85% of all examples respectively. Lower conditional error therefore does not establish better unconditional utility. Comparisons must specify abstention utility, query costs and coverage.

## Pairwise summaries do not determine portfolio utility

For four exchangeable judges, let K count errors. Start from Binomial(4,3/20), then perturb probabilities by delta times (1,−3,3,−1,0), with delta in {−1/1000,0,1/1000}. Conditional on K, distribute mass uniformly among error patterns. The same law applies in both truth classes.

The perturbation preserves total mass, first moment and second factorial moment. All marginal errors remain 3/20 and all pairwise joint errors remain 9/400. Pairwise covariance is zero and the variance-equivalent count is four in every condition. Nonetheless majority accuracy with random ties is 93.975%, 93.925% and 93.875%: an exact 0.10 percentage-point spread.

Consequently no deterministic function of the covariance matrix alone determines majority accuracy across unrestricted joint laws. This does not refute useful empirical covariance-based prediction or establish that higher-order estimation helps a finite-data controller. Pairwise independence is not joint independence. Known-law Bayes calculations in the source diagnostic use synthetic distributions, not an implementable learned oracle.

## Consequences for the research design

Report class-conditional errors and coverage; test rather than assume the sufficiency of diversity summaries. Keep fixed-bank selection, adaptive observation acquisition and natural-shift studies distinct. Predeclare utility/resource accounting and estimate diagnostics on source data before target outcomes. These examples motivate controls; they do not establish a practical verification gain.

## Reproduction and figure

Run `python3 build.py` in this directory. The build verifies committed source files against their manifests, independently checks plotted formulas using rational arithmetic, and exports PDF, SVG and PNG. Plot coordinates derive directly from fractions. The output manifest is regenerated by the builder and records current file hashes; it is not an externally authenticated seal. An independent reviewer must pin and verify a manifest separately. The first two panels must be interpreted together. The third panel holds covariance fixed; its narrow scale shows a small exact counterexample, not a large practical effect. Exact calculations require no statistical confidence intervals.

Related literature: Kuncheva and Whitaker (2003), Measures of Diversity in Classifier Ensembles and Their Relationship with the Ensemble Accuracy, Machine Learning 51(2), 181–207, DOI 10.1023/A:1022859003006. The [Bangor University record](https://research.bangor.ac.uk/en/publications/measures-of-diversity-in-classifier-ensembles-and-their-relations/) verifies bibliographic details only. This appendix does not claim the exact constructions are novel or reproduced from that paper.

No model calls, external spending, candidate execution or study advancement occurred. This draft is not yet published on the personal site.
'''
(p/'APPENDIX.md').write_text(md)
files={f.name:hashlib.sha256(f.read_bytes()).hexdigest() for f in p.iterdir() if f.is_file() and f.name!='manifest.json'}
(p/'manifest.json').write_text(json.dumps({'status':'DRAFT_EXACT_SYNTHETIC_METHODS_APPENDIX','files':files,'source_manifests':{s.name:hashlib.sha256((s/'manifest.json').read_bytes()).hexdigest() for s in sources},'model_calls':0,'external_spend_usd':0,'empirical_model_result':False,'frozen_H1_changed':False},indent=2)+'\n')
print(p)
