Files
faunosteo/packages/domain/tests/r2-conformance.test.ts
T
bchanot 0c47d0f837 feat(domain): R2.2 sheet integrity rules, publish check, SheetIndexData and SQL conformance in Rust
The 21 rules of validateSheetDocument ported with identical codes,
severities, paths and messages (frozen from the TypeScript on 26
conformance fixtures), createEmptySheetDocument, the publish check
(strict shape then rules), and the index data React reads once (positions
with Map semantics, names, spine ids, finding-path keys). The fixtures
also carry the codes private.sheet_document_issues returns: a cargo test
generates supabase/tests/011_sheet_conformance.sql and refuses drift
(PGlite 12/12 files, real stack 446/446). .prettierignore keeps the
byte-exact oracles and generated fixtures out of pnpm format.
2026-10-14 00:17:21 +02:00

360 lines
11 KiB
TypeScript

/**
* R2 conformance fixtures (RUST_ARCHITECTURE_REVIEW III.4): one mutated horse slice per
* rule family, with what the TypeScript rules report (code, severity, path, message) frozen
* from `validateSheetDocument`, and the codes the SQL re-check (`private.sheet_document_issues`)
* returns, sorted. Written under crates/core/tests/conformance with `MAKE_R2_ORACLES=1`,
* asserted otherwise; cargo checks the Rust rules against them and generates the pgTAP file
* supabase/tests/011_sheet_conformance.sql from them.
*/
import { readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
import {
AnatomicalSheetDocumentSchema,
validateSheetDocument,
type AnatomicalSheetDocument,
type Annotation,
type SheetView,
} from '../src'
import { HORSE_MAIN_ASSET_ID, horseSlice } from './fixtures/horse-slice'
const DIR = resolve(
dirname(fileURLToPath(import.meta.url)),
'../../../crates/core/tests/conformance',
)
const MAKE = process.env.MAKE_R2_ORACLES === '1'
type Doc = AnatomicalSheetDocument
type Raw = Record<string, unknown>
interface Case {
name: string
description: string
/** Mutation of the parsed horse slice (shape-valid documents). */
mutate?: (doc: Doc) => void
/** Mutation of the JSON form, for documents the shape tier refuses. */
raw?: (doc: Raw) => void
/** Codes `private.sheet_document_issues` returns, sorted (collate "C"). */
sql: string[]
}
function point(id: string, fields: Partial<Annotation> = {}): Annotation {
return {
id,
kind: 'point',
view_id: 'view-main',
category_id: 'articulations',
laterality: 'bilateral',
geometry: null,
review_status: 'inherited',
color: null,
name: { fr: id, en: id },
finding_zone_id: 'hip',
vertebral_region_code: null,
...fields,
} as Annotation
}
function trigger(id: string, viewId: string, opensViewId: string): Annotation {
return {
id,
kind: 'detail_trigger',
view_id: viewId,
category_id: 'cadrans-du-crane',
laterality: 'unpaired',
geometry: null,
review_status: 'inherited',
color: null,
name: null,
opens_view_id: opensViewId,
}
}
function detailView(id: string, parentId: string): SheetView {
return {
id,
kind: 'detail',
name: { fr: id, en: id },
parent_view_id: parentId,
svg_asset_id: HORSE_MAIN_ASSET_ID,
view_box: null,
}
}
function observable(doc: Doc, index: number) {
const annotation = doc.annotations[index]
if (!annotation || annotation.kind === 'detail_trigger')
throw new Error('fixture')
return annotation
}
const CASES: Case[] = [
{ name: 'clean', description: 'the horse slice: no issue', sql: [] },
{
name: 'view-main-count',
description: 'two main views',
mutate: (d) => d.views.push({ ...d.views[0]!, id: 'view-alt' }),
sql: ['view.main.count'],
},
{
name: 'view-id-duplicate',
description: 'a detail view listed twice',
mutate: (d) => d.views.push(structuredClone(d.views[1]!)),
sql: ['view.id.duplicate'],
},
{
name: 'view-parent-missing',
description: 'a detail view whose parent does not exist',
mutate: (d) => d.views.push(detailView('view-orphan', 'view-ghost')),
sql: ['view.parent.missing'],
},
{
name: 'view-parent-cycle',
description:
'two detail views parent of each other (SQL has no cycle rule)',
mutate: (d) => {
d.views.push(
detailView('view-a', 'view-b'),
detailView('view-b', 'view-a'),
)
d.annotations.push(trigger('open-a', 'view-b', 'view-a'))
d.annotations.push(trigger('open-b', 'view-a', 'view-b'))
},
sql: [],
},
{
name: 'view-unreachable',
description: 'the head view without its trigger',
mutate: (d) => {
d.annotations = d.annotations.filter((a) => a.id !== 'head-trigger')
},
sql: ['view.unreachable'],
},
{
name: 'view-asset-missing-main',
description: 'the main view without an SVG asset',
mutate: (d) => {
d.views[0]!.svg_asset_id = null
},
sql: ['view.asset.missing'],
},
{
name: 'view-asset-missing-detail',
description: 'a detail view with neither an asset nor a view_box',
mutate: (d) => {
d.views[1]!.svg_asset_id = null
d.views[1]!.view_box = null
},
sql: ['view.asset.missing'],
},
{
name: 'annotation-id-duplicate',
description: 'an annotation id repeated on another view',
mutate: (d) => {
d.annotations.push({
...structuredClone(d.annotations[4]!),
view_id: 'view-main',
})
},
sql: ['annotation.id.duplicate'],
},
{
name: 'annotation-view-missing',
description: 'an annotation on a view that does not exist',
mutate: (d) =>
d.annotations.push(point('ghost', { view_id: 'view-ghost' })),
sql: ['annotation.view.missing'],
},
{
name: 'annotation-category-missing',
description: 'an annotation in an undeclared category',
mutate: (d) => {
d.annotations[0]!.category_id = 'os'
},
sql: ['annotation.category.missing'],
},
{
name: 'annotation-opens-view-invalid',
description:
'triggers opening their own view, the main view and an absent view',
mutate: (d) => {
d.annotations.push(trigger('loop', 'view-head', 'view-head'))
d.annotations.push(trigger('to-main', 'view-main', 'view-main'))
d.annotations.push(trigger('to-ghost', 'view-main', 'view-ghost'))
},
sql: ['annotation.opens_view.invalid'],
},
{
name: 'annotation-finding-zone-missing',
description: 'an annotation linked to an undeclared finding zone',
mutate: (d) =>
d.annotations.push(point('stifle', { finding_zone_id: 'stifle' })),
sql: ['annotation.finding_zone.missing'],
},
{
name: 'annotation-region-missing',
description: 'a spine annotation on an unconfigured region',
mutate: (d) => {
observable(d, 1).vertebral_region_code = 'Q'
},
sql: ['annotation.region.missing'],
},
{
name: 'annotation-no-findings',
description:
'an annotation linked to no finding zone (warning, not mirrored by SQL)',
mutate: (d) =>
d.annotations.push(point('mandible', { finding_zone_id: null })),
sql: [],
},
{
name: 'region-code-duplicate',
description: 'a vertebral region listed twice',
mutate: (d) => {
const regions = d.vertebral_config.regions
regions.push(structuredClone(regions[0]!))
},
sql: ['region.code.duplicate'],
},
{
name: 'category-id-duplicate',
description: 'an annotation category listed twice',
mutate: (d) => d.categories.push(structuredClone(d.categories[0]!)),
sql: ['category.id.duplicate'],
},
{
name: 'finding-zone-id-duplicate',
description: 'a finding zone listed twice',
mutate: (d) => d.finding_zones.push(structuredClone(d.finding_zones[0]!)),
sql: ['finding_zone.id.duplicate'],
},
{
name: 'finding-id-duplicate',
description:
'sibling finding ids repeated at two depths (not mirrored by SQL)',
mutate: (d) => {
const categories = d.finding_zones[0]!.categories
categories.push(structuredClone(categories[0]!))
const articular = categories[0]!.children[0]!
articular.children.push(structuredClone(articular.children[0]!))
},
sql: [],
},
{
name: 'reference-id-duplicate',
description: 'a reference declared twice',
mutate: (d) => d.references.push(structuredClone(d.references[0]!)),
sql: ['reference.id.duplicate'],
},
{
name: 'finding-reference-missing',
description: 'undeclared citations on a category and on a nested node',
mutate: (d) => {
const hip = d.finding_zones[0]!.categories
hip[0]!.reference_ids = ['nav-2017']
hip[0]!.children[0]!.children[0]!.reference_ids = ['legacy-catalog', 'x']
},
sql: ['finding.reference.missing'],
},
{
name: 'region-count-range-invalid',
description: 'a usual vertebra count outside its documented range',
mutate: (d) => {
d.vertebral_config.regions[4]!.count_range = { min: 19, max: 21 }
},
sql: ['region.count_range.invalid'],
},
{
name: 'finding-zone-unreferenced',
description:
'a finding zone no annotation points to (warning, not mirrored by SQL)',
mutate: (d) =>
d.finding_zones.push({
id: 'stifle',
name: { fr: 'Grasset', en: 'Stifle' },
categories: [],
}),
sql: [],
},
{
name: 'several-errors',
description:
'errors of four families at once, duplicates of one code collapsed by SQL',
mutate: (d) => {
d.views[0]!.svg_asset_id = null
d.annotations[0]!.category_id = 'os'
d.annotations[2]!.category_id = 'os'
d.vertebral_config.regions[4]!.count_range = { min: 19, max: 21 }
},
sql: [
'annotation.category.missing',
'region.count_range.invalid',
'view.asset.missing',
],
},
{
name: 'shape-references-not-array',
description:
'a non-array references registry: the shape tier refuses it, SQL says document.shape',
raw: (d) => {
d.references = 'x'
},
sql: ['document.shape'],
},
{
name: 'shape-reference-url-scheme',
description:
'a javascript: reference url: the shape tier refuses it, SQL says reference.url.scheme',
raw: (d) => {
const refs = d.references as Raw[]
refs[0]!.url = 'javascript:alert(1)'
},
sql: ['reference.url.scheme'],
},
]
function fixtureOf(c: Case): unknown {
if (c.raw) {
const doc = structuredClone(horseSlice()) as unknown as Raw
c.raw(doc)
expect(AnatomicalSheetDocumentSchema.safeParse(doc).success).toBe(false)
return {
name: c.name,
description: c.description,
document: doc,
rust: { shape_error: true },
sql: c.sql,
}
}
const doc = horseSlice()
c.mutate?.(doc)
expect(AnatomicalSheetDocumentSchema.safeParse(doc).success).toBe(true)
const issues = validateSheetDocument(doc)
return {
name: c.name,
description: c.description,
document: doc,
rust: { issues },
sql: c.sql,
}
}
describe('sheet conformance fixtures', () => {
it.each(CASES.map((c) => [c.name, c] as const))('%s', (name, c) => {
const file = resolve(DIR, `${name}.json`)
const text = `${JSON.stringify(fixtureOf(c))}\n`
if (MAKE) writeFileSync(file, text)
expect(readFileSync(file, 'utf8')).toBe(text)
})
it('has no stale fixture file', () => {
const names = new Set(CASES.map((c) => `${c.name}.json`))
const stale = readdirSync(DIR).filter(
(f) => f.endsWith('.json') && !names.has(f),
)
if (MAKE) for (const f of stale) rmSync(resolve(DIR, f))
else expect(stale).toEqual([])
})
})