From c7479e5ec0413652bbf580327dfadc2abde6f021 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 11 Nov 2026 13:44:39 +0000 Subject: [PATCH 1/2] =?UTF-8?q?feat:=20Policies=20section=20=E2=80=94=20de?= =?UTF-8?q?clared=20vs=20recommended=20ranges,=20hang-matrix=20check,=20re?= =?UTF-8?q?adable=20decisions,=20version=20x=20flag=20x=20cores=20grid=20(?= =?UTF-8?q?PyAutoDNA#6)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - decisions may carry policy front matter (dna/policy_docs.py); jax-cpu-policy-2026-11 is the first - policy cards: declared range from the newest dependency audit vs recommended, derived status, versions the declared range allows that hang in the matrix (yellow state item), findings, links - small safe markdown renderer for decision pages (no new dependency) - hang matrix as pass/hang counts per jax x XLA flag x cores, plus per-call cost on the newest version Co-Authored-By: Claude Opus 5.5 --- decisions/jax-cpu-policy-2026-11.md | 21 +++ dna/board.py | 200 +++++++++++++++++++++++++++- dna/policy_docs.py | 187 ++++++++++++++++++++++++++ tests/test_board.py | 2 +- tests/test_policy_docs.py | 119 +++++++++++++++++ 5 files changed, 523 insertions(+), 6 deletions(-) create mode 100644 dna/policy_docs.py create mode 100644 tests/test_policy_docs.py diff --git a/decisions/jax-cpu-policy-2026-11.md b/decisions/jax-cpu-policy-2026-11.md index da8e192..52b97de 100644 --- a/decisions/jax-cpu-policy-2026-11.md +++ b/decisions/jax-cpu-policy-2026-11.md @@ -1,3 +1,24 @@ +--- +policy: jax-cpu +title: JAX CPU policy +status: Recommended 2026-11-11 (human-approved). The PyAutoNerves floor change is in progress, pending a Heart validation of jax 0.12 and a release. +declared_in: PyAutoNerves +packages: [jax, jaxlib] +recommended: + jax: ">=0.12.0,<0.13" + jaxlib: ">=0.12.0,<0.13" +matrix_package: jax +review_date: 2026-12-10 +findings: + - "jax 0.11.2 with no XLA flag hangs in compiled CPU likelihoods: on RAL every reproducer hung on its first call at 4 cores (25 of 25 cells), and none hung at 16 cores (0 of 25)." + - "jax 0.12.0 and 0.12.0.1 with no flag: 0 hangs in 30,000 calls, at 4 and 16 cores." + - "The eigen flag (`--xla_cpu_multi_thread_eigen=false`) avoids the hang on 0.11.2 but slows pixelized likelihoods by 18 % to about 50 % on 0.12, so it is not a default." + - "The FFT part of the bug is upstream jax-ml/jax#41265, fixed by openxla/xla#50091 in jax 0.12.0." +links: + - {label: "Research PyAutoNerves#213", url: "https://github.com/PyAutoLabs/PyAutoNerves/issues/213"} + - {label: "Floor change PyAutoNerves#215", url: "https://github.com/PyAutoLabs/PyAutoNerves/issues/215"} + - {label: "Hang matrix scripts", url: "https://github.com/PyAutoLabs/autolens_profiling/tree/main/scripts/misc/jax_version_policy"} +--- # JAX CPU policy: XLA:CPU deadlocks — November 2026 Status: RECOMMENDATION (research, PyAutoNerves#213). Evidence complete; awaiting a Heart diff --git a/dna/board.py b/dna/board.py index 048f9e5..549ac16 100644 --- a/dna/board.py +++ b/dna/board.py @@ -10,6 +10,7 @@ from .inventory import public_inventory, public_runtime, PUBLIC_PACKAGES, PUBLIC_REPOSITORIES from .matrix import CHECK_FIELDS, MATRIX_SOURCE from .schema import identifier, now, read, timestamp +from .policy_docs import inline, load_decisions, render_markdown, safe_url URL = 'https://pyautolabs.github.io/PyAutoDNA/' REPO = 'https://github.com/PyAutoLabs/PyAutoDNA' @@ -88,6 +89,118 @@ def jax_cpu_policy(records): return sorted(rows, key=lambda x: (x['jax'], x['environment'], ' '.join(x['xla_options']))) +FLAG_LABELS = {'xla_cpu_multi_thread_eigen': 'eigen off', 'xla_cpu_enable_concurrency_optimized_scheduler': 'scheduler off'} + + +def flag_label(xla_options): + """The hang-relevant part of a stack's XLA options, as a short column label.""" + names = sorted(FLAG_LABELS[o.lstrip('-').split('=')[0]] for o in (xla_options or []) + if o.lstrip('-').split('=')[0] in FLAG_LABELS) + return ' + '.join(names) if names else 'no flag' + + +def _version_key(text): + from packaging.version import InvalidVersion, Version + try: + return (0, Version(text)) + except InvalidVersion: + return (1, text) + + +def research_checks(records): + """Every check of the latest DNA research verdict per (stack, environment), flattened with + its environment, jax version and flag label.""" + stacks = {r['digest']: r for r in records if r['kind'] == 'stack'} + research = latest([r for r in records if r['kind'] == 'validation' and r.get('authority') == 'PyAutoDNA'], + 'validation', lambda r: (r['stack'], r['environment'])) + out = [] + for r in research.values(): + stack = stacks.get(r['stack'], {}) + jax = stack.get('packages', {}).get('jax') + if not jax: + continue + label = flag_label(stack.get('runtime_flags', {}).get('xla_options')) + for c in r.get('checks', []): + if isinstance(c, dict): + out.append(dict(c, environment=r['environment'], jax=jax, flag=label)) + return out + + +def matrix_grid(checks): + """``{environment: {'columns': [(flag, cores)], 'rows': {jax: {(flag, cores): (passed, hung, total)}}}}``. + ``cores`` is the pinned core count, or 'all' when the run was not pinned.""" + grid = {} + for c in checks: + cores = c.get('cpus_pinned') or 'all' + env = grid.setdefault(c['environment'], {'columns': set(), 'rows': {}}) + col = (c['flag'], cores) + env['columns'].add(col) + cell = env['rows'].setdefault(c['jax'], {}).setdefault(col, [0, 0, 0]) + cell[0] += c.get('outcome') == 'pass' + cell[1] += c.get('outcome') == 'hang' + cell[2] += 1 + order = {'no flag': 0, 'eigen off': 1, 'scheduler off': 2} + for env in grid.values(): + env['columns'] = sorted(env['columns'], key=lambda fc: (order.get(fc[0], 9), fc[0], str(fc[1]).zfill(4))) + return grid + + +def flag_cost(checks, environment, jax): + """Median steady per-call seconds of passing checks: ``(columns, {case: {(flag, cores): s}})``.""" + import statistics + cells = {} + for c in checks: + if c['environment'] != environment or c['jax'] != jax or c.get('outcome') != 'pass': + continue + value = c.get('steady_median_call_s') or c.get('median_call_s') + if isinstance(value, (int, float)): + cells.setdefault(c['case'], {}).setdefault((c['flag'], c.get('cpus_pinned') or 'all'), []).append(value) + columns = sorted({col for row in cells.values() for col in row}, key=lambda fc: (fc[0] != 'no flag', fc[0], str(fc[1]).zfill(4))) + return columns, {case: {col: statistics.median(v) for col, v in row.items()} for case, row in sorted(cells.items())} + + +def policy_cards(records, docs, checks=None): + """One card per decision with policy fields: declared (latest audit) vs recommended, derived + status, and the matrix versions the declared range allows that hang with no flag.""" + from packaging.requirements import Requirement + from packaging.specifiers import SpecifierSet + checks = research_checks(records) if checks is None else checks + hanging = sorted({c['jax'] for c in checks if c['flag'] == 'no flag' and c.get('outcome') == 'hang'}, key=_version_key) + audits = sorted((r for r in records if r['kind'] == 'audit'), key=lambda r: timestamp(r['created'])) + cards = [] + for doc in docs: + pol = doc.get('policy') + if not pol: + continue + declared, audited_at = {}, None + for audit in audits: # newest audit wins, package by package + for row in audit.get('rows', []): + if row.get('repository') == pol['declared_in'] and row.get('package') in pol['packages'] and row.get('declared'): + declared[row['package']] = str(Requirement(row['declared']).specifier) + audited_at = audit['created'] + rows, same = [], bool(declared) + for package in pol['packages']: + rec = SpecifierSet(str(pol['recommended'][package])) + dec = declared.get(package) + if dec is None or SpecifierSet(dec) != rec: + same = False + rows.append({'package': package, 'declared': dec, 'recommended': str(rec)}) + derived = 'not audited' if not declared else 'adopted' if same else 'recommended, not yet declared' + allowed_hanging, recommended_hanging = [], [] + mp = pol.get('matrix_package') + for version in hanging: + if mp in declared and SpecifierSet(declared[mp]).contains(version, prereleases=True): + allowed_hanging.append(version) + if SpecifierSet(str(pol['recommended'][mp])).contains(version, prereleases=True): + recommended_hanging.append(version) + cards.append({'policy': pol['policy'], 'title': pol['title'], 'status': pol['status'], 'derived': derived, + 'declared_in': pol['declared_in'], 'audited_at': audited_at, 'rows': rows, + 'findings': pol.get('findings', []), 'links': pol.get('links', []), + 'review_date': pol['review_date'], 'decision': doc['name'], + 'allowed_hanging': allowed_hanging, 'recommended_hanging': recommended_hanging}) + return cards + + def public_records(records): result = [] for obj in records: @@ -205,6 +318,67 @@ def evidence_age(obj, max_age_days): return 'Stale' if age > max_age_days * 86400 else 'Current receipt' +def render_policies(cards): + """The Policies section: one card per decision that sets a policy.""" + body = '

Policies

What each repository declares, what DNA recommends, and the evidence behind it.

' + if not cards: + return body + '

No decision sets a policy yet.

' + for c in cards: + body += '

' + esc(c['title']) + '

' + body += '

' + esc(c['derived']) + '' + esc(c['status']) + '

' + body += table(['Package', 'Declared in ' + c['declared_in'], 'Recommended'], [ + [r['package'], r['declared'] or 'Not audited', r['recommended']] for r in c['rows']], c['title'] + ' ranges') + when = ('declared range from the dependency audit of ' + c['audited_at'][:10]) if c['audited_at'] else 'no dependency audit recorded yet' + body += '

' + esc(when) + '. Review by ' + esc(c['review_date']) + '.

' + if c['allowed_hanging']: + body += ('

The declared range still allows jax ' + esc(', '.join(c['allowed_hanging'])) + + ', which hangs in the hang matrix without a flag. The recommended range excludes it.

') + elif c['rows'] and c['derived'] != 'not audited': + body += '

No version the declared range allows hangs in the hang matrix.

' + if c['recommended_hanging']: + body += '

The recommended range allows jax ' + esc(', '.join(c['recommended_hanging'])) + ', which hangs in the hang matrix.

' + if c['findings']: + body += '

Findings

    ' + ''.join('
  • ' + inline(str(f)) + '
  • ' for f in c['findings']) + '
' + links = [l for l in c['links'] if safe_url(l['url'])] + body += ('

' + ' · '.join('' + esc(l['label']) + '' for l in links) + + (' · ' if links else '') + 'Full decision

') + body += '
' + return body + '' + + +def render_matrix(checks): + """Pass/hang counts per jax version x XLA flag x cores, and per-call cost on the newest version.""" + if not checks: + return '

No hang-matrix checks recorded.

' + body = '' + for env, grid in sorted(matrix_grid(checks).items()): + cols = grid['columns'] + head = ['jax'] + [f"{flag}, {cores} cores" if cores != 'all' else f"{flag}, all cores" for flag, cores in cols] + rows = [] + for jax in sorted(grid['rows'], key=_version_key): + row = [jax] + for col in cols: + cell = grid['rows'][jax].get(col) + if not cell: + row.append('—') + else: + passed, hung, total = cell + other = total - passed - hung + text = f"{passed}/{total} pass" if not hung else f"{hung}/{total} hang" + (f" · {passed} pass" if passed else '') + row.append(text + (f" ({other} not run)" if other else '')) + rows.append(row) + body += '

' + esc(env) + ': cells passed or hung

' + table(head, rows, env + ' hang matrix by version, flag and cores') + newest = max(grid['rows'], key=_version_key) + cost_cols, cost = flag_cost(checks, env, newest) + if cost: + body += '

' + esc(env) + ': per-call time on jax ' + esc(newest) + ' (median, seconds)

' + body += table(['Reproducer'] + [f"{flag}, {cores} cores" if cores != 'all' else f"{flag}, all cores" for flag, cores in cost_cols], + [[case] + [f"{cost[case][col]:.3f}" if col in cost[case] else '—' for col in cost_cols] for case in cost], + env + ' per-call time by flag') + body += '

A cell counts repeated runs of every reproducer; "not run" covers a module that version cannot load. Per-call time is the steady median of passing runs.

' + return body + + def render(root, brain, output, max_age_days=7): theme = module(brain / 'board/_theme.py', 'dna_theme') state_contract = module(brain / 'board/_state.py', 'dna_state') @@ -238,19 +412,29 @@ def render(root, brain, output, max_age_days=7): 'text': f"{e['label']}: jax {key[0]} with {', '.join(key[1]) or 'no XLA:CPU hang flag'} hangs in the DNA hang matrix", 'url': URL + '#jax-cpu-policy'}) mismatches = mismatches + [(e, None) for e in exposed] - status = 'yellow' if mismatches else 'stale' if any(e['status'] == 'stale' for e in envs) else 'grey' + docs = load_decisions(root / 'decisions') if (root / 'decisions').is_dir() else [] + checks = research_checks(records) + cards = policy_cards(records, docs, checks) + open_policies = [c for c in cards if c['allowed_hanging']] + for card in open_policies: + items.append({'id': 'policy-' + card['policy'], 'severity': 'yellow', 'state': 'action_required', + 'text': f"{card['title']}: {card['declared_in']} still allows jax {', '.join(card['allowed_hanging'])}, which hangs in the DNA hang matrix", + 'url': URL + '#policies'}) + status = 'yellow' if mismatches or open_policies else 'stale' if any(e['status'] == 'stale' for e in envs) else 'grey' count = sum(e['status'] == 'observed' for e in envs) headline = f'{count} / {len(envs)} environments observed' if len(mismatches) > len(exposed): headline += f'; {len(mismatches) - len(exposed)} declaration mismatches' if exposed: headline += f'; {len(exposed)} on a hanging JAX CPU setup' + if open_policies: + headline += f"; {len(open_policies)} {'policy' if len(open_policies) == 1 else 'policies'} not yet declared" state = dict(schema_version=1, organ='dna', repo='PyAutoLabs/PyAutoDNA', status=status, headline=headline, updated=board['updated'], pages_url=URL, items=items) errors = state_contract.validate_state(state) if errors: raise ValueError('; '.join(errors)) - sections = ['environments', 'compatibility', 'decisions', 'campaigns'] + sections = ['policies', 'environments', 'compatibility', 'decisions', 'campaigns'] body = theme.hero('dna', 'Dashboard', navigation=[{'href': '#' + s, 'label': s.title()} for s in sections]) body += theme.orchestration_panel('dna', 'DNA', '', 'Review PyAutoDNA software stacks and compatibility. Read AGENTS.md and inspect current inventories, ' @@ -259,6 +443,7 @@ def render(root, brain, output, max_age_days=7): 'running science environments. Collection or refresh never installs packages or submits compute.', organ='dna', refreshed_at=board['refreshed_at'], refresh_url=REPO + '/actions/workflows/pages.yml', work_links=[{'label': 'DNA', 'href': REPO}, {'label': 'Brain', 'href': 'https://github.com/PyAutoLabs/PyAutoBrain'}]) + body += render_policies(cards) body += '

Environments

' body += table(['Environment', 'Profile', 'Observed Python / backend', 'XLA options', 'Last observation'], [ [e['label'], e['declared_python'] + ' / ' + e['declared_backend'], @@ -311,11 +496,14 @@ def render(root, brain, output, max_age_days=7): body += '

No dependency audit recorded. Package requirements remain authoritative in each repository.

' body += '

JAX CPU policy: hang matrix

' if policy: + body += render_matrix(checks) + body += '
Every recorded verdict' body += table(['jax', 'XLA options', 'Environment', 'Result', 'Reproducers passed', 'Hung (first call)', 'Recorded'], [ [r['jax'], ', '.join(r['xla_options']) or 'Default', r['environment'], r['result'], f"{r['passed']} / {r['cells']}", (', '.join(r['hung_cases']) + (f" (call {r['first_hang']})" if r['first_hang'] is not None else '')) if r['hung'] else 'None', r['created']] for r in policy], 'JAX version and XLA flag hang matrix') + body += '
' body += '

DNA research evidence: each reproducer runs many times in a process that imports only jax. A pass is not a Heart validation and never promotes a stack; a hang blocks one.

' else: body += '

No hang-matrix evidence recorded.

' @@ -334,8 +522,10 @@ def render(root, brain, output, max_age_days=7): else: body += '

No recommended stack has been promoted.

' body += '

Decisions

Reasons for version restrictions and when to review them.

' - for path in sorted((root / 'decisions').glob('*.md')): - body += '
' + esc(path.stem.replace('-', ' ')) + '
' + esc(path.read_text()) + '
' + for doc in docs: + title = doc['policy']['title'] if doc['policy'] else doc['name'].replace('-', ' ') + body += ('
' + esc(title) + '
' + + render_markdown(doc['body']) + '
') body += '

Campaigns

' campaigns = [r for r in records if r['kind'] == 'campaign'] if not campaigns: @@ -347,7 +537,7 @@ def render(root, brain, output, max_age_days=7): body += table(['Action', 'Environment', 'Recorded'], [[r['kind'], r.get('environment', 'Campaign'), r['created']] for r in sorted(events, key=lambda r: timestamp(r['created']))], 'Campaign history') if events else '

Candidate awaiting validation.

' body += '' body += '
' + theme.boards_footer(theme.board_links('https://pyautolabs.github.io', 'dna'), 'dna') - css = '.dna-table{overflow-x:auto;margin:1rem 0}.dna-table table{width:100%;border-collapse:collapse}.dna-table th,.dna-table td{padding:.65rem .8rem;text-align:left;vertical-align:top;border-bottom:1px solid var(--border,#d0d7de)}.dna-table th{white-space:nowrap}.dna-table td{min-width:7rem}.dna-prose{white-space:pre-wrap;font:inherit;line-height:1.6}code{overflow-wrap:anywhere}' + css = '.dna-table{overflow-x:auto;margin:1rem 0}.dna-table table{width:100%;border-collapse:collapse}.dna-table th,.dna-table td{padding:.65rem .8rem;text-align:left;vertical-align:top;border-bottom:1px solid var(--border,#d0d7de)}.dna-table th{white-space:nowrap}.dna-table td{min-width:7rem}.dna-prose{line-height:1.6;max-width:72ch}.dna-prose blockquote{margin:1rem 0;padding:.25rem 1rem;border-left:3px solid var(--border,#d0d7de)}.dna-prose pre{overflow-x:auto}.dna-card{border:1px solid var(--border,#d0d7de);border-radius:10px;padding:1rem 1.1rem;margin:1rem 0}.dna-card h3{margin-top:0}.dna-badge{display:inline-block;padding:.1rem .55rem;border-radius:999px;border:1px solid var(--border,#d0d7de);font-size:.85em;margin-right:.4rem}.dna-warn{border-left:4px solid #bf8700;padding:.4rem .8rem;margin:.6rem 0}code{overflow-wrap:anywhere}' page = 'PyAutoDNA — Software stacks and compatibility
' + body + '
' page = theme.section_layout(page) output.mkdir(parents=True, exist_ok=True) diff --git a/dna/policy_docs.py b/dna/policy_docs.py new file mode 100644 index 0000000..a5c25e4 --- /dev/null +++ b/dna/policy_docs.py @@ -0,0 +1,187 @@ +"""Decision pages: structured policy front matter and a small, safe markdown renderer. + +A decision page may start with a YAML front-matter block (between ``---`` lines) naming the +policy it sets. The board reads those fields to show what is declared versus what is +recommended; the prose below the block is rendered as HTML. Everything is escaped: the renderer +emits only the tags it builds itself, and links only to http(s) URLs or sibling decision pages. +PyAutoDNA#6. +""" +import html +import re +from datetime import date, datetime +from pathlib import Path +import yaml + +REPO_BLOB = 'https://github.com/PyAutoLabs/PyAutoDNA/blob/main/decisions/' +POLICY_KEYS = {'policy', 'title', 'status', 'declared_in', 'packages', 'recommended', + 'matrix_package', 'review_date', 'findings', 'links', 'supersedes'} + + +def split_front_matter(text): + """``(fields or None, body)``. A page without front matter is prose only.""" + if not text.startswith('---\n'): + return None, text + end = text.find('\n---\n', 4) + if end < 0: + raise ValueError('front matter opened but never closed') + fields = yaml.safe_load(text[4:end]) or {} + if not isinstance(fields, dict): + raise ValueError('front matter must be a mapping') + return fields, text[end + 5:] + + +def validate_policy(fields, source='decision'): + """Check a policy's fields; return them with ``review_date`` as an ISO string.""" + unknown = set(fields) - POLICY_KEYS + if unknown: + raise ValueError(f'{source}: unknown policy field(s) {sorted(unknown)}') + for key in ('policy', 'title', 'status', 'declared_in', 'packages', 'recommended', 'review_date'): + if not fields.get(key): + raise ValueError(f'{source}: policy field {key!r} is required') + if not re.fullmatch(r'[a-z0-9][a-z0-9-]{0,60}', str(fields['policy'])): + raise ValueError(f'{source}: policy id must be a short kebab-case name') + packages = fields['packages'] + if not isinstance(packages, list) or not all(isinstance(p, str) for p in packages): + raise ValueError(f'{source}: packages must be a list of names') + recommended = fields['recommended'] + if not isinstance(recommended, dict) or set(recommended) != set(packages): + raise ValueError(f'{source}: recommended must give a range for exactly the listed packages') + from packaging.specifiers import SpecifierSet + for spec in recommended.values(): + SpecifierSet(str(spec)) + review = fields['review_date'] + if isinstance(review, (date, datetime)): + review = review.isoformat()[:10] + datetime.strptime(str(review), '%Y-%m-%d') + for key in ('findings', 'links'): + if not isinstance(fields.get(key, []), list): + raise ValueError(f'{source}: {key} must be a list') + for link in fields.get('links', []): + if not isinstance(link, dict) or not {'label', 'url'} <= set(link) or not safe_url(link['url']): + raise ValueError(f'{source}: each link needs a label and an http(s) url') + out = dict(fields, review_date=str(review)) + out.setdefault('matrix_package', packages[0]) + return out + + +def load_decisions(folder): + """Every decision page: ``{'name', 'path', 'policy' (or None), 'body'}``, sorted by name.""" + docs = [] + for path in sorted(Path(folder).glob('*.md')): + fields, body = split_front_matter(path.read_text()) + policy = validate_policy(fields, path.name) if fields else None + docs.append({'name': path.stem, 'path': path, 'policy': policy, 'body': body}) + return docs + + +def safe_url(url): + return isinstance(url, str) and re.fullmatch(r'https?://[^\s"<>]+', url) is not None + + +def _link_target(url): + if safe_url(url): + return url + if re.fullmatch(r'[A-Za-z0-9_.-]+\.md(#[A-Za-z0-9_-]+)?', url): + return REPO_BLOB + url # a sibling decision page + return None + + +def inline(text): + """Escape, then add `code`, **bold** and [label](url) links.""" + parts = re.split(r'(`[^`]+`)', text) + out = [] + for part in parts: + if part.startswith('`') and part.endswith('`') and len(part) > 1: + out.append('' + html.escape(part[1:-1]) + '') + continue + chunk = html.escape(part, quote=False) + + def link(m): + target = _link_target(html.unescape(m.group(2))) + label = m.group(1) + if not target: + return label + return '' + label + '' + + chunk = re.sub(r'\[([^\]]+)\]\(([^)\s]+)\)', link, chunk) + chunk = re.sub(r'\*\*([^*]+)\*\*', r'\1', chunk) + out.append(chunk) + return ''.join(out) + + +def render_markdown(text, heading_offset=2): + """Headings, paragraphs, bullet / numbered lists (with indented continuations), pipe + tables, blockquotes and fenced code. Anything else is an escaped paragraph.""" + lines = text.splitlines() + out, i = [], 0 + + def heading(level, content): + level = min(6, level + heading_offset) + return f'' + inline(content) + f'' + + while i < len(lines): + line = lines[i] + stripped = line.strip() + if not stripped: + i += 1 + continue + if stripped.startswith('```'): + i += 1 + code = [] + while i < len(lines) and not lines[i].strip().startswith('```'): + code.append(lines[i]) + i += 1 + i += 1 + out.append('
' + html.escape('\n'.join(code)) + '
') + continue + m = re.match(r'(#{1,6})\s+(.*)', stripped) + if m: + out.append(heading(len(m.group(1)), m.group(2))) + i += 1 + continue + if stripped.startswith('|'): + rows = [] + while i < len(lines) and lines[i].strip().startswith('|'): + cells = [c.strip() for c in lines[i].strip().strip('|').split('|')] + if not all(re.fullmatch(r':?-{2,}:?', c) for c in cells): + rows.append(cells) + i += 1 + if rows: + head, *rest = rows + out.append('
' + + ''.join('' for c in head) + + '' + + ''.join('' + ''.join('' for c in r) + '' for r in rest) + + '
' + inline(c) + '
' + inline(c) + '
') + continue + if stripped.startswith('>'): + quote = [] + while i < len(lines) and lines[i].strip().startswith('>'): + quote.append(lines[i].strip()[1:].strip()) + i += 1 + out.append('

' + inline(' '.join(quote)) + '

') + continue + bullet = re.match(r'(\s*)([-*]|\d+\.)\s+(.*)', line) + if bullet: + ordered = bullet.group(2)[0].isdigit() + items = [] + while i < len(lines): + m = re.match(r'(\s*)([-*]|\d+\.)\s+(.*)', lines[i]) + if m and len(m.group(1)) <= len(bullet.group(1)): + items.append(m.group(3)) + elif lines[i].strip() and lines[i].startswith(' ') and items: + items[-1] += ' ' + lines[i].strip() # continuation or nested line + else: + break + i += 1 + tag = 'ol' if ordered else 'ul' + out.append(f'<{tag}>' + ''.join('
  • ' + inline(it) + '
  • ' for it in items) + f'') + continue + para = [] + while i < len(lines) and lines[i].strip() and not re.match(r'\s*(#{1,6}\s|[-*]\s|\d+\.\s|\||>|```)', lines[i]): + para.append(lines[i].strip()) + i += 1 + if not para: # a line the block rules declined (e.g. a lone marker): keep it as text + para, i = [stripped], i + 1 + out.append('

    ' + inline(' '.join(para)) + '

    ') + return '\n'.join(out) diff --git a/tests/test_board.py b/tests/test_board.py index ff7b9af..8c485a6 100644 --- a/tests/test_board.py +++ b/tests/test_board.py @@ -62,7 +62,7 @@ def test_standard_collapsed_sections_and_visible_package_versions(self): page = (self.root/'site/index.html').read_text() self.assertIn('0.11.2', page) self.assertIn('Last updated unavailable', page) - self.assertEqual(page.count('class="board-section"'), 4) + self.assertEqual(page.count('class="board-section"'), 5) # policies, environments, compatibility, decisions, campaigns self.assertNotIn('
    =0.12.0,<0.13" + jaxlib: ">=0.12.0,<0.13" +review_date: 2026-12-10 +findings: + - "0.11.2 hangs at 4 cores." +links: + - {label: "Research", url: "https://github.com/PyAutoLabs/PyAutoNerves/issues/213"} +--- +# Heading + +Body text. +''' + + +def audit(declared_jax, created_offset=0): + rows = [{'repository': 'PyAutoNerves', 'package': p, 'observed': '0.11.2', 'status': 'compatible', + 'declared': f'{p}{declared_jax}'} for p in ('jax', 'jaxlib')] + return record('audit', inventory='i' * 64, rows=rows, declarations=[]) + + +def research(jax, flags, outcomes): + stack = record('stack', name=f'jax-{jax}', python='3.13.13', backend='cpu', packages={'jax': jax, 'jaxlib': jax}, + runtime_flags={'XLA_FLAGS': flags}) + checks = [{'case': case, 'outcome': out, 'cpus_pinned': cores, 'steady_median_call_s': t} + for case, out, cores, t in outcomes] + val = record('validation', stack=stack['digest'], environment='ral-cpu', authority='PyAutoDNA', + result='fail' if any(o[1] == 'hang' for o in outcomes) else 'pass', checks=checks, + evidence='private', inventory='i' * 64) + return public_records([stack, val]) + + +class PolicyDocs(unittest.TestCase): + def test_front_matter_and_validation(self): + fields, body = split_front_matter(FRONT) + pol = validate_policy(fields) + self.assertEqual(pol['review_date'], '2026-12-10') + self.assertEqual(pol['matrix_package'], 'jax') + self.assertTrue(body.startswith('# Heading')) + self.assertEqual(split_front_matter('# plain')[0], None) + with self.assertRaises(ValueError): + validate_policy(dict(fields, recommended={'jax': '>=0.12'})) # jaxlib missing + with self.assertRaises(ValueError): + validate_policy(dict(fields, links=[{'label': 'x', 'url': 'javascript:alert(1)'}])) + with self.assertRaises(ValueError): + validate_policy(dict(fields, surprise=1)) + + def test_renderer_escapes_and_links(self): + out = render_markdown('# T\n\nA and `` and **bold** ' + '[ok](https://a.b/c) [bad](javascript:alert(1)) [sib](jax-2026-10-04.md)\n\n' + '- one\n continued\n- two\n\n| a | b |\n|---|---|\n| | 2 |\n\n> quote') + self.assertNotIn('