From 3a0f7f2c439d41211d1f0b76402ec311334b32c5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 14:48:12 +0000 Subject: [PATCH 1/2] checkRules: one_kind_cell, one value cell per statement, its kind's own [a quantity cell is named for its kind] (Jess Haley, 2026-12-02, did-schema docs/plans/did_v2_go_forward_class_audit.md): "exactly one kind cell per statement, matching its value-kind superclass (a rule)". Siblings first: the builder learns the rule before did-schema declares it (#469); it checks nothing until a class declares it. The name one_kind_cell is Proposed. A cell is a field named `value` or named for a value kind, at the top level of a flat document or directly in a block of a nested one. At most one, and that one the cell valueCellField names for the document's kind. An absent cell (value in bodies, or in a shared value document) is value_inline_or_body's question, not this rule's. checkRules takes the document as built (before ruleView renamed the cell to `value`) as a fifth argument. testBuildOneKindCell: on the loaded schema and, when it is nested, its flat kind-cell copy; each copied twice (a stand-in field named for another kind, with and without the rule declared on `value`). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FxKLA8Tbf9cpvDe7fuVeKf --- src/did/+did2/+build/Contents.m | 4 +- src/did/+did2/+build/document.m | 2 +- src/did/+did2/+build/private/checkRules.m | 127 ++++++++- tests/+did2/+unittest/testBuildOneKindCell.m | 269 +++++++++++++++++++ 4 files changed, 399 insertions(+), 3 deletions(-) create mode 100644 tests/+did2/+unittest/testBuildOneKindCell.m diff --git a/src/did/+did2/+build/Contents.m b/src/did/+did2/+build/Contents.m index d0f0ab93..a0ba5f8a 100644 --- a/src/did/+did2/+build/Contents.m +++ b/src/did/+did2/+build/Contents.m @@ -100,7 +100,9 @@ % fit_metric_unit, and the time-model rules absolute_reading_no_origin, % reading_one_epoch_frame, reading_end_not_before_start, origin_acyclic, % time_shared_or_inline, assertion_no_time, relative_reading_owner (its -% origin is another document, see checkTimeOrigins); the `dimensions` / `covariates` rules are checked by +% origin is another document, see checkTimeOrigins), and one_kind_cell +% (one value cell, the kind's own: [a quantity cell is named for its +% kind]); the `dimensions` / `covariates` rules are checked by % the builder's own dimension and covariate checks whether or not the % schema names them; ingredient_in_formulation is known but needs the % formulation, see checkDoseIngredients) -- an UNKNOWN rule is an error, diff --git a/src/did/+did2/+build/document.m b/src/did/+did2/+build/document.m index 6ab85e1e..41f83c1f 100644 --- a/src/did/+did2/+build/document.m +++ b/src/did/+did2/+build/document.m @@ -252,7 +252,7 @@ error('did2:build:badGap', '%s.', strjoin(problems, '; ')); end -checkRules(cache, className, ruleView(blocks, cellOwner, cellName), chain); +checkRules(cache, className, ruleView(blocks, cellOwner, cellName), chain, blocks); if options.Validate cache.validateDocument(doc); end diff --git a/src/did/+did2/+build/private/checkRules.m b/src/did/+did2/+build/private/checkRules.m index 8c0d6509..da7a5ddd 100644 --- a/src/did/+did2/+build/private/checkRules.m +++ b/src/did/+did2/+build/private/checkRules.m @@ -1,10 +1,16 @@ -function checkRules(cache, className, doc, chain) +function checkRules(cache, className, doc, chain, raw) %CHECKRULES The cross-field checks a per-field check cannot make. % % checkRules(CACHE, CLASSNAME, DOC, CHAIN) raises did2:build:ruleViolated when DOC % breaks one of them. Two kinds, both listed here so a reader has one place % to look: % +% checkRules(CACHE, CLASSNAME, DOC, CHAIN, RAW) also gives the document as +% built, before did2.build.document's ruleView renamed its value cell to +% `value` (and `external` to `data_body`) for the rules below; RAW is DOC +% when not given. Only one_kind_cell reads it: it is about the cell's own +% name. +% % 1. THE SCHEMA'S OWN `rules`, read from every class in the chain. Each rule % the builder can check is implemented below BY NAME. A rule name the % builder does not know is an ERROR (did2:build:unknownRule), not a skip: @@ -108,6 +114,26 @@ function checkRules(cache, className, doc, chain) % amending [a time states its relation % to its origin]) % +% The kind-cell rule (Decided by Jess Haley, 2026-12-02 [a quantity cell +% is named for its kind], did-schema did_v2_go_forward_class_audit.md: +% "exactly one kind cell per statement, matching its value-kind +% superclass (a rule)"). It lands here before did-schema declares it +% (siblings first; did-schema #469). Its name is Proposed (not decided). +% one_kind_cell the document holds one value cell, +% under the name the schema gives the +% cell of its value kind (the kind its +% superclasses list, or the kind its own +% chain holds: did2.schema.cache/ +% valueCellField), in that kind's block +% on a nested document: no field named +% for another value kind, and no second +% cell. A cell that is absent because +% the value is in data bodies (`external` +% true) or in a shared value document +% (`value_id`) is not a second cell; +% whether the value is somewhere is +% value_inline_or_body's question +% % BOTH NUMERIC SHAPES are read ([one shape for measured numbers], Jess % Haley, 2026-11-17, did-schema did_v2_numeric_shape_plan.md, step 1 of % its section 9): a covariate, condition or parameter may carry the new @@ -194,6 +220,9 @@ function checkRules(cache, className, doc, chain) if isempty(chain) chain = cache.classChain(className); end +if nargin < 5 || isempty(raw) + raw = doc; +end blocks = setdiff(fieldnames(doc), {'document_class', 'depends_on', 'files', 'file'}, 'stable'); edgeNames = {}; if isfield(doc, 'depends_on') && ~isempty(doc.depends_on) @@ -394,6 +423,10 @@ function checkRules(cache, className, doc, chain) % Jess Haley 2026-11-30 [time combinations refused by rule]: % the per-document halves (see the header and timeRule) timeRule(doc, ruleName, className); + case 'one_kind_cell' + % [a quantity cell is named for its kind] (Jess Haley, + % 2026-12-02): see the header + oneKindCell(cache, className, raw, ruleName); case 'relative_reading_owner' % [time combinations refused by rule], [time readings have no % clock term]: whether the origin is an epoch or a device is a @@ -1354,6 +1387,98 @@ function readingEndNotBeforeStart(t, ruleName, className) end end +function oneKindCell(cache, className, doc, ruleName) +% one_kind_cell (see the header): the value cells DOC holds, in either +% layout, are at most one, and that one is the cell the schema declares for +% the document's value kind. A cell is a field named `value` or named for a +% value kind (a class descending from `value`), at the top level of a flat +% document or directly in a block of a nested one; a cell embedded in +% another (a dose's ingredient `mass`) is part of that cell, not a second. +kind = ''; +if isfield(doc, 'document_class') && isstruct(doc.document_class) ... + && isfield(doc.document_class, 'superclasses') + kind = cache.documentValueKind(className, ... + superclassNames(doc.document_class.superclasses)); +end +[want, ~, owner] = cache.valueCellField(className, kind); +named = kind; +if isempty(named) + named = owner; +end +flatDoc = ~isfield(doc, 'base') && isfield(doc, 'id'); +if flatDoc + holders = {''}; +else + holders = setdiff(fieldnames(doc), {'document_class', 'depends_on', 'files', 'file'}, 'stable'); +end +found = {}; +for h = 1:numel(holders) + if flatDoc + b = doc; + else + b = doc.(holders{h}); + if ~isstruct(b) || ~isscalar(b) + continue; + end + end + names = fieldnames(b); + for k = 1:numel(names) + if strcmp(names{k}, 'value') || isValueKindName(cache, names{k}) + if flatDoc + found{end+1} = names{k}; %#ok + else + found{end+1} = [holders{h} '.' names{k}]; %#ok + end + end + end +end +expected = want; +if ~flatDoc && ~isempty(owner) + expected = [owner '.' want]; +end +if isempty(want) + % no value kind in the chain declares a cell: nothing to match (a class + % that declares the rule but takes no value kind is the schema's error, + % did-schema validate_v_eta R14) + return; +end +if numel(found) > 1 + violated(ruleName, className, sprintf( ... + ['a statement holds exactly one kind cell, `%s` (its value kind "%s"); ' ... + 'this document holds %d: %s.'], expected, named, numel(found), ... + strjoin(strcat('`', found, '`'), ', '))); +end +if numel(found) == 1 && ~strcmp(found{1}, expected) + violated(ruleName, className, sprintf( ... + ['the kind cell must match the value kind "%s" (`%s`); this document ' ... + 'holds `%s`.'], named, expected, found{1})); +end +end + +function names = superclassNames(sc) +% the class_name of each entry of a document_class.superclasses list +names = {}; +if isempty(sc) + return; +end +if iscell(sc) + items = sc(:)'; +else + items = num2cell(sc(:)'); +end +for k = 1:numel(items) + if isstruct(items{k}) && isfield(items{k}, 'class_name') + names{end+1} = char(items{k}.class_name); %#ok + end +end +end + +function tf = isValueKindName(cache, name) +% is NAME the name of a value kind (a class descending from `value`) +tf = ~strcmp(name, 'value') && cache.hasClass(name) ... + && any(strcmp(cache.superclasses(name), 'value')); +end + function violated(ruleName, where, message) error('did2:build:ruleViolated', '%s (%s): %s', ruleName, where, message); end diff --git a/tests/+did2/+unittest/testBuildOneKindCell.m b/tests/+did2/+unittest/testBuildOneKindCell.m new file mode 100644 index 00000000..cc541a54 --- /dev/null +++ b/tests/+did2/+unittest/testBuildOneKindCell.m @@ -0,0 +1,269 @@ +function tests = testBuildOneKindCell +%TESTBUILDONEKINDCELL did2.build checks the rule one_kind_cell: a statement +% holds exactly one kind cell, matching its value-kind superclass (did-schema +% docs/plans/did_v2_go_forward_class_audit.md, Decided by Jess Haley, +% 2026-12-02 [a quantity cell is named for its kind]; the rule's name is +% Proposed (not decided)). +% +% The rule lands in DID-matlab before did-schema declares it (siblings +% first; did-schema #469 declares it later), so no loaded schema declares it +% yet. For each schema measured, setupOnce makes two COPIES of it: +% 'field' `voltage` gains a second own field named `mass`, the name of +% another value kind (a stand-in for a document holding a cell +% of the wrong kind; a plain text field, since the rule reads +% names, not cell shapes); +% 'rule' the same, and `value` declares one_kind_cell, so every value +% kind (and every statement through its kind) carries it. +% The schemas measured are the loaded one (did-schema `main`: nested, the +% cell named `value`; or a flat kind-cell schema when the loaded one is), +% and, when the loaded one is nested, its flat kind-cell copy +% (did2.unittest.helpers.flatLayoutSchema, 'KindCells', true). The edits +% are text insertions; a missing anchor is an error, never a skip. +% +% Documents are built with 'Validate', false: the subject is checkRules, +% which runs before validation, and the extra field is in no registry. +% The denominator (schemas measured) is printed first. +% +% Run with: results = runtests('did2.unittest.testBuildOneKindCell'); + +tests = functiontests(localfunctions); +end + +function setupOnce(testCase) +did2.unittest.helpers.installSchemaPath(testCase, 'skipping did2 one_kind_cell tests'); +prev = did2.schema.cache.strictMode('TermRegistry', false); +testCase.addTeardown(@() did2.schema.cache.strictMode('TermRegistry', prev)); +loaded = did2.schema.cache.shared(); +sources = {loaded.schemaPath}; +labels = {layoutLabel(loaded)}; +if ~loaded.isFlat() + [~, kc] = did2.unittest.helpers.flatLayoutSchema(testCase, 'KindCells', true); + sources{end+1} = kc.schemaPath; + labels{end+1} = layoutLabel(kc); +end +m = struct('label', {}, 'field', {}, 'rule', {}); +for k = 1:numel(sources) + m(end+1) = struct('label', labels{k}, ... + 'field', editedCopy(testCase, sources{k}, false), ... + 'rule', editedCopy(testCase, sources{k}, true)); %#ok +end +% editedCopy builds caches without switching the shared one; the shared +% cache is put back to the loaded schema for the other tests +did2.schema.cache.setSchemaPath(loaded.schemaPath); +testCase.TestData.measured = m; +ids = struct(); +for n = {'sid', 'subject', 'timeref', 'a', 'b', 'config', 'policy'} + ids.(n{1}) = did.ido.unique_id(); +end +testCase.TestData.ids = ids; +fprintf('testBuildOneKindCell: %d schema(s) measured: %s\n', numel(m), strjoin({m.label}, ', ')); +end + +function teardownOnce(testCase) +did2.unittest.helpers.restoreSchemaPath(testCase); +end + +% ===================== the rule ============================================== + +function testTheRuleIsDeclaredOnlyInTheRuleCopy(testCase) +m = testCase.TestData.measured; +verifyNotEmpty(testCase, m, 'no schema measured'); +for k = 1:numel(m) + verifyTrue(testCase, declaresRule(m(k).rule, 'value'), [m(k).label ': rule copy']); + verifyFalse(testCase, declaresRule(m(k).field, 'value'), [m(k).label ': field copy']); +end +end + +function testOwnCellAloneIsAccepted(testCase) +m = testCase.TestData.measured; +for k = 1:numel(m) + doc = voltage(testCase, m(k).rule, true, false, false); + [v, ~, name] = m(k).rule.valueCellIn(doc); + verifyNotEmpty(testCase, v, [m(k).label ': the voltage cell is read back']); + verifyEqual(testCase, name, expectedCellName(m(k).rule, 'voltage'), m(k).label); +end +end + +function testValueInBodiesWithNoCellIsAccepted(testCase) +% `external` true and no cell: not a second cell, and not the rule's question +m = testCase.TestData.measured; +for k = 1:numel(m) + voltage(testCase, m(k).rule, false, false, true); +end +end + +function testTwoKindCellsAreRefused(testCase) +m = testCase.TestData.measured; +for k = 1:numel(m) + err = refused(testCase, @() voltage(testCase, m(k).rule, true, true, false), m(k).label); + verifyTrue(testCase, contains(err.message, 'one_kind_cell') ... + && contains(err.message, 'exactly one kind cell'), [m(k).label ': ' err.message]); +end +end + +function testACellOfAnotherKindIsRefused(testCase) +% only `mass` on a voltage statement whose value is in bodies, so the value +% rule (value_inline_or_body) holds and one_kind_cell is the one refusing +m = testCase.TestData.measured; +for k = 1:numel(m) + err = refused(testCase, @() voltage(testCase, m(k).rule, false, true, true), m(k).label); + verifyTrue(testCase, contains(err.message, 'one_kind_cell') ... + && contains(err.message, 'must match the value kind "voltage"'), [m(k).label ': ' err.message]); +end +end + +function testUndeclaredRuleChecksNothing(testCase) +% active only when a class declares it: the same two documents build on the +% copy without the rule +m = testCase.TestData.measured; +for k = 1:numel(m) + voltage(testCase, m(k).field, true, true, false); + voltage(testCase, m(k).field, false, true, true); +end +end + +function testOtherKindsAndOwnChainKindsAreAccepted(testCase) +% a term assertion (a kind the direction lists) and a clock_alignment (the +% kind `polynomial` in the class's own chain, a class with two parents) +m = testCase.TestData.measured; +ids = testCase.TestData.ids; +for k = 1:numel(m) + c = m(k).rule; + common = {'SessionId', ids.sid, 'CreationTimestamp', '2026-12-03T12:00:00.000Z', ... + 'SchemaCache', c, 'Validate', false}; + did2.build.statement('assertion', ids.subject, did2.build.term('NCIT:C45293', 'Species'), ... + did2.build.term('NCBITaxon:10090', 'Mus musculus'), 'ValueKind', 'term', common{:}); + doc = did2.build.document('clock_alignment', struct( ... + 'value', struct('coefficients', [0.5 1.0001], 'degree', 1), ... + 'relation', did2.build.term('EMPTY:0000440', 'temporally aligned with'), ... + 'cost', 0), 'Edges', struct('input_id', ids.a, 'output_id', ids.b, ... + 'clock_alignment_configuration_id', ids.config, ... + 'clock_alignment_policy_id', ids.policy), common{:}); + [~, ~, name] = c.valueCellIn(doc); + verifyEqual(testCase, name, expectedCellName(c, 'polynomial'), m(k).label); +end +end + +% ===================== helpers =============================================== + +function doc = voltage(testCase, c, withCell, withMass, external) +% a voltage observation on schema cache C: its own cell when WITHCELL, the +% stand-in `mass` field when WITHMASS, in data bodies when EXTERNAL +ids = testCase.TestData.ids; +value = []; +opts = {}; +if withCell + value = did2.build.valueCell('voltage', [0.01 0.02 0.03], 'SchemaCache', c); + opts = {'Dimensions', did2.build.dimension('time', 3)}; +end +if external + opts = [opts, {'DataBody', true}]; +end +if withMass + opts = [opts, {'Fields', struct('mass', 'stand-in cell of another kind')}]; +end +doc = did2.build.statement('observation', ids.subject, 'voltage', value, opts{:}, ... + 'TimeReferenceIds', {ids.timeref}, 'ValueKind', 'voltage', ... + 'SessionId', ids.sid, 'CreationTimestamp', '2026-12-03T12:00:00.000Z', ... + 'SchemaCache', c, 'Validate', false); +end + +function err = refused(testCase, fn, label) +err = []; +try + fn(); +catch err +end +verifyNotEmpty(testCase, err, [label ': built, expected did2:build:ruleViolated']); +if isempty(err) + err = MException('testBuildOneKindCell:notRefused', 'not refused'); + return; +end +verifyEqual(testCase, err.identifier, 'did2:build:ruleViolated', [label ': ' err.message]); +end + +function name = expectedCellName(c, kind) +name = c.valueCellField(kind); +end + +function tf = declaresRule(c, className) +tf = false; +s = c.getClass(className); +if ~isfield(s, 'rules') || isempty(s.rules) + return; +end +r = s.rules; +if ~iscell(r); r = num2cell(r); end +for k = 1:numel(r) + if isstruct(r{k}) && isfield(r{k}, 'name') && strcmp(char(r{k}.name), 'one_kind_cell') + tf = true; + return; + end +end +end + +function s = layoutLabel(c) +if c.isFlat() + s = sprintf('flat (voltage cell `%s`)', c.valueCellField('voltage')); +else + s = sprintf('nested (voltage cell `%s`)', c.valueCellField('voltage')); +end +end + +function c = editedCopy(testCase, src, withRule) +% a copy of the schema set at SRC with `voltage`'s extra `mass` field and, +% when WITHRULE, `value` declaring one_kind_cell; returns its cache +tmp = tempname; +mkdir(tmp); +testCase.addTeardown(@() rmdir(tmp, 's')); +did2.schema.cache.copySchemaSet(src, tmp); +f = onlyFile(tmp, 'voltage.json'); +insertAfter(f, sprintf('\n "fields": ['), sprintf([ ... + '\n {' ... + '\n "name": "mass",' ... + '\n "type": "char",' ... + '\n "blank_value": "",' ... + '\n "default_value": "",' ... + '\n "mustBeNonEmpty": false,' ... + '\n "mustBeScalar": true,' ... + '\n "mustNotHaveNaN": false,' ... + '\n "queryable": false,' ... + '\n "ontology": null,' ... + '\n "documentation": "TEST ONLY (testBuildOneKindCell): a field named for another value kind.",' ... + '\n "constraints": {}' ... + '\n },'])); +if withRule + insertAfter(onlyFile(tmp, 'value.json'), sprintf('\n "rules": ['), sprintf([ ... + '\n {' ... + '\n "name": "one_kind_cell",' ... + '\n "fields": [],' ... + '\n "statement": "TEST ONLY (testBuildOneKindCell): exactly one kind cell per statement, matching its value-kind superclass."' ... + '\n },'])); +end +did2.schema.cache.setSchemaPath(tmp); +c = did2.schema.cache.shared(); +end + +function f = onlyFile(root, name) +d = dir(fullfile(root, '**', name)); +if numel(d) ~= 1 + error('testBuildOneKindCell:anchor', '%d file(s) named %s under %s', numel(d), name, root); +end +f = fullfile(d(1).folder, d(1).name); +end + +function insertAfter(file, anchor, text) +txt = fileread(file); +at = strfind(txt, anchor); +if numel(at) ~= 1 + error('testBuildOneKindCell:anchor', '%s: anchor found %d time(s)', file, numel(at)); +end +e = at + numel(anchor) - 1; +txt = [txt(1:e) text txt(e+1:end)]; +fid = fopen(file, 'w'); +if fid < 0 + error('testBuildOneKindCell:write', 'cannot write %s', file); +end +fwrite(fid, txt); +fclose(fid); +end From 787f5fc7db5c1fb43b9d567eb4eb30eb21dddc72 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 14:57:13 +0000 Subject: [PATCH 2/2] checkRules: declare the fifth argument in the arguments block The first push failed every build with MATLAB:functionValidation:MismatchBetweenBlockAndLine (run 47131868427). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FxKLA8Tbf9cpvDe7fuVeKf --- src/did/+did2/+build/private/checkRules.m | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/did/+did2/+build/private/checkRules.m b/src/did/+did2/+build/private/checkRules.m index da7a5ddd..0e50bb79 100644 --- a/src/did/+did2/+build/private/checkRules.m +++ b/src/did/+did2/+build/private/checkRules.m @@ -215,12 +215,13 @@ function checkRules(cache, className, doc, chain, raw) className {mustBeText} doc (1,1) struct chain = {} + raw = [] end if isempty(chain) chain = cache.classChain(className); end -if nargin < 5 || isempty(raw) +if isempty(raw) raw = doc; end blocks = setdiff(fieldnames(doc), {'document_class', 'depends_on', 'files', 'file'}, 'stable');